FajarHidaa commited on
Commit
96536de
·
verified ·
1 Parent(s): c92f6c3

Update app.py

Browse files
Files changed (1) hide show
  1. app.py +555 -1
app.py CHANGED
@@ -14,6 +14,7 @@ from datetime import datetime, timezone
14
  from typing import Dict, List, Optional, Tuple, Any
15
  from dataclasses import dataclass
16
  import logging
 
17
 
18
  import gradio as gr
19
  import requests
@@ -119,6 +120,7 @@ VALID_SEVERITY = {"low", "medium", "high"}
119
  VALID_CONFIDENCE = {"low", "medium", "high"}
120
  VALID_PRIORITY = {"low", "medium", "high"}
121
 
 
122
  WEATHER_VARIABLES = [
123
  # Temperature and plant development
124
  "temperature_2m_max",
@@ -147,6 +149,7 @@ WEATHER_VARIABLES = [
147
  ]
148
 
149
 
 
150
  # ------------------------------------------------------------------
151
  # DATA CLASSES
152
  # ------------------------------------------------------------------
@@ -799,6 +802,7 @@ def handle_weather_and_analyze(weather_json_str: str, lat: float, lon: float, cr
799
  "current_concern": current_concern,
800
  },
801
  "raw_weather": raw_weather,
 
802
  "analysis": llm_output,
803
  "created_at": datetime.now(timezone.utc).isoformat()
804
  }
@@ -848,6 +852,480 @@ def handle_weather_and_analyze(weather_json_str: str, lat: float, lon: float, cr
848
  # ------------------------------------------------------------------
849
  # 4. ANALYTICS ENGINE
850
  # ------------------------------------------------------------------
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
851
  def normalize_weather_data(raw_data: Dict, lat: float, lon: float, client_date: str) -> Tuple[Optional[Dict], str]:
852
  try:
853
  timezone_str = raw_data.get("timezone", "UTC")
@@ -899,6 +1377,12 @@ def normalize_weather_data(raw_data: Dict, lat: float, lon: float, client_date:
899
  "today": today,
900
  "forecast": forecast
901
  }
 
 
 
 
 
 
902
  return normalized, ""
903
 
904
  except Exception as e:
@@ -933,6 +1417,49 @@ def build_llm_payload(normalized_data: Dict, lat: float, lon: float, client_date
933
  "location_timezone": location.get("timezone", "UTC")
934
  },
935
  "units": normalized_data.get("units", {}),
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
936
  "historical": {"daily": normalized_data.get("historical", {})},
937
  "forecast": {"daily": normalized_data.get("forecast", {})}
938
  }
@@ -1045,12 +1572,38 @@ def build_export_file(cache_entry: Optional[Dict]) -> Optional[str]:
1045
  lines.append(f"- Current Concern : {field_context.get('current_concern') or '-'}")
1046
  lines.append("")
1047
  lines.append("--- DATA CUACA MENTAH (Ecwf, historical 7 hari + forecast 7 hari) ---")
1048
- lines.append(json.dumps(cache_entry.get("raw_weather", {}), ensure_ascii=False, indent=2))
 
 
 
 
 
 
 
1049
  lines.append("")
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1050
  lines.append("--- HASIL ANALISIS GEMINI AI ---")
1051
  lines.append(f"Ringkasan: {analysis.get('summary', '-')}")
1052
  lines.append("")
1053
 
 
 
 
 
 
1054
  hist = analysis.get("historical", {}) or {}
1055
  lines.append("Historical (7 hari terakhir):")
1056
  lines.append(f" Kondisi : {hist.get('condition', '-')}")
@@ -1474,6 +2027,7 @@ def handle_analyze(lat: float, lon: float, state_dict: Dict):
1474
  "current_concern": current_concern,
1475
  },
1476
  "raw_weather": raw_weather,
 
1477
  "analysis": llm_output,
