Wall06 commited on
Commit
2a7686d
ยท
verified ยท
1 Parent(s): 9c498a0

Update app.py

Browse files
Files changed (1) hide show
  1. app.py +112 -64
app.py CHANGED
@@ -5,55 +5,53 @@ import plotly.express as px
5
  import os
6
 
7
  # ================================================================
8
- # Helper Function
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
- # 1. Fetch Wikipedia
16
  wiki_url = "https://en.wikipedia.org/w/api.php"
17
  params = {
18
- "action": "query",
19
- "format": "json",
20
- "prop": "extracts",
21
- "titles": species_name.replace(" ", "_"),
22
- "explaintext": True
23
  }
24
 
25
  try:
26
  response = requests.get(wiki_url, params=params).json()
27
  pages = response.get("query", {}).get("pages", {})
28
  if "-1" in pages:
29
- extract = "Species not found."
30
  else:
31
  page = next(iter(pages.values()))
32
  extract = page.get("extract", "No summary available.")
33
  except:
34
  extract = "Error fetching data."
35
 
36
- # Pad text if too short
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
- # Add Analysis
44
- analysis_text = f"""
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
- Higher disturbance values indicate increased pressure on this species' survival and reproduction.
52
- """
53
- summary += analysis_text
 
54
 
55
- # 2. Fetch GBIF Map
56
- gbif_url = f"https://api.gbif.org/v1/occurrence/search?scientificName={species_name}&limit=200"
57
  coords = []
58
  try:
59
  gbif_res = requests.get(gbif_url).json()
@@ -65,62 +63,112 @@ Higher disturbance values indicate increased pressure on this species' survival
65
 
66
  if coords:
67
  df = pd.DataFrame(coords)
68
- fig = px.scatter_mapbox(df, lat="lat", lon="lon", zoom=1, height=400)
69
- fig.update_layout(mapbox_style="open-street-map", margin={"r":0,"t":0,"l":0,"b":0})
 
 
 
 
 
70
  else:
71
- fig = px.scatter_mapbox(pd.DataFrame({"lat":[], "lon":[]}), lat="lat", lon="lon", zoom=1)
72
- fig.update_layout(mapbox_style="open-street-map")
73
 
74
- # 3. Create Downloadable Report File
75
  filename = "BioVigilus_Report.txt"
76
  with open(filename, "w", encoding="utf-8") as f:
77
- f.write(f"=== BioVigilus Biodiversity Report ===\n\n")
78
- f.write(f"Species: {species_name}\n")
79
- f.write(f"Source: Wikipedia & GBIF Data\n")
80
- f.write(f"--------------------------------------\n")
81
- f.write(summary)
82
 
83
- # Return path to the file for download
84
- return summary, fig, filename
85
 
86
  # ================================================================
87
- # CSS Styling (HTML Injection)
88
  # ================================================================
89
- css_code = """
90
- <style>
91
- body { background-color: #f2f7f4; }
92
- .gradio-container { font-family: 'Poppins', sans-serif; }
93
- h1 { color: #2e7d32; text-align: center; }
94
- .custom-box { border: 1px solid #ddd; padding: 20px; border-radius: 10px; background: white; }
95
- </style>
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
96
  """
97
 
98
  # ================================================================
99
- # UI Layout
100
  # ================================================================
101
 
102
- with gr.Blocks() as demo:
103
- gr.HTML(css_code)
104
 
105
- gr.Markdown("# ๐ŸŒฟ BioVigilus โ€” Biodiversity Impact Analyzer")
106
- gr.Markdown("Analyze species, habitats, and environmental stress factors.")
 
 
 
 
107
 
108
  with gr.Row():
