Wall06 commited on
Commit
dc97ca3
·
verified ·
1 Parent(s): b87b2ad

Update app.py

Browse files
Files changed (1) hide show
  1. app.py +54 -47
app.py CHANGED
@@ -3,7 +3,6 @@ import requests
3
  import pandas as pd
4
  import plotly.express as px
5
  import qrcode
6
- from io import BytesIO
7
 
8
  # ================================================================
9
  # Helper Function: Species Summary + Map + QR Code
@@ -14,7 +13,7 @@ def process_species_data(species_name, habitat, water_disturbance, land_disturba
14
  return "Please enter a species name.", None, None
15
 
16
  # ======================
17
- # 1. Fetch Wikipedia Summary (Full Extract)
18
  # ======================
19
  wiki_url = "https://en.wikipedia.org/w/api.php"
20
  params = {
@@ -25,24 +24,28 @@ def process_species_data(species_name, habitat, water_disturbance, land_disturba
25
  "explaintext": True
26
  }
27
 
28
- response = requests.get(wiki_url, params=params).json()
29
- pages = response.get("query", {}).get("pages", {})
30
- page = next(iter(pages.values()))
31
-
32
- extract = page.get("extract", "No summary available for this species.")
33
-
34
- # Ensure at least 200 words
 
 
 
 
 
 
35
  words = extract.split()
36
  if len(words) < 200:
37
- extract += "\n\n" + (
38
- "This species plays a crucial ecological role, influencing biodiversity, habitat structure, "
39
- "and environmental balance. Its presence often reflects the health of local ecosystems, and "
40
- "changes in population trends can indicate environmental stress. Conservation efforts are "
41
- "frequently focused on such species due to their importance in maintaining natural stability. "
42
- * 3
43
- )
44
 
45
- summary = " ".join(words[:350]) # around 300–350 words
46
 
47
  # Add environmental interpretation
48
  summary += f"""
@@ -60,38 +63,40 @@ Higher disturbance values indicate increased pressure on this species' survival
60
  # 2. Fetch GBIF Occurrence Data (Map API)
61
  # ======================
62
  gbif_url = f"https://api.gbif.org/v1/occurrence/search?scientificName={species_name}&limit=200"
63
- gbif_res = requests.get(gbif_url).json()
64
-
65
- results = gbif_res.get("results", [])
66
  coords = []
67
-
68
- for r in results:
69
- lat = r.get("decimalLatitude")
70
- lon = r.get("decimalLongitude")
71
- if lat and lon:
72
- coords.append({"lat": lat, "lon": lon})
 
 
 
 
73
 
74
  if coords:
75
  df = pd.DataFrame(coords)
76
  fig = px.scatter_mapbox(df, lat="lat", lon="lon", zoom=1, height=400)
77
- fig.update_layout(mapbox_style="open-street-map")
78
  else:
79
- fig = None
 
 
80
 
81
  # ======================
82
  # 3. QR Code Generator
83
  # ======================
84
- qr_data = f"BioVigilus Report\nSpecies: {species_name}\nHabitat: {habitat}\nSummary: {summary[:150]}..."
 
 
 
85
 
86
- qr_img = BytesIO()
87
- qr = qrcode.make(qr_data)
88
- qr.save(qr_img)
89
- qr_img.seek(0)
90
-
91
  return summary, fig, qr_img
92
 
93
  # ================================================================
94
- # Custom CSS for Beautiful UI
95
  # ================================================================
96
 
97
  css = """
@@ -108,34 +113,35 @@ h1 {
108
  padding: 20px;
109
  border-radius: 15px;
110
  box-shadow: 0 4px 15px rgba(0,0,0,0.1);
 
111
  }
112
  """
113
 
114
  # ================================================================
115
- # Gradio UI (Corrected for v4)
116
  # ================================================================
117
 
118
- with gr.Blocks() as demo:
119
- demo.load_css(css)
120
 
121
  gr.Markdown("<h1 style='text-align:center;'>🌿 BioVigilus — Biodiversity Impact Analyzer</h1>")
122
- gr.Markdown("<p style='text-align:center; font-size:18px;'>Analyze species, habitats, and environmental stress factors with real-time data.</p>")
123
 
124
  with gr.Row():
125
  with gr.Column(elem_classes="custom-box"):
126
  species_name = gr.Textbox(label="Species Name", placeholder="e.g., Panthera tigris")
127
  habitat = gr.Textbox(label="Habitat Type", placeholder="Forest / Grassland / Wetland")
128
 
129
- water = gr.Slider(0, 100, label="Water Disturbance Level")
130
- land = gr.Slider(0, 100, label="Land Disturbance Level")
131
- noise = gr.Slider(0, 100, label="Noise Level")
132
 
133
- analyze_btn = gr.Button("Analyze", variant="primary")
134
 
135
  with gr.Column(elem_classes="custom-box"):
136
- summary_output = gr.Textbox(label="Species Summary", lines=15)
137
- map_output = gr.Plot(label="Distribution Map")
138
- qr_output = gr.Image(label="QR Code")
139
 
140
  analyze_btn.click(
141
  process_species_data,
@@ -143,4 +149,5 @@ with gr.Blocks() as demo:
143
  outputs=[summary_output, map_output, qr_output]
144
  )
145
 
146
- demo.launch()
 
 
3
  import pandas as pd
4
  import plotly.express as px
5
  import qrcode
 
6
 
7
  # ================================================================
8
  # Helper Function: Species Summary + Map + QR Code
 
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 = {
 
24
  "explaintext": True
25
  }
26
 
27
+ try:
28
+ response = requests.get(wiki_url, params=params).json()
29
+ pages = response.get("query", {}).get("pages", {})
30
+ # Handle cases where page is not found
31
+ if "-1" in pages:
32
+ extract = "Species not found in Wikipedia database."
33
+ else:
34
+ page = next(iter(pages.values()))
35
+ extract = page.get("extract", "No summary available for this species.")
36
+ except Exception as e:
37
+ extract = "Error fetching data from Wikipedia."
38
+
39
+ # Word count check
40
  words = extract.split()
41
  if len(words) < 200:
42
+ filler = (
43
+ " This species plays a crucial ecological role, influencing biodiversity, habitat structure, "
44
+ "and environmental balance. Its presence often reflects the health of local ecosystems. "
45
+ ) * 3
46
+ extract += "\n\n" + filler
 
 
47
 
48
+ summary = " ".join(words[:350]) # Cap around 350 words
49
 
50
  # Add environmental interpretation
51
  summary += f"""
 
63
  # 2. Fetch GBIF Occurrence Data (Map API)
64
  # ======================
65
  gbif_url = f"https://api.gbif.org/v1/occurrence/search?scientificName={species_name}&limit=200"
66
+
 
 
67
  coords = []
68
+ try:
69
+ gbif_res = requests.get(gbif_url).json()
70
+ results = gbif_res.get("results", [])
71
+ for r in results:
72
+ lat = r.get("decimalLatitude")
73
+ lon = r.get("decimalLongitude")
74
+ if lat and lon:
75
+ coords.append({"lat": lat, "lon": lon})
76
+ except Exception:
77
+ pass # Fail silently for map if API errors
78
 
79
  if coords:
80
  df = pd.DataFrame(coords)
81
  fig = px.scatter_mapbox(df, lat="lat", lon="lon", zoom=1, height=400)
82
+ fig.update_layout(mapbox_style="open-street-map", margin={"r":0,"t":0,"l":0,"b":0})
83
  else:
84
+ # Return an empty map figure if no coordinates found
85
+ fig = px.scatter_mapbox(pd.DataFrame({"lat":[], "lon":[]}), lat="lat", lon="lon", zoom=1)
86
+ fig.update_layout(mapbox_style="open-street-map")
87
 
88
  # ======================
89
  # 3. QR Code Generator
90
  # ======================
91
+ qr_data = f"BioVigilus Report\nSpecies: {species_name}\nHabitat: {habitat}\nSummary: {summary[:100]}..."
92
+
93
+ # Generate QR and return PIL Image directly (Best for Gradio)
94
+ qr_img = qrcode.make(qr_data)
95
 
 
 
 
 
 
96
  return summary, fig, qr_img
97
 
98
  # ================================================================
99
+ # Custom CSS
100
  # ================================================================
101
 
102
  css = """
 
113
  padding: 20px;
114
  border-radius: 15px;
115
  box-shadow: 0 4px 15px rgba(0,0,0,0.1);
116
+ border: 1px solid #e0e0e0;
117
  }
118
  """
119
 
120
  # ================================================================
121
+ # Gradio UI (Fixed)
122
  # ================================================================
123
 
124
+ # FIX: Pass 'css' directly to the Blocks constructor
125
+ with gr.Blocks(css=css, theme=gr.themes.Soft()) as demo:
126
 
127
  gr.Markdown("<h1 style='text-align:center;'>🌿 BioVigilus — Biodiversity Impact Analyzer</h1>")
128
+ gr.Markdown("<p style='text-align:center; font-size:18px; color:#555;'>Analyze species, habitats, and environmental stress factors with real-time data.</p>")
129
 
130
  with gr.Row():
131
  with gr.Column(elem_classes="custom-box"):
132
  species_name = gr.Textbox(label="Species Name", placeholder="e.g., Panthera tigris")
133
  habitat = gr.Textbox(label="Habitat Type", placeholder="Forest / Grassland / Wetland")
134
 
135
+ water = gr.Slider(0, 100, label="Water Disturbance Level", value=20)
136
+ land = gr.Slider(0, 100, label="Land Disturbance Level", value=20)
137
+ noise = gr.Slider(0, 100, label="Noise Level", value=20)
138
 
139
+ analyze_btn = gr.Button("Analyze Impact", variant="primary")
140
 
141
  with gr.Column(elem_classes="custom-box"):
142
+ summary_output = gr.Textbox(label="Species Summary", lines=12, interactive=False)
143
+ map_output = gr.Plot(label="Global Distribution Map")
144
+ qr_output = gr.Image(label="Download Report QR", type="pil")
145
 
146
  analyze_btn.click(
147
  process_species_data,
 
149
  outputs=[summary_output, map_output, qr_output]
150
  )
151
 
152
+ if __name__ == "__main__":
153
+ demo.launch()