1478
  "created_at": datetime.now(timezone.utc).isoformat()
1479
  }
 
14
  from typing import Dict, List, Optional, Tuple, Any
15
  from dataclasses import dataclass
16
  import logging
17
+ import math
18
 
19
  import gradio as gr
20
  import requests
 
120
  VALID_CONFIDENCE = {"low", "medium", "high"}
121
  VALID_PRIORITY = {"low", "medium", "high"}
122
 
123
+
124
  WEATHER_VARIABLES = [
125
  # Temperature and plant development
126
  "temperature_2m_max",
 
149
  ]
150
 
151
 
152
+
153
  # ------------------------------------------------------------------
154
  # DATA CLASSES
155
  # ------------------------------------------------------------------
 
802
  "current_concern": current_concern,
803
  },
804
  "raw_weather": raw_weather,
805
+ "derived_features": normalized.get("derived_features", {}),
806
  "analysis": llm_output,
807
  "created_at": datetime.now(timezone.utc).isoformat()
808
  }
 
852
  # ------------------------------------------------------------------
853
  # 4. ANALYTICS ENGINE
854
  # ------------------------------------------------------------------
855
+
856
+
857
+
858
+ # ------------------------------------------------------------------
859
+ # AGRICULTURAL WEATHER FEATURE ENGINEERING
860
+ # ------------------------------------------------------------------
861
+
862
+ def _weather_num(value):
863
+ """Convert valid finite numeric values to float; otherwise None."""
864
+ try:
865
+ if value is None:
866
+ return None
867
+ number = float(value)
868
+ return number if math.isfinite(number) else None
869
+ except (TypeError, ValueError):
870
+ return None
871
+
872
+
873
+ def _weather_probability_fraction(value, unit=None):
874
+ """
875
+ Normalize a probability to 0-1.
876
+ Open-Meteo probability variables commonly use percent units.
877
+ """
878
+ number = _weather_num(value)
879
+ if number is None:
880
+ return None
881
+
882
+ if unit and "%" in str(unit):
883
+ number /= 100.0
884
+ elif number > 1.0:
885
+ number /= 100.0
886
+
887
+ return max(0.0, min(1.0, number))
888
+
889
+
890
+ def engineer_weather_features(normalized):
891
+ """
892
+ Build derived agricultural weather features from the existing
893
+ daily arrays. No crop, soil, or sensor input is required.
894
+
895
+ Input:
896
+ normalized["historical"], normalized["today"],
897
+ normalized["forecast"], normalized["units"]
898
+
899
+ Output:
900
+ Separate daily feature arrays plus period summaries.
901
+ """
902
+
903
+ units = normalized.get("units", {}) or {}
904
+ periods = ("historical", "today", "forecast")
905
+ records = []
906
+
907
+ # 1. Combine the three time periods chronologically.
908
+ for period in periods:
909
+ block = normalized.get(period, {}) or {}
910
+ dates = block.get("time", []) or []
911
+
912
+ for i, date in enumerate(dates):
913
+ raw = {}
914
+
915
+ for variable in WEATHER_VARIABLES:
916
+ values = block.get(variable, [])
917
+ value = (
918
+ values[i]
919
+ if isinstance(values, list) and i < len(values)
920
+ else None
921
+ )
922
+ raw[variable] = _weather_num(value)
923
+
924
+ rh = raw.get("relative_humidity_2m_mean")
925
+ leaf_wetness = _weather_probability_fraction(
926
+ raw.get("leaf_wetness_probability_mean"),
927
+ units.get("leaf_wetness_probability_mean"),
928
+ )
929
+ precip_probability = _weather_probability_fraction(
930
+ raw.get("precipitation_probability_max"),
931
+ units.get("precipitation_probability_max"),
932
+ )
933
+
934
+ temperature_mean = raw.get("temperature_2m_mean")
935
+ temperature_min = raw.get("temperature_2m_min")
936
+ temperature_max = raw.get("temperature_2m_max")
937
+ dewpoint_mean = raw.get("dew_point_2m_mean")
938
+ precipitation = raw.get("precipitation_sum")
939
+ precipitation_hours = raw.get("precipitation_hours")
940
+ et0 = raw.get("et0_fao_evapotranspiration")
941
+
942
+ water_balance = (
943
+ precipitation - et0
944
+ if precipitation is not None and et0 is not None
945
+ else None
946
+ )
947
+
948
+ features = {
949
+ # Temperature
950
+ "temperature_range_c": (
951
+ temperature_max - temperature_min
952
+ if temperature_max is not None
953
+ and temperature_min is not None
954
+ else None
955
+ ),
956
+
957
+ "dewpoint_depression_proxy_c": (
958
+ temperature_mean - dewpoint_mean
959
+ if temperature_mean is not None
960
+ and dewpoint_mean is not None
961
+ else None
962
+ ),
963
+
964
+ # Water balance proxy
965
+ "water_balance_proxy_mm": water_balance,
966
+
967
+ "precipitation_per_wet_hour_proxy": (
968
+ precipitation / precipitation_hours
969
+ if precipitation is not None
970
+ and precipitation_hours is not None
971
+ and precipitation_hours > 0
972
+ else None
973
+ ),
974
+
975
+ # Normalized probabilities
976
+ "leaf_wetness_fraction": leaf_wetness,
977
+ "precip_probability_fraction": precip_probability,
978
+
979
+ # Humidity and leaf-wetness interactions.
980
+ # These are environmental proxies, NOT disease probabilities.
981
+ "humidity_wetness_interaction": (
982
+ (rh / 100.0) * leaf_wetness
983
+ if rh is not None and leaf_wetness is not None
984
+ else None
985
+ ),
986
+
987
+ "wetness_duration_interaction": (
988
+ leaf_wetness
989
+ * max(0.0, min(1.0, precipitation_hours / 24.0))
990
+ if leaf_wetness is not None
991
+ and precipitation_hours is not None
992
+ else None
993
+ ),
994
+ }
995
+
996
+ records.append({
997
+ "date": date,
998
+ "period": period,
999
+ "raw": raw,
1000
+ "features": features,
1001
+ })
1002
+
1003
+ # 2. Consecutive days with nearly zero recorded precipitation.
1004
+ # 0.1 mm is an operational definition of a nearly rain-free day,
1005
+ # not a universal crop drought threshold.
1006
+ dry_streak = 0
1007
+
1008
+ for record in records:
1009
+ precipitation = record["raw"].get("precipitation_sum")
1010
+
1011
+ if precipitation is None:
1012
+ dry_streak = 0
1013
+ record["features"]["dry_spell_days"] = None
1014
+ elif precipitation <= 0.1:
1015
+ dry_streak += 1
1016
+ record["features"]["dry_spell_days"] = dry_streak
1017
+ else:
1018
+ dry_streak = 0
1019
+ record["features"]["dry_spell_days"] = 0
1020
+
1021
+ # 3. Trailing rolling sums and means across the continuous timeline.
1022
+ # Missing values are not replaced with zero.
1023
+ def rolling_value(index, source, key, window, operation):
1024
+ if index + 1 < window:
1025
+ return None
1026
+
1027
+ subset = records[index - window + 1:index + 1]
1028
+
1029
+ if source == "raw":
1030
+ values = [r["raw"].get(key) for r in subset]
1031
+ else:
1032
+ values = [r["features"].get(key) for r in subset]
1033
+
1034
+ if any(v is None for v in values):
1035
+ return None
1036
+
1037
+ if operation == "sum":
1038
+ return sum(values)
1039
+
1040
+ return sum(values) / len(values)
1041
+
1042
+ rolling_specs = {
1043
+ "precipitation_sum": ("raw", "precipitation_sum", "sum", "precipitation"),
1044
+ "et0_fao_evapotranspiration": (
1045
+ "raw", "et0_fao_evapotranspiration", "sum", "et0"
1046
+ ),
1047
+ "water_balance_proxy_mm": (
1048
+ "feature", "water_balance_proxy_mm", "sum", "water_balance"
1049
+ ),
1050
+ "growing_degree_days_base_0_limit_50": (
1051
+ "raw", "growing_degree_days_base_0_limit_50", "sum", "gdd"
1052
+ ),
1053
+ "temperature_2m_mean": (
1054
+ "raw", "temperature_2m_mean", "mean", "temperature_mean"
1055
+ ),
1056
+ "vapour_pressure_deficit_max": (
1057
+ "raw", "vapour_pressure_deficit_max", "mean", "vpd"
1058
+ ),
1059
+ "relative_humidity_2m_mean": (
1060
+ "raw", "relative_humidity_2m_mean", "mean", "rh_mean_pct"
1061
+ ),
1062
+ "leaf_wetness_fraction": (
1063
+ "feature", "leaf_wetness_fraction", "mean", "leaf_wetness"
1064
+ ),
1065
+ }
1066
+
1067
+ for i, record in enumerate(records):
1068
+ for window in (3, 7):
1069
+ for _, (source, key, operation, prefix) in rolling_specs.items():
1070
+ result_key = f"{prefix}_{window}d_{operation}"
1071
+ record["features"][result_key] = rolling_value(
1072
+ i, source, key, window, operation
1073
+ )
1074
+
1075
+ # 4. One-day changes; values compare against the immediately
1076
+ # preceding calendar day, including across history/today/forecast.
1077
+ delta_specs = {
1078
+ "temperature_mean_delta_1d": (
1079
+ "raw", "temperature_2m_mean"
1080
+ ),
1081
+ "vpd_delta_1d": (
1082
+ "raw", "vapour_pressure_deficit_max"
1083
+ ),
1084
+ "rh_mean_delta_1d": (
1085
+ "raw", "relative_humidity_2m_mean"
1086
+ ),
1087
+ "precipitation_delta_1d": (
1088
+ "raw", "precipitation_sum"
1089
+ ),
1090
+ "leaf_wetness_delta_1d": (
1091
+ "feature", "leaf_wetness_fraction"
1092
+ ),
1093
+ }
1094
+
1095
+ for i, record in enumerate(records):
1096
+ for feature_name in delta_specs:
1097
+ record["features"][feature_name] = None
1098
+
1099
+ if i == 0:
1100
+ continue
1101
+
1102
+ previous = records[i - 1]
1103
+
1104
+ for feature_name, (source, key) in delta_specs.items():
1105
+ current_value = (
1106
+ record["raw"].get(key)
1107
+ if source == "raw"
1108
+ else record["features"].get(key)
1109
+ )
1110
+ previous_value = (
1111
+ previous["raw"].get(key)
1112
+ if source == "raw"
1113
+ else previous["features"].get(key)
1114
+ )
1115
+
1116
+ if current_value is not None and previous_value is not None:
1117
+ record["features"][feature_name] = (
1118
+ current_value - previous_value
1119
+ )
1120
+
1121
+ # 5. Forecast daily values relative to the historical 7-day mean.
1122
+ anomaly_specs = {
1123
+ "temperature_mean_delta_vs_history7d": (
1124
+ "raw", "temperature_2m_mean"
1125
+ ),
1126
+ "vpd_delta_vs_history7d": (
1127
+ "raw", "vapour_pressure_deficit_max"
1128
+ ),
1129
+ "rh_mean_delta_vs_history7d": (
1130
+ "raw", "relative_humidity_2m_mean"
1131
+ ),
1132
+ "precipitation_delta_vs_history7d": (
1133
+ "raw", "precipitation_sum"
1134
+ ),
1135
+ "et0_delta_vs_history7d": (
1136
+ "raw", "et0_fao_evapotranspiration"
1137
+ ),
1138
+ "leaf_wetness_delta_vs_history7d": (
1139
+ "feature", "leaf_wetness_fraction"
1140
+ ),
1141
+ }
1142
+
1143
+ historical_records = [
1144
+ r for r in records if r["period"] == "historical"
1145
+ ]
1146
+
1147
+ baselines = {}
1148
+
1149
+ for feature_name, (source, key) in anomaly_specs.items():
1150
+ values = [
1151
+ r["raw"].get(key) if source == "raw"
1152
+ else r["features"].get(key)
1153
+ for r in historical_records
1154
+ ]
1155
+ values = [v for v in values if v is not None]
1156
+
1157
+ baselines[feature_name] = (
1158
+ sum(values) / len(values) if values else None
1159
+ )
1160
+
1161
+ for record in records:
1162
+ for feature_name, (source, key) in anomaly_specs.items():
1163
+ record["features"][feature_name] = None
1164
+
1165
+ if record["period"] != "forecast":
1166
+ continue
1167
+
1168
+ value = (
1169
+ record["raw"].get(key) if source == "raw"
1170
+ else record["features"].get(key)
1171
+ )
1172
+ baseline = baselines[feature_name]
1173
+
1174
+ if value is not None and baseline is not None:
1175
+ record["features"][feature_name] = value - baseline
1176
+
1177
+ # 6. Return feature arrays grouped by the original time windows.
1178
+ all_feature_names = sorted({
1179
+ key
1180
+ for record in records
1181
+ for key in record["features"]
1182
+ })
1183
+
1184
+ derived_blocks = {}
1185
+
1186
+ for period in periods:
1187
+ period_records = [
1188
+ r for r in records if r["period"] == period
1189
+ ]
1190
+
1191
+ derived_blocks[period] = {
1192
+ "time": [r["date"] for r in period_records],
1193
+ "features": {
1194
+ name: [
1195
+ r["features"].get(name)
1196
+ for r in period_records
1197
+ ]
1198
+ for name in all_feature_names
1199
+ },
1200
+ }
1201
+
1202
+ # 7. Compact period-level summary for the LLM.
1203
+ def mean_values(values):
1204
+ values = [v for v in values if v is not None]
1205
+ return sum(values) / len(values) if values else None
1206
+
1207
+ def total_values(values):
1208
+ # If any daily value is missing, avoid presenting a partial
1209
+ # sum as the complete period total.
1210
+ if not values or any(v is None for v in values):
1211
+ return None
1212
+ return sum(values)
1213
+
1214
+ def summarize_period(period):
1215
+ subset = [r for r in records if r["period"] == period]
1216
+
1217
+ def raw_values(key):
1218
+ return [r["raw"].get(key) for r in subset]
1219
+
1220
+ def feature_values(key):
1221
+ return [r["features"].get(key) for r in subset]
1222
+
1223
+ return {
1224
+ "days": len(subset),
1225
+ "temperature_mean_c": mean_values(
1226
+ raw_values("temperature_2m_mean")
1227
+ ),
1228
+ "temperature_max_peak_c": (
1229
+ max([v for v in raw_values("temperature_2m_max")
1230
+ if v is not None], default=None)
1231
+ ),
1232
+ "temperature_min_low_c": (
1233
+ min([v for v in raw_values("temperature_2m_min")
1234
+ if v is not None], default=None)
1235
+ ),
1236
+ "temperature_range_mean_c": mean_values(
1237
+ feature_values("temperature_range_c")
1238
+ ),
1239
+ "precipitation_total_mm": total_values(
1240
+ raw_values("precipitation_sum")
1241
+ ),
1242
+ "precipitation_hours_total": total_values(
1243
+ raw_values("precipitation_hours")
1244
+ ),
1245
+ "et0_total_mm": total_values(
1246
+ raw_values("et0_fao_evapotranspiration")
1247
+ ),
1248
+ "water_balance_proxy_total_mm": total_values(
1249
+ feature_values("water_balance_proxy_mm")
1250
+ ),
1251
+ "gdd_total": total_values(
1252
+ raw_values("growing_degree_days_base_0_limit_50")
1253
+ ),
1254
+ "vpd_mean": mean_values(
1255
+ raw_values("vapour_pressure_deficit_max")
1256
+ ),
1257
+ "relative_humidity_mean_pct": mean_values(
1258
+ raw_values("relative_humidity_2m_mean")
1259
+ ),
1260
+ "leaf_wetness_mean_fraction": mean_values(
1261
+ feature_values("leaf_wetness_fraction")
1262
+ ),
1263
+ "humidity_wetness_interaction_mean": mean_values(
1264
+ feature_values("humidity_wetness_interaction")
1265
+ ),
1266
+ "longest_dry_spell_days": max(
1267
+ [v for v in feature_values("dry_spell_days")
1268
+ if v is not None],
1269
+ default=None
1270
+ ),
1271
+ "max_wind_speed": max(
1272
+ [v for v in raw_values("wind_speed_10m_max")
1273
+ if v is not None],
1274
+ default=None
1275
+ ),
1276
+ "max_wind_gust": max(
1277
+ [v for v in raw_values("wind_gusts_10m_max")
1278
+ if v is not None],
1279
+ default=None
1280
+ ),
1281
+ "precip_probability_mean_fraction": mean_values(
1282
+ feature_values("precip_probability_fraction")
1283
+ ),
1284
+ }
1285
+
1286
+ history_summary = summarize_period("historical")
1287
+ forecast_summary = summarize_period("forecast")
1288
+
1289
+ comparison_keys = [
1290
+ "temperature_mean_c",
1291
+ "precipitation_total_mm",
1292
+ "et0_total_mm",
1293
+ "water_balance_proxy_total_mm",
1294
+ "gdd_total",
1295
+ "vpd_mean",
1296
+ "relative_humidity_mean_pct",
1297
+ "leaf_wetness_mean_fraction",
1298
+ ]
1299
+
1300
+ comparison = {}
1301
+
1302
+ for key in comparison_keys:
1303
+ h = history_summary.get(key)
1304
+ f = forecast_summary.get(key)
1305
+
1306
+ comparison[key + "_forecast_minus_history"] = (
1307
+ f - h if h is not None and f is not None else None
1308
+ )
1309
+
1310
+ return {
1311
+ "historical": derived_blocks["historical"],
1312
+ "today": derived_blocks["today"],
1313
+ "forecast": derived_blocks["forecast"],
1314
+ "summary": {
1315
+ "history_7d": history_summary,
1316
+ "forecast_7d": forecast_summary,
1317
+ "forecast_minus_history": comparison,
1318
+ },
1319
+ }
1320
+
1321
+
1322
+
1323
+
1324
+
1325
+
1326
+
1327
+
1328
+
1329
  def normalize_weather_data(raw_data: Dict, lat: float, lon: float, client_date: str) -> Tuple[Optional[Dict], str]:
1330
  try:
1331
  timezone_str = raw_data.get("timezone", "UTC")
 
1377
  "today": today,
1378
  "forecast": forecast
1379
  }
1380
+
1381
+
1382
+ normalized["derived_features"] = engineer_weather_features(
1383
+ normalized
1384
+ )
1385
+
1386
  return normalized, ""
1387
 
1388
  except Exception as e:
 
1417
  "location_timezone": location.get("timezone", "UTC")
1418
  },
1419
  "units": normalized_data.get("units", {}),
1420
+
1421
+
1422
+
1423
+ # NEW: engineered agricultural weather features
1424
+ "derived_features": normalized_data.get(
1425
+ "derived_features", {}
1426
+ ),
1427
+
1428
+ "derived_feature_guide": {
1429
+ "temperature_range_c":
1430
+ "Daily maximum temperature minus minimum temperature.",
1431
+ "dewpoint_depression_proxy_c":
1432
+ "Mean air temperature minus mean dewpoint.",
1433
+ "water_balance_proxy_mm":
1434
+ "Precipitation minus reference ET0; not soil water balance.",
1435
+ "precipitation_per_wet_hour_proxy":
1436
+ "Daily precipitation divided by precipitation hours; "
1437
+ "not peak rainfall intensity.",
1438
+ "humidity_wetness_interaction":
1439
+ "Relative humidity fraction multiplied by leaf-wetness "
1440
+ "probability fraction; not disease probability.",
1441
+ "wetness_duration_interaction":
1442
+ "Leaf-wetness probability multiplied by precipitation "
1443
+ "hours divided by 24; not measured leaf-wetness duration.",
1444
+ "dry_spell_days":
1445
+ "Consecutive days with precipitation at or below "
1446
+ "0.1 mm; not a crop-specific drought threshold.",
1447
+ "rolling_features":
1448
+ "Trailing 3-day and 7-day sums or means. Windows span "
1449
+ "the continuous history, today, and forecast timeline.",
1450
+ "delta_vs_history7d":
1451
+ "Forecast daily value minus the mean of available "
1452
+ "historical daily values over the previous 7 days.",
1453
+ "forecast_minus_history":
1454
+ "Difference between the 7-day forecast summary and "
1455
+ "the 7-day historical summary.",
1456
+ "probability_fraction":
1457
+ "Normalized to a 0-1 scale when the source unit is "
1458
+ "percent. Null means unavailable, not zero."
1459
+ },
1460
+
1461
+
1462
+
1463
  "historical": {"daily": normalized_data.get("historical", {})},