109
- with gr.Column(elem_classes="custom-box"):
110
- species_name = gr.Textbox(label="Species Name", placeholder="e.g. Panthera tigris")
111
- habitat = gr.Textbox(label="Habitat Type", placeholder="Forest")
112
- water = gr.Slider(0, 100, label="Water Disturbance")
113
- land = gr.Slider(0, 100, label="Land Disturbance")
114
- noise = gr.Slider(0, 100, label="Noise Level")
115
- btn = gr.Button("Analyze", variant="primary")
116
-
117
- with gr.Column(elem_classes="custom-box"):
118
- out_summary = gr.Textbox(label="Summary", lines=10)
119
- out_map = gr.Plot(label="Map")
120
- # Changed from Image (QR) to File (Download)
121
- out_file = gr.File(label="Download Report")
122
-
123
- btn.click(process_species_data, [species_name, habitat, water, land, noise], [out_summary, out_map, out_file])
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
124
 
125
  if __name__ == "__main__":
126
  demo.launch()
 
5
  import os
6
 
7
  # ================================================================
8
+ # Core Logic
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
+ # 1. Fetch Wikipedia Data
16
  wiki_url = "https://en.wikipedia.org/w/api.php"
17
  params = {
18
+ "action": "query", "format": "json", "prop": "extracts",
19
+ "titles": species_name.replace(" ", "_"), "explaintext": True
 
 
 
20
  }
21
 
22
  try:
23
  response = requests.get(wiki_url, params=params).json()
24
  pages = response.get("query", {}).get("pages", {})
25
  if "-1" in pages:
26
+ extract = "Species not found in Wikipedia database."
27
  else:
28
  page = next(iter(pages.values()))
29
  extract = page.get("extract", "No summary available.")
30
  except:
31
  extract = "Error fetching data."
32
 
33
+ # Pad text if short to maintain UI balance
34
  words = extract.split()
35
  if len(words) < 200:
36
+ extract += "\n\n" + ("This species is vital for the local ecosystem balance. " * 5)
37
 
38
+ summary = " ".join(words[:300]) + "..."
39
 
40
+ # Add Analysis Section
41
+ analysis = f"""
42
+
43
+ ---
44
+ ### ๐Ÿ“Š Environmental Impact Report
45
+ * **Habitat:** {habitat}
46
+ * **Water Stress:** {water_disturbance}/100
47
+ * **Land Stress:** {land_disturbance}/100
48
+ * **Noise Pollution:** {noise_level}/100
49
+ """
50
+
51
+ full_text = summary + analysis
52
 
53
+ # 2. Fetch GBIF Map Data
54
+ gbif_url = f"https://api.gbif.org/v1/occurrence/search?scientificName={species_name}&limit=300"
55
  coords = []
56
  try:
57
  gbif_res = requests.get(gbif_url).json()
 
63
 
64
  if coords:
65
  df = pd.DataFrame(coords)
66
+ fig = px.scatter_mapbox(df, lat="lat", lon="lon", zoom=1, height=350)
67
+ # Beautiful Map Styling
68
+ fig.update_layout(
69
+ mapbox_style="open-street-map",
70
+ margin={"r":0,"t":0,"l":0,"b":0},
71
+ paper_bgcolor="rgba(0,0,0,0)"
72
+ )
73
  else:
74
+ fig = px.scatter_mapbox(pd.DataFrame({"lat":[], "lon":[]}), lat="lat", lon="lon", zoom=0)
75
+ fig.update_layout(mapbox_style="open-street-map", margin={"r":0,"t":0,"l":0,"b":0})
76
 
77
+ # 3. Create Download File
78
  filename = "BioVigilus_Report.txt"
79
  with open(filename, "w", encoding="utf-8") as f:
80
+ f.write(f"=== BioVigilus Biodiversity Report ===\n{full_text}")
 
 
 
 
81
 
82
+ return full_text, fig, filename
 
83
 
84
  # ================================================================
85
+ # Custom CSS for "Beautiful" Look
86
  # ================================================================
