File size: 12,129 Bytes
c5db957
 
 
 
 
 
 
 
 
a842b9e
c5db957
ab35957
e6a4e89
45a8c99
c5db957
529e3cc
c5db957
34830a2
 
529e3cc
 
c5db957
529e3cc
 
 
 
 
 
 
ab35957
529e3cc
 
 
 
 
 
 
 
c5db957
 
529e3cc
 
 
 
 
 
 
 
 
 
c5db957
ab35957
529e3cc
 
 
 
 
 
 
 
 
 
 
 
 
 
c5db957
 
529e3cc
 
 
 
 
 
 
 
 
 
 
 
005abc8
45a8c99
529e3cc
 
34830a2
529e3cc
34830a2
005abc8
45a8c99
 
 
 
 
afb796a
529e3cc
45a8c99
 
 
 
 
 
 
 
 
 
 
 
529e3cc
34830a2
5d0d9f3
529e3cc
c5db957
529e3cc
 
 
c5db957
529e3cc
 
 
c5db957
 
529e3cc
 
 
 
 
 
 
 
 
 
c5db957
 
529e3cc
 
 
 
c5db957
529e3cc
 
c5db957
529e3cc
 
 
 
c5db957
 
529e3cc
 
 
 
 
 
 
 
 
 
 
 
c5db957
 
529e3cc
34830a2
529e3cc
 
34830a2
529e3cc
 
 
34830a2
529e3cc
 
 
 
 
 
 
34830a2
 
 
 
 
 
 
c5db957
529e3cc
 
 
 
 
 
 
 
 
 
34830a2
529e3cc
34830a2
529e3cc
 
 
34830a2
529e3cc
34830a2
529e3cc
6b4e3ea
529e3cc
 
509ffa7
529e3cc
 
c5db957
3c70ae8
529e3cc
 
 
 
34830a2
3c70ae8
45a8c99
3c70ae8
 
 
 
 
 
 
 
 
 
 
 
 
 
 
529e3cc
599bdb1
529e3cc
 
 
 
7353b8d
529e3cc
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
509ffa7
529e3cc
 
 
 
 
 
 
 
 
3c70ae8
 
 
 
45a8c99
3c70ae8
529e3cc
 
34830a2
529e3cc
 
 
 
 
 
 
a842b9e
529e3cc
34830a2
529e3cc
 
 
 
 
 
 
 
 
c5db957
599bdb1
6244153
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
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
import os
import gradio as gr
import numpy as np
import plotly.graph_objects as go
import requests
import cv2
from PIL import Image
import qrcode
from fpdf import FPDF
from sentinelhub import SHConfig
from groq import Groq
import google.generativeai as genai
import tempfile
import time  # For rate limit handling

# -------------------- ENVIRONMENT VARIABLES --------------------
HF_API_KEY = os.getenv("HF_API_KEY")
GROQ_API_KEY = "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"
GEMINI_API_KEY = "AIzaSyCqPnhDNwBP6Tsw1wkLGdXCIVDnNO44swY"
SENTINEL_CLIENT_ID = os.getenv("SENTINEL_CLIENT_ID")
SENTINEL_CLIENT_SECRET = os.getenv("SENTINEL_CLIENT_SECRET")

# -------------------- SENTINEL CONFIG --------------------
config = SHConfig()
if SENTINEL_CLIENT_ID and SENTINEL_CLIENT_SECRET:
    config.client_id = SENTINEL_CLIENT_ID
    config.client_secret = SENTINEL_CLIENT_SECRET

# -------------------- AI FUNCTIONS --------------------
def gemini_summary(text):
    try:
        if not GEMINI_API_KEY: return None, "Missing Key"
        genai.configure(api_key=GEMINI_API_KEY)
        model = genai.GenerativeModel('gemini-1.5-flash') 
        response = model.generate_content(text)
        return response.text, None
    except Exception as e:
        return None, str(e)

def groq_summary(text):
    try:
        if not GROQ_API_KEY: return None, "Missing Key"
        client = Groq(api_key=GROQ_API_KEY)
        completion = client.chat.completions.create(
            model="llama-3.3-70b-versatile",
            messages=[{"role": "user", "content": text}]
        )
        return completion.choices[0].message.content, None
    except Exception as e:
        return None, str(e)

def hf_summary(text):
    try:
        url = "https://api-inference.huggingface.co/models/HuggingFaceH4/zephyr-7b-beta"
        headers = {"Authorization": f"Bearer {HF_API_KEY}"}
        payload = {
            "inputs": f"<|system|>You are a scientist.</s><|user|>{text}</s><|assistant|>",
            "parameters": {"max_new_tokens": 800}
        }
        r = requests.post(url, headers=headers, json=payload, timeout=25)
        if r.status_code == 200:
            return r.json()[0]["generated_text"].split("<|assistant|>")[-1], None
        else:
            return None, f"Status {r.status_code}: {r.text}"
    except Exception as e:
        return None, str(e)