1464
  "forecast": {"daily": normalized_data.get("forecast", {})}
1465
  }
 
1572
  lines.append(f"- Current Concern : {field_context.get('current_concern') or '-'}")
1573
  lines.append("")
1574
  lines.append("--- DATA CUACA MENTAH (Ecwf, historical 7 hari + forecast 7 hari) ---")
1575
+
1576
+
1577
+ lines.append("--- DATA CUACA MENTAH (Open-Meteo, historical + forecast) ---")
1578
+ lines.append(json.dumps(
1579
+ cache_entry.get("raw_weather", {}),
1580
+ ensure_ascii=False,
1581
+ indent=2
1582
+ ))
1583
  lines.append("")
1584
+
1585
+ # FEATURE ENGINEERING: tambahkan tepat di sini
1586
+ lines.append("--- FITUR CUACA TURUNAN ---")
1587
+ lines.append(
1588
+ json.dumps(
1589
+ cache_entry.get("derived_features", {}),
1590
+ ensure_ascii=False,
1591
+ indent=2,
1592
+ allow_nan=False
1593
+ )
1594
+ )
1595
+ lines.append("")
1596
+
1597
+ # Bagian analisis Gemini tetap dilanjutkan seperti sebelumnya
1598
  lines.append("--- HASIL ANALISIS GEMINI AI ---")
1599
  lines.append(f"Ringkasan: {analysis.get('summary', '-')}")
1600
  lines.append("")
1601
 
1602
+
1603
+
1604
+ lines.append(f"Ringkasan: {analysis.get('summary', '-')}")
1605
+ lines.append("")
1606
+
1607
  hist = analysis.get("historical", {}) or {}
1608
  lines.append("Historical (7 hari terakhir):")
1609
  lines.append(f" Kondisi : {hist.get('condition', '-')}")
 
2027
  "current_concern": current_concern,
2028
  },
2029
  "raw_weather": raw_weather,
2030
+ "derived_features": normalized.get("derived_features", {}),
2031
  "analysis": llm_output,
2032
  "created_at": datetime.now(timezone.utc).isoformat()
2033
  }