Wall06 commited on
Commit
fd35ff4
Β·
verified Β·
1 Parent(s): 9f5edc3

Update app.py

Browse files
Files changed (1) hide show
  1. app.py +32 -41
app.py CHANGED
@@ -1,24 +1,23 @@
1
  import gradio as gr
2
- import requests
3
  import os
4
 
5
- # --- 1. SETUP API CONNECTION ---
6
- API_KEY = os.getenv("HF_API_KEY")
7
- # πŸ”΄ FIX: We use the NEW 'router' URL + Zephyr Model (Reliable)
8
- API_URL = "https://router.huggingface.co/models/HuggingFaceH4/zephyr-7b-beta"
9
- headers = {"Authorization": f"Bearer {API_KEY}"}
 
10
 
11
  # --- 2. DEFINE THE LOGIC ---
12
  def analyze_biodiversity(species, habitat, region, activity, noise, flow, pollutants, breeding, disturbance):
 
13
  if not API_KEY:
14
  return "⚠️ Error: API Key not found. Please add HF_API_KEY in Settings > Secrets."
15
 
16
- prompt = f"""
17
- <|system|>
18
- You are BioVigilus, an expert AI Ecologist.
19
- Analyze the environmental impact of the scenario below.
20
- </s>
21
- <|user|>
22
  SCENARIO:
23
  - Species: {species}
24
  - Habitat: {habitat} ({region})
@@ -28,40 +27,31 @@ def analyze_biodiversity(species, habitat, region, activity, noise, flow, pollut
28
  - Breeding Season: {breeding}
29
 
30
  TASK:
31
- Generate a professional Impact Assessment Report.
32
- Use clear headings and emojis.
33
- Include:
 
34
  1. πŸ›‘ **Risk Level** (Critical/High/Medium/Low)
35
- 2. 🌑️ **Sensitivity Score** (0-100)
36
  3. πŸ’€ **Predicted Consequences**
37
- 4. πŸ›‘οΈ **Mitigation Measures** (Bullet points)
38
  5. βš–οΈ **Final Verdict** (Proceed/Halt/Modify)
39
- </s>
40
- <|assistant|>
41
  """
42
 
43
  try:
44
- # Lower max_new_tokens for speed
45
- response = requests.post(API_URL, headers=headers, json={"inputs": prompt, "parameters": {"max_new_tokens": 500}})
46
-
47
- # --- ERROR HANDLING ---
48
- if response.status_code == 503:
49
- return "⏳ AI is waking up. Please wait 30 seconds and click 'Analyze' again."
50
-
51
- if response.status_code != 200:
52
- return f"⚠️ API Error {response.status_code}: {response.text}"
53
-
54
- result = response.json()
55
-
56
- if isinstance(result, list) and "generated_text" in result[0]:
57
- # Clean up the output to remove the prompt text
58
- raw_text = result[0]["generated_text"]
59
- return raw_text.replace(prompt, "").strip()
60
- else:
61
- return str(result)
62
 
63
  except Exception as e:
64
- return f"⚠️ Connection Failed: {str(e)}"
 
65
 
66
  # --- 3. CUSTOM STYLE (Trojan Horse Method) ---
67
  custom_style = """
@@ -79,13 +69,14 @@ custom_style = """
79
  }
80
  button.primary:hover { transform: scale(1.02); }
81
 
82
- .gr-box, .gr-input, input {
83
  background-color: #1e293b !important;
84
  border: 1px solid #334155 !important;
 
85
  }
86
  label span { color: #64748b !important; font-weight: bold; }
87
 
88
- .output-text { font-family: monospace; background-color: #1e293b; padding: 15px; border-radius: 8px; }
89
  </style>
90
  """
91
 
@@ -117,7 +108,7 @@ with gr.Blocks() as app:
117
  btn = gr.Button("πŸ” Analyze Ecological Impact", variant="primary")
118
 
119
  gr.Markdown("### πŸ“‹ Scientific Report")
120
- output = gr.Textbox(label="Assessment Results", lines=12, interactive=False, elem_classes=["output-text"])
121
 
122
  gr.Examples(
123
  examples=[
 
1
  import gradio as gr
2
+ from huggingface_hub import InferenceClient
3
  import os
4
 
5
+ # --- 1. SETUP API CONNECTION (The Official Way) ---
6
+ API_KEY = os.getenv("HF_API_KEY")
7
+
8
+ # We use the official client. It handles the URLs automatically.
9
+ # We are using "Mistral-7B" because it is the most stable on the free tier.
10
+ client = InferenceClient("mistralai/Mistral-7B-Instruct-v0.2", token=API_KEY)
11
 
12
  # --- 2. DEFINE THE LOGIC ---
13
  def analyze_biodiversity(species, habitat, region, activity, noise, flow, pollutants, breeding, disturbance):
14
+
15
  if not API_KEY:
16
  return "⚠️ Error: API Key not found. Please add HF_API_KEY in Settings > Secrets."
17
 
18
+ # Prompt Engineering
19
+ prompt = f"""[INST] You are BioVigilus, an expert AI Ecologist.
20
+
 
 
 
21
  SCENARIO:
22
  - Species: {species}
23
  - Habitat: {habitat} ({region})
 
27
  - Breeding Season: {breeding}
28
 
29
  TASK:
30
+ Generate a structured Environmental Impact Assessment (EIA).
31
+ Use clear headings, bullet points, and emojis.
32
+
33
+ Sections required:
34
  1. πŸ›‘ **Risk Level** (Critical/High/Medium/Low)
35
+ 2. 🌑️ **Ecological Sensitivity Score** (0-100)
36
  3. πŸ’€ **Predicted Consequences**
37
+ 4. πŸ›‘οΈ **Mitigation Measures** (List 3 specific actions)
38
  5. βš–οΈ **Final Verdict** (Proceed/Halt/Modify)
39
+ [/INST]
 
40
  """
41
 
42
  try:
43
+ # The stream=True makes it feel faster, but we will wait for full response
44
+ response = client.text_generation(
45
+ prompt,
46
+ max_new_tokens=600,
47
+ temperature=0.7,
48
+ details=False
49
+ )
50
+ return response
 
 
 
 
 
 
 
 
 
 
51
 
52
  except Exception as e:
53
+ # Detailed error message
54
+ return f"⚠️ Analysis Failed: {str(e)}"
55
 
56
  # --- 3. CUSTOM STYLE (Trojan Horse Method) ---
57
  custom_style = """
 
69
  }
70
  button.primary:hover { transform: scale(1.02); }
71
 
72
+ .gr-box, .gr-input, input, textarea {
73
  background-color: #1e293b !important;
74
  border: 1px solid #334155 !important;
75
+ color: white !important;
76
  }
77
  label span { color: #64748b !important; font-weight: bold; }
78
 
79
+ .output-text { font-family: monospace; background-color: #1e293b; padding: 15px; border-radius: 8px; border: 1px solid #475569; }
80
  </style>
81
  """
82
 
 
108
  btn = gr.Button("πŸ” Analyze Ecological Impact", variant="primary")
109
 
110
  gr.Markdown("### πŸ“‹ Scientific Report")
111
+ output = gr.Markdown("Results will appear here...", elem_classes=["output-text"])
112
 
113
  gr.Examples(
114
  examples=[