def smart_summary(text):
    errors = []
    out, err = groq_summary(text)
    if out: return out
    errors.append(f"Groq: {err}")
    out, err = gemini_summary(text)
    if out: return out
    errors.append(f"Gemini: {err}")
    if HF_API_KEY:
        out, err = hf_summary(text)
        if out: return out
        errors.append(f"HF: {err}")
    return "⚠ SYSTEM FAILURE. DEBUG LOG:\n" + "\n".join(errors)

# -------------------- AUDIO FUNCTION (IMPROVED) --------------------
def generate_audio_report(text):
    try:
        from gtts import gTTS
    except ImportError:
        raise gr.Error("❌ Library Missing! Add 'gTTS' to requirements.txt")

    if not text or len(text.strip()) < 5:
        raise gr.Error("❌ Report is too short or empty. Generate a report first!")

    # Clean text of Markdown symbols for better speech
    clean_text = text.replace("**", "").replace("#", "")

    try:
        # Retry logic for rate limits
        for i in range(3):
            try:
                tts = gTTS(text=clean_text[:1000], lang='en')
                with tempfile.NamedTemporaryFile(delete=False, suffix=".mp3") as f:
                    tts.save(f.name)
                    return f.name
            except Exception as e:
                if "429" in str(e) and i < 2:
                    time.sleep(2) # Wait 2 seconds and try again
                    continue
                raise e
    except Exception as e:
        raise gr.Error(f"Speech Generation Error: {str(e)}")

# -------------------- MATH & LOGIC --------------------
def calculate_wqi(pH, do, nutrients):
    wqi = (7 - abs(7 - pH)) * 0.2 + (do/14) * 0.5 + (10 - nutrients) * 0.3
    wqi_score = max(0, min(100, int(wqi*10)))
    return wqi_score

def calculate_hsi(flow_rate, temp, sediment):
    hsi = 100 - abs(flow_rate-50)*0.5 - abs(temp-20)*2 - sediment*1.5
    return max(0, min(100, int(hsi)))

def calculate_erosion(sediment, construction):
    score = sediment*1.5 + construction*2
    return max(0, min(100, int(score)))

def potability_status(wqi):
    if wqi > 80: return "Safe"
    elif wqi > 50: return "Boil Required"
    else: return "Toxic"

def river_stability(wqi, hsi, erosion):
    return int((wqi*0.4 + hsi*0.4 + (100-erosion)*0.2))

def analyze_satellite_image(img):
    if img is None: return 0
    img_array = np.array(img.convert("L"))
    turbidity_score = int(np.mean(img_array)/2.55)
    return turbidity_score

# -------------------- VISUALS & INSIGHTS --------------------
def create_plots(wqi, hsi, erosion, turbidity):
    fig = go.Figure()
    colors = ['#0061ff', '#60efff', '#ff4b4b', '#ffb347']
    fig.add_trace(go.Bar(name="Metrics", x=["WQI", "HSI", "Erosion", "Turbidity"],
                          y=[wqi, hsi, erosion, turbidity], marker_color=colors))
    fig.update_layout(title="River Health Metrics", yaxis=dict(range=[0,100]), template="plotly_white")
    return fig

def generate_graph_insights(wqi, hsi, erosion, turbidity):
    text = "### πŸ“‰ Graph Analysis\n\n"
    if wqi > 70: text += f"πŸ”΅ **Water Quality:** {wqi}/100. Excellent condition.\n\n"
    elif wqi > 40: text += f"πŸ”΅ **Water Quality:** {wqi}/100. Moderate pollution.\n\n"
    else: text += f"πŸ”΅ **Water Quality:** {wqi}/100. **CRITICAL**.\n\n"
    
    if hsi > 70: text += f"🟒 **Habitat:** {hsi}/100. Good biodiversity.\n\n"
    else: text += f"🟒 **Habitat:** {hsi}/100. Poor conditions.\n\n"
    return text

# -------------------- PDF ENGINE --------------------
def generate_pdf(wqi, hsi, erosion, turbidity, summary_text):
    pdf = FPDF()
    pdf.add_page()
    qr = qrcode.QRCode(box_size=3)
    qr.add_data(f"Verified FlumenIntel Report | WQI: {wqi}")
    qr.make(fit=True)
    img = qr.make_image(fill_color="black", back_color="white")
    
    with tempfile.NamedTemporaryFile(delete=False, suffix=".png") as tmp:
        img.save(tmp.name)
        pdf.image(tmp.name, x=165, y=10, w=30)
    
    pdf.set_y(15)
    pdf.set_font("Arial", "B", 24)
    pdf.set_text_color(0, 97, 255)
    pdf.cell(0, 10, "FlumenIntel", ln=True, align='L')
    pdf.ln(10)
    pdf.set_font("Arial", "", 12)
    pdf.set_text_color(0, 0, 0)
    
    clean_text = summary_text.encode('latin-1', 'replace').decode('latin-1')
    pdf.multi_cell(0, 6, clean_text)
    
    report_path = os.path.join(tempfile.gettempdir(), "FlumenIntel_Report.pdf")
    pdf.output(report_path)
    return report_path

