Spaces:
Sleeping
Sleeping
File size: 79,019 Bytes
1d0e569 | 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 303 304 305 306 307 308 309 310 311 312 313 314 315 316 317 318 319 320 321 322 323 324 325 326 327 328 329 330 331 332 333 334 335 336 337 338 339 340 341 342 343 344 345 346 347 348 349 350 351 352 353 354 355 356 357 358 359 360 361 362 363 364 365 366 367 368 369 370 371 372 373 374 375 376 377 378 379 380 381 382 383 384 385 386 387 388 389 390 391 392 393 394 395 396 397 398 399 400 401 402 403 404 405 406 407 408 409 410 411 412 413 414 415 416 417 418 419 420 421 422 423 424 425 426 427 428 429 430 431 432 433 434 435 436 437 438 439 440 441 442 443 444 445 446 447 448 449 450 451 452 453 454 455 456 457 458 459 460 461 462 463 464 465 466 467 468 469 470 471 472 473 474 475 476 477 478 479 480 481 482 483 484 485 486 487 488 489 490 491 492 493 494 495 496 497 498 499 500 501 502 503 504 505 506 507 508 509 510 511 512 513 514 515 516 517 518 519 520 521 522 523 524 525 526 527 528 529 530 531 532 533 534 535 536 537 538 539 540 541 542 543 544 545 546 547 548 549 550 551 552 553 554 555 556 557 558 559 560 561 562 563 564 565 566 567 568 569 570 571 572 573 574 575 576 577 578 579 580 581 582 583 584 585 586 587 588 589 590 591 592 593 594 595 596 597 598 599 600 601 602 603 604 605 606 607 608 609 610 611 612 613 614 615 616 617 618 619 620 621 622 623 624 625 626 627 628 629 630 631 632 633 634 635 636 637 638 639 640 641 642 643 644 645 646 647 648 649 650 651 652 653 654 655 656 657 658 659 660 661 662 663 664 665 666 667 668 669 670 671 672 673 674 675 676 677 678 679 680 681 682 683 684 685 686 687 688 689 690 691 692 693 694 695 696 697 698 699 700 701 702 703 704 705 706 707 708 709 710 711 712 713 714 715 716 717 718 719 720 721 722 723 724 725 726 727 728 729 730 731 732 733 734 735 736 737 738 739 740 741 742 743 744 745 746 747 748 749 750 751 752 753 754 755 756 757 758 759 760 761 762 763 764 765 766 767 768 769 770 771 772 773 774 775 776 777 778 779 780 781 782 783 784 785 786 787 788 789 790 791 792 793 794 795 796 797 798 799 800 801 802 803 804 805 806 807 808 809 810 811 812 813 814 815 816 817 818 819 820 821 822 823 824 825 826 827 828 829 830 831 832 833 834 835 836 837 838 839 840 841 842 843 844 845 846 847 848 849 850 851 852 853 854 855 856 857 858 859 860 861 862 863 864 865 866 867 868 869 870 871 872 873 874 875 876 877 878 879 880 881 882 883 884 885 886 887 888 889 890 891 892 893 894 895 896 897 898 899 900 901 902 903 904 905 906 907 908 909 910 911 912 913 914 915 916 917 918 919 920 921 922 923 924 925 926 927 928 929 930 931 932 933 934 935 936 937 938 939 940 941 942 943 944 945 946 947 948 949 950 951 952 953 954 955 956 957 958 959 960 961 962 963 964 965 966 967 968 969 970 971 972 973 974 975 976 977 978 979 980 981 982 983 984 985 986 987 988 989 990 991 992 993 994 995 996 997 998 999 1000 1001 1002 1003 1004 1005 1006 1007 1008 1009 1010 1011 1012 1013 1014 1015 1016 1017 1018 1019 1020 1021 1022 1023 1024 1025 1026 1027 1028 1029 1030 1031 1032 1033 1034 1035 1036 1037 1038 1039 1040 1041 1042 1043 1044 1045 1046 1047 1048 1049 1050 1051 1052 1053 1054 1055 1056 1057 1058 1059 1060 1061 1062 1063 1064 1065 1066 1067 1068 1069 1070 1071 1072 1073 1074 1075 1076 1077 1078 1079 1080 1081 1082 1083 1084 1085 1086 1087 1088 1089 1090 1091 1092 1093 1094 1095 1096 1097 1098 1099 1100 1101 1102 1103 1104 1105 1106 1107 1108 1109 1110 1111 1112 1113 1114 1115 1116 1117 1118 1119 1120 1121 1122 1123 1124 1125 1126 1127 1128 1129 1130 1131 1132 1133 1134 1135 1136 1137 1138 1139 1140 1141 1142 1143 1144 1145 1146 1147 1148 1149 1150 1151 1152 1153 1154 1155 1156 1157 1158 1159 1160 1161 1162 1163 1164 1165 1166 1167 1168 1169 1170 1171 1172 1173 1174 1175 1176 1177 1178 1179 1180 1181 1182 1183 1184 1185 1186 1187 1188 1189 1190 1191 1192 1193 1194 1195 1196 1197 1198 1199 1200 1201 1202 1203 1204 1205 1206 1207 1208 1209 1210 1211 1212 1213 1214 1215 1216 1217 1218 1219 1220 1221 1222 1223 1224 1225 1226 1227 1228 1229 1230 1231 1232 1233 1234 1235 1236 1237 1238 1239 1240 1241 1242 1243 1244 1245 1246 1247 1248 1249 1250 1251 1252 1253 1254 1255 1256 1257 1258 1259 1260 1261 1262 1263 1264 1265 1266 1267 1268 1269 1270 1271 1272 1273 1274 1275 1276 1277 1278 1279 1280 1281 1282 1283 1284 1285 1286 1287 1288 1289 1290 1291 1292 1293 1294 1295 1296 1297 1298 1299 1300 1301 1302 1303 1304 1305 1306 1307 1308 1309 1310 1311 1312 1313 1314 1315 1316 1317 1318 1319 1320 1321 1322 1323 1324 1325 1326 1327 1328 1329 1330 1331 1332 1333 1334 1335 1336 1337 1338 1339 1340 1341 1342 1343 1344 1345 1346 1347 1348 1349 1350 1351 1352 1353 1354 1355 1356 1357 1358 1359 1360 1361 1362 1363 1364 1365 1366 1367 1368 1369 1370 1371 1372 1373 1374 1375 1376 1377 1378 1379 1380 1381 1382 1383 1384 1385 1386 1387 1388 1389 1390 1391 1392 1393 1394 1395 1396 1397 1398 1399 1400 1401 1402 1403 1404 1405 1406 1407 1408 1409 1410 1411 1412 1413 1414 1415 1416 1417 1418 1419 1420 1421 1422 1423 1424 1425 1426 1427 1428 1429 1430 1431 1432 1433 1434 1435 1436 1437 1438 1439 1440 1441 1442 1443 1444 1445 1446 1447 1448 1449 1450 1451 1452 1453 1454 1455 1456 1457 1458 1459 1460 1461 1462 1463 1464 1465 1466 1467 1468 1469 1470 1471 1472 1473 1474 1475 1476 1477 1478 1479 1480 1481 1482 1483 1484 1485 1486 1487 1488 1489 1490 1491 1492 1493 1494 1495 1496 1497 1498 1499 1500 1501 1502 1503 1504 1505 1506 1507 1508 1509 1510 1511 1512 1513 1514 1515 1516 1517 1518 1519 1520 1521 1522 1523 1524 1525 1526 1527 1528 1529 1530 1531 1532 1533 1534 1535 1536 1537 1538 1539 1540 1541 1542 1543 1544 1545 1546 1547 1548 1549 1550 1551 1552 1553 1554 1555 1556 1557 1558 1559 1560 1561 1562 1563 1564 1565 1566 1567 1568 1569 1570 1571 1572 1573 1574 1575 1576 1577 1578 1579 1580 1581 1582 1583 1584 1585 1586 1587 1588 1589 1590 1591 1592 1593 1594 1595 1596 1597 1598 1599 1600 1601 1602 1603 1604 1605 1606 1607 1608 1609 1610 1611 1612 1613 1614 1615 1616 1617 1618 1619 1620 1621 1622 1623 1624 1625 1626 1627 1628 1629 1630 1631 1632 1633 1634 1635 1636 1637 1638 1639 1640 1641 1642 1643 1644 1645 1646 1647 1648 1649 1650 1651 1652 1653 1654 1655 1656 1657 1658 1659 1660 1661 1662 1663 1664 1665 1666 1667 1668 1669 1670 1671 1672 1673 1674 1675 1676 1677 1678 1679 1680 1681 1682 1683 1684 1685 1686 1687 1688 1689 1690 1691 1692 1693 1694 1695 1696 1697 1698 1699 1700 1701 1702 1703 1704 1705 1706 1707 1708 1709 1710 1711 1712 1713 1714 1715 1716 1717 1718 1719 1720 1721 1722 1723 1724 1725 1726 1727 1728 1729 1730 1731 1732 1733 1734 1735 1736 1737 1738 1739 1740 1741 1742 1743 1744 1745 1746 1747 1748 1749 1750 1751 1752 1753 1754 1755 1756 1757 1758 1759 1760 1761 1762 1763 1764 1765 1766 1767 1768 1769 1770 1771 1772 1773 1774 1775 1776 1777 1778 1779 1780 1781 1782 1783 1784 1785 1786 1787 1788 1789 1790 1791 1792 1793 1794 1795 1796 1797 1798 1799 1800 1801 1802 1803 1804 1805 1806 1807 1808 1809 1810 1811 1812 1813 1814 1815 1816 1817 1818 1819 1820 1821 1822 1823 1824 1825 1826 1827 1828 1829 1830 1831 1832 1833 1834 1835 1836 1837 1838 1839 1840 1841 1842 1843 1844 1845 1846 1847 1848 1849 1850 1851 1852 1853 1854 1855 1856 1857 1858 1859 1860 1861 1862 1863 1864 1865 1866 1867 1868 1869 1870 1871 1872 1873 1874 1875 1876 1877 1878 1879 1880 1881 1882 1883 1884 1885 1886 1887 1888 1889 1890 1891 1892 1893 1894 1895 1896 1897 1898 1899 1900 1901 1902 1903 1904 1905 1906 1907 1908 1909 1910 1911 1912 1913 1914 1915 1916 1917 1918 1919 1920 1921 1922 1923 1924 1925 1926 1927 1928 1929 1930 1931 1932 1933 1934 1935 1936 1937 1938 1939 1940 1941 1942 1943 1944 1945 1946 1947 1948 1949 1950 1951 1952 1953 1954 1955 1956 1957 1958 1959 1960 1961 1962 1963 1964 1965 1966 1967 1968 1969 1970 1971 1972 1973 1974 1975 1976 1977 1978 1979 1980 1981 1982 1983 1984 1985 1986 1987 1988 1989 1990 1991 1992 1993 1994 1995 1996 1997 1998 1999 2000 2001 2002 2003 2004 2005 2006 2007 2008 2009 2010 2011 2012 2013 2014 2015 2016 2017 2018 2019 | """
Space Weather - Weather Intelligence Application
Built with Gradio, LiteLLM, Open-Meteo, and Gemini
Compatible with Gradio 6.x
Browser-cache version: SINGLE ENTRY (overwrite old data)
"""
import os
import json
import re
import html
import uuid
from datetime import datetime, timezone
from typing import Dict, List, Optional, Tuple, Any
from dataclasses import dataclass
import logging
import gradio as gr
import requests
from litellm import completion
from gemini_key_manager import GeminiKeyManager, classify_gemini_error
# Suppress Gradio 6.x internal warnings
import warnings
warnings.filterwarnings("ignore", category=RuntimeWarning, message="coroutine.*was never awaited")
warnings.filterwarnings("ignore", category=RuntimeWarning, message=".*event loop.*")
# ------------------------------------------------------------------
# FILE LOADERS
# ------------------------------------------------------------------
def load_text(path: str) -> str:
try:
with open(path, "r", encoding="utf-8") as f:
return f.read()
except Exception as e:
logger.error(f"Failed to load {path}: {e}")
return ""
def load_json(path: str) -> dict:
try:
with open(path, "r", encoding="utf-8") as f:
return json.load(f)
except Exception as e:
logger.error(f"Failed to load {path}: {e}")
return {}
# ------------------------------------------------------------------
# CONFIGURATION
# ------------------------------------------------------------------
logging.basicConfig(level=logging.INFO)
logger = logging.getLogger(__name__)
OPEN_METEO_URL = "https://api.open-meteo.com/v1/forecast"
# Directory to write user-downloadable JSON export files
EXPORT_DIR = "/tmp/weather_exports"
# Definisikan link Shopee Affiliate di sini agar mudah diubah
SHOPEE_LINK = "https://shopee.co.id/"
# Gemini API key rotation manager (baca GEMINI_API_KEY_1..N dari secrets)
key_manager = GeminiKeyManager() # <-- BARU
# ------------------------------------------------------------------
# STATE MACHINE CONSTANTS
# ------------------------------------------------------------------
STATE_READY = "READY"
STATE_LOCATING = "LOCATING"
STATE_LOCATION_READY = "LOCATION_READY"
STATE_ANALYZING = "ANALYZING"
STATE_FETCHING_WEATHER = "FETCHING_WEATHER"
STATE_PROCESSING_DATA = "PROCESSING_DATA"
STATE_GENERATING_INSIGHT = "GENERATING_INSIGHT"
STATE_VALIDATING_OUTPUT = "VALIDATING_OUTPUT"
STATE_COMPLETED = "COMPLETED"
STATE_ERROR = "ERROR"
STATE_LOCKED_TODAY = "LOCKED_TODAY"
PROGRESS_STEPS = {
STATE_FETCHING_WEATHER: ("Step 1/5", "Getting weather data..."),
STATE_PROCESSING_DATA: ("Step 2/5", "Processing weather data..."),
STATE_GENERATING_INSIGHT: ("Step 3/5", "Generating weather insight..."),
STATE_VALIDATING_OUTPUT: ("Step 4/5", "Validating analysis..."),
STATE_COMPLETED: ("Step 5/5", "Analysis complete"),
}
STEP_ORDER = [
STATE_FETCHING_WEATHER,
STATE_PROCESSING_DATA,
STATE_GENERATING_INSIGHT,
STATE_VALIDATING_OUTPUT,
STATE_COMPLETED,
]
STEP_LABELS = ["Weather Data", "Processing", "Insight", "Validation", "Complete"]
STATUS_VARIANTS = {
STATE_READY: ("neutral", "Ready"),
STATE_LOCATION_READY: ("info", "Location ready"),
STATE_ANALYZING: ("active", "Analyzing"),
STATE_ERROR: ("error", "Error"),
STATE_LOCKED_TODAY: ("info", "Locked"),
STATE_COMPLETED: ("success", "Complete"),
}
VALID_SEVERITY = {"low", "medium", "high"}
VALID_CONFIDENCE = {"low", "medium", "high"}
VALID_PRIORITY = {"low", "medium", "high"}
WEATHER_VARIABLES = [
"temperature_2m_max", "temperature_2m_min", "rain_sum", "precipitation_sum",
"wind_gusts_10m_max", "shortwave_radiation_sum", "temperature_2m_mean",
"cloud_cover_mean", "et0_fao_evapotranspiration",
"growing_degree_days_base_0_limit_50", "leaf_wetness_probability_mean",
"vapour_pressure_deficit_max"
]
# ------------------------------------------------------------------
# DATA CLASSES
# ------------------------------------------------------------------
@dataclass
class AppState:
state: str = STATE_READY
is_analyzing: bool = False
location: Optional[Dict] = None
client_date: Optional[str] = None
client_timezone: Optional[str] = None
browser_date: Optional[str] = None
browser_timezone: Optional[str] = None
cache: Optional[Dict] = None # Now a SINGLE entry, not a dict of dates
def to_dict(self):
return {
"state": self.state,
"is_analyzing": self.is_analyzing,
"location": self.location,
"client_date": self.client_date,
"client_timezone": self.client_timezone,
"browser_date": self.browser_date,
"browser_timezone": self.browser_timezone,
"cache": self.cache,
}
@classmethod
def from_dict(cls, d):
return cls(
state=d.get("state", STATE_READY),
is_analyzing=d.get("is_analyzing", False),
location=d.get("location"),
client_date=d.get("client_date"),
client_timezone=d.get("client_timezone"),
browser_date=d.get("browser_date"),
browser_timezone=d.get("browser_timezone"),
cache=d.get("cache"),
)
# ------------------------------------------------------------------
# UTILITY FORMATTERS
# ------------------------------------------------------------------
def validate_coordinates(lat: Any, lon: Any) -> Tuple[bool, str]:
if lat is None or lon is None:
return False, "Invalid location. Please enter a valid latitude and longitude."
try:
lat_f = float(lat)
lon_f = float(lon)
except (ValueError, TypeError):
return False, "Invalid location. Please enter a valid latitude and longitude."
if not (-90 <= lat_f <= 90):
return False, "Invalid location. Latitude must be between -90 and 90."
if not (-180 <= lon_f <= 180):
return False, "Invalid location. Longitude must be between -180 and 180."
return True, ""
def validate_coordinates_ui(lat, lon, state_dict):
state = AppState.from_dict(state_dict)
if state.state == STATE_LOCKED_TODAY:
return gr.update(interactive=False)
if (lat is None or lat == 0) or (lon is None or lon == 0):
return gr.update(interactive=False)
return gr.update(interactive=True)
def esc(value: Any) -> str:
if value is None:
return ""
return html.escape(str(value))
def format_status(state: str, message: str = "") -> str:
if state in PROGRESS_STEPS and state not in STATUS_VARIANTS:
variant = "active"
label = PROGRESS_STEPS[state][1]
else:
variant, label = STATUS_VARIANTS.get(state, ("neutral", state.replace("_", " ").title()))
detail = f'<span class="status-detail">{esc(message)}</span>' if message else ""
return (
f'<div class="status-pill status-pill--{variant}">'
f'<span class="status-dot"></span>'
f'<span class="status-label">{esc(label)}</span>'
f'{detail}'
f'</div>'
)
def format_location_status(source: str, accuracy: Optional[float]) -> str:
source_label = {"gps": "GPS", "ip": "IP geolocation"}.get(source, source or "Manual")
accuracy_str = f" ±{accuracy:.0f}m" if accuracy else ""
return (
f'<div class="status-pill status-pill--info">'
f'<span class="status-dot"></span>'
f'<span class="status-label">Location ready</span>'
f'<span class="status-detail">{esc(source_label)}{accuracy_str}</span>'
f'</div>'
)
def render_step_tracker(state: str, error: bool = False) -> str:
if state not in STEP_ORDER:
return ""
idx = STEP_ORDER.index(state)
items = []
for i, label in enumerate(STEP_LABELS):
is_done = i < idx or (i == idx and state == STATE_COMPLETED)
if error and i == idx:
cls, marker = "is-error", "×"
elif is_done:
cls, marker = "is-done", "✓"
elif i == idx:
cls, marker = "is-active", f"{i + 1:02d}"
else:
cls, marker = "is-pending", f"{i + 1:02d}"
items.append(
f'<div class="step {cls}">'
f'<span class="step-marker">{marker}</span>'
f'<span class="step-label">{esc(label)}</span>'
f'</div>'
)
if i < len(STEP_LABELS) - 1:
filled = "filled" if is_done else ""
items.append(f'<div class="step-connector {filled}"></div>')
return f'<div class="step-tracker">{"".join(items)}</div>'
def format_progress(state: str, error: bool = False) -> str:
return render_step_tracker(state, error=error)
def format_cache_info(cache_entry: Optional[Dict]) -> str:
if not cache_entry:
return ""
# --- Tanggal analisis (sudah browser_date dari handle_weather_and_analyze) ---
client_date = cache_entry.get("client_date", "Unknown")
if client_date != "Unknown":
try:
client_date = datetime.strptime(client_date, "%Y-%m-%d").strftime("%d %b %Y")
except Exception:
pass
# --- Waktu generated: konversi UTC → browser timezone ---
created = cache_entry.get("created_at", "Unknown")
browser_tz = cache_entry.get("browser_timezone") or cache_entry.get("client_timezone") or "UTC"
if created != "Unknown":
try:
dt = datetime.fromisoformat(created)
# Pastikan aware (UTC)
if dt.tzinfo is None:
dt = dt.replace(tzinfo=timezone.utc)
if browser_tz and browser_tz != "UTC":
try:
from zoneinfo import ZoneInfo
dt_local = dt.astimezone(ZoneInfo(browser_tz))
created = dt_local.strftime("%d %b %Y, %H:%M") + f" · {browser_tz}"
except Exception:
# Fallback kalau ZoneInfo tidak kenal timezone
created = dt.strftime("%d %b %Y, %H:%M UTC")
else:
created = dt.strftime("%d %b %Y, %H:%M UTC")
except Exception:
pass
location = cache_entry.get("location", {}) or {}
source = location.get("source", "manual")
source_label = {"gps": "GPS", "ip": "IP Geolocation", "manual": "Manual"}.get(source, source)
return (
f'<div class="cache-card">'
f'<div class="cache-card-icon">✓</div>'
f'<div class="cache-card-body">'
f'<div class="cache-card-title">Today’s analysis is ready</div>'
f'<div class="cache-card-meta">'
f'<span>{esc(client_date)}</span><span class="dot-sep">·</span><span>{esc(source_label)}</span>'
f'</div>'
f'<div class="cache-card-meta cache-card-meta--faint">Generated {esc(created)}</div>'
f'</div>'
f'</div>'
)
def render_placeholder(title: str, message: str, variant: str = "neutral") -> str:
return (
f'<div class="placeholder-card placeholder-card--{variant}">'
f'<div class="placeholder-mark"></div>'
f'<div class="placeholder-title">{esc(title)}</div>'
f'<div class="placeholder-message">{esc(message)}</div>'
f'</div>'
)
def render_sponsors_html(sponsors: List[Dict]) -> str:
if not sponsors:
return '<div class="sponsor-empty">No sponsors listed.</div>'
items = []
for s in sponsors:
items.append(
f'<a class="sponsor-item" href="{esc(s.get("link", "#"))}" '
f'target="_blank" rel="noopener noreferrer" title="{esc(s.get("name", ""))}">'
f'<img class="sponsor-img" src="{esc(s.get("image", ""))}" '
f'alt="{esc(s.get("name", ""))}" loading="lazy">'
f'</a>'
)
return f'<div class="sponsor-grid">{"".join(items)}</div>'
def severity_badge(sev: Optional[str]) -> str:
sev_l = (sev or "unknown").lower()
cls = {"low": "badge--good", "medium": "badge--warn", "high": "badge--bad"}.get(sev_l, "badge--neutral")
return f'<span class="badge {cls}">{esc(sev_l.upper())}</span>'
def priority_badge(pri: Optional[str]) -> str:
pri_l = (pri or "unknown").lower()
cls = {"low": "badge--good", "medium": "badge--warn", "high": "badge--bad"}.get(pri_l, "badge--neutral")
return f'<span class="badge {cls}">{esc(pri_l.upper())} PRI.</span>'
def confidence_badge(conf: Optional[str]) -> str:
conf_l = (conf or "unknown").lower()
cls = {"high": "badge--good", "medium": "badge--warn", "low": "badge--neutral"}.get(conf_l, "badge--neutral")
return f'<span class="badge {cls} badge--outline">{esc(conf_l.upper())} CONF.</span>'
def render_summary_tab(analysis: Dict) -> str:
if not analysis:
return render_placeholder("No analysis yet", "Enter coordinates and select Analyze to generate today's insight.")
parts = ['<div class="insight-card">']
parts.append(f'<p class="insight-summary">{esc(analysis.get("summary", "No summary available."))}</p>')
overall = analysis.get("overall_confidence", "")
if overall:
parts.append(f'<div class="insight-footer">Overall confidence {confidence_badge(overall)}</div>')
parts.append('</div>')
return "".join(parts)
def render_historical_tab(analysis: Dict) -> str:
if not analysis:
return render_placeholder("No data yet", "Run analysis to view historical records.")
hist = analysis.get("historical", {}) or {}
parts = ['<div class="insight-card">']
parts.append('<div class="insight-section">')
parts.append('<div class="section-eyebrow">Historical · Last 7 Days</div>')
# New format: condition + impact
if hist.get("condition"):
parts.append(f'<p class="section-text"><strong>Kondisi:</strong> {esc(hist["condition"])}</p>')
if hist.get("impact"):
parts.append(f'<p class="section-text"><strong>Dampak:</strong> {esc(hist["impact"])}</p>')
# Old format: summary + key_conditions (backward-compatible)
if hist.get("summary"):
parts.append(f'<p class="section-text">{esc(hist["summary"])}</p>')
conds = hist.get("key_conditions") or []
if conds:
parts.append('<ul class="condition-list">' + "".join(f'<li>{esc(c)}</li>' for c in conds) + '</ul>')
# Fallback if nothing found
if not hist.get("condition") and not hist.get("impact") and not hist.get("summary") and not conds:
parts.append('<p class="section-text">No historical data recorded.</p>')
parts.append('</div></div>')
return "".join(parts)
def render_forecast_tab(analysis: Dict) -> str:
if not analysis:
return render_placeholder("No data yet", "Run analysis to view forecast records.")
fcst = analysis.get("forecast", {}) or {}
parts = ['<div class="insight-card">']
parts.append('<div class="insight-section">')
parts.append('<div class="section-eyebrow">Forecast · Next 7 Days</div>')
# New format: condition + impact
if fcst.get("condition"):
parts.append(f'<p class="section-text"><strong>Kondisi:</strong> {esc(fcst["condition"])}</p>')
if fcst.get("impact"):
parts.append(f'<p class="section-text"><strong>Dampak:</strong> {esc(fcst["impact"])}</p>')
# Old format: summary + key_conditions (backward-compatible)
if fcst.get("summary"):
parts.append(f'<p class="section-text">{esc(fcst["summary"])}</p>')
conds = fcst.get("key_conditions") or []
if conds:
parts.append('<ul class="condition-list">' + "".join(f'<li>{esc(c)}</li>' for c in conds) + '</ul>')
# Fallback if nothing found
if not fcst.get("condition") and not fcst.get("impact") and not fcst.get("summary") and not conds:
parts.append('<p class="section-text">No forecast data recorded.</p>')
parts.append('</div></div>')
return "".join(parts)
def render_risks_tab(analysis: Dict) -> str:
if not analysis:
return render_placeholder("No data yet", "Run analysis to view risk signals.")
risks = analysis.get("risks") or []
parts = ['<div class="insight-card">']
parts.append('<div class="insight-section">')
parts.append('<div class="section-eyebrow">Risk Signals</div>')
if risks:
parts.append('<div class="risk-list">')
for risk in risks:
# Backward-compatible: old data uses "type", new data uses "title"
title = str(risk.get("title") or risk.get("type", "Unknown Risk"))
# Old data uses "confidence", new data doesn't have it — just show severity
badges = severity_badge(risk.get("severity"))
parts.append('<div class="risk-item">')
parts.append(
f'<div class="risk-item-head">'
f'<span class="risk-item-title">{esc(title)}</span>'
f'<span class="risk-item-badges">{badges}</span>'
f'</div>'
)
# New format has "description", old format doesn't
if risk.get("description"):
parts.append(f'<p class="section-text" style="margin:6px 0 4px;font-size:13px;">{esc(risk["description"])}</p>')
if risk.get("evidence"):
parts.append(f'<p class="risk-item-evidence">{esc(risk["evidence"])}</p>')
# New format has "period", old format doesn't
if risk.get("period"):
parts.append(f'<p class="risk-item-evidence" style="color:var(--info);margin-top:4px;">📅 {esc(risk["period"])}</p>')
parts.append('</div>')
parts.append('</div>')
else:
parts.append('<p class="section-text">No significant weather risks detected.</p>')
parts.append('</div></div>')
return "".join(parts)
def render_recommendations_tab(analysis: Dict) -> str:
if not analysis:
return render_placeholder("No data yet", "Run analysis to view recommendations.")
parts = ['<div class="insight-card">']
parts.append('<div class="insight-section insight-section--recommendation" style="margin-bottom:0;">')
parts.append('<div class="section-eyebrow">Recommendation</div>')
recs = analysis.get("recommendations") or []
if recs:
parts.append('<div class="risk-list">')
for rec in recs:
# Backward-compatible: handle old string format AND new object format
if isinstance(rec, str):
# Old format: just a string
action = rec
reason = ""
priority = ""
else:
# New format: object with action, reason, priority
action = str(rec.get("action", ""))
reason = str(rec.get("reason", ""))
priority = rec.get("priority", "")
parts.append('<div class="risk-item" style="border-color:rgba(232,163,61,0.25);">')
parts.append(
f'<div class="risk-item-head">'
f'<span class="risk-item-title">{esc(action)}</span>'
f'<span class="risk-item-badges">{priority_badge(priority)}</span>'
f'</div>'
)
if reason:
parts.append(f'<p class="risk-item-evidence">{esc(reason)}</p>')
parts.append('</div>')
parts.append('</div>')
else:
parts.append('<p class="section-text">No immediate action indicated.</p>')
parts.append('</div></div>')
return "".join(parts)
# ------------------------------------------------------------------
# 3. WEATHER SERVICE
# ------------------------------------------------------------------
def fetch_weather_data(lat: float, lon: float) -> Tuple[Optional[Dict], str]:
variables_str = ",".join(WEATHER_VARIABLES)
url = (
f"{OPEN_METEO_URL}?latitude={lat}&longitude={lon}"
f"&daily={variables_str}"
f"&timezone=auto&past_days=7&forecast_days=7"
)
try:
resp = requests.get(url, timeout=30)
if resp.status_code != 200:
return None, f"Weather data unavailable. Please try again later. (HTTP {resp.status_code})"
data = resp.json()
if not isinstance(data, dict):
return None, "Weather data unavailable. Please try again later. (Invalid JSON)"
if "daily" not in data:
return None, "Weather data unavailable. Please try again later. (Missing daily data)"
daily = data["daily"]
required_vars = ["time"] + WEATHER_VARIABLES
for var in required_vars:
if var not in daily:
return None, f"Weather data unavailable. Please try again later. (Missing variable: {var})"
dates = daily["time"]
if not isinstance(dates, list) or len(dates) == 0:
return None, "Weather data unavailable. Please try again later. (Invalid date array)"
if len(dates) < 8:
return None, f"Weather data unavailable. Please try again later. (Insufficient data: {len(dates)} days)"
return data, ""
except requests.Timeout:
return None, "Weather data unavailable. Request timed out. Please try again later."
except Exception as e:
logger.error(f"Weather fetch error: {e}")
return None, "Weather data unavailable. Please try again later."
def handle_weather_and_analyze(weather_json_str: str, lat: float, lon: float, crop: str, phenology: str, notes: str, current_concern: str, state_dict: Dict):
state = AppState.from_dict(state_dict)
cache_entry = state.cache
if not weather_json_str:
yield (
state.to_dict(),
gr.update(interactive=True), gr.update(interactive=True),
format_status(STATE_READY),
format_progress(STATE_READY),
format_cache_info(cache_entry),
gr.update(visible=True),
gr.update(visible=False),
gr.update(visible=False),
render_summary_tab({}),
render_historical_tab({}),
render_forecast_tab({}),
render_risks_tab({}),
render_recommendations_tab({}),
json.dumps(cache_entry) if cache_entry else ""
)
return
try:
raw_weather = json.loads(weather_json_str)
except Exception as exc:
err_msg = f"Failed to parse weather data: {exc}"
yield (
state.to_dict(),
gr.update(interactive=True), gr.update(interactive=True),
format_status(STATE_ERROR, err_msg),
format_progress(STATE_FETCHING_WEATHER, error=True), "",
gr.update(visible=True),
gr.update(visible=False),
gr.update(visible=False),
render_placeholder("Analysis failed", err_msg, "error"),
render_placeholder("No data yet", "Analysis interrupted.", "neutral"),
render_placeholder("No data yet", "Analysis interrupted.", "neutral"),
render_placeholder("No data yet", "Analysis interrupted.", "neutral"),
render_placeholder("No data yet", "Analysis interrupted.", "neutral"),
gr.update(value="")
)
return
if "error" in raw_weather:
error_msg = raw_weather["error"]
yield (
state.to_dict(), gr.update(interactive=True), gr.update(interactive=True),
format_status(STATE_ERROR, error_msg),
format_progress(STATE_FETCHING_WEATHER, error=True), "",
gr.update(visible=True),
gr.update(visible=False),
gr.update(visible=False),
render_placeholder("Analysis failed", error_msg, "error"),
render_placeholder("No data yet", "Analysis interrupted.", "neutral"),
render_placeholder("No data yet", "Analysis interrupted.", "neutral"),
render_placeholder("No data yet", "Analysis interrupted.", "neutral"),
render_placeholder("No data yet", "Analysis interrupted.", "neutral"),
gr.update(value="")
)
return
# <-- UBAH: gunakan tanggal browser, fallback ke server
client_date = state.browser_date or datetime.now().strftime("%Y-%m-%d")
state.client_date = client_date
if "error" in raw_weather:
error_msg = raw_weather["error"]
yield (
state.to_dict(), gr.update(interactive=True), gr.update(interactive=True),
format_status(STATE_ERROR, error_msg),
format_progress(STATE_FETCHING_WEATHER, error=True), "",
gr.update(visible=True),
gr.update(visible=False),
gr.update(visible=False),
render_placeholder("Analysis failed", error_msg, "error"),
render_placeholder("No data yet", "Analysis interrupted.", "neutral"),
render_placeholder("No data yet", "Analysis interrupted.", "neutral"),
render_placeholder("No data yet", "Analysis interrupted.", "neutral"),
render_placeholder("No data yet", "Analysis interrupted.", "neutral"),
gr.update(value="")
)
return
now = datetime.now()
state.state = STATE_PROCESSING_DATA
yield (
state.to_dict(),
gr.update(interactive=False), gr.update(interactive=False),
format_status(STATE_PROCESSING_DATA),
format_progress(STATE_PROCESSING_DATA),
"",
gr.update(visible=True),
gr.update(visible=False),
gr.update(visible=False),
render_placeholder("Processing weather data", "Splitting historical and forecast windows and computing derived indices.", "active"),
render_placeholder("No data yet", "Waiting for processing...", "neutral"),
render_placeholder("No data yet", "Waiting for processing...", "neutral"),
render_placeholder("No data yet", "Waiting for processing...", "neutral"),
render_placeholder("No data yet", "Waiting for processing...", "neutral"),
gr.update(value="")
)
normalized, norm_error = normalize_weather_data(raw_weather, lat, lon, client_date)
if norm_error:
failed_step = state.state
state.is_analyzing = False
state.state = STATE_ERROR
yield (
state.to_dict(),
gr.update(interactive=True), gr.update(interactive=True),
format_status(STATE_ERROR, norm_error),
format_progress(failed_step, error=True), "",
gr.update(visible=True),
gr.update(visible=False),
gr.update(visible=False),
render_placeholder("Analysis failed", norm_error, "error"),
render_placeholder("No data yet", "Analysis interrupted.", "neutral"),
render_placeholder("No data yet", "Analysis interrupted.", "neutral"),
render_placeholder("No data yet", "Analysis interrupted.", "neutral"),
render_placeholder("No data yet", "Analysis interrupted.", "neutral"),
gr.update(value="")
)
return
state.state = STATE_GENERATING_INSIGHT
yield (
state.to_dict(),
gr.update(interactive=False), gr.update(interactive=False),
format_status(STATE_GENERATING_INSIGHT),
format_progress(STATE_GENERATING_INSIGHT),
"",
gr.update(visible=True),
gr.update(visible=False),
gr.update(visible=False),
render_placeholder("Generating weather insight", "Gemini is interpreting the data for risks and recommendations.", "active"),
render_placeholder("No data yet", "Waiting for insight...", "neutral"),
render_placeholder("No data yet", "Waiting for insight...", "neutral"),
render_placeholder("No data yet", "Waiting for insight...", "neutral"),
render_placeholder("No data yet", "Waiting for insight...", "neutral"),
gr.update(value="")
)
payload = build_llm_payload(normalized, lat, lon, client_date, crop, phenology, notes, current_concern)
llm_output, gemini_error = call_gemini(payload)
if gemini_error:
failed_step = state.state
state.is_analyzing = False
state.state = STATE_ERROR
yield (
state.to_dict(),
gr.update(interactive=True), gr.update(interactive=True),
format_status(STATE_ERROR, gemini_error),
format_progress(failed_step, error=True), "",
gr.update(visible=True),
gr.update(visible=False),
gr.update(visible=False),
render_placeholder("Analysis failed", gemini_error, "error"),
render_placeholder("No data yet", "Analysis interrupted.", "neutral"),
render_placeholder("No data yet", "Analysis interrupted.", "neutral"),
render_placeholder("No data yet", "Analysis interrupted.", "neutral"),
render_placeholder("No data yet", "Analysis interrupted.", "neutral"),
gr.update(value="")
)
return
state.state = STATE_VALIDATING_OUTPUT
yield (
state.to_dict(),
gr.update(interactive=False), gr.update(interactive=False),
format_status(STATE_VALIDATING_OUTPUT),
format_progress(STATE_VALIDATING_OUTPUT),
"",
gr.update(visible=True),
gr.update(visible=False),
gr.update(visible=False),
render_placeholder("Validating analysis", "Checking the response against the expected schema.", "active"),
render_placeholder("No data yet", "Waiting for validation...", "neutral"),
render_placeholder("No data yet", "Waiting for validation...", "neutral"),
render_placeholder("No data yet", "Waiting for validation...", "neutral"),
render_placeholder("No data yet", "Waiting for validation...", "neutral"),
gr.update(value="")
)
valid, val_error = validate_llm_output(llm_output)
if not valid:
failed_step = state.state
state.is_analyzing = False
state.state = STATE_ERROR
yield (
state.to_dict(),
gr.update(interactive=True), gr.update(interactive=True),
format_status(STATE_ERROR, val_error),
format_progress(failed_step, error=True), "",
gr.update(visible=True),
gr.update(visible=False),
gr.update(visible=False),
render_placeholder("Analysis failed", val_error, "error"),
render_placeholder("No data yet", "Analysis interrupted.", "neutral"),
render_placeholder("No data yet", "Analysis interrupted.", "neutral"),
render_placeholder("No data yet", "Analysis interrupted.", "neutral"),
render_placeholder("No data yet", "Analysis interrupted.", "neutral"),
gr.update(value="")
)
return
state.state = STATE_COMPLETED
timezone_str = raw_weather.get("timezone", "UTC")
location_date = normalized.get("meta", {}).get("location_date", client_date)
cache_entry = {
"location": state.location,
"client_date": client_date,
"location_date": location_date,
"location_timezone": timezone_str,
"client_timezone": state.client_timezone or "UTC",
"field_context": {
"crop_type": crop,
"phenology_phase": phenology,
"field_notes": notes,
"current_concern": current_concern,
},
"raw_weather": raw_weather,
"analysis": llm_output,
"created_at": datetime.now(timezone.utc).isoformat()
}
state.cache = cache_entry
state.is_analyzing = False
yield (
state.to_dict(),
gr.update(interactive=False), gr.update(interactive=False),
format_status(STATE_COMPLETED),
format_progress(STATE_COMPLETED),
format_cache_info(cache_entry),
gr.update(visible=False), # initial_placeholder hidden
gr.update(visible=True), # view_insight_btn visible
gr.update(visible=False), # tabs_container hidden until clicked
render_summary_tab(llm_output),
render_historical_tab(llm_output),
render_forecast_tab(llm_output),
render_risks_tab(llm_output),
render_recommendations_tab(llm_output),
json.dumps(cache_entry)
)
state.state = STATE_LOCKED_TODAY
yield (
state.to_dict(),
gr.update(interactive=False), gr.update(interactive=False),
format_status(STATE_LOCKED_TODAY, "Today's analysis complete. Return tomorrow for a new analysis."),
"",
format_cache_info(cache_entry),
gr.update(visible=False), # initial_placeholder hidden
gr.update(visible=True), # view_insight_btn visible
gr.update(visible=False), # tabs_container hidden until clicked
render_summary_tab(llm_output),
render_historical_tab(llm_output),
render_forecast_tab(llm_output),
render_risks_tab(llm_output),
render_recommendations_tab(llm_output),
json.dumps(cache_entry)
)
# ------------------------------------------------------------------
# 4. ANALYTICS ENGINE
# ------------------------------------------------------------------
def normalize_weather_data(raw_data: Dict, lat: float, lon: float, client_date: str) -> Tuple[Optional[Dict], str]:
try:
timezone_str = raw_data.get("timezone", "UTC")
dates = raw_data["daily"]["time"]
location_date = dates[7] if len(dates) > 7 else client_date
daily = raw_data["daily"]
historical_dates = dates[:7]
today_date = [dates[7]] if len(dates) > 7 else []
forecast_dates = dates[8:] if len(dates) > 8 else []
def extract_block(date_list):
if not date_list:
return {}
result = {"time": date_list}
for var in WEATHER_VARIABLES:
values = daily.get(var, [])
idx_start = dates.index(date_list[0])
idx_end = idx_start + len(date_list)
result[var] = values[idx_start:idx_end]
return result
historical = extract_block(historical_dates)
today = extract_block(today_date)
forecast = extract_block(forecast_dates)
units = raw_data.get("daily_units", {})
units_filtered = {k: v for k, v in units.items() if k != "time"}
normalized = {
"meta": {
"location": {
"latitude": raw_data.get("latitude", lat),
"longitude": raw_data.get("longitude", lon),
"timezone": timezone_str,
"elevation_m": raw_data.get("elevation")
},
"client_date": client_date,
"location_date": location_date,
"analysis_period": {
"historical": f"{len(historical_dates)} days",
"forecast": f"{len(forecast_dates)} days",
"anchor_date": client_date
}
},
"units": units_filtered,
"historical": historical,
"today": today,
"forecast": forecast
}
return normalized, ""
except Exception as e:
logger.error(f"Normalization error: {e}")
return None, "Failed to process weather data. Please try again later."
# ------------------------------------------------------------------
# 5. LLM ENGINE
# ------------------------------------------------------------------
def build_llm_payload(normalized_data: Dict, lat: float, lon: float, client_date: str, crop: str = "", phenology: str = "", notes: str = "", current_concern: str = "") -> Dict:
meta = normalized_data.get("meta", {})
location = meta.get("location", {})
return {
"location": {
"latitude": lat,
"longitude": lon,
"timezone": location.get("timezone", "UTC")
},
"field_context": {
"crop_type": crop or "Tidak ditentukan",
"phenology_phase": phenology or "Tidak ditentukan",
"field_notes": notes or "Tidak ada catatan khusus",
"current_concern": current_concern or "Tidak ada concern khusus"
},
"analysis_period": {
"historical": meta.get("analysis_period", {}).get("historical", "7 days"),
"forecast": meta.get("analysis_period", {}).get("forecast", "7 days"),
"anchor_date": client_date,
"anchor_type": "client_time",
"location_date": meta.get("location_date", client_date),
"location_timezone": location.get("timezone", "UTC")
},
"units": normalized_data.get("units", {}),
"historical": {"daily": normalized_data.get("historical", {})},
"forecast": {"daily": normalized_data.get("forecast", {})}
}
def call_gemini(payload: Dict) -> Tuple[Optional[Dict], str]:
system_prompt = load_text("prompts/system_prompt.txt")
if not system_prompt:
return None, "System prompt file is missing or empty. Please check prompts/system_prompt.txt"
user_prompt = f"Weather data for analysis:\n\n{json.dumps(payload, indent=2)}"
messages = [
{"role": "system", "content": system_prompt},
{"role": "user", "content": user_prompt},
]
candidate_keys = key_manager.get_rotation_order()
last_error_msg = "Unknown error"
for key in candidate_keys:
if not key_manager._is_available(key):
continue
try:
response = completion(
model="gemini/gemini-3.5-flash",
messages=messages,
api_key=key,
temperature=1.0,
max_tokens=4000,
timeout=30,
)
content = response.choices[0].message.content
json_match = re.search(r"```(?:json)?\s*([\s\S]*?)\s*```", content)
if json_match:
content = json_match.group(1)
content = content.strip()
start_idx = content.find("{")
end_idx = content.rfind("}")
if start_idx != -1 and end_idx != -1:
content = content[start_idx:end_idx + 1]
result = json.loads(content)
return result, ""
except json.JSONDecodeError as e:
logger.error(f"JSON decode error: {e}")
return None, "Analysis could not be validated. Please try again. (Invalid JSON)"
except Exception as e:
kind = classify_gemini_error(e)
logger.warning(f"Key ...{key[-6:]} gagal ({kind}): {e}")
if kind == "rpd":
key_manager.mark_rpd_exhausted(key)
last_error_msg = "Satu atau lebih API key mencapai limit harian."
continue
elif kind == "rpm":
last_error_msg = "Key sedang sibuk (limit per menit), mencoba key lain."
continue
else:
last_error_msg = str(e)
continue
return None, (
"Weather data was retrieved, but the analysis could not be generated. "
f"Semua API key gagal atau kena limit. ({last_error_msg})"
)
# ------------------------------------------------------------------
# 6. OUTPUT + CACHE
# ------------------------------------------------------------------
def build_export_file(cache_entry: Optional[Dict]) -> Optional[str]:
"""
Rangkai satu file TXT (plain text, mudah dibaca manusia maupun LLM)
berisi: input pengguna (lokasi & konteks lahan), data cuaca mentah
(historical + forecast dari Open-Meteo), dan hasil analisis Gemini.
File ini dimaksudkan agar pengguna bisa memakainya sebagai context
input di LLM lain untuk analisis lanjutan.
"""
if not cache_entry:
return None
location = cache_entry.get("location", {}) or {}
field_context = cache_entry.get("field_context", {}) or {}
analysis = cache_entry.get("analysis", {}) or {}
lines: List[str] = []
lines.append("=== EXPORT DATA ANALISIS CUACA ===")
lines.append(f"Dibuat pada : {datetime.now(timezone.utc).isoformat()}")
lines.append("Tujuan : Context data untuk analisis lanjutan")
lines.append("Sumber App : DigiTanist/tanam")
lines.append("")
lines.append("--- INPUT PENGGUNA ---")
lines.append(f"Latitude : {location.get('latitude')}")
lines.append(f"Longitude : {location.get('longitude')}")
lines.append(f"Sumber lokasi : {location.get('source') or '-'}")
if location.get("accuracy_m"):
lines.append(f"Akurasi GPS : {location.get('accuracy_m')} m")
lines.append(f"Tanggal analisis : {cache_entry.get('client_date')}")
lines.append(f"Timezone lokasi : {cache_entry.get('location_timezone')}")
lines.append("")
lines.append("Konteks Lahan:")
lines.append(f"- Jenis Tanaman : {field_context.get('crop_type') or '-'}")
lines.append(f"- Fase Fenologi : {field_context.get('phenology_phase') or '-'}")
lines.append(f"- Catatan Lapangan : {field_context.get('field_notes') or '-'}")
lines.append(f"- Current Concern : {field_context.get('current_concern') or '-'}")
lines.append("")
lines.append("--- DATA CUACA MENTAH (Ecwf, historical 7 hari + forecast 7 hari) ---")
lines.append(json.dumps(cache_entry.get("raw_weather", {}), ensure_ascii=False, indent=2))
lines.append("")
lines.append("--- HASIL ANALISIS GEMINI AI ---")
lines.append(f"Ringkasan: {analysis.get('summary', '-')}")
lines.append("")
hist = analysis.get("historical", {}) or {}
lines.append("Historical (7 hari terakhir):")
lines.append(f" Kondisi : {hist.get('condition', '-')}")
lines.append(f" Dampak : {hist.get('impact', '-')}")
lines.append("")
fcst = analysis.get("forecast", {}) or {}
lines.append("Forecast (7 hari ke depan):")
lines.append(f" Kondisi : {fcst.get('condition', '-')}")
lines.append(f" Dampak : {fcst.get('impact', '-')}")
lines.append("")
risks = analysis.get("risks", []) or []
lines.append(f"Risiko ({len(risks)}):")
if risks:
for i, r in enumerate(risks, 1):
lines.append(f" {i}. {r.get('title', '-')} [severity: {r.get('severity', '-')}]")
lines.append(f" Deskripsi : {r.get('description', '-')}")
lines.append(f" Bukti : {r.get('evidence', '-')}")
lines.append(f" Periode : {r.get('period', '-')}")
else:
lines.append(" Tidak ada risiko signifikan.")
lines.append("")
recs = analysis.get("recommendations", []) or []
lines.append(f"Rekomendasi ({len(recs)}):")
if recs:
for i, r in enumerate(recs, 1):
lines.append(f" {i}. {r.get('action', '-')} [priority: {r.get('priority', '-')}]")
lines.append(f" Alasan : {r.get('reason', '-')}")
else:
lines.append(" Tidak ada tindakan khusus diperlukan.")
lines.append("")
lines.append(f"Overall Confidence: {analysis.get('overall_confidence', '-')}")
content = "\n".join(lines)
try:
os.makedirs(EXPORT_DIR, exist_ok=True)
date_tag = (cache_entry.get("client_date") or "unknown").replace("-", "")
unique_id = uuid.uuid4().hex[:8] # cegah tabrakan nama file antar-user/klik
path = os.path.join(EXPORT_DIR, f"weather_analysis_{date_tag}_{unique_id}.txt")
with open(path, "w", encoding="utf-8") as f:
f.write(content)
return path
except Exception as e:
logger.error(f"Failed to build export file: {e}")
return None
def validate_llm_output(output: Dict) -> Tuple[bool, str]:
required_fields = ["summary", "historical", "forecast", "risks", "recommendations", "overall_confidence"]
for field in required_fields:
if field not in output:
return False, f"Analysis could not be validated. Missing field: {field}"
# Validate historical structure
hist = output.get("historical", {})
if not isinstance(hist, dict):
return False, "Analysis could not be validated. Invalid historical format."
if "condition" not in hist or "impact" not in hist:
return False, "Analysis could not be validated. Historical missing condition or impact."
# Validate forecast structure
fcst = output.get("forecast", {})
if not isinstance(fcst, dict):
return False, "Analysis could not be validated. Invalid forecast format."
if "condition" not in fcst or "impact" not in fcst:
return False, "Analysis could not be validated. Forecast missing condition or impact."
# Validate risks
if not isinstance(output["risks"], list):
return False, "Analysis could not be validated. Invalid risks format."
for i, risk in enumerate(output["risks"]):
if not isinstance(risk, dict):
return False, f"Analysis could not be validated. Invalid risk at index {i}."
risk_required = ["title", "description", "evidence", "period", "severity"]
for rf in risk_required:
if rf not in risk:
return False, f"Analysis could not be validated. Risk {i} missing field: {rf}"
if risk.get("severity") not in VALID_SEVERITY:
return False, f"Analysis could not be validated. Invalid severity: {risk.get('severity')}"
# Validate recommendations
if not isinstance(output["recommendations"], list):
return False, "Analysis could not be validated. Invalid recommendations format."
for i, rec in enumerate(output["recommendations"]):
if not isinstance(rec, dict):
return False, f"Analysis could not be validated. Invalid recommendation at index {i}."
rec_required = ["action", "reason", "priority"]
for rf in rec_required:
if rf not in rec:
return False, f"Analysis could not be validated. Recommendation {i} missing field: {rf}"
if rec.get("priority") not in VALID_PRIORITY:
return False, f"Analysis could not be validated. Invalid priority: {rec.get('priority')}"
# Validate overall_confidence
if output.get("overall_confidence") not in VALID_CONFIDENCE:
return False, f"Analysis could not be validated. Invalid overall_confidence."
return True, ""
# ------------------------------------------------------------------
# MAIN HANDLERS
# ------------------------------------------------------------------
def init_app(composite_json: str):
cache_entry = None
browser_date = None
browser_timezone = "UTC"
if composite_json and composite_json.strip() and composite_json != '{}':
try:
parsed = json.loads(composite_json)
if isinstance(parsed, dict):
# Format BARU: object composite dari JS
if "browser_date" in parsed:
cache_raw = parsed.get("cache", "{}")
browser_date = parsed.get("browser_date")
browser_timezone = parsed.get("browser_timezone", "UTC")
if isinstance(cache_raw, str) and cache_raw.strip() and cache_raw != '{}':
cache_parsed = json.loads(cache_raw)
if isinstance(cache_parsed, dict) and "analysis" in cache_parsed:
cache_entry = cache_parsed
# Format LAMA: langsung cache entry (backward-compatible)
elif "analysis" in parsed:
cache_entry = parsed
except Exception:
cache_entry = None
# Fallback ke server time jika browser tidak mengirimkan waktu
if not browser_date:
now = datetime.now()
browser_date = now.strftime("%Y-%m-%d")
browser_timezone = "UTC"
# <-- KUNCI: bandingkan cache dengan TANGGAL BROWSER, bukan tanggal server
today_cache = cache_entry if (
cache_entry and cache_entry.get("client_date") == browser_date
) else None
state = AppState(
state=STATE_READY,
is_analyzing=False,
client_date=browser_date,
client_timezone=browser_timezone,
browser_date=browser_date, # <-- BARU
browser_timezone=browser_timezone, # <-- BARU
cache=today_cache
)
if today_cache:
state.state = STATE_LOCKED_TODAY
location = today_cache.get("location", {})
lat = location.get("latitude", 0)
lon = location.get("longitude", 0)
analysis = today_cache.get("analysis", {})
return (
state.to_dict(), lat, lon,
gr.update(interactive=False), gr.update(interactive=False),
format_status(STATE_LOCKED_TODAY, "Today's analysis already exists."),
"",
format_cache_info(today_cache),
gr.update(visible=False),
gr.update(visible=True),
gr.update(visible=False),
render_summary_tab(analysis),
render_historical_tab(analysis),
render_forecast_tab(analysis),
render_risks_tab(analysis),
render_recommendations_tab(analysis),
gr.update(value="")
)
else:
return (
state.to_dict(), 0, 0,
gr.update(interactive=True),
gr.update(interactive=False),
format_status(STATE_READY),
"",
"",
gr.update(visible=True),
gr.update(visible=False),
gr.update(visible=False),
render_summary_tab({}),
render_historical_tab({}),
render_forecast_tab({}),
render_risks_tab({}),
render_recommendations_tab({}),
gr.update(value="")
)
def handle_gps_result(gps_json: str, state_dict: Dict):
state = AppState.from_dict(state_dict)
if not gps_json:
return state.to_dict(), 0, 0, format_status(STATE_ERROR, "No location data received.")
try:
data = json.loads(gps_json)
except Exception:
return state.to_dict(), 0, 0, format_status(STATE_ERROR, "Invalid location data.")
if "error" in data:
return state.to_dict(), 0, 0, format_status(STATE_ERROR, data["error"])
lat = data.get("latitude")
lon = data.get("longitude")
source = data.get("source", "unknown")
accuracy = data.get("accuracy_m")
valid, msg = validate_coordinates(lat, lon)
if not valid:
return state.to_dict(), 0, 0, format_status(STATE_ERROR, msg)
state.location = {
"latitude": lat,
"longitude": lon,
"source": source,
"accuracy_m": accuracy
}
state.state = STATE_LOCATION_READY
status = format_location_status(source, accuracy)
return state.to_dict(), lat, lon, status
def handle_analyze(lat: float, lon: float, state_dict: Dict):
state = AppState.from_dict(state_dict)
cache_entry = state.cache # Single entry, not a dict
if state.is_analyzing:
yield (
state.to_dict(),
gr.update(), gr.update(),
format_status(STATE_ANALYZING, "Analysis already in progress."),
"", "",
render_placeholder("Analysis in progress", "Please wait for the current analysis to finish.", "active"),
gr.update(value="")
)
return
valid, msg = validate_coordinates(lat, lon)
if not valid:
yield (
state.to_dict(),
gr.update(interactive=True), gr.update(interactive=True),
format_status(STATE_ERROR, msg),
"", "",
render_placeholder("Invalid location", msg, "error"),
gr.update(value="")
)
return
prev_source = (state.location or {}).get("source", "manual")
prev_accuracy = (state.location or {}).get("accuracy_m")
state.location = {
"latitude": lat,
"longitude": lon,
"source": prev_source,
"accuracy_m": prev_accuracy
}
client_date = state.browser_date or datetime.now().strftime("%Y-%m-%d")
state.client_date = client_date
# Check if today's analysis already exists in the single cache entry
if cache_entry and cache_entry.get("client_date") == client_date:
state.state = STATE_LOCKED_TODAY
yield (
state.to_dict(),
gr.update(interactive=False), gr.update(interactive=False),
format_status(STATE_LOCKED_TODAY, "Today's analysis already exists."),
"",
format_cache_info(cache_entry),
render_analysis(cache_entry.get("analysis", {})),
gr.update(value="")
)
return
state.is_analyzing = True
state.state = STATE_ANALYZING
yield (
state.to_dict(),
gr.update(interactive=False), gr.update(interactive=False),
format_status(STATE_ANALYZING),
format_progress(STATE_ANALYZING),
"",
render_placeholder("Starting analysis", "Preparing to fetch weather data...", "active"),
gr.update(value="")
)
state.state = STATE_FETCHING_WEATHER
yield (
state.to_dict(),
gr.update(interactive=False), gr.update(interactive=False),
format_status(STATE_FETCHING_WEATHER),
format_progress(STATE_FETCHING_WEATHER),
"",
render_placeholder("Fetching weather data", "Retrieving historical and forecast records from Open-Meteo.", "active"),
gr.update(value="")
)
raw_weather, error = fetch_weather_data(lat, lon)
if error:
failed_step = state.state
state.is_analyzing = False
state.state = STATE_ERROR
yield (
state.to_dict(),
gr.update(interactive=True), gr.update(interactive=True),
format_status(STATE_ERROR, error),
format_progress(failed_step, error=True), "",
render_placeholder("Analysis failed", error, "error"),
gr.update(value="")
)
return
state.state = STATE_PROCESSING_DATA
yield (
state.to_dict(),
gr.update(interactive=False), gr.update(interactive=False),
format_status(STATE_PROCESSING_DATA),
format_progress(STATE_PROCESSING_DATA),
"",
render_placeholder("Processing weather data", "Splitting historical and forecast windows and computing derived indices.", "active"),
gr.update(value="")
)
normalized, error = normalize_weather_data(raw_weather, lat, lon, client_date)
if error:
failed_step = state.state
state.is_analyzing = False
state.state = STATE_ERROR
yield (
state.to_dict(),
gr.update(interactive=True), gr.update(interactive=True),
format_status(STATE_ERROR, error),
format_progress(failed_step, error=True), "",
render_placeholder("Analysis failed", error, "error"),
gr.update(value="")
)
return
state.state = STATE_GENERATING_INSIGHT
yield (
state.to_dict(),
gr.update(interactive=False), gr.update(interactive=False),
format_status(STATE_GENERATING_INSIGHT),
format_progress(STATE_GENERATING_INSIGHT),
"",
render_placeholder("Generating weather insight", "Gemini is interpreting the data for risks and recommendations.", "active"),
gr.update(value="")
)
payload = build_llm_payload(normalized, lat, lon, client_date)
llm_output, error = call_gemini(payload)
if error:
failed_step = state.state
state.is_analyzing = False
state.state = STATE_ERROR
yield (
state.to_dict(),
gr.update(interactive=True), gr.update(interactive=True),
format_status(STATE_ERROR, error),
format_progress(failed_step, error=True), "",
render_placeholder("Analysis failed", error, "error"),
gr.update(value="")
)
return
state.state = STATE_VALIDATING_OUTPUT
yield (
state.to_dict(),
gr.update(interactive=False), gr.update(interactive=False),
format_status(STATE_VALIDATING_OUTPUT),
format_progress(STATE_VALIDATING_OUTPUT),
"",
render_placeholder("Validating analysis", "Checking the response against the expected schema.", "active"),
gr.update(value="")
)
valid, error = validate_llm_output(llm_output)
if not valid:
failed_step = state.state
state.is_analyzing = False
state.state = STATE_ERROR
yield (
state.to_dict(),
gr.update(interactive=True), gr.update(interactive=True),
format_status(STATE_ERROR, error),
format_progress(failed_step, error=True), "",
render_placeholder("Analysis failed", error, "error"),
gr.update(value="")
)
return
state.state = STATE_COMPLETED
timezone_str = raw_weather.get("timezone", "UTC")
location_date = normalized.get("meta", {}).get("location_date", client_date)
# SINGLE ENTRY: directly overwrite state.cache
cache_entry = {
"location": state.location,
"client_date": client_date,
"location_date": location_date,
"location_timezone": timezone_str,
"client_timezone": state.client_timezone or "UTC",
"field_context": {
"crop_type": crop,
"phenology_phase": phenology,
"field_notes": notes,
"current_concern": current_concern,
},
"raw_weather": raw_weather,
"analysis": llm_output,
"created_at": datetime.now(timezone.utc).isoformat()
}
state.cache = cache_entry
state.is_analyzing = False
yield (
state.to_dict(),
gr.update(interactive=False), gr.update(interactive=False),
format_status(STATE_COMPLETED),
format_progress(STATE_COMPLETED),
format_cache_info(cache_entry),
render_analysis(llm_output),
json.dumps(cache_entry) # cache_out: save single entry to browser
)
state.state = STATE_LOCKED_TODAY
yield (
state.to_dict(),
gr.update(interactive=False), gr.update(interactive=False),
format_status(STATE_LOCKED_TODAY, "Today's analysis complete. Return tomorrow for a new analysis."),
"",
format_cache_info(cache_entry),
render_analysis(llm_output),
json.dumps(cache_entry) # cache_out: save single entry to browser
)
# ------------------------------------------------------------------
# GRADIO UI (Gradio 6.x compatible)
# ------------------------------------------------------------------
THEME = gr.themes.Base(
font=[gr.themes.GoogleFont("IBM Plex Sans"), "sans-serif"],
font_mono=[gr.themes.GoogleFont("IBM Plex Mono"), "monospace"],
).set(
body_background_fill="#0B1B22",
body_background_fill_dark="#0B1B22",
body_text_color="#E7F1F0",
body_text_color_dark="#E7F1F0",
body_text_color_subdued="#7E9CA3",
body_text_color_subdued_dark="#7E9CA3",
background_fill_primary="#122631",
background_fill_primary_dark="#122631",
background_fill_secondary="#0F2229",
background_fill_secondary_dark="#0F2229",
border_color_primary="#23414F",
border_color_primary_dark="#23414F",
block_background_fill="#122631",
block_background_fill_dark="#122631",
block_border_color="#23414F",
block_border_color_dark="#23414F",
block_label_text_color="#7E9CA3",
block_label_text_color_dark="#7E9CA3",
block_label_background_fill="#122631",
block_label_background_fill_dark="#122631",
block_title_text_color="#E7F1F0",
block_title_text_color_dark="#E7F1F0",
panel_background_fill="#0F2229",
panel_background_fill_dark="#0F2229",
panel_border_color="#23414F",
panel_border_color_dark="#23414F",
input_background_fill="#0F2229",
input_background_fill_dark="#0F2229",
input_border_color="#23414F",
input_border_color_dark="#23414F",
input_border_color_focus="#E8A33D",
input_border_color_focus_dark="#E8A33D",
button_primary_background_fill="#E8A33D",
button_primary_background_fill_dark="#E8A33D",
button_primary_background_fill_hover="#F2B457",
button_primary_background_fill_hover_dark="#F2B457",
button_primary_text_color="#0B1B22",
button_primary_text_color_dark="#0B1B22",
button_primary_border_color="#E8A33D",
button_primary_border_color_dark="#E8A33D",
button_secondary_background_fill="#16303D",
button_secondary_background_fill_dark="#16303D",
button_secondary_background_fill_hover="#1B3945",
button_secondary_background_fill_hover_dark="#1B3945",
button_secondary_text_color="#E7F1F0",
button_secondary_text_color_dark="#E7F1F0",
button_secondary_border_color="#23414F",
button_secondary_border_color_dark="#23414F",
error_background_fill="#2A1714",
error_background_fill_dark="#2A1714",
error_border_color="#E2604F",
error_border_color_dark="#E2604F",
)
# ------------------------------------------------------------------
# EXTERNAL ASSETS
# ------------------------------------------------------------------
CSS = load_text("assets/styles.css")
SPONSORS_RAW = load_json("assets/sponsors.json")
SPONSORS_DATA = [(s["image"], s["name"]) for s in SPONSORS_RAW.get("sponsors", [])]
SPONSOR_LINKS = [s["link"] for s in SPONSORS_RAW.get("sponsors", [])]
SPONSOR_HTML = render_sponsors_html(SPONSORS_RAW.get("sponsors", []))
HEADER_HTML = HEADER_HTML = """
<div class="hero-banner">
<div class="app-header">
<div class="eyebrow">Field Telemetry · Weather Intelligence</div>
<h1>DigiTanist/tanam</h1>
<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>
</div>
<div class="farmer-counter">
<span class="farmer-counter-badge">
<span class="farmer-counter-dot"></span>
<span><strong id="farmer-count">—</strong> petani sudah menganalisis hari ini</span>
</span>
</div>
</div>
"""
FOOTER_HTML = """
<div class="app-footer">DATA · OPEN-METEO | ANALYSIS · GEMINI | ONE READ PER DAY</div>
"""
GA4_HEAD = """
<!-- Google tag (gtag.js) -->
<script async src="https://www.googletagmanager.com/gtag/js?id=G-VWC31N398K"></script>
<script>
window.dataLayer = window.dataLayer || [];
function gtag(){dataLayer.push(arguments);}
gtag('js', new Date());
gtag('config', 'G-VWC31N398K');
</script>
<script>
function getTodayFarmerCount() {
// ====================== PENGATURAN ANGKA ======================
const BASE_MIN = 220;
const BASE_MAX = 380;
const INCREASE_PER_10_MIN = 2; // Jumlah penambahan setiap 10 menit (bisa disesuaikan)
// ==============================================================
const now = new Date();
const today = now.getFullYear() + '-' +
String(now.getMonth() + 1).padStart(2, '0') + '-' +
String(now.getDate()).padStart(2, '0');
let seed = 0;
for (let i = 0; i < today.length; i++) {
seed = (seed * 31 + today.charCodeAt(i)) & 0xffff;
}
const base = BASE_MIN + (seed % (BASE_MAX - BASE_MIN + 1));
// 1. Hitung total menit yang sudah berlalu sejak pukul 00:00 hari ini
const totalMinutes = (now.getHours() * 60) + now.getMinutes();
// 2. Hitung berapa banyak blok 10 menit yang sudah terlewati
const blocksOf10Min = Math.floor(totalMinutes / 10);
// 3. Hitung tambahan angka berdasarkan jumlah blok 10 menit
const extra = blocksOf10Min * INCREASE_PER_10_MIN;
return base + extra;
}
function animateCount(el, target, duration = 3300) {
const start = Math.max(0, target - Math.floor(target * 0.15)); // mulai dari ~85%
const startTime = performance.now();
function tick(now) {
const progress = Math.min((now - startTime) / duration, 1);
const eased = 1 - Math.pow(1 - progress, 3); // ease-out cubic
el.innerText = Math.round(start + (target - start) * eased).toLocaleString("id-ID");
if (progress < 1) requestAnimationFrame(tick);
}
requestAnimationFrame(tick);
}
function updateFarmerCount() {
const el = document.getElementById("farmer-count");
if (el) {
animateCount(el, getTodayFarmerCount());
return true; // berhasil
}
return false; // elemen belum ada
}
// Coba terus sampai elemen muncul (maksimal 10 detik)
function tryUpdateCounter(attempts = 0) {
if (updateFarmerCount() || attempts > 20) return;
setTimeout(() => tryUpdateCounter(attempts + 1), 500);
}
// Mulai mencoba segera
tryUpdateCounter();
// Update rutin setiap 5 menit
setInterval(updateFarmerCount, 5 * 60 * 1000);
</script>
"""
with gr.Blocks(title="Space Weather", head=GA4_HEAD) as demo:
gr.HTML(HEADER_HTML)
app_state = gr.State({})
gps_data = gr.Textbox(visible=False, elem_id="gps_data_input")
cache_in = gr.Textbox(visible=False, elem_id="browser_cache_in")
cache_out = gr.Textbox(visible=False, elem_id="browser_cache_out")
weather_json = gr.Textbox(visible=False, elem_id="weather_json_input")
with gr.Row(elem_classes=["main-row"]):
with gr.Column(scale=1, min_width=320, elem_classes=["rail-col"]):
with gr.Column(elem_classes=["console-panel"]):
gr.HTML('<div class="panel-eyebrow">Location</div>')
lat_input = gr.Number(
label="Latitude",
precision=6,
value=0,
info="-90 to 90"
)
lon_input = gr.Number(
label="Longitude",
precision=6,
value=0,
info="-180 to 180"
)
crop_input = gr.Textbox(
label="Jenis Tanaman",
placeholder="Contoh: Padi, Jagung, Cabai",
lines=1
)
phenology_input = gr.Textbox(
label="Fase Fenologi",
placeholder="Contoh: Vegetatif, Pembungaan, Pematangan",
lines=1
)
notes_input = gr.Textbox(
label="Catatan Lapangan",
placeholder="Contoh: Ada genangan air, gejala serangan hama ringan",
lines=2
)
current_concern_input = gr.Textbox(
label="Current Concern",
placeholder="Contoh: Khawatir kekurangan air atau risiko penyakit jamur",
info="Opsional. Masukkan kondisi atau pertanyaan yang ingin diperiksa berdasarkan cuaca.",
lines=2
)
with gr.Row(elem_classes=["btn-row"]):
get_loc_btn = gr.Button("Ambil lokasi dari GPS perangkat", variant="secondary", size="sm")
analyze_btn = gr.Button("Analyze", variant="primary", size="sm", interactive=False)
with gr.Column():
status_html = gr.HTML("")
step_html = gr.HTML("")
cache_html = gr.HTML("")
with gr.Column(scale=2, elem_classes=["content-col"]):
# Placeholder awal sebelum ada analisis atau saat loading
initial_placeholder = gr.HTML(render_placeholder("Initializing", "Loading today's status..."))
# Tombol View Insight (awalnya disembunyikan)
view_insight_btn = gr.Button("View Insight", variant="primary", visible=False, size="lg")
# Kontainer Tab dibungkus Column dan disembunyikan secara default (visible=False)
with gr.Column(visible=False) as tabs_container:
with gr.Tabs():
with gr.TabItem("Summary"):
summary_html = gr.HTML()
with gr.TabItem("Historical"):
historical_html = gr.HTML()
with gr.TabItem("Forecast"):
forecast_html = gr.HTML()
with gr.TabItem("Risks"):
risks_html = gr.HTML()
with gr.TabItem("Recommendations"):
recommendations_html = gr.HTML()
# Tombol download data mentah (JSON): tersembunyi, muncul
# bersamaan dengan tabs insight saat "View Insight" diklik.
download_data_btn = gr.DownloadButton(
"Download Data Analisis (TXT)",
visible=False,
size="md",
variant="secondary",
elem_classes=["download-data-btn"]
)
# Sponsor section (paling bawah)
gr.HTML('<div style="height: 16px;"></div>')
with gr.Column(elem_classes=["console-panel"]):
gr.HTML('<div class="panel-eyebrow" style="padding: 14px 14px 6px;">Supported By</div>')
gr.HTML(SPONSOR_HTML)
gr.HTML(FOOTER_HTML)
# 1. Page load: read localStorage into hidden textbox
# 1. Page load: baca localStorage + waktu browser, kirim sebagai composite JSON
demo.load(
fn=None,
js="""() => {
let cache = '{}';
try {
cache = localStorage.getItem('space_weather_cache') || '{}';
} catch (e) {
cache = '{}';
}
const now = new Date();
const browserDate = now.getFullYear() + '-' +
String(now.getMonth() + 1).padStart(2, '0') + '-' +
String(now.getDate()).padStart(2, '0');
const browserTz = Intl.DateTimeFormat().resolvedOptions().timeZone || 'UTC';
return JSON.stringify({
cache: cache,
browser_date: browserDate,
browser_timezone: browserTz
});
}""",
outputs=cache_in
)
# 2. When cache_in changes, initialize app from browser cache
cache_in.change(
fn=init_app,
inputs=[cache_in],
outputs=[
app_state, lat_input, lon_input, get_loc_btn, analyze_btn,
status_html, step_html, cache_html,
initial_placeholder, view_insight_btn, tabs_container,
summary_html, historical_html, forecast_html, risks_html, recommendations_html,
cache_out
]
)
# 3. Get Current Location -> JS geolocation -> hidden textbox
get_loc_btn.click(
fn=None,
js="""
async () => {
return new Promise((resolve) => {
if (navigator.geolocation) {
navigator.geolocation.getCurrentPosition(
(position) => {
resolve(JSON.stringify({
latitude: position.coords.latitude,
longitude: position.coords.longitude,
source: "gps",
accuracy_m: position.coords.accuracy
}));
},
async (error) => {
try {
const resp = await fetch('https://ipwho.is/');
const data = await resp.json();
if (data.success) {
resolve(JSON.stringify({
latitude: data.latitude,
longitude: data.longitude,
source: "ip",
accuracy_m: null
}));
} else {
resolve(JSON.stringify({
error: "Unable to determine your location. Please enter coordinates manually."
}));
}
} catch (e) {
resolve(JSON.stringify({
error: "Unable to determine your location. Please enter coordinates manually."
}));
}
},
{timeout: 10000, maximumAge: 60000}
);
} else {
fetch('https://ipwho.is/')
.then(r => r.json())
.then(data => {
if (data.success) {
resolve(JSON.stringify({
latitude: data.latitude,
longitude: data.longitude,
source: "ip",
accuracy_m: null
}));
} else {
resolve(JSON.stringify({
error: "Unable to determine your location. Please enter coordinates manually."
}));
}
})
.catch(() => {
resolve(JSON.stringify({
error: "Unable to determine your location. Please enter coordinates manually."
}));
});
}
});
}
""",
outputs=gps_data
)
gps_data.change(
fn=handle_gps_result,
inputs=[gps_data, app_state],
outputs=[app_state, lat_input, lon_input, status_html]
)
analyze_btn.click(
fn=None,
js="""async (lat, lon) => {
if (typeof gtag === 'function') {
gtag('event', 'analyze_click', {
'event_category': 'engagement',
'latitude': lat,
'longitude': lon
});
}
if (lat === null || lon === null || isNaN(lat) || isNaN(lon)) {
return JSON.stringify({ error: "Invalid coordinates. Please enter a valid latitude and longitude." });
}
const variables = [
"temperature_2m_max", "temperature_2m_min", "rain_sum", "precipitation_sum",
"wind_gusts_10m_max", "shortwave_radiation_sum", "temperature_2m_mean",
"cloud_cover_mean", "et0_fao_evapotranspiration",
"growing_degree_days_base_0_limit_50", "leaf_wetness_probability_mean",
"vapour_pressure_deficit_max"
].join(",");
const url = `https://api.open-meteo.com/v1/forecast?latitude=${lat}&longitude=${lon}&daily=${variables}&timezone=auto&past_days=7&forecast_days=7`;
try {
const resp = await fetch(url);
if (!resp.ok) {
return JSON.stringify({ error: `Weather data unavailable. Please try again later. (HTTP ${resp.status})` });
}
const data = await resp.json();
return JSON.stringify(data);
} catch (e) {
return JSON.stringify({ error: "Weather data unavailable. Network error. Please try again later." });
}
}""",
inputs=[lat_input, lon_input],
outputs=[weather_json]
)
weather_json.change(
fn=handle_weather_and_analyze,
inputs=[weather_json, lat_input, lon_input, crop_input, phenology_input, notes_input, current_concern_input, app_state],
outputs=[
app_state, get_loc_btn, analyze_btn,
status_html, step_html, cache_html,
initial_placeholder, view_insight_btn, tabs_container,
summary_html, historical_html, forecast_html, risks_html, recommendations_html,
cache_out
]
)
lat_input.change(
fn=validate_coordinates_ui,
inputs=[lat_input, lon_input, app_state],
outputs=[analyze_btn]
)
lon_input.change(
fn=validate_coordinates_ui,
inputs=[lat_input, lon_input, app_state],
outputs=[analyze_btn]
)
def show_insight_view(state_dict):
# Langkah 1: tampilkan tabs + tombol download TERLEBIH DAHULU,
# tapi tanpa value/file dulu (href kosong). Ini memastikan
# elemen tombolnya sudah ter-mount & visible di DOM sebelum
# kita isi hrefnya di langkah 2 (.then()). Kalau visible=True
# dan value diisi dalam SATU update yang sama, kadang Gradio
# sempat me-render ulang elemennya sehingga href belum
# "nyantol" saat klik pertama -> baru berfungsi di klik kedua.
state = AppState.from_dict(state_dict)
has_cache = bool(state.cache)
return (
gr.update(visible=False),
gr.update(visible=True),
gr.update(visible=has_cache, value=None)
)
def prepare_download_file(state_dict):
# Langkah 2: baru sekarang isi value (href) tombol, SETELAH
# tombolnya sudah pasti ter-mount & visible dari langkah 1.
state = AppState.from_dict(state_dict)
export_path = build_export_file(state.cache)
return gr.update(value=export_path, visible=bool(export_path))
view_insight_btn.click(
fn=show_insight_view,
inputs=[app_state],
js=f"""() => {{
if (typeof gtag === 'function') {{
gtag('event', 'view_insight_click', {{
'event_category': 'engagement'
}});
}}
window.open('{SHOPEE_LINK}', '_blank');
}}""",
outputs=[view_insight_btn, tabs_container, download_data_btn]
).then(
fn=prepare_download_file,
inputs=[app_state],
outputs=[download_data_btn]
)
# 4. When cache_out changes, save to localStorage (overwrite old data)
cache_out.change(
fn=None,
js="""(data) => {
if (data && data !== '{}' && data !== '') {
try {
// Always overwrite — never accumulate
localStorage.setItem('space_weather_cache', data);
} catch (e) {
console.error('Failed to save cache to localStorage:', e);
}
}
return [];
}""",
inputs=[cache_out]
)
if __name__ == "__main__":
demo.launch(
server_name="0.0.0.0",
server_port=7860,
theme=THEME,
css=CSS,
allowed_paths=["assets"]
)
|