Spaces:
Sleeping
Sleeping
| import gradio as gr | |
| from transformers import pipeline | |
| import matplotlib.pyplot as plt | |
| import numpy as np | |
| import datetime | |
| import os | |
| # --- 1. SETUP LOCAL AI (CPU Optimized) --- | |
| print("β³ Initializing BioVigilus Core... please wait.") | |
| # Using LaMini for concise, professional summaries | |
| ai_pipe = pipeline("text2text-generation", model="MBZUAI/LaMini-Flan-T5-783M", device=-1) | |
| # --- 2. COMPLIANCE & LOGIC ENGINE --- | |
| def calculate_carbon_footprint(activity, disturbance): | |
| base_emission = 50 | |
| if "mining" in activity.lower() or "construction" in activity.lower(): | |
| base_emission = 500 | |
| loss_factor = disturbance * 2.5 | |
| return int(base_emission + loss_factor) | |
| def calculate_economic_loss(habitat, region, disturbance): | |
| habitat_value = 1500 | |
| if "forest" in habitat.lower() or "cliffs" in habitat.lower(): | |
| habitat_value = 5000 | |
| loss = habitat_value * disturbance * 10 | |
| return f"${loss:,.2f}" | |
| def check_compliance(noise, flow, disturbance): | |
| violations = [] | |
| if noise > 85: violations.append("β **Noise Violation:** Exceeds 85dB limit.") | |
| if flow > 50: violations.append("β **Aquatic Violation:** Flow diversion > 50%.") | |
| if disturbance > 70: violations.append("β **Land Violation:** Critical habitat loss > 70%.") | |
| if not violations: return "β **Compliant:** Within standards." | |
| return "<br>".join(violations) | |
| def get_mitigation_plan(noise, flow, disturbance, breeding): | |
| strategies = [] | |
| if noise > 60: | |
| strategies.append("π **Acoustic Buffering:** Install 4m noise barriers.") | |
| strategies.append("β° **Curfew:** No machinery 18:00-06:00.") | |
| if disturbance > 40: | |
| strategies.append("π± **Bio-Restoration:** 2:1 Replanting commitment.") | |
| strategies.append("π§ **Buffer Zones:** 500m exclusion zone.") | |
| if flow > 30: | |
| strategies.append("π§ **Aquatic Bypass:** Install culverts.") | |
| if breeding == "Yes": | |
| strategies.append("π **SEASONAL STOP-WORK:** Mandatory shutdown.") | |
| if not strategies: | |
| strategies.append("β Standard Monitoring.") | |
| return strategies | |
| # --- 3. VISUALIZATION ENGINE --- | |
| def create_dashboard_plots(noise, flow, disturbance, breeding): | |
| fig = plt.figure(figsize=(12, 5)) | |
| fig.patch.set_facecolor('#0f172a') | |
| # Radar Chart | |
| ax1 = fig.add_subplot(131, polar=True) | |
| labels = ['Noise', 'Water', 'Land'] | |
| stats = [noise, flow, disturbance] | |
| stats_loop = np.concatenate((stats, [stats[0]])) | |
| angles = np.linspace(0, 2 * np.pi, len(labels), endpoint=False).tolist() | |
| angles += angles[:1] | |
| ax1.fill(angles, stats_loop, color='#10b981', alpha=0.4) | |
| ax1.plot(angles, stats_loop, color='#34d399', linewidth=2) | |
| ax1.set_facecolor('#0f172a') | |
| ax1.set_xticks(angles[:-1]) | |
| ax1.set_xticklabels(labels, color='white', size=9, weight='bold') | |
| ax1.tick_params(axis='y', colors='#94a3b8') | |
| ax1.set_title("Threat Profile", color='white', pad=15) | |
| # Seasonal Chart | |
| ax2 = fig.add_subplot(132) | |
| ax2.set_facecolor('#0f172a') | |
| months = ['J', 'F', 'M', 'A', 'M', 'J', 'J', 'A', 'S', 'O', 'N', 'D'] | |
| base_risk = [noise/2 + disturbance/3] * 12 | |
| if breeding == "Yes": | |
| for i in range(3, 8): base_risk[i] += 30 | |
| ax2.plot(months, base_risk, color='#facc15', marker='o') | |
| ax2.set_ylim(0, 100) | |
| ax2.tick_params(colors='white') | |
| ax2.set_title("Seasonal Risk", color='white', pad=15) | |
| # Compliance Chart | |
| ax3 = fig.add_subplot(133) | |
| ax3.set_facecolor('#0f172a') | |
| metrics = ['Comp.', 'Risk'] | |
| scores = [100 - (len(check_compliance(noise, flow, disturbance))/5 * 20), (noise+flow+disturbance)/3] | |
| ax3.bar(metrics, scores, color=['#3b82f6', '#ef4444'], alpha=0.7) | |
| ax3.set_ylim(0, 100) | |
| ax3.tick_params(colors='white') | |
| ax3.set_title("Scorecard", color='white', pad=15) | |
| plt.tight_layout() | |
| return fig | |
| # --- 4. MAIN REPORT GENERATOR --- | |
| def generate_full_report(species, habitat, region, activity, noise, flow, pollutants, breeding, disturbance): | |
| risk_score = int((noise + flow + disturbance) / 3) | |
| if breeding == "Yes": risk_score += 15 | |
| risk_score = min(risk_score, 100) | |
| risk_level = "LOW" | |
| if risk_score > 75: risk_level = "CRITICAL" | |
| elif risk_score > 50: risk_level = "HIGH" | |
| elif risk_score > 25: risk_level = "MODERATE" | |
| carbon = calculate_carbon_footprint(activity, disturbance) | |
| money_loss = calculate_economic_loss(habitat, region, disturbance) | |
| compliance = check_compliance(noise, flow, disturbance) | |
| mitigation = get_mitigation_plan(noise, flow, disturbance, breeding) | |
| prompt = f""" | |
| Write an executive summary for an EIA. | |
| Project: {activity} on {species} in {region}. | |
| Threats: Noise {noise}%, Habitat Loss {disturbance}%. | |
| """ | |
| try: | |
| ai_sum = ai_pipe(prompt, max_length=200, do_sample=True, temperature=0.6)[0]['generated_text'] | |
| except: | |
| ai_sum = "Executive summary generation unavailable." | |
| timestamp = datetime.datetime.now().strftime("%Y-%m-%d") | |
| mitigation_html = "".join([f"<li>{m}</li>" for m in mitigation]) | |
| html_report = f""" | |
| <div style="font-family: sans-serif; color: #333;"> | |
| <h1 style="color: #2c3e50;">πΏ BioVigilus Impact Report</h1> | |
| <p><strong>Date:</strong> {timestamp} | <strong>Analyst:</strong> Abdullah</p> | |
| <div style="background-color: #f8f9fa; padding: 15px; border-left: 5px solid #10b981;"> | |
| <h3>1. Executive Summary</h3> | |
| <p>{ai_sum}</p> | |
| </div> | |
| <h3>2. Economic & Carbon Data</h3> | |
| <p><strong>Carbon Footprint:</strong> {carbon} tons/yr <br> <strong>Ecosystem Loss:</strong> {money_loss}/yr</p> | |
| <h3>3. Mitigation Plan</h3> | |
| <ul>{mitigation_html}</ul> | |
| </div> | |
| """ | |
| filename = "BioVigilus_Official_Report.html" | |
| with open(filename, "w") as f: | |
| f.write(html_report) | |
| display_text = f""" | |
| ### π Executive Summary | |
| {ai_sum} | |
| --- | |
| ### π Carbon & Economic Impact | |
| * **Est. Carbon Footprint:** {carbon} tons CO2e / year | |
| * **Ecosystem Value Loss:** {money_loss} / year | |
| ### βοΈ Regulatory Compliance | |
| {compliance} | |
| ### π‘οΈ Mitigation Strategy | |
| {chr(10).join(['- ' + m for m in mitigation])} | |
| **π¨ BioVigilus Risk Score:** {risk_score}/100 ({risk_level}) | |
| """ | |
| return display_text, create_dashboard_plots(noise, flow, disturbance, breeding), filename | |
| # --- 5. UI LAYOUT --- | |
| custom_css = """ | |
| <style> | |
| body, .gradio-container { background-color: #0f172a !important; color: #e2e8f0 !important; } | |
| .input-panel { background-color: #1e293b; padding: 20px; border-radius: 12px; border: 1px solid #334155; } | |
| button.primary { background: linear-gradient(135deg, #059669, #10b981) !important; color: white; font-weight: bold; } | |
| .output-text { font-family: sans-serif; background-color: #1e293b; padding: 20px; border-radius: 12px; border: 1px solid #334155; font-size: 15px; line-height: 1.6; } | |
| h1, h3 { text-align: center; color: #34d399; } | |
| </style> | |
| """ | |
| with gr.Blocks() as app: | |
| gr.HTML(custom_css) | |
| with gr.Row(): | |
| gr.Markdown("# πΏ BioVigilus Pro") | |
| gr.Markdown("### *Advanced Environmental Intelligence | Deployed by Abdullah*") | |
| with gr.Row(): | |
| with gr.Column(scale=1, elem_classes=["input-panel"]): | |
| gr.Markdown("### π Project Parameters") | |
| species = gr.Textbox(label="Species", value="Markhor") | |
| habitat = gr.Textbox(label="Habitat", value="Cliffs") | |
| region = gr.Textbox(label="Region", value="Chitral") | |
| activity = gr.Textbox(label="Activity", value="Mining") | |
| breeding = gr.Radio(["Yes", "No"], label="Breeding Season?", value="Yes") | |
| gr.Markdown("### π Environmental Metrics") | |
| noise = gr.Slider(0, 100, label="Noise Level", value=88) | |
| flow = gr.Slider(0, 100, label="Water Flow Impact", value=25) | |
| disturbance = gr.Slider(0, 100, label="Land Disturbance", value=75) | |
| pollutants = gr.Textbox(label="Pollutants", value="Heavy Metals") | |
| btn = gr.Button("π GENERATE COMPREHENSIVE REPORT", variant="primary") | |
| with gr.Column(scale=2): | |
| with gr.Tabs(): | |
| with gr.TabItem("π Analysis"): | |
| output_text = gr.Markdown("Ready for analysis...", elem_classes=["output-text"]) | |
| with gr.TabItem("π Multi-View Charts"): | |
| output_plot = gr.Plot(label="Impact Metrics") | |
| with gr.TabItem("π₯ Export"): | |
| gr.Markdown("### Download Official Report") | |
| download_btn = gr.File(label="Download HTML Report") | |
| btn.click( | |
| generate_full_report, | |
| inputs=[species, habitat, region, activity, noise, flow, pollutants, breeding, disturbance], | |
| outputs=[output_text, output_plot, download_btn] | |
| ) | |
| if __name__ == "__main__": | |
| app.launch(server_name="0.0.0.0", server_port=7860, share=False, ssr_mode=False) | |