FajarHidaa commited on
Commit
8d0f2bd
·
verified ·
1 Parent(s): 5998792

Update app.py

Browse files
Files changed (1) hide show
  1. app.py +49 -9
app.py CHANGED
@@ -84,6 +84,29 @@ GEMINI_MAX_ROUNDS = 3 # putaran retry jika kena limit per menit (RPM)
84
  CONCURRENCY_LIMIT = 20 # analisis Gemini paralel
85
  MAX_UPLOAD_SIZE = "8mb"
86
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
87
  key_manager = GeminiKeyManager()
88
  preload() # load model & embedding produk di background thread
89
 
@@ -943,13 +966,15 @@ DERIVED_FEATURE_GUIDE = {
943
 
944
  def build_llm_payload(normalized_data: Dict, lat: float, lon: float, client_date: str,
945
  crop: str = "", phenology: str = "", notes: str = "",
946
- current_concern: str = "", has_image: bool = False) -> Dict:
 
947
  meta = normalized_data.get("meta", {})
948
  location = meta.get("location", {})
949
  tz = location.get("timezone", "UTC")
950
  return {
951
  "location": {"latitude": lat, "longitude": lon, "timezone": tz},
952
  "field_context": {
 
953
  "crop_type": crop or "Tidak ditentukan",
954
  "phenology_phase": phenology or "Tidak ditentukan",
955
  "field_notes": notes or "Tidak ada catatan khusus",
@@ -1161,6 +1186,7 @@ def build_export_file(cache_entry: Optional[Dict]) -> Optional[str]:
1161
  f"Timezone lokasi : {cache_entry.get('location_timezone')}",
1162
  "",
1163
  "Konteks Lahan:",
 
1164
  f"- Jenis Tanaman : {field_context.get('crop_type') or '-'}",
1165
  f"- Fase Fenologi : {field_context.get('phenology_phase') or '-'}",
1166
  f"- Catatan Lapangan : {field_context.get('field_notes') or '-'}",
@@ -1333,8 +1359,8 @@ def handle_gps_result(gps_json: str, state_dict: Dict):
1333
  return state.to_dict(), lat, lon, format_location_status(source, accuracy)
1334
 
1335
 
1336
- def _analysis_pipeline(state: AppState, weather_json_str: str, lat, lon, crop, phenology,
1337
- notes, current_concern, image_path):
1338
  """Generator utama. `state` dimutasi di sini dan dikirim balik lewat yield."""
1339
 
1340
  # --- Input kosong: tidak ada yang diubah ---
@@ -1384,6 +1410,8 @@ def _analysis_pipeline(state: AppState, weather_json_str: str, lat, lon, crop, p
1384
  yield error_outputs(state, STATE_FETCHING_WEATHER, coord_msg)
1385
  return
1386
 
 
 
1387
  prev = state.location or {}
1388
  state.location = {
1389
  "latitude": lat,
@@ -1416,7 +1444,7 @@ def _analysis_pipeline(state: AppState, weather_json_str: str, lat, lon, crop, p
1416
 
1417
  payload = build_llm_payload(
1418
  normalized, lat, lon, client_date, crop, phenology, notes, current_concern,
1419
- has_image=bool(image_data_url),
1420
  )
1421
  llm_output, gemini_error = call_gemini(payload, image_data_url)
1422
  image_data_url = None # lepas dari memori
@@ -1437,6 +1465,9 @@ def _analysis_pipeline(state: AppState, weather_json_str: str, lat, lon, crop, p
1437
  yield error_outputs(state, STATE_VALIDATING_OUTPUT, val_error)
1438
  return
1439
 
 
 
 
1440
  # --- Selesai: simpan SATU entry cache (tanpa foto) ---
1441
  cache_entry = {
1442
  "location": state.location,
@@ -1445,6 +1476,7 @@ def _analysis_pipeline(state: AppState, weather_json_str: str, lat, lon, crop, p
1445
  "location_timezone": raw_weather.get("timezone", "UTC"),
1446
  "client_timezone": state.client_timezone or "UTC",
1447
  "field_context": {
 
1448
  "crop_type": crop,
1449
  "phenology_phase": phenology,
1450
  "field_notes": notes,
@@ -1477,13 +1509,14 @@ def _analysis_pipeline(state: AppState, weather_json_str: str, lat, lon, crop, p
1477
  )
1478
 
1479
 
1480
- def handle_weather_and_analyze(weather_json_str: str, lat: float, lon: float, crop: str,
1481
- phenology: str, notes: str, current_concern: str,
1482
  image_path: Optional[str], state_dict: Dict):
1483
  state = AppState.from_dict(state_dict)
1484
  try:
1485
  yield from _analysis_pipeline(
1486
- state, weather_json_str, lat, lon, crop, phenology, notes, current_concern, image_path
 
1487
  )
1488
  except Exception:
1489
  logger.exception("Unexpected error in analysis pipeline")
@@ -1805,6 +1838,13 @@ with gr.Blocks(title="Space Weather", head=GA4_HEAD, delete_cache=(600, 600)) as
1805
  lat_input = gr.Number(label="Latitude", precision=6, value=0, info="-90 to 90")
1806
  lon_input = gr.Number(label="Longitude", precision=6, value=0, info="-180 to 180")
1807
 
 
 
 
 
 
 
 
1808
  crop_input = gr.Textbox(
1809
  label="Jenis Tanaman",
1810
  placeholder="Contoh: Padi, Jagung, Cabai",
@@ -1823,7 +1863,7 @@ with gr.Blocks(title="Space Weather", head=GA4_HEAD, delete_cache=(600, 600)) as
1823
  current_concern_input = gr.Textbox(
1824
  label="Current Concern",
1825
  placeholder="Contoh: Khawatir kekurangan air atau risiko penyakit jamur",
1826
- info="Opsional. Masukkan kondisi atau pertanyaan yang ingin diperiksa berdasarkan cuaca.",
1827
  lines=2,
1828
  )
1829
 
@@ -1908,7 +1948,7 @@ with gr.Blocks(title="Space Weather", head=GA4_HEAD, delete_cache=(600, 600)) as
1908
  analysis_event = weather_json.change(
1909
  fn=handle_weather_and_analyze,
1910
  inputs=[
1911
- weather_json, lat_input, lon_input, crop_input, phenology_input,
1912
  notes_input, current_concern_input, image_input, app_state,
1913
  ],
1914
  outputs=[
 
84
  CONCURRENCY_LIMIT = 20 # analisis Gemini paralel
85
  MAX_UPLOAD_SIZE = "8mb"
86
 
87
+ # Profil pengguna: dropdown mengirim KEY stabil (bukan label beremoji).
88
+ # Server memvalidasi key dengan whitelist lalu memetakannya ke label bersih untuk LLM.
89
+ PROFILE_CHOICES = [
90
+ ("🧑‍🌾 Petani Sawah / Lahan Terbuka", "petani_lahan_terbuka"),
91
+ ("🥬 Petani Hidroponik / Kebun Kota", "hidroponik_kebun_kota"),
92
+ ("🏡 Tanam di Rumah (Pekarangan / Pot)", "tanam_di_rumah"),
93
+ ("🪴 Pecinta Tanaman Hias", "tanaman_hias"),
94
+ ("🌱 Lainnya / Pemula Umum", "lainnya_pemula"),
95
+ ]
96
+ PROFILE_LABELS = {
97
+ "petani_lahan_terbuka": "Petani Sawah / Lahan Terbuka",
98
+ "hidroponik_kebun_kota": "Petani Hidroponik / Kebun Kota",
99
+ "tanam_di_rumah": "Tanam di Rumah (Pekarangan / Pot)",
100
+ "tanaman_hias": "Pecinta Tanaman Hias",
101
+ "lainnya_pemula": "Lainnya / Pemula Umum",
102
+ }
103
+
104
+
105
+ def normalize_profile(value: Any) -> str:
106
+ """Kembalikan key profil yang valid, atau "" bila tidak dipilih / tidak dikenal."""
107
+ return value if isinstance(value, str) and value in PROFILE_LABELS else ""
108
+
109
+
110
  key_manager = GeminiKeyManager()
111
  preload() # load model & embedding produk di background thread
112
 
 
966
 
967
  def build_llm_payload(normalized_data: Dict, lat: float, lon: float, client_date: str,
968
  crop: str = "", phenology: str = "", notes: str = "",
969
+ current_concern: str = "", has_image: bool = False,
970
+ user_profile: str = "") -> Dict:
971
  meta = normalized_data.get("meta", {})
972
  location = meta.get("location", {})
973
  tz = location.get("timezone", "UTC")
974
  return {
975
  "location": {"latitude": lat, "longitude": lon, "timezone": tz},
976
  "field_context": {
977
+ "user_profile": PROFILE_LABELS.get(user_profile, "Tidak ditentukan"),
978
  "crop_type": crop or "Tidak ditentukan",
979
  "phenology_phase": phenology or "Tidak ditentukan",
980
  "field_notes": notes or "Tidak ada catatan khusus",
 
1186
  f"Timezone lokasi : {cache_entry.get('location_timezone')}",
1187
  "",
1188
  "Konteks Lahan:",
1189
+ f"- Profil Pengguna : {PROFILE_LABELS.get(field_context.get('user_profile'), '-')}",
1190
  f"- Jenis Tanaman : {field_context.get('crop_type') or '-'}",
1191
  f"- Fase Fenologi : {field_context.get('phenology_phase') or '-'}",
1192
  f"- Catatan Lapangan : {field_context.get('field_notes') or '-'}",
 
1359
  return state.to_dict(), lat, lon, format_location_status(source, accuracy)
1360
 
1361
 
1362
+ def _analysis_pipeline(state: AppState, weather_json_str: str, lat, lon, user_profile, crop,
1363
+ phenology, notes, current_concern, image_path):
1364
  """Generator utama. `state` dimutasi di sini dan dikirim balik lewat yield."""
1365
 
1366
  # --- Input kosong: tidak ada yang diubah ---
 
1410
  yield error_outputs(state, STATE_FETCHING_WEATHER, coord_msg)
1411
  return
1412
 
1413
+ user_profile = normalize_profile(user_profile)
1414
+
1415
  prev = state.location or {}
1416
  state.location = {
1417
  "latitude": lat,
 
1444
 
1445
  payload = build_llm_payload(
1446
  normalized, lat, lon, client_date, crop, phenology, notes, current_concern,
1447
+ has_image=bool(image_data_url), user_profile=user_profile,
1448
  )
1449
  llm_output, gemini_error = call_gemini(payload, image_data_url)
1450
  image_data_url = None # lepas dari memori
 
1465
  yield error_outputs(state, STATE_VALIDATING_OUTPUT, val_error)
1466
  return
1467
 
1468
+ # Field lama (sudah dihapus dari skema) tidak ikut tersimpan di cache/export
1469
+ llm_output.pop("concern_answer", None)
1470
+
1471
  # --- Selesai: simpan SATU entry cache (tanpa foto) ---
1472
  cache_entry = {
1473
  "location": state.location,
 
1476
  "location_timezone": raw_weather.get("timezone", "UTC"),
1477
  "client_timezone": state.client_timezone or "UTC",
1478
  "field_context": {
1479
+ "user_profile": user_profile,
1480
  "crop_type": crop,
1481
  "phenology_phase": phenology,
1482
  "field_notes": notes,
 
1509
  )
1510
 
1511
 
1512
+ def handle_weather_and_analyze(weather_json_str: str, lat: float, lon: float, user_profile: Optional[str],
1513
+ crop: str, phenology: str, notes: str, current_concern: str,
1514
  image_path: Optional[str], state_dict: Dict):
1515
  state = AppState.from_dict(state_dict)
1516
  try:
1517
  yield from _analysis_pipeline(
1518
+ state, weather_json_str, lat, lon, user_profile, crop, phenology, notes,
1519
+ current_concern, image_path
1520
  )
1521
  except Exception:
1522
  logger.exception("Unexpected error in analysis pipeline")
 
1838
  lat_input = gr.Number(label="Latitude", precision=6, value=0, info="-90 to 90")
1839
  lon_input = gr.Number(label="Longitude", precision=6, value=0, info="-180 to 180")
1840
 
1841
+ profile_input = gr.Dropdown(
1842
+ label="Profil Anda",
1843
+ choices=PROFILE_CHOICES,
1844
+ value=None,
1845
+ filterable=False, # mencegah keyboard HP muncul
1846
+ info="Opsional. Membantu menyesuaikan bahasa dan saran dengan situasi Anda.",
1847
+ )
1848
  crop_input = gr.Textbox(
1849
  label="Jenis Tanaman",
1850
  placeholder="Contoh: Padi, Jagung, Cabai",
 
1863
  current_concern_input = gr.Textbox(
1864
  label="Current Concern",
1865
  placeholder="Contoh: Khawatir kekurangan air atau risiko penyakit jamur",
1866
+ info="Opsional. Kekhawatiran atau pertanyaan Anda akan dijawab dalam ringkasan analisis.",
1867
  lines=2,
1868
  )
1869
 
 
1948
  analysis_event = weather_json.change(
1949
  fn=handle_weather_and_analyze,
1950
  inputs=[
1951
+ weather_json, lat_input, lon_input, profile_input, crop_input, phenology_input,
1952
  notes_input, current_concern_input, image_input, app_state,
1953
  ],
1954
  outputs=[