# -------------------- MAIN PROCESSOR --------------------
def process_data(flow_rate, water_temp, sediment, construction, pH, do, nutrients, sat_img):
    try:
        wqi = calculate_wqi(pH, do, nutrients)
        hsi = calculate_hsi(flow_rate, water_temp, sediment)
        erosion = calculate_erosion(sediment, construction)
        turbidity = analyze_satellite_image(sat_img)
        stability = river_stability(wqi, hsi, erosion)
        potability = potability_status(wqi)
        
        prompt = f"Write a professional health report for a river. WQI: {wqi}, HSI: {hsi}, Erosion: {erosion}, Turbidity: {turbidity}. Potability: {potability}."
        summary = smart_summary(prompt)
        
        fig = create_plots(wqi, hsi, erosion, turbidity)
        graph_text = generate_graph_insights(wqi, hsi, erosion, turbidity)
        
        pdf_path = generate_pdf(wqi, hsi, erosion, turbidity, summary)
        
        status_text = f"Stability Index: {stability}/100\nStatus: {potability}"
        return status_text, fig, graph_text, summary, pdf_path

    except Exception as e:
        return str(e), None, "", "", None

def run_app(flow, temp, sediment, construction, ph, do, nutrients, sat_img):
    return process_data(flow, temp, sediment, construction, ph, do, nutrients, sat_img)

# -------------------- UI DESIGN (WITH SCROLLBAR) --------------------
custom_css = """
@import url('https://fonts.googleapis.com/css2?family=Poppins:wght@300;400;600&display=swap');
* { font-family: 'Poppins', sans-serif !important; }
#title-box { background: linear-gradient(135deg, #0061ff 0%, #60efff 100%); color: white; padding: 20px; border-radius: 12px; text-align: center;}
#analyze-btn { background: #0061ff; color: white; border: none; font-weight: bold; cursor: pointer; border-radius: 8px;}

/* Custom Scroll Wheel Styling */
#scroll-area textarea {
    overflow-y: scroll !important;
    scrollbar-width: thin;
    scrollbar-color: #0061ff #2d2d2d;
}
#scroll-area textarea::-webkit-scrollbar {
    width: 8px;
}
#scroll-area textarea::-webkit-scrollbar-track {
    background: #1a1a1a;
}
#scroll-area textarea::-webkit-scrollbar-thumb {
    background-color: #0061ff;
    border-radius: 10px;
}
"""

with gr.Blocks(title="FlumenIntel") as demo:
    gr.HTML(f"<style>{custom_css}</style>")
    with gr.Column(elem_id="title-box"):
        gr.Markdown("# FlumenIntel 🌊\n### Advanced River Health Analytics")

    with gr.Tabs():
        with gr.TabItem("πŸš€ Dashboard"):
            with gr.Row():
                with gr.Column(scale=1):
                    gr.Markdown("### 1. Hydrological Data")
                    flow = gr.Number(label="Flow Rate", value=45)
                    temp = gr.Number(label="Temperature", value=18)
                    sediment = gr.Slider(0, 10, label="Sediment", value=2)
                    construction = gr.Slider(0, 10, label="Construction", value=0)
                    
                    gr.Markdown("### 2. Chemical Data")
                    ph = gr.Number(label="pH Level", value=7.2)
                    do = gr.Number(label="Dissolved Oxygen", value=9.5)
                    nutrients = gr.Slider(0, 10, label="Nutrient Load", value=1)
                    
                    gr.Markdown("### 3. Visual Analysis")
                    sat_img = gr.Image(label="Satellite Image", type="pil")
                    
                    analyze_btn = gr.Button("GENERATE REPORT", elem_id="analyze-btn")

                with gr.Column(scale=2):
                    status_box = gr.Textbox(label="System Status", interactive=False)
                    
                    with gr.Tabs():
                        with gr.TabItem("πŸ“Š Visual Analytics"):
                            plot_output = gr.Plot(label="Metric Visualization")
                            graph_summary_box = gr.Markdown("### Insights...")
                        
                        with gr.TabItem("πŸ“„ Official Report"):
                            ai_summary = gr.Textbox(
                                label="Scientist's Assessment", 
                                lines=15, 
                                interactive=False, 
                                elem_id="scroll-area" # Added specifically for the CSS
                            )
                            
                            with gr.Row():
                                audio_btn = gr.Button("πŸ”Š Listen to Report (gTTS)")
                                audio_out = gr.Audio(label="Player", type="filepath")
                            
                            audio_btn.click(
                                fn=generate_audio_report, 
                                inputs=ai_summary, 
                                outputs=audio_out
                            )

                        with gr.TabItem("πŸ“₯ Export"):
                            pdf_output = gr.File(label="Download Official FlumenIntel Report")

        with gr.TabItem("πŸ‘€ About Me"):
             gr.Markdown("## Abdullah\nComputer Engineering Undergraduate | AI & Hardware Enthusiast")

    analyze_btn.click(
        run_app,
        inputs=[flow, temp, sediment, construction, ph, do, nutrients, sat_img],
        outputs=[status_box, plot_output, graph_summary_box, ai_summary, pdf_output]
    )

if __name__ == "__main__":
    demo.launch()