FajarHidaa commited on
Commit
9a0bee7
·
verified ·
1 Parent(s): 4f9af06

Delete app.py

Browse files
Files changed (1) hide show
  1. app.py +0 -2164
app.py DELETED
@@ -1,2164 +0,0 @@
1
- """
2
- Space Weather - Weather Intelligence Application
3
- Built with Gradio, LiteLLM, Open-Meteo, and Gemini
4
- Compatible with Gradio 6.x
5
- Browser-cache version: SINGLE ENTRY (overwrite old data)
6
-
7
- Fitur: foto lahan/tanaman opsional (dikompres di memori, tidak disimpan).
8
- """
9
-
10
- import html
11
- import json
12
- import logging
13
- import math
14
- import os
15
- import random
16
- import re
17
- import time
18
- import uuid
19
- import warnings
20
- from dataclasses import dataclass
21
- from datetime import datetime, timezone
22
- from typing import Any, Dict, List, Optional, Tuple
23
-
24
- import gradio as gr
25
- from litellm import completion
26
-
27
- from gemini_key_manager import GeminiKeyManager, classify_gemini_error
28
- from image_utils import compress_image_to_data_url
29
- from product_search import build_recommendation_modal, preload
30
-
31
- warnings.filterwarnings("ignore", category=RuntimeWarning, message="coroutine.*was never awaited")
32
- warnings.filterwarnings("ignore", category=RuntimeWarning, message=".*event loop.*")
33
-
34
- logging.basicConfig(level=logging.INFO)
35
- logger = logging.getLogger(__name__)
36
-
37
-
38
- # ------------------------------------------------------------------
39
- # FILE LOADERS
40
- # ------------------------------------------------------------------
41
- def load_text(path: str) -> str:
42
- try:
43
- with open(path, "r", encoding="utf-8") as f:
44
- return f.read()
45
- except Exception as e:
46
- logger.error(f"Failed to load {path}: {e}")
47
- return ""
48
-
49
-
50
- def load_json(path: str) -> dict:
51
- try:
52
- with open(path, "r", encoding="utf-8") as f:
53
- return json.load(f)
54
- except Exception as e:
55
- logger.error(f"Failed to load {path}: {e}")
56
- return {}
57
-
58
-
59
- _SYSTEM_PROMPT: Optional[str] = None
60
-
61
-
62
- def get_system_prompt() -> str:
63
- """System prompt dibaca sekali lalu di-cache di memori."""
64
- global _SYSTEM_PROMPT
65
- if not _SYSTEM_PROMPT:
66
- _SYSTEM_PROMPT = load_text("prompts/system_prompt.txt")
67
- return _SYSTEM_PROMPT
68
-
69
-
70
- # ------------------------------------------------------------------
71
- # CONFIGURATION
72
- # ------------------------------------------------------------------
73
- EXPORT_DIR = "/tmp/weather_exports"
74
- EXPORT_MAX_AGE_S = 3600
75
-
76
- SHOPEE_LINK = "https://shopee.co.id/"
77
-
78
- GEMINI_MODEL = "gemini/gemini-3.5-flash"
79
- GEMINI_TIMEOUT_S = 30
80
- GEMINI_TIMEOUT_IMAGE_S = 45
81
- GEMINI_TOTAL_BUDGET_S = 100 # batas total waktu satu analisis (semua key + retry)
82
- GEMINI_MAX_ROUNDS = 3 # putaran retry jika kena limit per menit (RPM)
83
- GEMINI_MAX_TOKENS = 6000 # output lebih panjang (photo_assessment + concern_answer) + ruang token berpikir
84
-
85
- MAX_SHORT_CHARS = 80 # jenis tanaman, fase fenologi
86
- MAX_LONG_CHARS = 500 # catatan lapangan, current concern
87
-
88
- # Dipakai jika foto gagal diproses/ditolak sehingga permintaan diulang tanpa gambar.
89
- NO_IMAGE_FALLBACK = {
90
- "provided": False,
91
- "note": "Foto gagal diproses dan tidak dianalisis; jangan menyebut isi foto.",
92
- }
93
-
94
- CONCURRENCY_LIMIT = 20 # analisis Gemini paralel
95
- MAX_UPLOAD_SIZE = "8mb"
96
-
97
- key_manager = GeminiKeyManager()
98
- preload() # load model & embedding produk di background thread
99
-
100
- # ------------------------------------------------------------------
101
- # STATE MACHINE CONSTANTS
102
- # ------------------------------------------------------------------
103
- STATE_READY = "READY"
104
- STATE_LOCATING = "LOCATING"
105
- STATE_LOCATION_READY = "LOCATION_READY"
106
- STATE_ANALYZING = "ANALYZING"
107
- STATE_FETCHING_WEATHER = "FETCHING_WEATHER"
108
- STATE_PROCESSING_DATA = "PROCESSING_DATA"
109
- STATE_GENERATING_INSIGHT = "GENERATING_INSIGHT"
110
- STATE_VALIDATING_OUTPUT = "VALIDATING_OUTPUT"
111
- STATE_COMPLETED = "COMPLETED"
112
- STATE_ERROR = "ERROR"
113
- STATE_LOCKED_TODAY = "LOCKED_TODAY"
114
-
115
- PROGRESS_STEPS = {
116
- STATE_FETCHING_WEATHER: ("Step 1/5", "Getting weather data..."),
117
- STATE_PROCESSING_DATA: ("Step 2/5", "Processing weather data..."),
118
- STATE_GENERATING_INSIGHT: ("Step 3/5", "Generating weather insight..."),
119
- STATE_VALIDATING_OUTPUT: ("Step 4/5", "Validating analysis..."),
120
- STATE_COMPLETED: ("Step 5/5", "Analysis complete"),
121
- }
122
-
123
- STEP_ORDER = [
124
- STATE_FETCHING_WEATHER,
125
- STATE_PROCESSING_DATA,
126
- STATE_GENERATING_INSIGHT,
127
- STATE_VALIDATING_OUTPUT,
128
- STATE_COMPLETED,
129
- ]
130
- STEP_LABELS = ["Weather Data", "Processing", "Insight", "Validation", "Complete"]
131
-
132
- STATUS_VARIANTS = {
133
- STATE_READY: ("neutral", "Ready"),
134
- STATE_LOCATION_READY: ("info", "Location ready"),
135
- STATE_ANALYZING: ("active", "Analyzing"),
136
- STATE_ERROR: ("error", "Error"),
137
- STATE_LOCKED_TODAY: ("info", "Locked"),
138
- STATE_COMPLETED: ("success", "Complete"),
139
- }
140
-
141
- VALID_SEVERITY = {"low", "medium", "high"}
142
- VALID_CONFIDENCE = {"low", "medium", "high"}
143
- VALID_PRIORITY = {"low", "medium", "high"}
144
- VALID_LIKELIHOOD = {"low", "medium", "high"}
145
- VALID_PHOTO_STATUS = {"not_provided", "usable", "limited", "unusable"}
146
- VALID_CATEGORY = {
147
- "fungal_disease", "bacterial_disease", "viral_disease", "insect_pest", "nutrient_issue",
148
- "water_stress", "weather_stress", "physical_damage", "chemical_injury", "unclear",
149
- }
150
- CATEGORY_LABELS = {
151
- "fungal_disease": "Kemungkinan penyakit jamur",
152
- "bacterial_disease": "Kemungkinan penyakit bakteri",
153
- "viral_disease": "Kemungkinan penyakit virus",
154
- "insect_pest": "Kemungkinan serangan hama",
155
- "nutrient_issue": "Kemungkinan masalah unsur hara",
156
- "water_stress": "Kemungkinan stres air",
157
- "weather_stress": "Kemungkinan stres cuaca",
158
- "physical_damage": "Kemungkinan kerusakan fisik",
159
- "chemical_injury": "Kemungkinan dampak bahan kimia",
160
- "unclear": "Penyebab belum jelas",
161
- }
162
- PHOTO_STATUS_LABELS = {
163
- "usable": "Foto cukup jelas",
164
- "limited": "Foto terbatas",
165
- "unusable": "Foto tidak dapat dinilai",
166
- }
167
- MAX_HYPOTHESES = 3
168
- MAX_OBSERVATIONS = 6
169
-
170
- WEATHER_VARIABLES = [
171
- # Temperature and plant development
172
- "temperature_2m_max",
173
- "temperature_2m_min",
174
- "temperature_2m_mean",
175
- "growing_degree_days_base_0_limit_50",
176
-
177
- # Rainfall and water balance
178
- "precipitation_sum",
179
- "precipitation_hours",
180
- "precipitation_probability_max",
181
- "et0_fao_evapotranspiration",
182
-
183
- # Humidity and disease-related conditions
184
- "relative_humidity_2m_mean",
185
- "relative_humidity_2m_max",
186
- "dew_point_2m_mean",
187
- "leaf_wetness_probability_mean",
188
- "vapour_pressure_deficit_max",
189
-
190
- # Radiation, clouds, and wind
191
- "shortwave_radiation_sum",
192
- "cloud_cover_mean",
193
- "wind_speed_10m_max",
194
- "wind_gusts_10m_max",
195
- ]
196
-
197
-
198
- # ------------------------------------------------------------------
199
- # DATA CLASSES
200
- # ------------------------------------------------------------------
201
- @dataclass
202
- class AppState:
203
- state: str = STATE_READY
204
- is_analyzing: bool = False
205
- location: Optional[Dict] = None
206
- client_date: Optional[str] = None
207
- client_timezone: Optional[str] = None
208
- browser_date: Optional[str] = None
209
- browser_timezone: Optional[str] = None
210
- cache: Optional[Dict] = None # SINGLE entry
211
-
212
- def to_dict(self):
213
- return {
214
- "state": self.state,
215
- "is_analyzing": self.is_analyzing,
216
- "location": self.location,
217
- "client_date": self.client_date,
218
- "client_timezone": self.client_timezone,
219
- "browser_date": self.browser_date,
220
- "browser_timezone": self.browser_timezone,
221
- "cache": self.cache,
222
- }
223
-
224
- @classmethod
225
- def from_dict(cls, d):
226
- d = d or {}
227
- return cls(
228
- state=d.get("state", STATE_READY),
229
- is_analyzing=d.get("is_analyzing", False),
230
- location=d.get("location"),
231
- client_date=d.get("client_date"),
232
- client_timezone=d.get("client_timezone"),
233
- browser_date=d.get("browser_date"),
234
- browser_timezone=d.get("browser_timezone"),
235
- cache=d.get("cache"),
236
- )
237
-
238
-
239
- # ------------------------------------------------------------------
240
- # UTILITY FORMATTERS
241
- # ------------------------------------------------------------------
242
- def validate_coordinates(lat: Any, lon: Any) -> Tuple[bool, str]:
243
- if lat is None or lon is None:
244
- return False, "Invalid location. Please enter a valid latitude and longitude."
245
- try:
246
- lat_f = float(lat)
247
- lon_f = float(lon)
248
- except (ValueError, TypeError):
249
- return False, "Invalid location. Please enter a valid latitude and longitude."
250
-
251
- if not (-90 <= lat_f <= 90):
252
- return False, "Invalid location. Latitude must be between -90 and 90."
253
- if not (-180 <= lon_f <= 180):
254
- return False, "Invalid location. Longitude must be between -180 and 180."
255
- return True, ""
256
-
257
-
258
- def validate_coordinates_ui(lat, lon, state_dict):
259
- state = AppState.from_dict(state_dict)
260
- if state.state == STATE_LOCKED_TODAY:
261
- return gr.update(interactive=False)
262
- if (lat is None or lat == 0) or (lon is None or lon == 0):
263
- return gr.update(interactive=False)
264
- return gr.update(interactive=True)
265
-
266
-
267
- def esc(value: Any) -> str:
268
- if value is None:
269
- return ""
270
- return html.escape(str(value))
271
-
272
-
273
- def format_status(state: str, message: str = "") -> str:
274
- if state in PROGRESS_STEPS and state not in STATUS_VARIANTS:
275
- variant = "active"
276
- label = PROGRESS_STEPS[state][1]
277
- else:
278
- variant, label = STATUS_VARIANTS.get(state, ("neutral", state.replace("_", " ").title()))
279
-
280
- detail = f'<span class="status-detail">{esc(message)}</span>' if message else ""
281
- return (
282
- f'<div class="status-pill status-pill--{variant}">'
283
- f'<span class="status-dot"></span>'
284
- f'<span class="status-label">{esc(label)}</span>'
285
- f'{detail}'
286
- f'</div>'
287
- )
288
-
289
-
290
- def format_location_status(source: str, accuracy: Optional[float]) -> str:
291
- source_label = {"gps": "GPS", "ip": "IP geolocation"}.get(source, source or "Manual")
292
- accuracy_str = f" &plusmn;{accuracy:.0f}m" if accuracy else ""
293
- return (
294
- f'<div class="status-pill status-pill--info">'
295
- f'<span class="status-dot"></span>'
296
- f'<span class="status-label">Location ready</span>'
297
- f'<span class="status-detail">{esc(source_label)}{accuracy_str}</span>'
298
- f'</div>'
299
- )
300
-
301
-
302
- def render_step_tracker(state: str, error: bool = False) -> str:
303
- if state not in STEP_ORDER:
304
- return ""
305
- idx = STEP_ORDER.index(state)
306
-
307
- items = []
308
- for i, label in enumerate(STEP_LABELS):
309
- is_done = i < idx or (i == idx and state == STATE_COMPLETED)
310
- if error and i == idx:
311
- cls, marker = "is-error", "&times;"
312
- elif is_done:
313
- cls, marker = "is-done", "&check;"
314
- elif i == idx:
315
- cls, marker = "is-active", f"{i + 1:02d}"
316
- else:
317
- cls, marker = "is-pending", f"{i + 1:02d}"
318
-
319
- items.append(
320
- f'<div class="step {cls}">'
321
- f'<span class="step-marker">{marker}</span>'
322
- f'<span class="step-label">{esc(label)}</span>'
323
- f'</div>'
324
- )
325
- if i < len(STEP_LABELS) - 1:
326
- filled = "filled" if is_done else ""
327
- items.append(f'<div class="step-connector {filled}"></div>')
328
-
329
- return f'<div class="step-tracker">{"".join(items)}</div>'
330
-
331
-
332
- def format_progress(state: str, error: bool = False) -> str:
333
- return render_step_tracker(state, error=error)
334
-
335
-
336
- def format_cache_info(cache_entry: Optional[Dict]) -> str:
337
- if not cache_entry:
338
- return ""
339
-
340
- client_date = cache_entry.get("client_date", "Unknown")
341
- if client_date != "Unknown":
342
- try:
343
- client_date = datetime.strptime(client_date, "%Y-%m-%d").strftime("%d %b %Y")
344
- except Exception:
345
- pass
346
-
347
- created = cache_entry.get("created_at", "Unknown")
348
- browser_tz = cache_entry.get("browser_timezone") or cache_entry.get("client_timezone") or "UTC"
349
-
350
- if created != "Unknown":
351
- try:
352
- dt = datetime.fromisoformat(created)
353
- if dt.tzinfo is None:
354
- dt = dt.replace(tzinfo=timezone.utc)
355
- if browser_tz and browser_tz != "UTC":
356
- try:
357
- from zoneinfo import ZoneInfo
358
- dt_local = dt.astimezone(ZoneInfo(browser_tz))
359
- created = dt_local.strftime("%d %b %Y, %H:%M") + f" · {browser_tz}"
360
- except Exception:
361
- created = dt.strftime("%d %b %Y, %H:%M UTC")
362
- else:
363
- created = dt.strftime("%d %b %Y, %H:%M UTC")
364
- except Exception:
365
- pass
366
-
367
- location = cache_entry.get("location", {}) or {}
368
- source = location.get("source", "manual")
369
- source_label = {"gps": "GPS", "ip": "IP Geolocation", "manual": "Manual"}.get(source, source)
370
-
371
- return (
372
- f'<div class="cache-card">'
373
- f'<div class="cache-card-icon">&check;</div>'
374
- f'<div class="cache-card-body">'
375
- f'<div class="cache-card-title">Today&rsquo;s analysis is ready</div>'
376
- f'<div class="cache-card-meta">'
377
- f'<span>{esc(client_date)}</span><span class="dot-sep">&middot;</span><span>{esc(source_label)}</span>'
378
- f'</div>'
379
- f'<div class="cache-card-meta cache-card-meta--faint">Generated {esc(created)}</div>'
380
- f'</div>'
381
- f'</div>'
382
- )
383
-
384
-
385
- def render_placeholder(title: str, message: str, variant: str = "neutral") -> str:
386
- return (
387
- f'<div class="placeholder-card placeholder-card--{variant}">'
388
- f'<div class="placeholder-mark"></div>'
389
- f'<div class="placeholder-title">{esc(title)}</div>'
390
- f'<div class="placeholder-message">{esc(message)}</div>'
391
- f'</div>'
392
- )
393
-
394
-
395
- def render_sponsors_html(sponsors: List[Dict]) -> str:
396
- if not sponsors:
397
- return '<div class="sponsor-empty">No sponsors listed.</div>'
398
- items = []
399
- for s in sponsors:
400
- items.append(
401
- f'<a class="sponsor-item" href="{esc(s.get("link", "#"))}" '
402
- f'target="_blank" rel="noopener noreferrer" title="{esc(s.get("name", ""))}">'
403
- f'<img class="sponsor-img" src="{esc(s.get("image", ""))}" '
404
- f'alt="{esc(s.get("name", ""))}" loading="lazy">'
405
- f'</a>'
406
- )
407
- return f'<div class="sponsor-grid">{"".join(items)}</div>'
408
-
409
-
410
- # ------------------------------------------------------------------
411
- # TAB RENDERERS
412
- # ------------------------------------------------------------------
413
- _LEVEL_CLASS = {"low": "badge--good", "medium": "badge--warn", "high": "badge--bad"}
414
-
415
-
416
- def severity_badge(sev: Optional[str]) -> str:
417
- sev_l = (sev or "unknown").lower()
418
- return f'<span class="badge {_LEVEL_CLASS.get(sev_l, "badge--neutral")}">{esc(sev_l.upper())}</span>'
419
-
420
-
421
- def priority_badge(pri: Optional[str]) -> str:
422
- pri_l = (pri or "unknown").lower()
423
- return f'<span class="badge {_LEVEL_CLASS.get(pri_l, "badge--neutral")}">{esc(pri_l.upper())} PRI.</span>'
424
-
425
-
426
- def confidence_badge(conf: Optional[str]) -> str:
427
- conf_l = (conf or "unknown").lower()
428
- cls = {"high": "badge--good", "medium": "badge--warn", "low": "badge--neutral"}.get(conf_l, "badge--neutral")
429
- return f'<span class="badge {cls} badge--outline">{esc(conf_l.upper())} CONF.</span>'
430
-
431
-
432
- def likelihood_badge(level: Optional[str]) -> str:
433
- lvl = (level or "unknown").lower()
434
- cls = {"low": "badge--neutral", "medium": "badge--warn", "high": "badge--bad"}.get(lvl, "badge--neutral")
435
- label = {"low": "RENDAH", "medium": "SEDANG", "high": "TINGGI"}.get(lvl, lvl.upper())
436
- return f'<span class="badge {cls}">KEMUNGKINAN {esc(label)}</span>'
437
-
438
-
439
- def render_photo_block(analysis: Dict) -> str:
440
- """Blok analisis foto di tab Summary. Kosong jika tidak ada foto (cache lama juga aman)."""
441
- pa = analysis.get("photo_assessment")
442
- if not isinstance(pa, dict) or pa.get("photo_status") in (None, "", "not_provided"):
443
- return ""
444
-
445
- parts = ['<div class="insight-section" style="margin-top:18px;">']
446
- parts.append('<div class="section-eyebrow">Analisis Foto &middot; perkiraan, bukan diagnosis</div>')
447
-
448
- label = PHOTO_STATUS_LABELS.get(pa.get("photo_status"), "")
449
- note = str(pa.get("image_quality_note") or "").strip()
450
- status_text = " ".join(x for x in [f"{label}." if label else "", note] if x)
451
- if status_text:
452
- parts.append(f'<p class="section-text">{esc(status_text)}</p>')
453
-
454
- observations = pa.get("visible_observations") or []
455
- if observations:
456
- parts.append('<p class="section-text"><strong>Yang tampak di foto:</strong></p>')
457
- parts.append('<ul class="condition-list">' + "".join(f"<li>{esc(o)}</li>" for o in observations) + "</ul>")
458
-
459
- for h in pa.get("hypotheses") or []:
460
- parts.append(
461
- '<div class="risk-item" style="margin-top:8px;">'
462
- '<div class="risk-item-head">'
463
- f'<span class="risk-item-title">{esc(h.get("name"))}</span>'
464
- f'<span class="risk-item-badges">{likelihood_badge(h.get("likelihood"))}</span>'
465
- '</div>'
466
- f'<p class="risk-item-evidence" style="margin-top:4px;">{esc(CATEGORY_LABELS.get(h.get("category"), ""))}</p>'
467
- f'<p class="risk-item-evidence">Bukti visual: {esc(h.get("visual_evidence"))}</p>'
468
- f'<p class="risk-item-evidence">Kaitan cuaca: {esc(h.get("weather_link"))}</p>'
469
- f'<p class="risk-item-evidence" style="color:var(--info);">Cara memeriksa: {esc(h.get("how_to_verify"))}</p>'
470
- '</div>'
471
- )
472
-
473
- if pa.get("limitations"):
474
- parts.append(f'<p class="risk-item-evidence">Keterbatasan: {esc(pa["limitations"])}</p>')
475
- parts.append("</div>")
476
- return "".join(parts)
477
-
478
-
479
- def render_summary_tab(analysis: Dict) -> str:
480
- if not analysis:
481
- return render_placeholder("No analysis yet", "Enter coordinates and select Analyze to generate today's insight.")
482
- parts = ['<div class="insight-card">']
483
- parts.append(f'<p class="insight-summary">{esc(analysis.get("summary", "No summary available."))}</p>')
484
- concern_answer = str(analysis.get("concern_answer") or "").strip()
485
- if concern_answer:
486
- parts.append(
487
- '<div class="insight-section">'
488
- '<div class="section-eyebrow">Jawaban untuk pertanyaan Anda</div>'
489
- f'<p class="section-text">{esc(concern_answer)}</p>'
490
- '</div>'
491
- )
492
- parts.append(render_photo_block(analysis))
493
- overall = analysis.get("overall_confidence", "")
494
- if overall:
495
- parts.append(f'<div class="insight-footer">Overall confidence&nbsp;{confidence_badge(overall)}</div>')
496
- parts.append('</div>')
497
- return "".join(parts)
498
-
499
-
500
- def _render_period_tab(analysis: Dict, key: str, eyebrow: str, empty_title: str,
501
- empty_msg: str, nothing_msg: str) -> str:
502
- """Dipakai bersama oleh tab Historical dan Forecast (mendukung format lama)."""
503
- if not analysis:
504
- return render_placeholder(empty_title, empty_msg)
505
- block = analysis.get(key, {}) or {}
506
- parts = ['<div class="insight-card"><div class="insight-section">']
507
- parts.append(f'<div class="section-eyebrow">{eyebrow}</div>')
508
- if block.get("condition"):
509
- parts.append(f'<p class="section-text"><strong>Kondisi:</strong> {esc(block["condition"])}</p>')
510
- if block.get("impact"):
511
- parts.append(f'<p class="section-text"><strong>Dampak:</strong> {esc(block["impact"])}</p>')
512
- # Format lama (backward-compatible)
513
- if block.get("summary"):
514
- parts.append(f'<p class="section-text">{esc(block["summary"])}</p>')
515
- conds = block.get("key_conditions") or []
516
- if conds:
517
- parts.append('<ul class="condition-list">' + "".join(f'<li>{esc(c)}</li>' for c in conds) + '</ul>')
518
- if not (block.get("condition") or block.get("impact") or block.get("summary") or conds):
519
- parts.append(f'<p class="section-text">{nothing_msg}</p>')
520
- parts.append('</div></div>')
521
- return "".join(parts)
522
-
523
-
524
- def render_historical_tab(analysis: Dict) -> str:
525
- return _render_period_tab(
526
- analysis, "historical", "Historical &middot; Last 7 Days",
527
- "No data yet", "Run analysis to view historical records.", "No historical data recorded.",
528
- )
529
-
530
-
531
- def render_forecast_tab(analysis: Dict) -> str:
532
- return _render_period_tab(
533
- analysis, "forecast", "Forecast &middot; Next 7 Days",
534
- "No data yet", "Run analysis to view forecast records.", "No forecast data recorded.",
535
- )
536
-
537
-
538
- def render_risks_tab(analysis: Dict) -> str:
539
- if not analysis:
540
- return render_placeholder("No data yet", "Run analysis to view risk signals.")
541
- risks = analysis.get("risks") or []
542
- parts = ['<div class="insight-card"><div class="insight-section">']
543
- parts.append('<div class="section-eyebrow">Risk Signals</div>')
544
- if risks:
545
- parts.append('<div class="risk-list">')
546
- for risk in risks:
547
- title = str(risk.get("title") or risk.get("type", "Unknown Risk"))
548
- parts.append('<div class="risk-item">')
549
- parts.append(
550
- f'<div class="risk-item-head">'
551
- f'<span class="risk-item-title">{esc(title)}</span>'
552
- f'<span class="risk-item-badges">{severity_badge(risk.get("severity"))}</span>'
553
- f'</div>'
554
- )
555
- if risk.get("description"):
556
- parts.append(f'<p class="section-text" style="margin:6px 0 4px;font-size:13px;">{esc(risk["description"])}</p>')
557
- if risk.get("evidence"):
558
- parts.append(f'<p class="risk-item-evidence">{esc(risk["evidence"])}</p>')
559
- if risk.get("period"):
560
- parts.append(f'<p class="risk-item-evidence" style="color:var(--info);margin-top:4px;">&#128197; {esc(risk["period"])}</p>')
561
- parts.append('</div>')
562
- parts.append('</div>')
563
- else:
564
- parts.append('<p class="section-text">No significant weather risks detected.</p>')
565
- parts.append('</div></div>')
566
- return "".join(parts)
567
-
568
-
569
- def render_recommendations_tab(analysis: Dict) -> str:
570
- if not analysis:
571
- return render_placeholder("No data yet", "Run analysis to view recommendations.")
572
- parts = ['<div class="insight-card">']
573
- parts.append('<div class="insight-section insight-section--recommendation" style="margin-bottom:0;">')
574
- parts.append('<div class="section-eyebrow">Recommendation</div>')
575
- recs = analysis.get("recommendations") or []
576
- if recs:
577
- parts.append('<div class="risk-list">')
578
- for rec in recs:
579
- if isinstance(rec, str): # format lama
580
- action, reason, priority = rec, "", ""
581
- else:
582
- action = str(rec.get("action", ""))
583
- reason = str(rec.get("reason", ""))
584
- priority = rec.get("priority", "")
585
- parts.append('<div class="risk-item" style="border-color:rgba(232,163,61,0.25);">')
586
- parts.append(
587
- f'<div class="risk-item-head">'
588
- f'<span class="risk-item-title">{esc(action)}</span>'
589
- f'<span class="risk-item-badges">{priority_badge(priority)}</span>'
590
- f'</div>'
591
- )
592
- if reason:
593
- parts.append(f'<p class="risk-item-evidence">{esc(reason)}</p>')
594
- parts.append('</div>')
595
- parts.append('</div>')
596
- else:
597
- parts.append('<p class="section-text">No immediate action indicated.</p>')
598
- parts.append('</div></div>')
599
- return "".join(parts)
600
-
601
-
602
- def render_all_tabs(analysis: Dict) -> Tuple[str, str, str, str, str]:
603
- return (
604
- render_summary_tab(analysis),
605
- render_historical_tab(analysis),
606
- render_forecast_tab(analysis),
607
- render_risks_tab(analysis),
608
- render_recommendations_tab(analysis),
609
- )
610
-
611
-
612
- # ------------------------------------------------------------------
613
- # UI OUTPUT HELPERS (satu tempat untuk tuple 15 elemen)
614
- # ------------------------------------------------------------------
615
- def tabs_placeholder(title: str, message: str, variant: str = "neutral",
616
- rest: str = "Waiting...") -> Tuple[str, str, str, str, str]:
617
- first = render_placeholder(title, message, variant)
618
- other = render_placeholder("No data yet", rest, "neutral")
619
- return (first, other, other, other, other)
620
-
621
-
622
- def ui_outputs(state: AppState, *, lock_inputs: bool, status: str, step: str = "",
623
- cache_info: str = "", show_placeholder: bool, show_view_btn: bool,
624
- tabs: Tuple[str, str, str, str, str], cache_json: str = ""):
625
- """Urutan harus cocok dengan `outputs` pada weather_json.change."""
626
- return (
627
- state.to_dict(),
628
- gr.update(interactive=not lock_inputs), # get_loc_btn
629
- gr.update(interactive=not lock_inputs), # analyze_btn
630
- status,
631
- step,
632
- cache_info,
633
- gr.update(visible=show_placeholder), # initial_placeholder
634
- gr.update(visible=show_view_btn), # view_insight_btn
635
- gr.update(visible=False), # tabs_container (baru tampil setelah View Insight)
636
- *tabs,
637
- cache_json if cache_json else gr.update(value=""),
638
- )
639
-
640
-
641
- def progress_outputs(state: AppState, step_state: str, title: str, message: str):
642
- state.state = step_state
643
- return ui_outputs(
644
- state, lock_inputs=True,
645
- status=format_status(step_state), step=format_progress(step_state),
646
- show_placeholder=True, show_view_btn=False,
647
- tabs=tabs_placeholder(title, message, "active"),
648
- )
649
-
650
-
651
- def error_outputs(state: AppState, failed_step: str, message: str):
652
- state.is_analyzing = False
653
- state.state = STATE_ERROR
654
- step = format_progress(failed_step if failed_step in STEP_ORDER else STATE_FETCHING_WEATHER, error=True)
655
- return ui_outputs(
656
- state, lock_inputs=False,
657
- status=format_status(STATE_ERROR, message), step=step,
658
- show_placeholder=True, show_view_btn=False,
659
- tabs=tabs_placeholder("Analysis failed", message, "error", "Analysis interrupted."),
660
- )
661
-
662
-
663
- # ------------------------------------------------------------------
664
- # WEATHER VALIDATION & FEATURE ENGINEERING
665
- # ------------------------------------------------------------------
666
- MAX_DAILY_ROWS = 40
667
-
668
-
669
- def validate_weather_payload(raw: Any) -> str:
670
- """Respons cuaca datang dari browser, jadi struktur harus diperiksa di server."""
671
- if not isinstance(raw, dict):
672
- return "Weather data unavailable. Please try again later. (Invalid JSON)"
673
- daily = raw.get("daily")
674
- if not isinstance(daily, dict):
675
- return "Weather data unavailable. Please try again later. (Missing daily data)"
676
- dates = daily.get("time")
677
- if not isinstance(dates, list) or len(dates) < 8:
678
- return "Weather data unavailable. Please try again later. (Insufficient data)"
679
- if len(dates) > MAX_DAILY_ROWS:
680
- return "Weather data unavailable. Please try again later. (Too many rows)"
681
- for var in WEATHER_VARIABLES:
682
- values = daily.get(var)
683
- if not isinstance(values, list) or len(values) != len(dates):
684
- return f"Weather data unavailable. Please try again later. (Missing variable: {var})"
685
- return ""
686
-
687
-
688
- def _weather_num(value):
689
- """Convert valid finite numeric values to float; otherwise None."""
690
- try:
691
- if value is None:
692
- return None
693
- number = float(value)
694
- return number if math.isfinite(number) else None
695
- except (TypeError, ValueError):
696
- return None
697
-
698
-
699
- def _weather_probability_fraction(value, unit=None):
700
- """Normalize a probability to 0-1 (Open-Meteo biasanya dalam persen)."""
701
- number = _weather_num(value)
702
- if number is None:
703
- return None
704
- if unit and "%" in str(unit):
705
- number /= 100.0
706
- elif number > 1.0:
707
- number /= 100.0
708
- return max(0.0, min(1.0, number))
709
-
710
-
711
- def _get(record: Dict, source: str, key: str):
712
- return record["raw"].get(key) if source == "raw" else record["features"].get(key)
713
-
714
-
715
- def engineer_weather_features(normalized):
716
- """
717
- Build derived agricultural weather features from the daily arrays.
718
- Output: feature arrays per periode + ringkasan periode.
719
- """
720
- units = normalized.get("units", {}) or {}
721
- periods = ("historical", "today", "forecast")
722
- records = []
723
-
724
- # 1. Gabungkan tiga periode secara kronologis
725
- for period in periods:
726
- block = normalized.get(period, {}) or {}
727
- dates = block.get("time", []) or []
728
-
729
- for i, date in enumerate(dates):
730
- raw = {}
731
- for variable in WEATHER_VARIABLES:
732
- values = block.get(variable, [])
733
- value = values[i] if isinstance(values, list) and i < len(values) else None
734
- raw[variable] = _weather_num(value)
735
-
736
- rh = raw.get("relative_humidity_2m_mean")
737
- leaf_wetness = _weather_probability_fraction(
738
- raw.get("leaf_wetness_probability_mean"),
739
- units.get("leaf_wetness_probability_mean"),
740
- )
741
- precip_probability = _weather_probability_fraction(
742
- raw.get("precipitation_probability_max"),
743
- units.get("precipitation_probability_max"),
744
- )
745
-
746
- t_mean = raw.get("temperature_2m_mean")
747
- t_min = raw.get("temperature_2m_min")
748
- t_max = raw.get("temperature_2m_max")
749
- dew = raw.get("dew_point_2m_mean")
750
- precip = raw.get("precipitation_sum")
751
- precip_hours = raw.get("precipitation_hours")
752
- et0 = raw.get("et0_fao_evapotranspiration")
753
-
754
- features = {
755
- "temperature_range_c": (
756
- t_max - t_min if t_max is not None and t_min is not None else None
757
- ),
758
- "dewpoint_depression_proxy_c": (
759
- t_mean - dew if t_mean is not None and dew is not None else None
760
- ),
761
- "water_balance_proxy_mm": (
762
- precip - et0 if precip is not None and et0 is not None else None
763
- ),
764
- "precipitation_per_wet_hour_proxy": (
765
- precip / precip_hours
766
- if precip is not None and precip_hours is not None and precip_hours > 0
767
- else None
768
- ),
769
- "leaf_wetness_fraction": leaf_wetness,
770
- "precip_probability_fraction": precip_probability,
771
- # Proksi lingkungan, BUKAN probabilitas penyakit.
772
- "humidity_wetness_interaction": (
773
- (rh / 100.0) * leaf_wetness
774
- if rh is not None and leaf_wetness is not None
775
- else None
776
- ),
777
- "wetness_duration_interaction": (
778
- leaf_wetness * max(0.0, min(1.0, precip_hours / 24.0))
779
- if leaf_wetness is not None and precip_hours is not None
780
- else None
781
- ),
782
- }
783
- records.append({"date": date, "period": period, "raw": raw, "features": features})
784
-
785
- # 2. Hari berturut-turut dengan presipitasi <= 0.1 mm
786
- dry_streak = 0
787
- for record in records:
788
- precip = record["raw"].get("precipitation_sum")
789
- if precip is None:
790
- dry_streak = 0
791
- record["features"]["dry_spell_days"] = None
792
- elif precip <= 0.1:
793
- dry_streak += 1
794
- record["features"]["dry_spell_days"] = dry_streak
795
- else:
796
- dry_streak = 0
797
- record["features"]["dry_spell_days"] = 0
798
-
799
- # 3. Rolling 3 dan 7 hari (nilai hilang tidak diganti nol)
800
- def rolling_value(index, source, key, window, operation):
801
- if index + 1 < window:
802
- return None
803
- subset = records[index - window + 1:index + 1]
804
- values = [_get(r, source, key) for r in subset]
805
- if any(v is None for v in values):
806
- return None
807
- return sum(values) if operation == "sum" else sum(values) / len(values)
808
-
809
- rolling_specs = [
810
- # (source, key, operation, prefix)
811
- ("raw", "precipitation_sum", "sum", "precipitation"),
812
- ("raw", "et0_fao_evapotranspiration", "sum", "et0"),
813
- ("feature", "water_balance_proxy_mm", "sum", "water_balance"),
814
- ("raw", "growing_degree_days_base_0_limit_50", "sum", "gdd"),
815
- ("raw", "temperature_2m_mean", "mean", "temperature_mean"),
816
- ("raw", "vapour_pressure_deficit_max", "mean", "vpd"),
817
- ("raw", "relative_humidity_2m_mean", "mean", "rh_mean_pct"),
818
- ("feature", "leaf_wetness_fraction", "mean", "leaf_wetness"),
819
- ]
820
- for i, record in enumerate(records):
821
- for window in (3, 7):
822
- for source, key, operation, prefix in rolling_specs:
823
- record["features"][f"{prefix}_{window}d_{operation}"] = rolling_value(
824
- i, source, key, window, operation
825
- )
826
-
827
- # 4. Perubahan 1 hari
828
- delta_specs = {
829
- "temperature_mean_delta_1d": ("raw", "temperature_2m_mean"),
830
- "vpd_delta_1d": ("raw", "vapour_pressure_deficit_max"),
831
- "rh_mean_delta_1d": ("raw", "relative_humidity_2m_mean"),
832
- "precipitation_delta_1d": ("raw", "precipitation_sum"),
833
- "leaf_wetness_delta_1d": ("feature", "leaf_wetness_fraction"),
834
- }
835
- for i, record in enumerate(records):
836
- for name, (source, key) in delta_specs.items():
837
- value = None
838
- if i > 0:
839
- cur = _get(record, source, key)
840
- prev = _get(records[i - 1], source, key)
841
- if cur is not None and prev is not None:
842
- value = cur - prev
843
- record["features"][name] = value
844
-
845
- # 5. Prakiraan relatif terhadap rata-rata historis 7 hari
846
- anomaly_specs = {
847
- "temperature_mean_delta_vs_history7d": ("raw", "temperature_2m_mean"),
848
- "vpd_delta_vs_history7d": ("raw", "vapour_pressure_deficit_max"),
849
- "rh_mean_delta_vs_history7d": ("raw", "relative_humidity_2m_mean"),
850
- "precipitation_delta_vs_history7d": ("raw", "precipitation_sum"),
851
- "et0_delta_vs_history7d": ("raw", "et0_fao_evapotranspiration"),
852
- "leaf_wetness_delta_vs_history7d": ("feature", "leaf_wetness_fraction"),
853
- }
854
- historical_records = [r for r in records if r["period"] == "historical"]
855
- baselines = {}
856
- for name, (source, key) in anomaly_specs.items():
857
- values = [v for v in (_get(r, source, key) for r in historical_records) if v is not None]
858
- baselines[name] = sum(values) / len(values) if values else None
859
-
860
- for record in records:
861
- for name, (source, key) in anomaly_specs.items():
862
- value = None
863
- if record["period"] == "forecast":
864
- cur = _get(record, source, key)
865
- base = baselines[name]
866
- if cur is not None and base is not None:
867
- value = cur - base
868
- record["features"][name] = value
869
-
870
- # 6. Susun array fitur per periode
871
- all_feature_names = sorted({k for r in records for k in r["features"]})
872
- derived_blocks = {}
873
- for period in periods:
874
- period_records = [r for r in records if r["period"] == period]
875
- derived_blocks[period] = {
876
- "time": [r["date"] for r in period_records],
877
- "features": {
878
- name: [r["features"].get(name) for r in period_records]
879
- for name in all_feature_names
880
- },
881
- }
882
-
883
- # 7. Ringkasan periode
884
- def mean_values(values):
885
- values = [v for v in values if v is not None]
886
- return sum(values) / len(values) if values else None
887
-
888
- def total_values(values):
889
- # Jangan tampilkan jumlah parsial sebagai total periode.
890
- if not values or any(v is None for v in values):
891
- return None
892
- return sum(values)
893
-
894
- def max_values(values):
895
- return max([v for v in values if v is not None], default=None)
896
-
897
- def min_values(values):
898
- return min([v for v in values if v is not None], default=None)
899
-
900
- def summarize_period(period):
901
- subset = [r for r in records if r["period"] == period]
902
-
903
- def raw_values(key):
904
- return [r["raw"].get(key) for r in subset]
905
-
906
- def feature_values(key):
907
- return [r["features"].get(key) for r in subset]
908
-
909
- return {
910
- "days": len(subset),
911
- "temperature_mean_c": mean_values(raw_values("temperature_2m_mean")),
912
- "temperature_max_peak_c": max_values(raw_values("temperature_2m_max")),
913
- "temperature_min_low_c": min_values(raw_values("temperature_2m_min")),
914
- "temperature_range_mean_c": mean_values(feature_values("temperature_range_c")),
915
- "precipitation_total_mm": total_values(raw_values("precipitation_sum")),
916
- "precipitation_hours_total": total_values(raw_values("precipitation_hours")),
917
- "et0_total_mm": total_values(raw_values("et0_fao_evapotranspiration")),
918
- "water_balance_proxy_total_mm": total_values(feature_values("water_balance_proxy_mm")),
919
- "gdd_total": total_values(raw_values("growing_degree_days_base_0_limit_50")),
920
- "vpd_mean": mean_values(raw_values("vapour_pressure_deficit_max")),
921
- "relative_humidity_mean_pct": mean_values(raw_values("relative_humidity_2m_mean")),
922
- "leaf_wetness_mean_fraction": mean_values(feature_values("leaf_wetness_fraction")),
923
- "humidity_wetness_interaction_mean": mean_values(feature_values("humidity_wetness_interaction")),
924
- "longest_dry_spell_days": max_values(feature_values("dry_spell_days")),
925
- "max_wind_speed": max_values(raw_values("wind_speed_10m_max")),
926
- "max_wind_gust": max_values(raw_values("wind_gusts_10m_max")),
927
- "precip_probability_mean_fraction": mean_values(feature_values("precip_probability_fraction")),
928
- }
929
-
930
- history_summary = summarize_period("historical")
931
- forecast_summary = summarize_period("forecast")
932
-
933
- comparison_keys = [
934
- "temperature_mean_c", "precipitation_total_mm", "et0_total_mm",
935
- "water_balance_proxy_total_mm", "gdd_total", "vpd_mean",
936
- "relative_humidity_mean_pct", "leaf_wetness_mean_fraction",
937
- ]
938
- comparison = {}
939
- for key in comparison_keys:
940
- h, f = history_summary.get(key), forecast_summary.get(key)
941
- comparison[key + "_forecast_minus_history"] = f - h if h is not None and f is not None else None
942
-
943
- return {
944
- "historical": derived_blocks["historical"],
945
- "today": derived_blocks["today"],
946
- "forecast": derived_blocks["forecast"],
947
- "summary": {
948
- "history_7d": history_summary,
949
- "forecast_7d": forecast_summary,
950
- "forecast_minus_history": comparison,
951
- },
952
- }
953
-
954
-
955
- def normalize_weather_data(raw_data: Dict, lat: float, lon: float, client_date: str) -> Tuple[Optional[Dict], str]:
956
- try:
957
- timezone_str = raw_data.get("timezone", "UTC")
958
- daily = raw_data["daily"]
959
- dates = daily["time"]
960
- location_date = dates[7] if len(dates) > 7 else client_date
961
-
962
- def extract_block(start: int, end: Optional[int]) -> Dict:
963
- time_slice = dates[start:end]
964
- if not time_slice:
965
- return {}
966
- block = {"time": time_slice}
967
- for var in WEATHER_VARIABLES:
968
- block[var] = daily.get(var, [])[start:end]
969
- return block
970
-
971
- historical = extract_block(0, 7)
972
- today = extract_block(7, 8)
973
- forecast = extract_block(8, None)
974
-
975
- units = raw_data.get("daily_units", {}) or {}
976
- units_filtered = {k: v for k, v in units.items() if k != "time"}
977
-
978
- normalized = {
979
- "meta": {
980
- "location": {
981
- "latitude": raw_data.get("latitude", lat),
982
- "longitude": raw_data.get("longitude", lon),
983
- "timezone": timezone_str,
984
- "elevation_m": raw_data.get("elevation"),
985
- },
986
- "client_date": client_date,
987
- "location_date": location_date,
988
- "analysis_period": {
989
- "historical": f"{len(historical.get('time', []))} days",
990
- "forecast": f"{len(forecast.get('time', []))} days",
991
- "anchor_date": client_date,
992
- },
993
- },
994
- "units": units_filtered,
995
- "historical": historical,
996
- "today": today,
997
- "forecast": forecast,
998
- }
999
- normalized["derived_features"] = engineer_weather_features(normalized)
1000
- return normalized, ""
1001
-
1002
- except Exception as e:
1003
- logger.error(f"Normalization error: {e}")
1004
- return None, "Failed to process weather data. Please try again later."
1005
-
1006
-
1007
- # ------------------------------------------------------------------
1008
- # LLM ENGINE
1009
- # ------------------------------------------------------------------
1010
- DERIVED_FEATURE_GUIDE = {
1011
- "temperature_range_c": "Daily maximum temperature minus minimum temperature.",
1012
- "dewpoint_depression_proxy_c": "Mean air temperature minus mean dewpoint.",
1013
- "water_balance_proxy_mm": "Precipitation minus reference ET0; not soil water balance.",
1014
- "precipitation_per_wet_hour_proxy":
1015
- "Daily precipitation divided by precipitation hours; not peak rainfall intensity.",
1016
- "humidity_wetness_interaction":
1017
- "Relative humidity fraction multiplied by leaf-wetness probability fraction; not disease probability.",
1018
- "wetness_duration_interaction":
1019
- "Leaf-wetness probability multiplied by precipitation hours divided by 24; "
1020
- "not measured leaf-wetness duration.",
1021
- "dry_spell_days":
1022
- "Consecutive days with precipitation at or below 0.1 mm; not a crop-specific drought threshold.",
1023
- "rolling_features":
1024
- "Trailing 3-day and 7-day sums or means. Windows span the continuous history, today, "
1025
- "and forecast timeline.",
1026
- "delta_vs_history7d":
1027
- "Forecast daily value minus the mean of available historical daily values over the previous 7 days.",
1028
- "forecast_minus_history":
1029
- "Difference between the 7-day forecast summary and the 7-day historical summary.",
1030
- "probability_fraction":
1031
- "Normalized to a 0-1 scale when the source unit is percent. Null means unavailable, not zero.",
1032
- }
1033
-
1034
-
1035
- def build_llm_payload(normalized_data: Dict, lat: float, lon: float, client_date: str,
1036
- crop: str = "", phenology: str = "", notes: str = "",
1037
- current_concern: str = "", has_image: bool = False) -> Dict:
1038
- meta = normalized_data.get("meta", {})
1039
- location = meta.get("location", {})
1040
- tz = location.get("timezone", "UTC")
1041
- return {
1042
- "location": {"latitude": lat, "longitude": lon, "timezone": tz},
1043
- "field_context": {
1044
- "crop_type": crop or "Tidak ditentukan",
1045
- "phenology_phase": phenology or "Tidak ditentukan",
1046
- "field_notes": notes or "Tidak ada catatan khusus",
1047
- "current_concern": current_concern or "Tidak ada concern khusus",
1048
- },
1049
- "user_image": {
1050
- "provided": has_image,
1051
- "note": "Foto lahan/tanaman dari pengguna terlampir (dikompresi, belum diverifikasi). "
1052
- "Analisis foto lebih dulu sesuai bagian 3A."
1053
- if has_image else "Tidak ada foto yang dianalisis.",
1054
- },
1055
- "analysis_period": {
1056
- "historical": meta.get("analysis_period", {}).get("historical", "7 days"),
1057
- "forecast": meta.get("analysis_period", {}).get("forecast", "7 days"),
1058
- "anchor_date": client_date,
1059
- "anchor_type": "client_time",
1060
- "location_date": meta.get("location_date", client_date),
1061
- "location_timezone": tz,
1062
- },
1063
- "units": normalized_data.get("units", {}),
1064
- "derived_features": normalized_data.get("derived_features", {}),
1065
- "derived_feature_guide": DERIVED_FEATURE_GUIDE,
1066
- "historical": {"daily": normalized_data.get("historical", {})},
1067
- "today": {"daily": normalized_data.get("today", {})},
1068
- "forecast": {"daily": normalized_data.get("forecast", {})},
1069
- }
1070
-
1071
-
1072
- def _build_messages(system_prompt: str, payload: Dict, image_data_url: Optional[str]) -> List[Dict]:
1073
- text = "Weather data for analysis:\n\n" + json.dumps(
1074
- payload, ensure_ascii=False, separators=(",", ":")
1075
- )
1076
- if image_data_url:
1077
- user_content: Any = [
1078
- {"type": "text", "text": text},
1079
- {"type": "image_url", "image_url": {"url": image_data_url}},
1080
- ]
1081
- else:
1082
- user_content = text
1083
- return [
1084
- {"role": "system", "content": system_prompt},
1085
- {"role": "user", "content": user_content},
1086
- ]
1087
-
1088
-
1089
- def _extract_json(content: str) -> Dict:
1090
- m = re.search(r"```(?:json)?\s*([\s\S]*?)\s*```", content)
1091
- if m:
1092
- content = m.group(1)
1093
- content = content.strip()
1094
- start, end = content.find("{"), content.rfind("}")
1095
- if start != -1 and end != -1:
1096
- content = content[start:end + 1]
1097
- return json.loads(content)
1098
-
1099
-
1100
- def call_gemini(payload: Dict, image_data_url: Optional[str] = None) -> Tuple[Optional[Dict], str, bool]:
1101
- """Return (hasil, error, image_used). image_used=False jika foto tidak jadi dikirim."""
1102
- system_prompt = get_system_prompt()
1103
- if not system_prompt:
1104
- return None, "System prompt file is missing or empty. Please check prompts/system_prompt.txt", False
1105
-
1106
- use_image = bool(image_data_url)
1107
- messages = _build_messages(system_prompt, payload, image_data_url)
1108
- last_error_msg = "Unknown error"
1109
- deadline = time.monotonic() + GEMINI_TOTAL_BUDGET_S
1110
-
1111
- for attempt in range(GEMINI_MAX_ROUNDS):
1112
- saw_rpm = False
1113
-
1114
- for key in key_manager.get_rotation_order():
1115
- if time.monotonic() > deadline:
1116
- last_error_msg = "Batas waktu analisis terlampaui."
1117
- break
1118
- if not key_manager._is_available(key):
1119
- continue
1120
-
1121
- try:
1122
- response = completion(
1123
- model=GEMINI_MODEL,
1124
- messages=messages,
1125
- api_key=key,
1126
- temperature=1.0,
1127
- max_tokens=GEMINI_MAX_TOKENS,
1128
- timeout=GEMINI_TIMEOUT_IMAGE_S if use_image else GEMINI_TIMEOUT_S,
1129
- )
1130
- return _extract_json(response.choices[0].message.content), "", use_image
1131
-
1132
- except json.JSONDecodeError as e:
1133
- logger.error(f"JSON decode error: {e}")
1134
- return None, "Analysis could not be validated. Please try again. (Invalid JSON)", use_image
1135
-
1136
- except Exception as e:
1137
- kind = classify_gemini_error(e)
1138
- logger.warning(f"Key ...{key[-6:]} gagal ({kind}): {e}")
1139
- if kind == "rpd":
1140
- key_manager.mark_rpd_exhausted(key)
1141
- last_error_msg = "Satu atau lebih API key mencapai limit harian."
1142
- elif kind == "rpm":
1143
- saw_rpm = True
1144
- last_error_msg = "Key sedang sibuk (limit per menit)."
1145
- else:
1146
- last_error_msg = str(e)
1147
- if use_image: # mungkin gambar yang ditolak -> coba tanpa gambar
1148
- use_image = False
1149
- payload = {**payload, "user_image": NO_IMAGE_FALLBACK}
1150
- messages = _build_messages(system_prompt, payload, None)
1151
-
1152
- if not saw_rpm or time.monotonic() > deadline:
1153
- break
1154
- time.sleep(2 * (attempt + 1) + random.random()) # backoff + jitter
1155
-
1156
- return None, (
1157
- "Weather data was retrieved, but the analysis could not be generated. "
1158
- f"Semua API key gagal atau kena limit. ({last_error_msg})"
1159
- ), False
1160
-
1161
-
1162
- def validate_llm_output(output: Any) -> Tuple[bool, str]:
1163
- if not isinstance(output, dict):
1164
- return False, "Analysis could not be validated. Invalid output format."
1165
-
1166
- for field in ["summary", "historical", "forecast", "risks", "recommendations", "overall_confidence"]:
1167
- if field not in output:
1168
- return False, f"Analysis could not be validated. Missing field: {field}"
1169
-
1170
- for name in ("historical", "forecast"):
1171
- block = output.get(name)
1172
- if not isinstance(block, dict):
1173
- return False, f"Analysis could not be validated. Invalid {name} format."
1174
- if "condition" not in block or "impact" not in block:
1175
- return False, f"Analysis could not be validated. {name.title()} missing condition or impact."
1176
-
1177
- if not isinstance(output["risks"], list):
1178
- return False, "Analysis could not be validated. Invalid risks format."
1179
- for i, risk in enumerate(output["risks"]):
1180
- if not isinstance(risk, dict):
1181
- return False, f"Analysis could not be validated. Invalid risk at index {i}."
1182
- for rf in ["title", "description", "evidence", "period", "severity"]:
1183
- if rf not in risk:
1184
- return False, f"Analysis could not be validated. Risk {i} missing field: {rf}"
1185
- if risk.get("severity") not in VALID_SEVERITY:
1186
- return False, f"Analysis could not be validated. Invalid severity: {risk.get('severity')}"
1187
-
1188
- if not isinstance(output["recommendations"], list):
1189
- return False, "Analysis could not be validated. Invalid recommendations format."
1190
- for i, rec in enumerate(output["recommendations"]):
1191
- if not isinstance(rec, dict):
1192
- return False, f"Analysis could not be validated. Invalid recommendation at index {i}."
1193
- for rf in ["action", "reason", "priority"]:
1194
- if rf not in rec:
1195
- return False, f"Analysis could not be validated. Recommendation {i} missing field: {rf}"
1196
- if rec.get("priority") not in VALID_PRIORITY:
1197
- return False, f"Analysis could not be validated. Invalid priority: {rec.get('priority')}"
1198
-
1199
- if output.get("overall_confidence") not in VALID_CONFIDENCE:
1200
- return False, "Analysis could not be validated. Invalid overall_confidence."
1201
-
1202
- return True, ""
1203
-
1204
-
1205
- def _clean_str(value: Any, max_chars: int = 600) -> str:
1206
- return re.sub(r"\s+", " ", str(value or "")).strip()[:max_chars]
1207
-
1208
-
1209
- def sanitize_photo_assessment(output: Dict, image_used: bool, has_concern: bool,
1210
- image_dropped: bool = False) -> None:
1211
- """
1212
- Rapikan photo_assessment dan concern_answer. TIDAK PERNAH menggagalkan analisis:
1213
- nilai tak valid diperbaiki secara konservatif. Dipanggil setelah validate_llm_output lolos.
1214
- """
1215
- output["concern_answer"] = _clean_str(output.get("concern_answer"), 900) if has_concern else ""
1216
-
1217
- empty = {
1218
- "photo_status": "not_provided",
1219
- "image_quality_note": "",
1220
- "visible_observations": [],
1221
- "hypotheses": [],
1222
- "limitations": "",
1223
- }
1224
-
1225
- if image_dropped: # pengguna mengunggah foto, tetapi tidak jadi dianalisis
1226
- empty["photo_status"] = "unusable"
1227
- empty["image_quality_note"] = (
1228
- "Foto tidak dapat diproses atau ditolak, sehingga analisis hanya memakai data cuaca dan catatan Anda."
1229
- )
1230
- output["photo_assessment"] = empty
1231
- return
1232
-
1233
- pa = output.get("photo_assessment")
1234
- if not image_used or not isinstance(pa, dict):
1235
- output["photo_assessment"] = empty
1236
- return
1237
-
1238
- status = pa.get("photo_status")
1239
- if status not in VALID_PHOTO_STATUS or status == "not_provided":
1240
- status = "limited" # foto ada tetapi status tidak valid -> perlakukan sebagai terbatas
1241
-
1242
- observations = pa.get("visible_observations")
1243
- observations = [_clean_str(o, 300) for o in observations] if isinstance(observations, list) else []
1244
- observations = [o for o in observations if o][:MAX_OBSERVATIONS]
1245
-
1246
- hypotheses = []
1247
- if status in ("usable", "limited"):
1248
- raw_h = pa.get("hypotheses")
1249
- for h in (raw_h if isinstance(raw_h, list) else [])[:MAX_HYPOTHESES]:
1250
- if not isinstance(h, dict) or not _clean_str(h.get("name")):
1251
- continue
1252
- likelihood = h.get("likelihood") if h.get("likelihood") in VALID_LIKELIHOOD else "low"
1253
- if status != "usable" and likelihood == "high":
1254
- likelihood = "medium" # pagar keamanan: foto terbatas tidak boleh 'high'
1255
- hypotheses.append({
1256
- "category": h.get("category") if h.get("category") in VALID_CATEGORY else "unclear",
1257
- "name": _clean_str(h.get("name"), 120),
1258
- "likelihood": likelihood,
1259
- "visual_evidence": _clean_str(h.get("visual_evidence"), 400),
1260
- "weather_link": _clean_str(h.get("weather_link"), 400),
1261
- "how_to_verify": _clean_str(h.get("how_to_verify"), 400),
1262
- })
1263
-
1264
- output["photo_assessment"] = {
1265
- "photo_status": status,
1266
- "image_quality_note": _clean_str(pa.get("image_quality_note"), 300),
1267
- "visible_observations": observations if status != "unusable" else [],
1268
- "hypotheses": hypotheses,
1269
- "limitations": _clean_str(pa.get("limitations"), 400),
1270
- }
1271
-
1272
-
1273
- # ------------------------------------------------------------------
1274
- # EXPORT
1275
- # ------------------------------------------------------------------
1276
- def cleanup_exports(max_age_s: int = EXPORT_MAX_AGE_S) -> None:
1277
- """Hapus file export lama agar /tmp tidak penuh."""
1278
- try:
1279
- now = time.time()
1280
- for name in os.listdir(EXPORT_DIR):
1281
- if not name.startswith("weather_analysis_"):
1282
- continue
1283
- path = os.path.join(EXPORT_DIR, name)
1284
- try:
1285
- if now - os.path.getmtime(path) > max_age_s:
1286
- os.remove(path)
1287
- except OSError:
1288
- pass
1289
- except FileNotFoundError:
1290
- pass
1291
- except Exception as e:
1292
- logger.warning(f"Export cleanup failed: {e}")
1293
-
1294
-
1295
- def build_export_file(cache_entry: Optional[Dict]) -> Optional[str]:
1296
- """
1297
- Satu file TXT berisi input pengguna, data cuaca mentah, fitur turunan,
1298
- dan hasil analisis Gemini, untuk dipakai sebagai context di LLM lain.
1299
- Foto pengguna TIDAK disertakan (memang tidak disimpan).
1300
- """
1301
- if not cache_entry:
1302
- return None
1303
-
1304
- location = cache_entry.get("location", {}) or {}
1305
- field_context = cache_entry.get("field_context", {}) or {}
1306
- analysis = cache_entry.get("analysis", {}) or {}
1307
-
1308
- lines: List[str] = [
1309
- "=== EXPORT DATA ANALISIS CUACA ===",
1310
- f"Dibuat pada : {datetime.now(timezone.utc).isoformat()}",
1311
- "Tujuan : Context data untuk analisis lanjutan",
1312
- "Sumber App : DigiTanist/tanam",
1313
- "",
1314
- "--- INPUT PENGGUNA ---",
1315
- f"Latitude : {location.get('latitude')}",
1316
- f"Longitude : {location.get('longitude')}",
1317
- f"Sumber lokasi : {location.get('source') or '-'}",
1318
- ]
1319
- if location.get("accuracy_m"):
1320
- lines.append(f"Akurasi GPS : {location.get('accuracy_m')} m")
1321
- lines += [
1322
- f"Tanggal analisis : {cache_entry.get('client_date')}",
1323
- f"Timezone lokasi : {cache_entry.get('location_timezone')}",
1324
- "",
1325
- "Konteks Lahan:",
1326
- f"- Jenis Tanaman : {field_context.get('crop_type') or '-'}",
1327
- f"- Fase Fenologi : {field_context.get('phenology_phase') or '-'}",
1328
- f"- Catatan Lapangan : {field_context.get('field_notes') or '-'}",
1329
- f"- Current Concern : {field_context.get('current_concern') or '-'}",
1330
- "",
1331
- "--- DATA CUACA MENTAH (Open-Meteo, historical 7 hari + forecast 7 hari) ---",
1332
- json.dumps(cache_entry.get("raw_weather", {}), ensure_ascii=False, indent=2),
1333
- "",
1334
- "--- FITUR CUACA TURUNAN ---",
1335
- json.dumps(cache_entry.get("derived_features", {}), ensure_ascii=False, indent=2),
1336
- "",
1337
- "--- HASIL ANALISIS GEMINI AI ---",
1338
- f"Ringkasan: {analysis.get('summary', '-')}",
1339
- "",
1340
- ]
1341
-
1342
- if analysis.get("concern_answer"):
1343
- lines += ["Jawaban atas Current Concern:", f" {analysis['concern_answer']}", ""]
1344
-
1345
- pa = analysis.get("photo_assessment")
1346
- if isinstance(pa, dict) and pa.get("photo_status") not in (None, "", "not_provided"):
1347
- lines.append(f"Analisis Foto (perkiraan, bukan diagnosis) - status: {pa.get('photo_status')}")
1348
- lines.append(" (Foto itu sendiri tidak disimpan maupun disertakan di file ini.)")
1349
- if pa.get("image_quality_note"):
1350
- lines.append(f" Catatan kualitas : {pa['image_quality_note']}")
1351
- for o in pa.get("visible_observations") or []:
1352
- lines.append(f" - Terlihat: {o}")
1353
- for i, h in enumerate(pa.get("hypotheses") or [], 1):
1354
- lines.append(
1355
- f" {i}. {h.get('name', '-')} [kategori: {h.get('category', '-')}, "
1356
- f"kemungkinan: {h.get('likelihood', '-')}]"
1357
- )
1358
- lines.append(f" Bukti visual : {h.get('visual_evidence', '-')}")
1359
- lines.append(f" Kaitan cuaca : {h.get('weather_link', '-')}")
1360
- lines.append(f" Cara memeriksa : {h.get('how_to_verify', '-')}")
1361
- if pa.get("limitations"):
1362
- lines.append(f" Keterbatasan : {pa['limitations']}")
1363
- lines.append("")
1364
-
1365
- hist = analysis.get("historical", {}) or {}
1366
- lines += [
1367
- "Historical (7 hari terakhir):",
1368
- f" Kondisi : {hist.get('condition', '-')}",
1369
- f" Dampak : {hist.get('impact', '-')}",
1370
- "",
1371
- ]
1372
-
1373
- fcst = analysis.get("forecast", {}) or {}
1374
- lines += [
1375
- "Forecast (7 hari ke depan):",
1376
- f" Kondisi : {fcst.get('condition', '-')}",
1377
- f" Dampak : {fcst.get('impact', '-')}",
1378
- "",
1379
- ]
1380
-
1381
- risks = [r for r in (analysis.get("risks") or []) if isinstance(r, dict)]
1382
- lines.append(f"Risiko ({len(risks)}):")
1383
- if risks:
1384
- for i, r in enumerate(risks, 1):
1385
- lines.append(f" {i}. {r.get('title', '-')} [severity: {r.get('severity', '-')}]")
1386
- lines.append(f" Deskripsi : {r.get('description', '-')}")
1387
- lines.append(f" Bukti : {r.get('evidence', '-')}")
1388
- lines.append(f" Periode : {r.get('period', '-')}")
1389
- else:
1390
- lines.append(" Tidak ada risiko signifikan.")
1391
- lines.append("")
1392
-
1393
- recs = analysis.get("recommendations") or []
1394
- lines.append(f"Rekomendasi ({len(recs)}):")
1395
- if recs:
1396
- for i, r in enumerate(recs, 1):
1397
- if isinstance(r, str):
1398
- lines.append(f" {i}. {r}")
1399
- continue
1400
- lines.append(f" {i}. {r.get('action', '-')} [priority: {r.get('priority', '-')}]")
1401
- lines.append(f" Alasan : {r.get('reason', '-')}")
1402
- else:
1403
- lines.append(" Tidak ada tindakan khusus diperlukan.")
1404
- lines += ["", f"Overall Confidence: {analysis.get('overall_confidence', '-')}"]
1405
-
1406
- try:
1407
- os.makedirs(EXPORT_DIR, exist_ok=True)
1408
- cleanup_exports()
1409
- date_tag = (cache_entry.get("client_date") or "unknown").replace("-", "")
1410
- path = os.path.join(EXPORT_DIR, f"weather_analysis_{date_tag}_{uuid.uuid4().hex[:8]}.txt")
1411
- with open(path, "w", encoding="utf-8") as f:
1412
- f.write("\n".join(lines))
1413
- return path
1414
- except Exception as e:
1415
- logger.error(f"Failed to build export file: {e}")
1416
- return None
1417
-
1418
-
1419
- # ------------------------------------------------------------------
1420
- # MAIN HANDLERS
1421
- # ------------------------------------------------------------------
1422
- def init_app(composite_json: str):
1423
- cache_entry = None
1424
- browser_date = None
1425
- browser_timezone = "UTC"
1426
-
1427
- if composite_json and composite_json.strip() and composite_json != "{}":
1428
- try:
1429
- parsed = json.loads(composite_json)
1430
- if isinstance(parsed, dict):
1431
- if "browser_date" in parsed: # format baru (composite dari JS)
1432
- cache_raw = parsed.get("cache", "{}")
1433
- browser_date = parsed.get("browser_date")
1434
- browser_timezone = parsed.get("browser_timezone", "UTC")
1435
- if isinstance(cache_raw, str) and cache_raw.strip() and cache_raw != "{}":
1436
- cache_parsed = json.loads(cache_raw)
1437
- if isinstance(cache_parsed, dict) and "analysis" in cache_parsed:
1438
- cache_entry = cache_parsed
1439
- elif "analysis" in parsed: # format lama
1440
- cache_entry = parsed
1441
- except Exception:
1442
- cache_entry = None
1443
-
1444
- if not browser_date:
1445
- browser_date = datetime.now().strftime("%Y-%m-%d")
1446
- browser_timezone = "UTC"
1447
-
1448
- # Bandingkan cache dengan TANGGAL BROWSER, bukan tanggal server
1449
- today_cache = cache_entry if (cache_entry and cache_entry.get("client_date") == browser_date) else None
1450
-
1451
- state = AppState(
1452
- state=STATE_READY,
1453
- client_date=browser_date,
1454
- client_timezone=browser_timezone,
1455
- browser_date=browser_date,
1456
- browser_timezone=browser_timezone,
1457
- cache=today_cache,
1458
- )
1459
-
1460
- if today_cache:
1461
- state.state = STATE_LOCKED_TODAY
1462
- location = today_cache.get("location") or {}
1463
- state.location = location or None
1464
- analysis = today_cache.get("analysis", {})
1465
- return (
1466
- state.to_dict(),
1467
- location.get("latitude", 0), location.get("longitude", 0),
1468
- gr.update(interactive=False), gr.update(interactive=False),
1469
- format_status(STATE_LOCKED_TODAY, "Today's analysis already exists."),
1470
- "",
1471
- format_cache_info(today_cache),
1472
- gr.update(visible=False),
1473
- gr.update(visible=True),
1474
- gr.update(visible=False),
1475
- *render_all_tabs(analysis),
1476
- gr.update(value=""),
1477
- )
1478
-
1479
- return (
1480
- state.to_dict(), 0, 0,
1481
- gr.update(interactive=True), gr.update(interactive=False),
1482
- format_status(STATE_READY),
1483
- "",
1484
- "",
1485
- gr.update(visible=True),
1486
- gr.update(visible=False),
1487
- gr.update(visible=False),
1488
- *render_all_tabs({}),
1489
- gr.update(value=""),
1490
- )
1491
-
1492
-
1493
- def handle_gps_result(gps_json: str, state_dict: Dict):
1494
- state = AppState.from_dict(state_dict)
1495
-
1496
- if not gps_json:
1497
- return state.to_dict(), 0, 0, format_status(STATE_ERROR, "No location data received.")
1498
-
1499
- try:
1500
- data = json.loads(gps_json)
1501
- except Exception:
1502
- return state.to_dict(), 0, 0, format_status(STATE_ERROR, "Invalid location data.")
1503
-
1504
- if "error" in data:
1505
- return state.to_dict(), 0, 0, format_status(STATE_ERROR, data["error"])
1506
-
1507
- lat = data.get("latitude")
1508
- lon = data.get("longitude")
1509
- source = data.get("source", "unknown")
1510
- accuracy = data.get("accuracy_m")
1511
-
1512
- valid, msg = validate_coordinates(lat, lon)
1513
- if not valid:
1514
- return state.to_dict(), 0, 0, format_status(STATE_ERROR, msg)
1515
-
1516
- state.location = {"latitude": lat, "longitude": lon, "source": source, "accuracy_m": accuracy}
1517
- state.state = STATE_LOCATION_READY
1518
- return state.to_dict(), lat, lon, format_location_status(source, accuracy)
1519
-
1520
-
1521
- def _analysis_pipeline(state: AppState, weather_json_str: str, lat, lon, crop, phenology,
1522
- notes, current_concern, image_path):
1523
- """Generator utama. `state` dimutasi di sini dan dikirim balik lewat yield."""
1524
-
1525
- # --- Input kosong: tidak ada yang diubah ---
1526
- if not weather_json_str:
1527
- yield (state.to_dict(),) + tuple(gr.update() for _ in range(14))
1528
- return
1529
-
1530
- # --- Sudah ada analisis hari ini: jangan jalankan lagi ---
1531
- client_date = state.browser_date or datetime.now().strftime("%Y-%m-%d")
1532
- state.client_date = client_date
1533
- existing = state.cache
1534
- if existing and existing.get("client_date") == client_date:
1535
- state.state = STATE_LOCKED_TODAY
1536
- yield ui_outputs(
1537
- state, lock_inputs=True,
1538
- status=format_status(STATE_LOCKED_TODAY, "Today's analysis already exists."),
1539
- cache_info=format_cache_info(existing),
1540
- show_placeholder=False, show_view_btn=True,
1541
- tabs=render_all_tabs(existing.get("analysis", {})),
1542
- )
1543
- return
1544
-
1545
- if state.is_analyzing:
1546
- yield (state.to_dict(),) + tuple(gr.update() for _ in range(14))
1547
- return
1548
-
1549
- # --- Parse & validasi data cuaca dari browser ---
1550
- try:
1551
- raw_weather = json.loads(weather_json_str)
1552
- except Exception as exc:
1553
- yield error_outputs(state, STATE_FETCHING_WEATHER, f"Failed to parse weather data: {exc}")
1554
- return
1555
-
1556
- if isinstance(raw_weather, dict) and "error" in raw_weather:
1557
- err = raw_weather.get("reason") or raw_weather["error"]
1558
- yield error_outputs(state, STATE_FETCHING_WEATHER, str(err))
1559
- return
1560
-
1561
- valid_weather = validate_weather_payload(raw_weather)
1562
- if valid_weather:
1563
- yield error_outputs(state, STATE_FETCHING_WEATHER, valid_weather)
1564
- return
1565
- raw_weather.pop("_client_ts", None)
1566
-
1567
- valid_coords, coord_msg = validate_coordinates(lat, lon)
1568
- if not valid_coords:
1569
- yield error_outputs(state, STATE_FETCHING_WEATHER, coord_msg)
1570
- return
1571
-
1572
- # Batasi panjang input teks bebas (hemat token, mempersulit prompt injection)
1573
- crop = _clean_str(crop, MAX_SHORT_CHARS)
1574
- phenology = _clean_str(phenology, MAX_SHORT_CHARS)
1575
- notes = _clean_str(notes, MAX_LONG_CHARS)
1576
- current_concern = _clean_str(current_concern, MAX_LONG_CHARS)
1577
-
1578
- prev = state.location or {}
1579
- state.location = {
1580
- "latitude": lat,
1581
- "longitude": lon,
1582
- "source": prev.get("source", "manual"),
1583
- "accuracy_m": prev.get("accuracy_m"),
1584
- }
1585
- state.is_analyzing = True
1586
-
1587
- # --- Step 2: proses data + foto ---
1588
- yield progress_outputs(
1589
- state, STATE_PROCESSING_DATA, "Processing weather data",
1590
- "Splitting historical and forecast windows and computing derived indices.",
1591
- )
1592
-
1593
- normalized, norm_error = normalize_weather_data(raw_weather, lat, lon, client_date)
1594
- if norm_error:
1595
- yield error_outputs(state, STATE_PROCESSING_DATA, norm_error)
1596
- return
1597
-
1598
- image_data_url, image_err = compress_image_to_data_url(image_path)
1599
- if image_err:
1600
- logger.info(f"Lanjut tanpa foto: {image_err}")
1601
-
1602
- # --- Step 3: Gemini ---
1603
- yield progress_outputs(
1604
- state, STATE_GENERATING_INSIGHT, "Generating weather insight",
1605
- "Gemini is interpreting the data for risks and recommendations.",
1606
- )
1607
-
1608
- payload = build_llm_payload(
1609
- normalized, lat, lon, client_date, crop, phenology, notes, current_concern,
1610
- has_image=bool(image_data_url),
1611
- )
1612
- llm_output, gemini_error, image_used = call_gemini(payload, image_data_url)
1613
- image_data_url = None # lepas dari memori
1614
- payload = None
1615
-
1616
- if gemini_error:
1617
- yield error_outputs(state, STATE_GENERATING_INSIGHT, gemini_error)
1618
- return
1619
-
1620
- # --- Step 4: validasi ---
1621
- yield progress_outputs(
1622
- state, STATE_VALIDATING_OUTPUT, "Validating analysis",
1623
- "Checking the response against the expected schema.",
1624
- )
1625
-
1626
- valid, val_error = validate_llm_output(llm_output)
1627
- if not valid:
1628
- yield error_outputs(state, STATE_VALIDATING_OUTPUT, val_error)
1629
- return
1630
- sanitize_photo_assessment(
1631
- llm_output,
1632
- image_used=image_used,
1633
- has_concern=bool(current_concern),
1634
- image_dropped=bool(image_path) and not image_used,
1635
- )
1636
-
1637
- # --- Selesai: simpan SATU entry cache (tanpa foto) ---
1638
- cache_entry = {
1639
- "location": state.location,
1640
- "client_date": client_date,
1641
- "location_date": normalized.get("meta", {}).get("location_date", client_date),
1642
- "location_timezone": raw_weather.get("timezone", "UTC"),
1643
- "client_timezone": state.client_timezone or "UTC",
1644
- "field_context": {
1645
- "crop_type": crop,
1646
- "phenology_phase": phenology,
1647
- "field_notes": notes,
1648
- "current_concern": current_concern,
1649
- },
1650
- "raw_weather": raw_weather,
1651
- "derived_features": normalized.get("derived_features", {}),
1652
- "analysis": llm_output,
1653
- "created_at": datetime.now(timezone.utc).isoformat(),
1654
- }
1655
- state.cache = cache_entry
1656
- state.is_analyzing = False
1657
- cache_json = json.dumps(cache_entry)
1658
- tabs = render_all_tabs(llm_output)
1659
-
1660
- state.state = STATE_COMPLETED
1661
- yield ui_outputs(
1662
- state, lock_inputs=True,
1663
- status=format_status(STATE_COMPLETED), step=format_progress(STATE_COMPLETED),
1664
- cache_info=format_cache_info(cache_entry),
1665
- show_placeholder=False, show_view_btn=True, tabs=tabs, cache_json=cache_json,
1666
- )
1667
-
1668
- state.state = STATE_LOCKED_TODAY
1669
- yield ui_outputs(
1670
- state, lock_inputs=True,
1671
- status=format_status(STATE_LOCKED_TODAY, "Today's analysis complete. Return tomorrow for a new analysis."),
1672
- cache_info=format_cache_info(cache_entry),
1673
- show_placeholder=False, show_view_btn=True, tabs=tabs, cache_json=cache_json,
1674
- )
1675
-
1676
-
1677
- def handle_weather_and_analyze(weather_json_str: str, lat: float, lon: float, crop: str,
1678
- phenology: str, notes: str, current_concern: str,
1679
- image_path: Optional[str], state_dict: Dict):
1680
- state = AppState.from_dict(state_dict)
1681
- try:
1682
- yield from _analysis_pipeline(
1683
- state, weather_json_str, lat, lon, crop, phenology, notes, current_concern, image_path
1684
- )
1685
- except Exception:
1686
- logger.exception("Unexpected error in analysis pipeline")
1687
- yield error_outputs(state, state.state, "Terjadi kesalahan tak terduga. Silakan coba lagi.")
1688
-
1689
-
1690
- # ------------------------------------------------------------------
1691
- # GRADIO UI (Gradio 6.x compatible)
1692
- # ------------------------------------------------------------------
1693
- THEME = gr.themes.Base(
1694
- font=[gr.themes.GoogleFont("IBM Plex Sans"), "sans-serif"],
1695
- font_mono=[gr.themes.GoogleFont("IBM Plex Mono"), "monospace"],
1696
- ).set(
1697
- body_background_fill="#0B1B22",
1698
- body_background_fill_dark="#0B1B22",
1699
- body_text_color="#E7F1F0",
1700
- body_text_color_dark="#E7F1F0",
1701
- body_text_color_subdued="#7E9CA3",
1702
- body_text_color_subdued_dark="#7E9CA3",
1703
- background_fill_primary="#122631",
1704
- background_fill_primary_dark="#122631",
1705
- background_fill_secondary="#0F2229",
1706
- background_fill_secondary_dark="#0F2229",
1707
- border_color_primary="#23414F",
1708
- border_color_primary_dark="#23414F",
1709
- block_background_fill="#122631",
1710
- block_background_fill_dark="#122631",
1711
- block_border_color="#23414F",
1712
- block_border_color_dark="#23414F",
1713
- block_label_text_color="#7E9CA3",
1714
- block_label_text_color_dark="#7E9CA3",
1715
- block_label_background_fill="#122631",
1716
- block_label_background_fill_dark="#122631",
1717
- block_title_text_color="#E7F1F0",
1718
- block_title_text_color_dark="#E7F1F0",
1719
- panel_background_fill="#0F2229",
1720
- panel_background_fill_dark="#0F2229",
1721
- panel_border_color="#23414F",
1722
- panel_border_color_dark="#23414F",
1723
- input_background_fill="#0F2229",
1724
- input_background_fill_dark="#0F2229",
1725
- input_border_color="#23414F",
1726
- input_border_color_dark="#23414F",
1727
- input_border_color_focus="#E8A33D",
1728
- input_border_color_focus_dark="#E8A33D",
1729
- button_primary_background_fill="#E8A33D",
1730
- button_primary_background_fill_dark="#E8A33D",
1731
- button_primary_background_fill_hover="#F2B457",
1732
- button_primary_background_fill_hover_dark="#F2B457",
1733
- button_primary_text_color="#0B1B22",
1734
- button_primary_text_color_dark="#0B1B22",
1735
- button_primary_border_color="#E8A33D",
1736
- button_primary_border_color_dark="#E8A33D",
1737
- button_secondary_background_fill="#16303D",
1738
- button_secondary_background_fill_dark="#16303D",
1739
- button_secondary_background_fill_hover="#1B3945",
1740
- button_secondary_background_fill_hover_dark="#1B3945",
1741
- button_secondary_text_color="#E7F1F0",
1742
- button_secondary_text_color_dark="#E7F1F0",
1743
- button_secondary_border_color="#23414F",
1744
- button_secondary_border_color_dark="#23414F",
1745
- error_background_fill="#2A1714",
1746
- error_background_fill_dark="#2A1714",
1747
- error_border_color="#E2604F",
1748
- error_border_color_dark="#E2604F",
1749
- )
1750
-
1751
- # ------------------------------------------------------------------
1752
- # EXTERNAL ASSETS
1753
- # ------------------------------------------------------------------
1754
- CSS = load_text("assets/styles.css")
1755
- SPONSORS_RAW = load_json("assets/sponsors.json")
1756
- SPONSOR_HTML = render_sponsors_html(SPONSORS_RAW.get("sponsors", []))
1757
-
1758
- HEADER_HTML = """
1759
- <div class="hero-banner">
1760
- <div class="app-header">
1761
- <div class="eyebrow">Field Telemetry &middot; Weather Intelligence</div>
1762
- <h1>DigiTanist/tanam</h1>
1763
- <p class="subtitle">Cegah kerugian akibat cuaca buruk lebih lewat pantauan risiko harian berbasis rekam jejak dan prakiraan cuaca 14 hari. Ditenagai BMKG dan Gemini AI.</p>
1764
- </div>
1765
-
1766
- <div class="farmer-counter">
1767
- <span class="farmer-counter-badge">
1768
- <span class="farmer-counter-dot"></span>
1769
- <span><strong id="farmer-count">—</strong> petani sudah menganalisis hari ini</span>
1770
- </span>
1771
- </div>
1772
- </div>
1773
- """
1774
-
1775
- FOOTER_HTML = """
1776
- <div class="app-footer">DATA &middot; OPEN-METEO&nbsp;&nbsp;|&nbsp;&nbsp;ANALYSIS &middot; GEMINI&nbsp;&nbsp;|&nbsp;&nbsp;ONE READ PER DAY</div>
1777
- """
1778
-
1779
- IMAGE_NOTE_HTML = (
1780
- '<div style="font-size:12px;color:#7E9CA3;margin:-4px 2px 8px;line-height:1.4;">'
1781
- 'Opsional. Foto close-up daun yang bermasalah dengan cahaya cukup dan fokus tajam; '
1782
- 'sertakan juga foto tanaman utuh jika bisa. Foto dikompres lalu dikirim ke Gemini hanya '
1783
- 'untuk analisis ini, tidak disimpan permanen dan tidak masuk file export. '
1784
- 'Hasil analisis foto berupa perkiraan, bukan diagnosis.'
1785
- '</div>'
1786
- )
1787
-
1788
- GA4_HEAD = """
1789
- <!-- Google tag (gtag.js) -->
1790
- <script async src="https://www.googletagmanager.com/gtag/js?id=G-VWC31N398K"></script>
1791
- <script>
1792
- window.dataLayer = window.dataLayer || [];
1793
- function gtag(){dataLayer.push(arguments);}
1794
- gtag('js', new Date());
1795
- gtag('config', 'G-VWC31N398K');
1796
- </script>
1797
-
1798
- <script>
1799
- function getTodayFarmerCount() {
1800
- // ====================== PENGATURAN ANGKA ======================
1801
- const BASE_MIN = 220;
1802
- const BASE_MAX = 380;
1803
- const INCREASE_PER_10_MIN = 2; // Jumlah penambahan setiap 10 menit (bisa disesuaikan)
1804
- // ==============================================================
1805
-
1806
- const now = new Date();
1807
-
1808
- const today = now.getFullYear() + '-' +
1809
- String(now.getMonth() + 1).padStart(2, '0') + '-' +
1810
- String(now.getDate()).padStart(2, '0');
1811
-
1812
- let seed = 0;
1813
- for (let i = 0; i < today.length; i++) {
1814
- seed = (seed * 31 + today.charCodeAt(i)) & 0xffff;
1815
- }
1816
-
1817
- const base = BASE_MIN + (seed % (BASE_MAX - BASE_MIN + 1));
1818
- const totalMinutes = (now.getHours() * 60) + now.getMinutes();
1819
- const blocksOf10Min = Math.floor(totalMinutes / 10);
1820
- const extra = blocksOf10Min * INCREASE_PER_10_MIN;
1821
-
1822
- return base + extra;
1823
- }
1824
-
1825
- function animateCount(el, target, duration = 3300) {
1826
- const start = Math.max(0, target - Math.floor(target * 0.15)); // mulai dari ~85%
1827
- const startTime = performance.now();
1828
- function tick(now) {
1829
- const progress = Math.min((now - startTime) / duration, 1);
1830
- const eased = 1 - Math.pow(1 - progress, 3); // ease-out cubic
1831
- el.innerText = Math.round(start + (target - start) * eased).toLocaleString("id-ID");
1832
- if (progress < 1) requestAnimationFrame(tick);
1833
- }
1834
- requestAnimationFrame(tick);
1835
- }
1836
-
1837
- function updateFarmerCount() {
1838
- const el = document.getElementById("farmer-count");
1839
- if (el) {
1840
- animateCount(el, getTodayFarmerCount());
1841
- return true;
1842
- }
1843
- return false;
1844
- }
1845
-
1846
- // Coba terus sampai elemen muncul (maksimal 10 detik)
1847
- function tryUpdateCounter(attempts = 0) {
1848
- if (updateFarmerCount() || attempts > 20) return;
1849
- setTimeout(() => tryUpdateCounter(attempts + 1), 500);
1850
- }
1851
-
1852
- tryUpdateCounter();
1853
- setInterval(updateFarmerCount, 5 * 60 * 1000);
1854
- </script>
1855
- """
1856
-
1857
- LOAD_JS = """() => {
1858
- let cache = '{}';
1859
- try {
1860
- cache = localStorage.getItem('space_weather_cache') || '{}';
1861
- } catch (e) {
1862
- cache = '{}';
1863
- }
1864
- const now = new Date();
1865
- const browserDate = now.getFullYear() + '-' +
1866
- String(now.getMonth() + 1).padStart(2, '0') + '-' +
1867
- String(now.getDate()).padStart(2, '0');
1868
- const browserTz = Intl.DateTimeFormat().resolvedOptions().timeZone || 'UTC';
1869
- return JSON.stringify({
1870
- cache: cache,
1871
- browser_date: browserDate,
1872
- browser_timezone: browserTz
1873
- });
1874
- }"""
1875
-
1876
- GPS_JS = """
1877
- async () => {
1878
- const fail = () => JSON.stringify({
1879
- error: "Unable to determine your location. Please enter coordinates manually."
1880
- });
1881
- const fromIp = async () => {
1882
- try {
1883
- const resp = await fetch('https://ipwho.is/');
1884
- const data = await resp.json();
1885
- if (data.success) {
1886
- return JSON.stringify({
1887
- latitude: data.latitude, longitude: data.longitude,
1888
- source: "ip", accuracy_m: null
1889
- });
1890
- }
1891
- } catch (e) {}
1892
- return fail();
1893
- };
1894
- return new Promise((resolve) => {
1895
- if (!navigator.geolocation) {
1896
- fromIp().then(resolve);
1897
- return;
1898
- }
1899
- navigator.geolocation.getCurrentPosition(
1900
- (position) => resolve(JSON.stringify({
1901
- latitude: position.coords.latitude,
1902
- longitude: position.coords.longitude,
1903
- source: "gps",
1904
- accuracy_m: position.coords.accuracy
1905
- })),
1906
- () => { fromIp().then(resolve); },
1907
- {timeout: 10000, maximumAge: 60000}
1908
- );
1909
- });
1910
- }
1911
- """
1912
-
1913
- # Daftar variabel disuntik dari WEATHER_VARIABLES supaya JS dan Python selalu sinkron.
1914
- # `_client_ts` membuat setiap klik Analyze menghasilkan string unik, sehingga event
1915
- # `change` pada textbox tersembunyi selalu terpicu (juga saat mencoba ulang setelah error).
1916
- ANALYZE_JS = """async (lat, lon) => {
1917
- if (typeof gtag === 'function') {
1918
- gtag('event', 'analyze_click', {
1919
- 'event_category': 'engagement',
1920
- 'latitude': lat,
1921
- 'longitude': lon
1922
- });
1923
- }
1924
- const stamp = (obj) => JSON.stringify(Object.assign({}, obj, {_client_ts: Date.now()}));
1925
-
1926
- if (lat === null || lon === null || isNaN(lat) || isNaN(lon)) {
1927
- return stamp({ error: "Invalid coordinates. Please enter a valid latitude and longitude." });
1928
- }
1929
-
1930
- const variables = __VARS__.join(",");
1931
- const url = `https://api.open-meteo.com/v1/forecast?latitude=${lat}&longitude=${lon}&daily=${variables}&timezone=auto&past_days=7&forecast_days=7`;
1932
- try {
1933
- const resp = await fetch(url);
1934
- if (!resp.ok) {
1935
- return stamp({ error: `Weather data unavailable. Please try again later. (HTTP ${resp.status})` });
1936
- }
1937
- const data = await resp.json();
1938
- return stamp(data);
1939
- } catch (e) {
1940
- return stamp({ error: "Weather data unavailable. Network error. Please try again later." });
1941
- }
1942
- }""".replace("__VARS__", json.dumps(WEATHER_VARIABLES))
1943
-
1944
- VIEW_INSIGHT_JS = """() => {
1945
- if (typeof gtag === 'function') {
1946
- gtag('event', 'view_insight_click', {'event_category': 'engagement'});
1947
- }
1948
- }"""
1949
-
1950
- SAVE_CACHE_JS = """(data) => {
1951
- if (data && data !== '{}' && data !== '') {
1952
- try {
1953
- localStorage.setItem('space_weather_cache', data); // selalu timpa
1954
- } catch (e) {
1955
- console.error('Failed to save cache to localStorage:', e);
1956
- }
1957
- }
1958
- return [];
1959
- }"""
1960
-
1961
-
1962
- def show_insight_view(state_dict):
1963
- state = AppState.from_dict(state_dict)
1964
- has_cache = bool(state.cache)
1965
- modal_html = build_recommendation_modal(state.cache, skip_url=SHOPEE_LINK) if has_cache else ""
1966
- # Tombol download ditampilkan dulu tanpa file; href diisi di langkah berikutnya (.then)
1967
- # agar elemen sudah ter-mount dan klik pertama langsung bekerja.
1968
- return (
1969
- gr.update(visible=False),
1970
- gr.update(visible=True),
1971
- gr.update(visible=has_cache, value=None),
1972
- modal_html,
1973
- )
1974
-
1975
-
1976
- def prepare_download_file(state_dict):
1977
- state = AppState.from_dict(state_dict)
1978
- export_path = build_export_file(state.cache)
1979
- return gr.update(value=export_path, visible=bool(export_path))
1980
-
1981
-
1982
- def clear_image_after_success(state_dict):
1983
- """Lepas referensi foto setelah analisis sukses; biarkan jika gagal agar bisa dicoba lagi."""
1984
- if AppState.from_dict(state_dict).cache:
1985
- return gr.update(value=None)
1986
- return gr.update()
1987
-
1988
-
1989
- with gr.Blocks(title="Space Weather", head=GA4_HEAD, delete_cache=(600, 600)) as demo:
1990
-
1991
- gr.HTML(HEADER_HTML)
1992
-
1993
- app_state = gr.State({})
1994
- gps_data = gr.Textbox(visible=False, elem_id="gps_data_input")
1995
- cache_in = gr.Textbox(visible=False, elem_id="browser_cache_in")
1996
- cache_out = gr.Textbox(visible=False, elem_id="browser_cache_out")
1997
- weather_json = gr.Textbox(visible=False, elem_id="weather_json_input")
1998
-
1999
- with gr.Row(elem_classes=["main-row"]):
2000
- with gr.Column(scale=1, min_width=320, elem_classes=["rail-col"]):
2001
- with gr.Column(elem_classes=["console-panel"]):
2002
- gr.HTML('<div class="panel-eyebrow">Location</div>')
2003
-
2004
- lat_input = gr.Number(label="Latitude", precision=6, value=0, info="-90 to 90")
2005
- lon_input = gr.Number(label="Longitude", precision=6, value=0, info="-180 to 180")
2006
-
2007
- crop_input = gr.Textbox(
2008
- label="Jenis Tanaman",
2009
- placeholder="Contoh: Padi, Jagung, Cabai",
2010
- max_length=MAX_SHORT_CHARS,
2011
- lines=1,
2012
- )
2013
- phenology_input = gr.Textbox(
2014
- label="Fase Fenologi",
2015
- placeholder="Contoh: Vegetatif, Pembungaan, Pematangan",
2016
- max_length=MAX_SHORT_CHARS,
2017
- lines=1,
2018
- )
2019
- notes_input = gr.Textbox(
2020
- label="Catatan Lapangan",
2021
- placeholder="Contoh: Ada genangan air, gejala serangan hama ringan",
2022
- max_length=MAX_LONG_CHARS,
2023
- lines=2,
2024
- )
2025
- current_concern_input = gr.Textbox(
2026
- label="Current Concern",
2027
- placeholder="Contoh: Daun bawah cabai menguning, apakah karena hujan terus-menerus?",
2028
- max_length=MAX_LONG_CHARS,
2029
- info="Opsional. Tuliskan satu pertanyaan utama. Akan dijawab dari seluruh data: cuaca, catatan, dan foto.",
2030
- lines=2,
2031
- )
2032
-
2033
- # Foto opsional: filepath agar bisa didecode hemat memori (PIL draft)
2034
- image_input = gr.Image(
2035
- label="Foto Lahan/Tanaman (Opsional)",
2036
- type="filepath",
2037
- sources=["upload"],
2038
- height=200,
2039
- )
2040
- gr.HTML(IMAGE_NOTE_HTML)
2041
-
2042
- with gr.Row(elem_classes=["btn-row"]):
2043
- get_loc_btn = gr.Button("Ambil lokasi dari GPS perangkat", variant="secondary", size="sm")
2044
- analyze_btn = gr.Button("Analyze", variant="primary", size="sm", interactive=False)
2045
-
2046
- with gr.Column():
2047
- status_html = gr.HTML("")
2048
- step_html = gr.HTML("")
2049
- cache_html = gr.HTML("")
2050
-
2051
- with gr.Column(scale=2, elem_classes=["content-col"]):
2052
- initial_placeholder = gr.HTML(render_placeholder("Initializing", "Loading today's status..."))
2053
- view_insight_btn = gr.Button("View Insight", variant="primary", visible=False, size="lg")
2054
-
2055
- with gr.Column(visible=False) as tabs_container:
2056
- with gr.Tabs():
2057
- with gr.TabItem("Summary"):
2058
- summary_html = gr.HTML()
2059
- with gr.TabItem("Historical"):
2060
- historical_html = gr.HTML()
2061
- with gr.TabItem("Forecast"):
2062
- forecast_html = gr.HTML()
2063
- with gr.TabItem("Risks"):
2064
- risks_html = gr.HTML()
2065
- with gr.TabItem("Recommendations"):
2066
- recommendations_html = gr.HTML()
2067
-
2068
- download_data_btn = gr.DownloadButton(
2069
- "Download Data Analisis (TXT)",
2070
- visible=False,
2071
- size="md",
2072
- variant="secondary",
2073
- elem_classes=["download-data-btn"],
2074
- )
2075
-
2076
- gr.HTML('<div style="height: 16px;"></div>')
2077
- with gr.Column(elem_classes=["console-panel"]):
2078
- gr.HTML('<div class="panel-eyebrow" style="padding: 14px 14px 6px;">Supported By</div>')
2079
- gr.HTML(SPONSOR_HTML)
2080
-
2081
- modal_output = gr.HTML("", elem_id="modal-output")
2082
- gr.HTML(FOOTER_HTML)
2083
-
2084
- # 1. Page load: baca localStorage + waktu browser
2085
- demo.load(fn=None, js=LOAD_JS, outputs=cache_in)
2086
-
2087
- # 2. Inisialisasi app dari cache browser
2088
- cache_in.change(
2089
- fn=init_app,
2090
- inputs=[cache_in],
2091
- outputs=[
2092
- app_state, lat_input, lon_input, get_loc_btn, analyze_btn,
2093
- status_html, step_html, cache_html,
2094
- initial_placeholder, view_insight_btn, tabs_container,
2095
- summary_html, historical_html, forecast_html, risks_html, recommendations_html,
2096
- cache_out,
2097
- ],
2098
- )
2099
-
2100
- # 3. Lokasi: GPS -> fallback IP
2101
- get_loc_btn.click(fn=None, js=GPS_JS, outputs=gps_data)
2102
- gps_data.change(
2103
- fn=handle_gps_result,
2104
- inputs=[gps_data, app_state],
2105
- outputs=[app_state, lat_input, lon_input, status_html],
2106
- )
2107
-
2108
- # 4. Analyze: browser fetch Open-Meteo -> textbox tersembunyi -> server
2109
- analyze_btn.click(fn=None, js=ANALYZE_JS, inputs=[lat_input, lon_input], outputs=[weather_json])
2110
-
2111
- analysis_event = weather_json.change(
2112
- fn=handle_weather_and_analyze,
2113
- inputs=[
2114
- weather_json, lat_input, lon_input, crop_input, phenology_input,
2115
- notes_input, current_concern_input, image_input, app_state,
2116
- ],
2117
- outputs=[
2118
- app_state, get_loc_btn, analyze_btn,
2119
- status_html, step_html, cache_html,
2120
- initial_placeholder, view_insight_btn, tabs_container,
2121
- summary_html, historical_html, forecast_html, risks_html, recommendations_html,
2122
- cache_out,
2123
- ],
2124
- concurrency_limit=CONCURRENCY_LIMIT,
2125
- concurrency_id="gemini_analysis",
2126
- )
2127
- analysis_event.then(
2128
- fn=clear_image_after_success,
2129
- inputs=[app_state],
2130
- outputs=[image_input],
2131
- show_progress="hidden",
2132
- )
2133
-
2134
- lat_input.change(fn=validate_coordinates_ui, inputs=[lat_input, lon_input, app_state], outputs=[analyze_btn])
2135
- lon_input.change(fn=validate_coordinates_ui, inputs=[lat_input, lon_input, app_state], outputs=[analyze_btn])
2136
-
2137
- # 5. View Insight (+ modal rekomendasi + file download)
2138
- view_insight_btn.click(
2139
- fn=show_insight_view,
2140
- inputs=[app_state],
2141
- js=VIEW_INSIGHT_JS,
2142
- outputs=[view_insight_btn, tabs_container, download_data_btn, modal_output],
2143
- ).then(
2144
- fn=prepare_download_file,
2145
- inputs=[app_state],
2146
- outputs=[download_data_btn],
2147
- )
2148
-
2149
- # 6. Simpan cache ke localStorage (timpa data lama)
2150
- cache_out.change(fn=None, js=SAVE_CACHE_JS, inputs=[cache_out])
2151
-
2152
-
2153
- demo.queue(default_concurrency_limit=10, max_size=100)
2154
-
2155
- if __name__ == "__main__":
2156
- demo.launch(
2157
- server_name="0.0.0.0",
2158
- server_port=7860,
2159
- theme=THEME,
2160
- css=CSS,
2161
- allowed_paths=["assets"],
2162
- max_threads=60,
2163
- max_file_size=MAX_UPLOAD_SIZE,
2164
- )