87
+
88
+ custom_css = """
89
+ /* Gradient Background */
90
+ body, .gradio-container {
91
+ background: linear-gradient(135deg, #e0f2f1 0%, #a5d6a7 100%) !important;
92
+ }
93
+
94
+ /* Card Styling (Glass effect) */
95
+ .group-box {
96
+ background: rgba(255, 255, 255, 0.9) !important;
97
+ border-radius: 15px !important;
98
+ border: 1px solid #c8e6c9 !important;
99
+ box-shadow: 0 8px 32px 0 rgba(31, 38, 135, 0.07) !important;
100
+ padding: 20px !important;
101
+ }
102
+
103
+ /* Headings */
104
+ h1 {
105
+ color: #1b5e20 !important;
106
+ font-family: 'Helvetica Neue', sans-serif;
107
+ text-shadow: 1px 1px 2px rgba(0,0,0,0.1);
108
+ }
109
+
110
+ /* Button Styling */
111
+ button.primary-btn {
112
+ background: linear-gradient(90deg, #2e7d32 0%, #43a047 100%) !important;
113
+ border: none !important;
114
+ box-shadow: 0 4px 15px rgba(46, 125, 50, 0.3) !important;
115
+ }
116
  """
117
 
118
  # ================================================================
119
+ # Modern UI Layout
120
  # ================================================================
121
 
122
+ # We use the Soft theme for a clean, professional look
123
+ with gr.Blocks(theme=gr.themes.Soft(primary_hue="green"), css=custom_css) as demo:
124
 
125
+ gr.Markdown(
126
+ """
127
+ # ๐ŸŒฟ BioVigilus
128
+ ### Biodiversity Impact & Distribution Analyzer
129
+ """
130
+ )
131
 
132
  with gr.Row():
133
+ # LEFT COLUMN: INPUTS
134
+ with gr.Column(elem_classes="group-box"):
135
+ gr.Markdown("### ๐Ÿ” Input Parameters")
136
+ species_name = gr.Textbox(label="Scientific Name", placeholder="e.g., Panthera tigris", show_label=False)
137
+
138
+ # Interactive Dropdown instead of Textbox
139
+ habitat = gr.Dropdown(
140
+ ["Tropical Rainforest", "Savanna", "Desert", "Wetlands", "Tundra", "Urban Area"],
141
+ label="Habitat Type", value="Tropical Rainforest"
142
+ )
143
+
144
+ gr.Markdown("### โš ๏ธ Environmental Stressors")
145
+ water = gr.Slider(0, 100, label="Water Disturbance", value=30, info="Pollution/Drought level")
146
+ land = gr.Slider(0, 100, label="Land Disturbance", value=40, info="Deforestation/Construction")
147
+ noise = gr.Slider(0, 100, label="Noise Level", value=20, info="Decibels/Traffic")
148
+
149
+ analyze_btn = gr.Button("๐Ÿš€ Analyze Impact", variant="primary", elem_classes="primary-btn")
150
+
151
+ # RIGHT COLUMN: OUTPUTS
152
+ with gr.Column(elem_classes="group-box"):
153
+ gr.Markdown("### ๐ŸŒ Analysis Results")
154
+
155
+ # Tabbed interface for cleaner look
156
+ with gr.Tabs():
157
+ with gr.TabItem("๐Ÿ“„ Summary"):
158
+ out_summary = gr.Textbox(label="AI Report", lines=10, interactive=False)
159
+
160
+ with gr.TabItem("๐Ÿ—บ๏ธ Distribution Map"):
161
+ out_map = gr.Plot(label="Global Occurrences")
162
+
163
+ # Download Button
164
+ out_file = gr.File(label="๐Ÿ“ฅ Download Full Report", file_count="single")
165
+
166
+ # Connect logic
167
+ analyze_btn.click(
168
+ process_species_data,
169
+ inputs=[species_name, habitat, water, land, noise],
170
+ outputs=[out_summary, out_map, out_file]
171
+ )
172
 
173
  if __name__ == "__main__":
174
  demo.launch()