File size: 7,510 Bytes
75ec19f b87b2ad 98c0a64 b87b2ad 75ec19f 98c0a64 b87b2ad 75ec19f 98c0a64 75ec19f 98c0a64 75ec19f a69b66d 98c0a64 a69b66d 96e2820 75ec19f b87b2ad dc97ca3 a69b66d dc97ca3 a69b66d dc97ca3 98c0a64 dc97ca3 fb5a224 a69b66d dc97ca3 98c0a64 75ec19f 98c0a64 a69b66d 98c0a64 a69b66d 98c0a64 a69b66d 96e2820 a69b66d 98c0a64 a69b66d fb5a224 96e2820 a69b66d 98c0a64 2a7686d a69b66d 98c0a64 a69b66d 98c0a64 a69b66d 98c0a64 2a7686d a69b66d 75ec19f 98c0a64 b87b2ad dc97ca3 a69b66d fb5a224 75ec19f b87b2ad 2a7686d 88da70d 75ec19f 2a7686d 75ec19f 98c0a64 c8f566e 98c0a64 b87b2ad a69b66d 75ec19f b87b2ad 98c0a64 b87b2ad 2a7686d a69b66d 88da70d a69b66d 88da70d a69b66d 96e2820 88da70d a69b66d 88da70d a69b66d 96e2820 88da70d a69b66d 98c0a64 96e2820 a69b66d 88da70d a69b66d 88da70d 75ec19f b87b2ad a69b66d b87b2ad 75ec19f 88da70d ba210e9 a69b66d 88da70d a69b66d 98c0a64 a69b66d 75ec19f b87b2ad a69b66d 98c0a64 a69b66d 2a7686d a69b66d 2a7686d a69b66d 98c0a64 a69b66d 96e2820 a69b66d 98c0a64 a69b66d 98c0a64 96e2820 a69b66d 88da70d 2a7686d 88da70d 98c0a64 2a7686d 75ec19f dc97ca3 |
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 |
import gradio as gr
import requests
import pandas as pd
import plotly.express as px
# ================================================================
# 1. Core Logic (Robust Data Fetching)
# ================================================================
def process_species_data(species_name, habitat, water_disturbance, land_disturbance, noise_level):
if not species_name:
return "Please enter a species name.", None, None
# --- A. Fetch Wikipedia Data (With User-Agent Fix) ---
wiki_url = "https://en.wikipedia.org/w/api.php"
headers = {
'User-Agent': 'BioVigilusApp/1.0 (educational-research-project)'
}
params = {
"action": "query",
"format": "json",
"prop": "extracts",
"titles": species_name.replace(" ", "_"),
"explaintext": True,
"exintro": False,
}
try:
response = requests.get(wiki_url, params=params, headers=headers).json()
pages = response.get("query", {}).get("pages", {})
if "-1" in pages:
extract = f"Species '{species_name}' not found. Please check spelling (e.g., use 'Panthera tigris' instead of 'Tiger')."
else:
page = next(iter(pages.values()))
extract = page.get("extract", "No summary available.")
except Exception as e:
extract = f"Connection Error: {str(e)}"
# --- B. Length Enforcement (150-250 words) ---
words = extract.split()
# If text is too short, append educational filler
if len(words) < 150:
educational_filler = (
"\n\n[Additional Ecological Context]\n"
f"The species {species_name} is an integral part of its local food web. "
"Biodiversity loss regarding this species could trigger a trophic cascade, affecting both prey and predator populations. "
"Conservationists monitor such species as bio-indicators of environmental health. "
"Preserving their natural habitat is essential not just for their survival, but for the stability of the entire ecosystem. "
"Effective conservation strategies include habitat restoration, anti-poaching laws, and community awareness programs."
)
extract += educational_filler
words = extract.split()
# Cap at ~250 words
summary_text = " ".join(words[:250]) + "..."
# --- C. Impact Analysis ---
analysis_section = f"""
------------------------------------------------
📊 ENVIRONMENTAL IMPACT ANALYSIS
------------------------------------------------
• Target Habitat: {habitat}
⚠️ STRESS INDICATORS:
• Water Stress: {water_disturbance}/100
(High levels indicate pollution or drought risk)
• Land Disturbance: {land_disturbance}/100
(Reflects habitat fragmentation or loss)
• Noise Pollution: {noise_level}/100
(Impacts communication and breeding patterns)
"""
final_output = summary_text + analysis_section
# --- D. Fetch GBIF Map Data ---
gbif_url = f"https://api.gbif.org/v1/occurrence/search?scientificName={species_name}&limit=300"
coords = []
try:
gbif_res = requests.get(gbif_url).json()
results = gbif_res.get("results", [])
for r in results:
if r.get("decimalLatitude") and r.get("decimalLongitude"):
coords.append({"lat": r.get("decimalLatitude"), "lon": r.get("decimalLongitude")})
except:
pass
if coords:
df = pd.DataFrame(coords)
fig = px.scatter_mapbox(df, lat="lat", lon="lon", zoom=1, height=350)
fig.update_layout(mapbox_style="open-street-map", margin={"r":0,"t":0,"l":0,"b":0})
else:
fig = px.scatter_mapbox(pd.DataFrame({"lat":[], "lon":[]}), lat="lat", lon="lon", zoom=0)
fig.update_layout(mapbox_style="open-street-map", margin={"r":0,"t":0,"l":0,"b":0})
# --- E. Create Download File ---
filename = "BioVigilus_Report.txt"
with open(filename, "w", encoding="utf-8") as f:
f.write(f"=== BioVigilus Project Report ===\n{final_output}")
return final_output, fig, filename
# ================================================================
# 2. VIBRANT CSS (Safe Mode)
# ================================================================
vibrant_css = """
<style>
.gradio-container {
background: linear-gradient(135deg, #004d40 0%, #2e7d32 100%) !important;
}
#main-title {
color: #ffffff !important;
font-family: sans-serif;
font-weight: 800;
font-size: 2.5rem;
text-shadow: 2px 2px 4px rgba(0,0,0,0.3);
text-align: center;
margin-bottom: 5px;
}
#sub-title {
color: #a5d6a7 !important;
font-size: 1.2rem;
text-align: center;
margin-bottom: 25px;
font-family: sans-serif;
}
.custom-card {
background: #ffffff !important;
padding: 25px !important;
border-radius: 12px !important;
box-shadow: 0 10px 30px rgba(0,0,0,0.2) !important;
border: none !important;
}
/* Button - Gradient Green */
button.primary {
background: linear-gradient(90deg, #1b5e20 0%, #2e7d32 100%) !important;
color: white !important;
font-size: 1.1rem !important;
border-radius: 8px !important;
}
</style>
"""
# ================================================================
# 3. UI Layout
# ================================================================
with gr.Blocks() as demo:
gr.HTML(vibrant_css)
gr.HTML("""
<div id="main-title">🌿 BioVigilus</div>
<div id="sub-title">Advanced Biodiversity & Environmental Stress Analyzer</div>
""")
with gr.Row():
# --- LEFT: INPUTS ---
with gr.Column(elem_classes="custom-card"):
gr.Markdown("### 🔍 Species Configuration")
species_name = gr.Textbox(
label="Scientific Name",
placeholder="e.g. Panthera tigris",
value="Panthera tigris"
)
habitat = gr.Dropdown(
["Tropical Rainforest", "Savanna", "Desert", "Wetlands", "Urban", "Marine"],
label="Habitat Environment",
value="Tropical Rainforest"
)
gr.Markdown("---")
gr.Markdown("### ⚠️ Environmental Stressors")
water = gr.Slider(0, 100, value=25, label="Water Pollution Level")
land = gr.Slider(0, 100, value=65, label="Land Degradation")
noise = gr.Slider(0, 100, value=30, label="Noise Pollution (dB)")
analyze_btn = gr.Button("🚀 Run Analysis", variant="primary")
# --- RIGHT: OUTPUTS ---
with gr.Column(elem_classes="custom-card"):
gr.Markdown("### 📊 Analysis Results")
# REMOVED 'show_copy_button' to fix crash
out_summary = gr.Textbox(
label="Ecological Summary & Impact Report",
lines=12,
interactive=False
)
out_map = gr.Plot(label="Global Occurrence Map")
out_file = gr.File(label="📥 Download Full Report")
analyze_btn.click(
process_species_data,
inputs=[species_name, habitat, water, land, noise],
outputs=[out_summary, out_map, out_file]
)
if __name__ == "__main__":
demo.launch() |