Wall06 commited on
Commit
fb5a224
·
verified ·
1 Parent(s): ba210e9

Update app.py

Browse files
Files changed (1) hide show
  1. app.py +45 -84
app.py CHANGED
@@ -3,18 +3,17 @@ import requests
3
  import pandas as pd
4
  import plotly.express as px
5
  import qrcode
 
6
 
7
  # ================================================================
8
- # Helper Function: Species Summary + Map + QR Code
9
  # ================================================================
10
 
11
  def process_species_data(species_name, habitat, water_disturbance, land_disturbance, noise_level):
12
  if not species_name:
13
  return "Please enter a species name.", None, None
14
 
15
- # ======================
16
- # 1. Fetch Wikipedia Summary
17
- # ======================
18
  wiki_url = "https://en.wikipedia.org/w/api.php"
19
  params = {
20
  "action": "query",
@@ -28,128 +27,90 @@ def process_species_data(species_name, habitat, water_disturbance, land_disturba
28
  response = requests.get(wiki_url, params=params).json()
29
  pages = response.get("query", {}).get("pages", {})
30
  if "-1" in pages:
31
- extract = "Species not found in Wikipedia database."
32
  else:
33
  page = next(iter(pages.values()))
34
- extract = page.get("extract", "No summary available for this species.")
35
- except Exception:
36
- extract = "Error fetching data from Wikipedia."
37
 
38
- # Word count check and padding
39
  words = extract.split()
40
  if len(words) < 200:
41
- filler = (
42
- " This species plays a crucial ecological role, influencing biodiversity, habitat structure, "
43
- "and environmental balance. Its presence often reflects the health of local ecosystems. "
44
- ) * 3
45
- extract += "\n\n" + filler
46
-
47
  summary = " ".join(words[:350])
48
-
49
- # Add environmental interpretation
50
  summary += f"""
51
 
52
- Environmental Impact Assessment (Based on User Inputs):
53
- - Water Disturbance Level: {water_disturbance}/100
54
- - Land Disturbance Level: {land_disturbance}/100
55
  - Noise Level: {noise_level}/100
56
- - Habitat Type: {habitat}
57
-
58
- Higher disturbance values indicate increased pressure on this species' survival and reproduction.
59
  """
60
 
61
- # ======================
62
- # 2. Fetch GBIF Occurrence Data (Map API)
63
- # ======================
64
  gbif_url = f"https://api.gbif.org/v1/occurrence/search?scientificName={species_name}&limit=200"
65
-
66
  coords = []
67
  try:
68
  gbif_res = requests.get(gbif_url).json()
69
- results = gbif_res.get("results", [])
70
- for r in results:
71
- lat = r.get("decimalLatitude")
72
- lon = r.get("decimalLongitude")
73
- if lat and lon:
74
- coords.append({"lat": lat, "lon": lon})
75
- except Exception:
76
- pass
77
 
78
  if coords:
79
  df = pd.DataFrame(coords)
80
  fig = px.scatter_mapbox(df, lat="lat", lon="lon", zoom=1, height=400)
81
  fig.update_layout(mapbox_style="open-street-map", margin={"r":0,"t":0,"l":0,"b":0})
82
  else:
83
- # Empty map fallback
84
  fig = px.scatter_mapbox(pd.DataFrame({"lat":[], "lon":[]}), lat="lat", lon="lon", zoom=1)
85
  fig.update_layout(mapbox_style="open-street-map")
86
 
87
- # ======================
88
- # 3. QR Code Generator
89
- # ======================
90
- qr_data = f"BioVigilus Report\nSpecies: {species_name}\nHabitat: {habitat}\nSummary: {summary[:100]}..."
91
- qr_img = qrcode.make(qr_data)
92
 
93
- return summary, fig, qr_img
94
 
95
  # ================================================================
96
- # Custom CSS
97
  # ================================================================
98
-
99
- css_style = """
100
  <style>
101
- body { background-color: #f2f7f4 !important; }
102
  .gradio-container { font-family: 'Poppins', sans-serif; }
103
-
104
- h1 {
105
- color: #2e7d32 !important;
106
- font-weight: 700;
107
- }
108
-
109
- .custom-box {
110
- background: white;
111
- padding: 20px;
112
- border-radius: 15px;
113
- box-shadow: 0 4px 15px rgba(0,0,0,0.1);
114
- border: 1px solid #e0e0e0;
115
- }
116
  </style>
117
  """
118
 
119
  # ================================================================
120
- # Gradio UI (Universal Fix)
121
  # ================================================================
122
 
123
- # We remove the 'css' argument here to avoid the TypeError
124
- with gr.Blocks(theme=gr.themes.Soft()) as demo:
 
125
 
126
- # INJECTION: We add the CSS here using HTML
127
- gr.HTML(css_style)
128
-
129
- gr.Markdown("<h1 style='text-align:center;'>🌿 BioVigilus — Biodiversity Impact Analyzer</h1>")
130
- gr.Markdown("<p style='text-align:center; font-size:18px; color:#555;'>Analyze species, habitats, and environmental stress factors with real-time data.</p>")
131
 
132
  with gr.Row():
133
  with gr.Column(elem_classes="custom-box"):
134
- species_name = gr.Textbox(label="Species Name", placeholder="e.g., Panthera tigris")
135
- habitat = gr.Textbox(label="Habitat Type", placeholder="Forest / Grassland / Wetland")
136
-
137
- water = gr.Slider(0, 100, label="Water Disturbance Level", value=20)
138
- land = gr.Slider(0, 100, label="Land Disturbance Level", value=20)
139
- noise = gr.Slider(0, 100, label="Noise Level", value=20)
140
-
141
- analyze_btn = gr.Button("Analyze Impact", variant="primary")
142
 
143
  with gr.Column(elem_classes="custom-box"):
144
- summary_output = gr.Textbox(label="Species Summary", lines=12, interactive=False)
145
- map_output = gr.Plot(label="Global Distribution Map")
146
- qr_output = gr.Image(label="Download Report QR", type="pil")
147
-
148
- analyze_btn.click(
149
- process_species_data,
150
- inputs=[species_name, habitat, water, land, noise],
151
- outputs=[summary_output, map_output, qr_output]
152
- )
153
 
154
  if __name__ == "__main__":
155
  demo.launch()
 
3
  import pandas as pd
4
  import plotly.express as px
5
  import qrcode
6
+ from io import BytesIO
7
 
8
  # ================================================================
9
+ # Helper Function
10
  # ================================================================
11
 
12
  def process_species_data(species_name, habitat, water_disturbance, land_disturbance, noise_level):
13
  if not species_name:
14
  return "Please enter a species name.", None, None
15
 
16
+ # 1. Fetch Wikipedia
 
 
17
  wiki_url = "https://en.wikipedia.org/w/api.php"
18
  params = {
19
  "action": "query",
 
27
  response = requests.get(wiki_url, params=params).json()
28
  pages = response.get("query", {}).get("pages", {})
29
  if "-1" in pages:
30
+ extract = "Species not found."
31
  else:
32
  page = next(iter(pages.values()))
33
+ extract = page.get("extract", "No summary available.")
34
+ except:
35
+ extract = "Error fetching data."
36
 
 
37
  words = extract.split()
38
  if len(words) < 200:
39
+ extract += "\n\n" + ("Conservation of this species is critical for biodiversity. " * 5)
40
+
 
 
 
 
41
  summary = " ".join(words[:350])
42
+
 
43
  summary += f"""
44
 
45
+ Environmental Impact Assessment:
46
+ - Water Disturbance: {water_disturbance}/100
47
+ - Land Disturbance: {land_disturbance}/100
48
  - Noise Level: {noise_level}/100
49
+ - Habitat: {habitat}
 
 
50
  """
51
 
52
+ # 2. Fetch GBIF Map
 
 
53
  gbif_url = f"https://api.gbif.org/v1/occurrence/search?scientificName={species_name}&limit=200"
 
54
  coords = []
55
  try:
56
  gbif_res = requests.get(gbif_url).json()
57
+ for r in gbif_res.get("results", []):
58
+ if r.get("decimalLatitude") and r.get("decimalLongitude"):
59
+ coords.append({"lat": r.get("decimalLatitude"), "lon": r.get("decimalLongitude")})
60
+ except:
61
+ pass
 
 
 
62
 
63
  if coords:
64
  df = pd.DataFrame(coords)
65
  fig = px.scatter_mapbox(df, lat="lat", lon="lon", zoom=1, height=400)
66
  fig.update_layout(mapbox_style="open-street-map", margin={"r":0,"t":0,"l":0,"b":0})
67
  else:
 
68
  fig = px.scatter_mapbox(pd.DataFrame({"lat":[], "lon":[]}), lat="lat", lon="lon", zoom=1)
69
  fig.update_layout(mapbox_style="open-street-map")
70
 
71
+ # 3. QR Code
72
+ qr = qrcode.make(f"BioVigilus: {species_name}")
 
 
 
73
 
74
+ return summary, fig, qr
75
 
76
  # ================================================================
77
+ # CSS Styling (HTML Injection)
78
  # ================================================================
79
+ css_code = """
 
80
  <style>
81
+ body { background-color: #f2f7f4; }
82
  .gradio-container { font-family: 'Poppins', sans-serif; }
83
+ h1 { color: #2e7d32; text-align: center; }
84
+ .custom-box { border: 1px solid #ddd; padding: 20px; border-radius: 10px; background: white; }
 
 
 
 
 
 
 
 
 
 
 
85
  </style>
86
  """
87
 
88
  # ================================================================
89
+ # UI Layout (Strict Compatibility Mode)
90
  # ================================================================
91
 
92
+ # NOTE: Removed 'theme' and 'css' arguments to prevent errors on old versions
93
+ with gr.Blocks() as demo:
94
+ gr.HTML(css_code) # Inject CSS here instead
95
 
96
+ gr.Markdown("# 🌿 BioVigilus Biodiversity Impact Analyzer")
97
+ gr.Markdown("Analyze species, habitats, and environmental stress factors.")
 
 
 
98
 
99
  with gr.Row():
100
  with gr.Column(elem_classes="custom-box"):
101
+ species_name = gr.Textbox(label="Species Name", placeholder="e.g. Panthera tigris")
102
+ habitat = gr.Textbox(label="Habitat Type", placeholder="Forest")
103
+ water = gr.Slider(0, 100, label="Water Disturbance")
104
+ land = gr.Slider(0, 100, label="Land Disturbance")
105
+ noise = gr.Slider(0, 100, label="Noise Level")
106
+ btn = gr.Button("Analyze", variant="primary")
 
 
107
 
108
  with gr.Column(elem_classes="custom-box"):
109
+ out_summary = gr.Textbox(label="Summary", lines=10)
110
+ out_map = gr.Plot(label="Map")
111
+ out_qr = gr.Image(label="QR Code", type="pil")
112
+
113
+ btn.click(process_species_data, [species_name, habitat, water, land, noise], [out_summary, out_map, out_qr])
 
 
 
 
114
 
115
  if __name__ == "__main__":
116
  demo.launch()