Files changed (1) hide show
  1. app.py +84 -84
app.py CHANGED
@@ -4,6 +4,7 @@ import datetime
4
  import json
5
  import numpy as np
6
  import cv2
 
7
 
8
  # --- TÙY CHỌN MÔ PHỎNG DỮ LIỆU ĐỂ TEST GIAO DIỆN ---
9
  current_detected_disease_context = "Chưa thực hiện quét mẫu bệnh phẩm."
@@ -101,9 +102,9 @@ def login_auth(username, password):
101
  is_admin = (current_user_role == "admin")
102
  is_user = (current_user_role == "user")
103
  return (
104
- gr.update(visible=False),
105
- gr.update(visible=True),
106
- "",
107
  gr.update(visible=is_admin),
108
  gr.update(visible=is_user),
109
  gr.update(visible=is_user),
@@ -124,17 +125,17 @@ def logout_fn():
124
  current_detected_disease_context = "Chưa thực hiện quét mẫu bệnh phẩm."
125
  current_user_role = "user"
126
  return (
127
- gr.update(visible=True),
128
- gr.update(visible=False),
129
- gr.update(value="Cây cà chua"),
130
- None,
131
- None,
132
- "",
133
- "",
134
- "",
135
- None,
136
- gr.update(value=[{"role": "assistant", "content": "🤖 Hệ thống đang đợi mẫu quét. Sau khi phân tích xong ảnh lá, tôi sẽ tự động nắm thông tin bệnh lý để kê đơn thuốc chính xác cho bà con!"}]),
137
- ""
138
  )
139
 
140
  def get_ticket_status_display(ticket):
@@ -151,11 +152,11 @@ def get_admin_tickets_list(selected_value=None):
151
 
152
  if not visible_tickets:
153
  return gr.update(choices=[], value=None), "", "Hiện chưa có yêu cầu hỗ trợ nào.", None, gr.update(visible=is_user)
154
-
155
  sorted_tickets = sorted(visible_tickets, key=lambda t: (get_ticket_status_display(t)[1], -t['id']))
156
  choices = [f"#{t['id']} - {t['plant']} - {t['time']} - [{get_ticket_status_display(t)[0]}]" for t in sorted_tickets]
157
  ticket_map = {c: t for c, t in zip(choices, sorted_tickets)}
158
-
159
  target_choice = selected_value if (selected_value and selected_value in choices) else choices[0]
160
  target_ticket = ticket_map[target_choice]
161
 
@@ -166,7 +167,7 @@ def delete_current_ticket(selected_option):
166
  if not selected_option:
167
  dropdown_up, h_info, c_info, img_p, followup_vis = get_admin_tickets_list()
168
  return "⚠️ Chưa chọn câu hỏi nào để xóa!", dropdown_up, h_info, c_info, img_p, followup_vis
169
-
170
  ticket_id = int(selected_option.split(" - ")[0].replace("#", ""))
171
  tickets = load_expert_tickets()
172
  for t in tickets:
@@ -228,44 +229,44 @@ def submit_admin_reply(selected_option, reply_text):
228
  if not selected_option or not reply_text.strip():
229
  dropdown_up, h_info, c_info, img_p, followup_vis = get_admin_tickets_list(selected_option)
230
  return "⚠️ Vui lòng chọn yêu cầu và nhập nội dung trả lời!", dropdown_up, h_info, c_info, img_p, followup_vis
231
-
232
  ticket_id = int(selected_option.split(" - ")[0].replace("#", ""))
233
  tickets = load_expert_tickets()
234
  now = datetime.datetime.now().strftime("%Y-%m-%d %H:%M:%S")
235
  target_ticket = None
236
-
237
  for t in tickets:
238
  if t['id'] == ticket_id:
239
  t['status'] = "ANSWERED"
240
  t['admin_reply'] = reply_text.strip()
241
- t['deleted_by_user'] = False
242
  if "messages" not in t: t["messages"] = [{"sender": "USER", "text": t["user_query"], "time": t["time"]}]
243
  t["messages"].append({"sender": "ADMIN", "text": reply_text.strip(), "time": now})
244
  target_ticket = t
245
  break
246
-
247
  if target_ticket:
248
  save_expert_tickets(tickets)
249
  status_label, _ = get_ticket_status_display(target_ticket)
250
  updated_option_str = f"#{ticket_id} - {target_ticket['plant']} - {target_ticket['time']} - [{status_label}]"
251
  dropdown_update, h_info, c_info, img_p, followup_vis = get_admin_tickets_list(updated_option_str)
252
  return "🎉 Đã gửi phản hồi chuyên gia thành công!", dropdown_update, h_info, c_info, img_p, followup_vis
253
-
254
  return "❌ Lỗi không tìm thấy yêu cầu!", *get_admin_tickets_list(selected_option)
255
 
256
  def submit_user_followup(selected_option, followup_text):
257
  if not selected_option or not followup_text.strip():
258
  return *get_admin_tickets_list(selected_option), ""
259
-
260
  ticket_id = int(selected_option.split(" - ")[0].replace("#", ""))
261
  tickets = load_expert_tickets()
262
  now = datetime.datetime.now().strftime("%Y-%m-%d %H:%M:%S")
263
  target_ticket = None
264
-
265
  for t in tickets:
266
  if t['id'] == ticket_id:
267
  t['status'] = "PENDING"
268
- t['deleted_by_admin'] = False
269
  if "messages" not in t:
270
  t["messages"] = [{"sender": "USER", "text": t["user_query"], "time": t["time"]}]
271
  if t.get("admin_reply"):
@@ -273,7 +274,7 @@ def submit_user_followup(selected_option, followup_text):
273
  t["messages"].append({"sender": "USER", "text": followup_text.strip(), "time": now})
274
  target_ticket = t
275
  break
276
-
277
  if target_ticket: save_expert_tickets(tickets)
278
  status_label, _ = get_ticket_status_display(target_ticket)
279
  updated_option_str = f"#{ticket_id} - {target_ticket['plant']} - {target_ticket['time']} - [{status_label}]"
@@ -291,7 +292,7 @@ def submit_expert_request(user_question, selected_plant, input_image):
291
  if not user_question.strip():
292
  txt, img_p = check_user_expert_status()
293
  return "⚠️ Vui lòng nhập thắc mắc của bạn trước khi bấm gửi chuyên gia!", txt, img_p
294
-
295
  tickets = load_expert_tickets()
296
  new_id = len(tickets) + 1
297
  now = datetime.datetime.now().strftime("%Y-%m-%d %H:%M:%S")
@@ -324,34 +325,33 @@ def go_to_history_panel():
324
  def go_back_to_main_panel():
325
  return gr.update(visible=True), gr.update(visible=False)
326
 
327
- # MÔ PHỎNG XỬ LÝ ẢNH (KHÔNG CẦN FILE WEIGHT .PT)
 
328
  def analyze_leaf(selected_plant, input_image):
329
- global current_detected_disease_context
330
  if input_image is None:
331
- return None, "⚠️ CHÚ Ý: Hệ thống chưa nhận được mẫu bệnh phẩm đầu vào. Vui lòng cung cấp hình ảnh bề mặt lá cây!", [{"role": "assistant", "content": "🤖 Hệ thống đang đợi mẫu quét hợp lệ từ bà con."}], load_diagnose_history()
332
-
333
- # Tạo ảnh mock với khung viền xanh lá mô phỏng AI khoanh vùng
334
  h, w, _ = input_image.shape
335
  annotated_rgb = input_image.copy()
336
  cv2.rectangle(annotated_rgb, (int(w*0.2), int(h*0.2)), (int(w*0.8), int(h*0.8)), (45, 122, 18), 3)
337
  cv2.putText(annotated_rgb, f"Mock: {selected_plant} (92.5%)", (int(w*0.2), int(h*0.2)-10), cv2.FONT_HERSHEY_SIMPLEX, 0.7, (45, 122, 18), 2)
338
-
339
  current_detected_disease_context = f"Đối tượng kiểm tra: {selected_plant}. Ghi nhận dấu hiệu bệnh lý mô phỏng trên bề mặt lá."
340
  result_text = f"📋 BIÊN BẢN CHẨN ĐOÁN LÂM SÀNG ({selected_plant.upper()}):\n\n🧬 Bệnh đốm lá (Mô phỏng) ➔ Mức độ: 92.5%\n\n🚨 HỆ THỐNG ĐÃ KÍCH HOẠT TRỢ LÝ AI: Mời bà con trò chuyện để nhận tư vấn!"
341
  clear_chat_history = [
342
  {"role": "assistant", "content": f"🤖 Chào bà con! Tôi đã nhận dữ liệu quét mẫu cho **{selected_plant}**. Bà con cần tư vấn loại thuốc hay phác đồ nào không?"}
343
  ]
344
- save_diagnose_log(selected_plant, result_text)
345
  return annotated_rgb, result_text, clear_chat_history, load_diagnose_history()
346
 
347
- # MÔ PHỎNG CHATBOT (KHÔNG CẦN GEMINI API KEY)
348
  def chatbot_response(user_message, history):
349
  if history is None: history = []
350
- if not user_message.strip(): return "", history
351
-
352
  ai_reply = f"🤖 [Mô phỏng AI Doctor]: Tôi đã ghi nhận câu hỏi '{user_message}'. Đối với tình trạng hiện tại, bà con nên cách ly cây bệnh và bổ sung hoạt chất bảo vệ thực vật theo đúng liều lượng khuyến nghị."
353
  history.append({"role": "user", "content": user_message})
354
- history.append({"role": "assistant", "content": ai_reply})
355
  save_chat_log(user_message, ai_reply)
356
  return "", history
357
 
@@ -656,7 +656,7 @@ LEAF_HERO_HEAD = r"""
656
 
657
  resize(); render(years); requestAnimationFrame(tick);
658
  window.addEventListener("resize", () => { applyResponsive(); resize(); });
659
-
660
  setInterval(function () {
661
  const el = document.getElementById("login_wrapper");
662
  const onLogin = !!el && el.offsetParent !== null;
@@ -739,8 +739,8 @@ body.leaf-on .gradio-container { background: transparent !important; }
739
  }
740
  /* =================== END LEAF HERO LOGIN =================== */
741
 
742
- .gradio-container {
743
- background: linear-gradient(180deg, #eff5f3 0%, #e1ebe7 100%) !important;
744
  font-family: 'Inter', system-ui, sans-serif !important;
745
  }
746
  .medical-cross-red {
@@ -755,8 +755,8 @@ body.leaf-on .gradio-container { background: transparent !important; }
755
  .hospital-header-center .title-wrapper-h1 { display: inline-flex; align-items: center; justify-content: center; gap: 16px; text-align: center; margin: 0 auto; }
756
  .hospital-header-center h1 { text-align: center !important; color: white !important; font-weight: 800 !important; font-size: 28px !important; margin: 0 !important; display: inline-block; }
757
  .hospital-header-center p { text-align: center !important; margin: 8px auto 0 auto !important; color: #b2dfdb !important; font-size: 14px !important; }
758
- .scan-btn {
759
- background: linear-gradient(135deg, #007965, #00bfa5) !important; color: white !important; font-weight: 700 !important;
760
  border: none !important; border-radius: 12px !important; box-shadow: 0 5px 15px rgba(0, 121, 101, 0.2) !important; height: 48px; cursor: pointer;
761
  transition: all 0.25s ease !important;
762
  }
@@ -772,7 +772,7 @@ body.leaf-on .gradio-container { background: transparent !important; }
772
 
773
  .inline-history-btn {
774
  background: #ffffff !important; color: #007965 !important; border: 1.5px solid #007965 !important;
775
- font-weight: 700 !important; border-radius: 8px !important; padding: 0px 14px !important;
776
  height: 32px !important; font-size: 13px !important; cursor: pointer; transition: all 0.2s ease !important;
777
  box-shadow: 0 2px 5px rgba(0, 0, 0, 0.05) !important; display: inline-flex !important; align-items: center; justify-content: center;
778
  }
@@ -807,7 +807,7 @@ body.leaf-on .gradio-container { background: transparent !important; }
807
 
808
  initial_ticket_text, initial_ticket_img = check_user_expert_status()
809
 
810
- with gr.Blocks(title="Bệnh Viện Cây Trồng - Hệ Thống Chẩn Đoán AI", css=custom_css, head=LEAF_HERO_HEAD) as demo:
811
  with gr.Row(visible=True, elem_id="login_wrapper") as login_panel:
812
  with gr.Column(elem_id="login_content_col"):
813
  gr.HTML("""
@@ -837,42 +837,42 @@ with gr.Blocks(title="Bệnh Viện Cây Trồng - Hệ Thống Chẩn Đoán AI
837
  """)
838
  with gr.Column(scale=2, min_width=210):
839
  with gr.Row():
840
- btn_logout = gr.Button("🚪 ĐĂNG XUẤT HỆ THỐNG", elem_classes="logout-btn-style")
841
  with gr.Row():
842
  with gr.Column(scale=10):
843
  with gr.Group(elem_classes="gr-group"):
844
  gr.Markdown("<p style='color: #004b39; font-weight: 700; margin: 8px 10px; font-size: 15px;'>🗂️ 1. TIẾP NHẬN MẪU XÉT NGHIỆM</p>")
845
  plant_dropdown = gr.Dropdown(
846
- choices=["Cây lúa", "Cây ớt", "Cây cà chua", "Cây dâu tây", "Cây cà phê", "Cây ngô (Bắp)"],
847
  value="Cây cà chua", label="Lựa chọn phân khoa điều trị thực vật"
848
  )
849
  with gr.Group(elem_classes="gr-group"):
850
  image_input = gr.Image(type="numpy", label="Ảnh quét tế bào bề mặt lá", height=370)
851
  gr.HTML("<div style='padding: 0 10px 10px 10px;'>")
852
  btn_analyze = gr.Button("🩺 TIẾN HÀNH QUÉT & CHẨN ĐOÁN LÂM SÀNG", variant="primary", elem_classes="scan-btn")
853
- gr.HTML("</div>")
854
  with gr.Column(scale=11, elem_id="prescription_col"):
855
  with gr.Group(elem_classes="gr-group"):
856
  gr.Markdown("<p style='color: #004b39; font-weight: 700; margin: 8px 10px; font-size: 15px;'>🔬 2. KẾT QUẢ QUÉT THỊ GIÁC HỌC SÂU (AI DETECT)</p>")
857
- image_output = gr.Image(type="numpy", label="Bản đồ nội soi vi vị trí: Khoanh vùng khu trú ổ bệnh", height=370)
858
  gr.Markdown("<p style='color: #004b39; font-weight: 700; margin: 8px 10px 4px 10px; font-size: 15px;'>📄 3. ĐƠN THUỐC LÂM SÀNG SƠ BỘ</p>")
859
  text_output = gr.Textbox(
860
- label="Hồ sơ bệnh án điện tử xuất từ thuật toán",
861
- lines=5,
862
  placeholder="Hồ sơ bệnh án sơ bộ sẽ tự động xuất ra tại đây...",
863
  elem_classes="textbox_custom"
864
- )
865
 
866
  with gr.Column(scale=12, elem_id="chatbot_col"):
867
  with gr.Row(elem_classes="chatbot-title-container"):
868
  gr.Markdown("<p style='color: #2980b9; font-weight: 700; margin: 0; font-size: 16px; display: inline-block;'>💬 4. HỘI ĐỒNG TƯ VẤN THUỐC BẢO VỆ THỰC VẬT (CHATBOT AI)</p>")
869
- btn_history_nav = gr.Button("📂 Xem Lại Lịch Sử Bệnh Án", elem_classes="inline-history-btn")
870
  chatbot = gr.Chatbot(
871
  value=[{"role": "assistant", "content": "🤖 Hệ thống đang đợi mẫu quét. Sau khi phân tích xong ảnh lá, tôi sẽ tự động nắm thông tin bệnh lý để kê đơn thuốc chính xác cho bà con!"}],
872
  height=550,
873
  label="Trò chuyện trực tiếp với Chuyên gia Bảo vệ Thực vật AI",
874
  elem_classes="chatbot_custom"
875
- )
876
  with gr.Row(elem_id="chat_input_row"):
877
  chat_msg = gr.Textbox(
878
  placeholder="Hỏi chuyên gia về cách chữa trị, tên thuốc, liều lượng phun bón cho loại bệnh vừa quét...",
@@ -888,7 +888,7 @@ with gr.Blocks(title="Bệnh Viện Cây Trồng - Hệ Thống Chẩn Đoán AI
888
  expert_status_box = gr.HTML(value=initial_ticket_text)
889
  expert_ticket_img_view = gr.Image(value=initial_ticket_img, label="Ảnh mẫu lá bệnh do nhà nông gửi lên", height=250, interactive=False)
890
 
891
- gr.HTML("<div class='footer-text'>🔏 Hệ thống lõi được bảo mật bởi AI Doctor Lab © 2026 | Nền tảng Phân tích Công nghệ cao Học máy Ultralytics YOLOv8 & Google Gemini AI</div>")
892
 
893
  with gr.Column(visible=False) as history_panel:
894
  with gr.Row(elem_classes="hospital-header"):
@@ -899,7 +899,7 @@ with gr.Blocks(title="Bệnh Viện Cây Trồng - Hệ Thống Chẩn Đoán AI
899
  """)
900
  with gr.Column(scale=2, min_width=150):
901
  btn_back_to_clinic = gr.Button("⬅️ QUAY LẠI PHÒNG KHÁM", elem_classes="history-back-btn-style")
902
-
903
  with gr.Row():
904
  with gr.Column(visible=True) as user_diagnose_col:
905
  gr.Markdown("### ⏳ Nhật Ký Chẩn Đoán Ảnh:")
@@ -919,16 +919,16 @@ with gr.Blocks(title="Bệnh Viện Cây Trồng - Hệ Thống Chẩn Đoán AI
919
  interactive=False
920
  )
921
  btn_clear_chat = gr.Button("🗑️ XÓA NHẬT KÝ CHAT", variant="stop")
922
-
923
  gr.HTML("<hr style='margin: 25px 0; border: 1px solid #d4deda;'>")
924
-
925
  with gr.Group(elem_classes="gr-group"):
926
  gr.Markdown("<h3 style='color: #004b39; font-weight: 800; margin: 10px 12px; font-size: 18px;'>👨‍⚕️ HỘP THƯ TƯ VẤN CHUYÊN GIA (LỊCH SỬ HỎI ĐÁP)</h3>")
927
-
928
  with gr.Row(elem_id="expert_select_row"):
929
  admin_ticket_select = gr.Dropdown(label="Danh sách các câu hỏi hỗ trợ:", choices=[], value=None, scale=8)
930
  btn_delete_ticket = gr.Button("🗑️ XÓA CÂU HỎI / HỘI THOẠI NÀY", elem_classes="delete-btn-style", scale=2)
931
-
932
  with gr.Row():
933
  with gr.Column(scale=1):
934
  admin_ticket_detail = gr.HTML(value="Hiện chưa có yêu cầu hỗ trợ nào.")
@@ -937,7 +937,7 @@ with gr.Blocks(title="Bệnh Viện Cây Trồng - Hệ Thống Chẩn Đoán AI
937
 
938
  with gr.Row():
939
  admin_ticket_conversation = gr.HTML(value="", elem_id="full_width_conversation")
940
-
941
  with gr.Row():
942
  with gr.Column(scale=1, visible=False) as admin_control_panel:
943
  gr.Markdown("<hr style='margin: 15px 0; border: 1px dashed #007965;'>")
@@ -953,34 +953,34 @@ with gr.Blocks(title="Bệnh Viện Cây Trồng - Hệ Thống Chẩn Đoán AI
953
  btn_send_followup = gr.Button("💬 GỬI CÂU HỎI TIẾP TỤC CHO CHUYÊN GIA", variant="primary")
954
 
955
  btn_login.click(
956
- login_auth,
957
- inputs=[username_input, password_input],
958
  outputs=[login_panel, main_panel, error_output, admin_control_panel, user_followup_panel, user_expert_section, user_diagnose_col]
959
  )
960
-
961
  btn_logout.click(
962
- logout_fn,
963
  outputs=[
964
- login_panel,
965
- main_panel,
966
- plant_dropdown,
967
- image_input,
968
- image_output,
969
- text_output,
970
- expert_user_query,
971
- expert_status_box,
972
- expert_ticket_img_view,
973
- chatbot,
974
  chat_msg
975
  ]
976
  )
977
-
978
  btn_history_nav.click(
979
- go_to_history_panel,
980
  outputs=[main_panel, history_panel, history_diagnose_box, history_chat_box, admin_ticket_select, admin_ticket_detail, admin_ticket_conversation, admin_ticket_img_display, admin_control_panel, user_followup_panel, user_diagnose_col, user_chat_col]
981
  )
982
  btn_back_to_clinic.click(go_back_to_main_panel, outputs=[main_panel, history_panel])
983
-
984
  btn_analyze.click(analyze_leaf, inputs=[plant_dropdown, image_input], outputs=[image_output, text_output, chatbot, history_diagnose_box])
985
  btn_send.click(chatbot_response, inputs=[chat_msg, chatbot], outputs=[chat_msg, chatbot])
986
  chat_msg.submit(chatbot_response, inputs=[chat_msg, chatbot], outputs=[chat_msg, chatbot])
@@ -989,18 +989,18 @@ with gr.Blocks(title="Bệnh Viện Cây Trồng - Hệ Thống Chẩn Đoán AI
989
  btn_clear_chat.click(clear_chat_history_fn, outputs=[history_chat_box])
990
 
991
  btn_send_expert.click(
992
- submit_expert_request,
993
- inputs=[expert_user_query, plant_dropdown, image_input],
994
  outputs=[expert_user_query, expert_status_box, expert_ticket_img_view]
995
  )
996
  admin_ticket_select.change(
997
- on_select_admin_ticket,
998
- inputs=[admin_ticket_select],
999
  outputs=[admin_ticket_detail, admin_ticket_conversation, admin_ticket_img_display, user_followup_panel]
1000
  )
1001
  btn_submit_admin_reply.click(
1002
- submit_admin_reply,
1003
- inputs=[admin_ticket_select, admin_reply_input],
1004
  outputs=[admin_reply_status, admin_ticket_select, admin_ticket_detail, admin_ticket_conversation, admin_ticket_img_display, user_followup_panel]
1005
  )
1006
 
 
4
  import json
5
  import numpy as np
6
  import cv2
7
+ import spaces # <-- BẮT BUỘC cho ZeroGPU của HuggingFace
8
 
9
  # --- TÙY CHỌN MÔ PHỎNG DỮ LIỆU ĐỂ TEST GIAO DIỆN ---
10
  current_detected_disease_context = "Chưa thực hiện quét mẫu bệnh phẩm."
 
102
  is_admin = (current_user_role == "admin")
103
  is_user = (current_user_role == "user")
104
  return (
105
+ gr.update(visible=False),
106
+ gr.update(visible=True),
107
+ "",
108
  gr.update(visible=is_admin),
109
  gr.update(visible=is_user),
110
  gr.update(visible=is_user),
 
125
  current_detected_disease_context = "Chưa thực hiện quét mẫu bệnh phẩm."
126
  current_user_role = "user"
127
  return (
128
+ gr.update(visible=True),
129
+ gr.update(visible=False),
130
+ gr.update(value="Cây cà chua"),
131
+ None,
132
+ None,
133
+ "",
134
+ "",
135
+ "",
136
+ None,
137
+ gr.update(value=[{"role": "assistant", "content": "🤖 Hệ thống đang đợi mẫu quét. Sau khi phân tích xong ảnh lá, tôi sẽ tự động nắm thông tin bệnh lý để kê đơn thuốc chính xác cho bà con!"}]),
138
+ ""
139
  )
140
 
141
  def get_ticket_status_display(ticket):
 
152
 
153
  if not visible_tickets:
154
  return gr.update(choices=[], value=None), "", "Hiện chưa có yêu cầu hỗ trợ nào.", None, gr.update(visible=is_user)
155
+
156
  sorted_tickets = sorted(visible_tickets, key=lambda t: (get_ticket_status_display(t)[1], -t['id']))
157
  choices = [f"#{t['id']} - {t['plant']} - {t['time']} - [{get_ticket_status_display(t)[0]}]" for t in sorted_tickets]
158
  ticket_map = {c: t for c, t in zip(choices, sorted_tickets)}
159
+
160
  target_choice = selected_value if (selected_value and selected_value in choices) else choices[0]
161
  target_ticket = ticket_map[target_choice]
162
 
 
167
  if not selected_option:
168
  dropdown_up, h_info, c_info, img_p, followup_vis = get_admin_tickets_list()
169
  return "⚠️ Chưa chọn câu hỏi nào để xóa!", dropdown_up, h_info, c_info, img_p, followup_vis
170
+
171
  ticket_id = int(selected_option.split(" - ")[0].replace("#", ""))
172
  tickets = load_expert_tickets()
173
  for t in tickets:
 
229
  if not selected_option or not reply_text.strip():
230
  dropdown_up, h_info, c_info, img_p, followup_vis = get_admin_tickets_list(selected_option)
231
  return "⚠️ Vui lòng chọn yêu cầu và nhập nội dung trả lời!", dropdown_up, h_info, c_info, img_p, followup_vis
232
+
233
  ticket_id = int(selected_option.split(" - ")[0].replace("#", ""))
234
  tickets = load_expert_tickets()
235
  now = datetime.datetime.now().strftime("%Y-%m-%d %H:%M:%S")
236
  target_ticket = None
237
+
238
  for t in tickets:
239
  if t['id'] == ticket_id:
240
  t['status'] = "ANSWERED"
241
  t['admin_reply'] = reply_text.strip()
242
+ t['deleted_by_user'] = False
243
  if "messages" not in t: t["messages"] = [{"sender": "USER", "text": t["user_query"], "time": t["time"]}]
244
  t["messages"].append({"sender": "ADMIN", "text": reply_text.strip(), "time": now})
245
  target_ticket = t
246
  break
247
+
248
  if target_ticket:
249
  save_expert_tickets(tickets)
250
  status_label, _ = get_ticket_status_display(target_ticket)
251
  updated_option_str = f"#{ticket_id} - {target_ticket['plant']} - {target_ticket['time']} - [{status_label}]"
252
  dropdown_update, h_info, c_info, img_p, followup_vis = get_admin_tickets_list(updated_option_str)
253
  return "🎉 Đã gửi phản hồi chuyên gia thành công!", dropdown_update, h_info, c_info, img_p, followup_vis
254
+
255
  return "❌ Lỗi không tìm thấy yêu cầu!", *get_admin_tickets_list(selected_option)
256
 
257
  def submit_user_followup(selected_option, followup_text):
258
  if not selected_option or not followup_text.strip():
259
  return *get_admin_tickets_list(selected_option), ""
260
+
261
  ticket_id = int(selected_option.split(" - ")[0].replace("#", ""))
262
  tickets = load_expert_tickets()
263
  now = datetime.datetime.now().strftime("%Y-%m-%d %H:%M:%S")
264
  target_ticket = None
265
+
266
  for t in tickets:
267
  if t['id'] == ticket_id:
268
  t['status'] = "PENDING"
269
+ t['deleted_by_admin'] = False
270
  if "messages" not in t:
271
  t["messages"] = [{"sender": "USER", "text": t["user_query"], "time": t["time"]}]
272
  if t.get("admin_reply"):
 
274
  t["messages"].append({"sender": "USER", "text": followup_text.strip(), "time": now})
275
  target_ticket = t
276
  break
277
+
278
  if target_ticket: save_expert_tickets(tickets)
279
  status_label, _ = get_ticket_status_display(target_ticket)
280
  updated_option_str = f"#{ticket_id} - {target_ticket['plant']} - {target_ticket['time']} - [{status_label}]"
 
292
  if not user_question.strip():
293
  txt, img_p = check_user_expert_status()
294
  return "⚠️ Vui lòng nhập thắc mắc của bạn trước khi bấm gửi chuyên gia!", txt, img_p
295
+
296
  tickets = load_expert_tickets()
297
  new_id = len(tickets) + 1
298
  now = datetime.datetime.now().strftime("%Y-%m-%d %H:%M:%S")
 
325
  def go_back_to_main_panel():
326
  return gr.update(visible=True), gr.update(visible=False)
327
 
328
+ # ==== HÀM CHẠY TRÊN GPU (BẮT BUỘC PHẢI CÓ @spaces.GPU CHO ZEROGPU) ====
329
+ @spaces.GPU(duration=60)
330
  def analyze_leaf(selected_plant, input_image):
331
+ global current_detected_disease_context
332
  if input_image is None:
333
+ return None, "⚠️ CHÚ Ý: Hệ thống chưa nhận được mẫu bệnh phẩm đầu vào. Vui lòng cung cấp hình ảnh bề mặt lá cây!", [{"role": "assistant", "content": "🤖 Hệ thống đang đợi mẫu quét hợp lệ từ bà con."}], load_diagnose_history()
334
+
 
335
  h, w, _ = input_image.shape
336
  annotated_rgb = input_image.copy()
337
  cv2.rectangle(annotated_rgb, (int(w*0.2), int(h*0.2)), (int(w*0.8), int(h*0.8)), (45, 122, 18), 3)
338
  cv2.putText(annotated_rgb, f"Mock: {selected_plant} (92.5%)", (int(w*0.2), int(h*0.2)-10), cv2.FONT_HERSHEY_SIMPLEX, 0.7, (45, 122, 18), 2)
339
+
340
  current_detected_disease_context = f"Đối tượng kiểm tra: {selected_plant}. Ghi nhận dấu hiệu bệnh lý mô phỏng trên bề mặt lá."
341
  result_text = f"📋 BIÊN BẢN CHẨN ĐOÁN LÂM SÀNG ({selected_plant.upper()}):\n\n🧬 Bệnh đốm lá (Mô phỏng) ➔ Mức độ: 92.5%\n\n🚨 HỆ THỐNG ĐÃ KÍCH HOẠT TRỢ LÝ AI: Mời bà con trò chuyện để nhận tư vấn!"
342
  clear_chat_history = [
343
  {"role": "assistant", "content": f"🤖 Chào bà con! Tôi đã nhận dữ liệu quét mẫu cho **{selected_plant}**. Bà con cần tư vấn loại thuốc hay phác đồ nào không?"}
344
  ]
345
+ save_diagnose_log(selected_plant, result_text)
346
  return annotated_rgb, result_text, clear_chat_history, load_diagnose_history()
347
 
 
348
  def chatbot_response(user_message, history):
349
  if history is None: history = []
350
+ if not user_message.strip(): return "", history
351
+
352
  ai_reply = f"🤖 [Mô phỏng AI Doctor]: Tôi đã ghi nhận câu hỏi '{user_message}'. Đối với tình trạng hiện tại, bà con nên cách ly cây bệnh và bổ sung hoạt chất bảo vệ thực vật theo đúng liều lượng khuyến nghị."
353
  history.append({"role": "user", "content": user_message})
354
+ history.append({"role": "assistant", "content": ai_reply})
355
  save_chat_log(user_message, ai_reply)
356
  return "", history
357
 
 
656
 
657
  resize(); render(years); requestAnimationFrame(tick);
658
  window.addEventListener("resize", () => { applyResponsive(); resize(); });
659
+
660
  setInterval(function () {
661
  const el = document.getElementById("login_wrapper");
662
  const onLogin = !!el && el.offsetParent !== null;
 
739
  }
740
  /* =================== END LEAF HERO LOGIN =================== */
741
 
742
+ .gradio-container {
743
+ background: linear-gradient(180deg, #eff5f3 0%, #e1ebe7 100%) !important;
744
  font-family: 'Inter', system-ui, sans-serif !important;
745
  }
746
  .medical-cross-red {
 
755
  .hospital-header-center .title-wrapper-h1 { display: inline-flex; align-items: center; justify-content: center; gap: 16px; text-align: center; margin: 0 auto; }
756
  .hospital-header-center h1 { text-align: center !important; color: white !important; font-weight: 800 !important; font-size: 28px !important; margin: 0 !important; display: inline-block; }
757
  .hospital-header-center p { text-align: center !important; margin: 8px auto 0 auto !important; color: #b2dfdb !important; font-size: 14px !important; }
758
+ .scan-btn {
759
+ background: linear-gradient(135deg, #007965, #00bfa5) !important; color: white !important; font-weight: 700 !important;
760
  border: none !important; border-radius: 12px !important; box-shadow: 0 5px 15px rgba(0, 121, 101, 0.2) !important; height: 48px; cursor: pointer;
761
  transition: all 0.25s ease !important;
762
  }
 
772
 
773
  .inline-history-btn {
774
  background: #ffffff !important; color: #007965 !important; border: 1.5px solid #007965 !important;
775
+ font-weight: 700 !important; border-radius: 8px !important; padding: 0px 14px !important;
776
  height: 32px !important; font-size: 13px !important; cursor: pointer; transition: all 0.2s ease !important;
777
  box-shadow: 0 2px 5px rgba(0, 0, 0, 0.05) !important; display: inline-flex !important; align-items: center; justify-content: center;
778
  }
 
807
 
808
  initial_ticket_text, initial_ticket_img = check_user_expert_status()
809
 
810
+ with gr.Blocks(title="Bệnh Viện Cây Trồng - Hệ Thống Chẩn Đoán AI", css=custom_css, head=LEAF_HERO_HEAD) as demo:
811
  with gr.Row(visible=True, elem_id="login_wrapper") as login_panel:
812
  with gr.Column(elem_id="login_content_col"):
813
  gr.HTML("""
 
837
  """)
838
  with gr.Column(scale=2, min_width=210):
839
  with gr.Row():
840
+ btn_logout = gr.Button("🚪 ĐĂNG XUẤT HỆ THỐNG", elem_classes="logout-btn-style")
841
  with gr.Row():
842
  with gr.Column(scale=10):
843
  with gr.Group(elem_classes="gr-group"):
844
  gr.Markdown("<p style='color: #004b39; font-weight: 700; margin: 8px 10px; font-size: 15px;'>🗂️ 1. TIẾP NHẬN MẪU XÉT NGHIỆM</p>")
845
  plant_dropdown = gr.Dropdown(
846
+ choices=["Cây lúa", "Cây ớt", "Cây cà chua", "Cây dâu tây", "Cây cà phê", "Cây ngô (Bắp)"],
847
  value="Cây cà chua", label="Lựa chọn phân khoa điều trị thực vật"
848
  )
849
  with gr.Group(elem_classes="gr-group"):
850
  image_input = gr.Image(type="numpy", label="Ảnh quét tế bào bề mặt lá", height=370)
851
  gr.HTML("<div style='padding: 0 10px 10px 10px;'>")
852
  btn_analyze = gr.Button("🩺 TIẾN HÀNH QUÉT & CHẨN ĐOÁN LÂM SÀNG", variant="primary", elem_classes="scan-btn")
853
+ gr.HTML("</div>")
854
  with gr.Column(scale=11, elem_id="prescription_col"):
855
  with gr.Group(elem_classes="gr-group"):
856
  gr.Markdown("<p style='color: #004b39; font-weight: 700; margin: 8px 10px; font-size: 15px;'>🔬 2. KẾT QUẢ QUÉT THỊ GIÁC HỌC SÂU (AI DETECT)</p>")
857
+ image_output = gr.Image(type="numpy", label="Bản đồ nội soi vi vị trí: Khoanh vùng khu trú ổ bệnh", height=370)
858
  gr.Markdown("<p style='color: #004b39; font-weight: 700; margin: 8px 10px 4px 10px; font-size: 15px;'>📄 3. ĐƠN THUỐC LÂM SÀNG SƠ BỘ</p>")
859
  text_output = gr.Textbox(
860
+ label="Hồ sơ bệnh án điện tử xuất từ thuật toán",
861
+ lines=5,
862
  placeholder="Hồ sơ bệnh án sơ bộ sẽ tự động xuất ra tại đây...",
863
  elem_classes="textbox_custom"
864
+ )
865
 
866
  with gr.Column(scale=12, elem_id="chatbot_col"):
867
  with gr.Row(elem_classes="chatbot-title-container"):
868
  gr.Markdown("<p style='color: #2980b9; font-weight: 700; margin: 0; font-size: 16px; display: inline-block;'>💬 4. HỘI ĐỒNG TƯ VẤN THUỐC BẢO VỆ THỰC VẬT (CHATBOT AI)</p>")
869
+ btn_history_nav = gr.Button("📂 Xem Lại Lịch Sử Bệnh Án", elem_classes="inline-history-btn")
870
  chatbot = gr.Chatbot(
871
  value=[{"role": "assistant", "content": "🤖 Hệ thống đang đợi mẫu quét. Sau khi phân tích xong ảnh lá, tôi sẽ tự động nắm thông tin bệnh lý để kê đơn thuốc chính xác cho bà con!"}],
872
  height=550,
873
  label="Trò chuyện trực tiếp với Chuyên gia Bảo vệ Thực vật AI",
874
  elem_classes="chatbot_custom"
875
+ )
876
  with gr.Row(elem_id="chat_input_row"):
877
  chat_msg = gr.Textbox(
878
  placeholder="Hỏi chuyên gia về cách chữa trị, tên thuốc, liều lượng phun bón cho loại bệnh vừa quét...",
 
888
  expert_status_box = gr.HTML(value=initial_ticket_text)
889
  expert_ticket_img_view = gr.Image(value=initial_ticket_img, label="Ảnh mẫu lá bệnh do nhà nông gửi lên", height=250, interactive=False)
890
 
891
+ gr.HTML("<div class='footer-text'>🔏 Hệ thống lõi được bảo mật bởi AI Doctor Lab © 2026 | Nền tảng Phân tích Công nghệ cao Học máy Ultralytics YOLOv8 & Google Gemini AI</div>")
892
 
893
  with gr.Column(visible=False) as history_panel:
894
  with gr.Row(elem_classes="hospital-header"):
 
899
  """)
900
  with gr.Column(scale=2, min_width=150):
901
  btn_back_to_clinic = gr.Button("⬅️ QUAY LẠI PHÒNG KHÁM", elem_classes="history-back-btn-style")
902
+
903
  with gr.Row():
904
  with gr.Column(visible=True) as user_diagnose_col:
905
  gr.Markdown("### ⏳ Nhật Ký Chẩn Đoán Ảnh:")
 
919
  interactive=False
920
  )
921
  btn_clear_chat = gr.Button("🗑️ XÓA NHẬT KÝ CHAT", variant="stop")
922
+
923
  gr.HTML("<hr style='margin: 25px 0; border: 1px solid #d4deda;'>")
924
+
925
  with gr.Group(elem_classes="gr-group"):
926
  gr.Markdown("<h3 style='color: #004b39; font-weight: 800; margin: 10px 12px; font-size: 18px;'>👨‍⚕️ HỘP THƯ TƯ VẤN CHUYÊN GIA (LỊCH SỬ HỎI ĐÁP)</h3>")
927
+
928
  with gr.Row(elem_id="expert_select_row"):
929
  admin_ticket_select = gr.Dropdown(label="Danh sách các câu hỏi hỗ trợ:", choices=[], value=None, scale=8)
930
  btn_delete_ticket = gr.Button("🗑️ XÓA CÂU HỎI / HỘI THOẠI NÀY", elem_classes="delete-btn-style", scale=2)
931
+
932
  with gr.Row():
933
  with gr.Column(scale=1):
934
  admin_ticket_detail = gr.HTML(value="Hiện chưa có yêu cầu hỗ trợ nào.")
 
937
 
938
  with gr.Row():
939
  admin_ticket_conversation = gr.HTML(value="", elem_id="full_width_conversation")
940
+
941
  with gr.Row():
942
  with gr.Column(scale=1, visible=False) as admin_control_panel:
943
  gr.Markdown("<hr style='margin: 15px 0; border: 1px dashed #007965;'>")
 
953
  btn_send_followup = gr.Button("💬 GỬI CÂU HỎI TIẾP TỤC CHO CHUYÊN GIA", variant="primary")
954
 
955
  btn_login.click(
956
+ login_auth,
957
+ inputs=[username_input, password_input],
958
  outputs=[login_panel, main_panel, error_output, admin_control_panel, user_followup_panel, user_expert_section, user_diagnose_col]
959
  )
960
+
961
  btn_logout.click(
962
+ logout_fn,
963
  outputs=[
964
+ login_panel,
965
+ main_panel,
966
+ plant_dropdown,
967
+ image_input,
968
+ image_output,
969
+ text_output,
970
+ expert_user_query,
971
+ expert_status_box,
972
+ expert_ticket_img_view,
973
+ chatbot,
974
  chat_msg
975
  ]
976
  )
977
+
978
  btn_history_nav.click(
979
+ go_to_history_panel,
980
  outputs=[main_panel, history_panel, history_diagnose_box, history_chat_box, admin_ticket_select, admin_ticket_detail, admin_ticket_conversation, admin_ticket_img_display, admin_control_panel, user_followup_panel, user_diagnose_col, user_chat_col]
981
  )
982
  btn_back_to_clinic.click(go_back_to_main_panel, outputs=[main_panel, history_panel])
983
+
984
  btn_analyze.click(analyze_leaf, inputs=[plant_dropdown, image_input], outputs=[image_output, text_output, chatbot, history_diagnose_box])
985
  btn_send.click(chatbot_response, inputs=[chat_msg, chatbot], outputs=[chat_msg, chatbot])
986
  chat_msg.submit(chatbot_response, inputs=[chat_msg, chatbot], outputs=[chat_msg, chatbot])
 
989
  btn_clear_chat.click(clear_chat_history_fn, outputs=[history_chat_box])
990
 
991
  btn_send_expert.click(
992
+ submit_expert_request,
993
+ inputs=[expert_user_query, plant_dropdown, image_input],
994
  outputs=[expert_user_query, expert_status_box, expert_ticket_img_view]
995
  )
996
  admin_ticket_select.change(
997
+ on_select_admin_ticket,
998
+ inputs=[admin_ticket_select],
999
  outputs=[admin_ticket_detail, admin_ticket_conversation, admin_ticket_img_display, user_followup_panel]
1000
  )
1001
  btn_submit_admin_reply.click(
1002
+ submit_admin_reply,
1003
+ inputs=[admin_ticket_select, admin_reply_input],
1004
  outputs=[admin_reply_status, admin_ticket_select, admin_ticket_detail, admin_ticket_conversation, admin_ticket_img_display, user_followup_panel]
1005
  )
1006