import os import cv2 import gradio as gr from ultralytics import YOLO from google import genai from google.genai import types import datetime import json import numpy as np import time import requests import threading VN_TIMEZONE = datetime.timezone(datetime.timedelta(hours=7)) def get_vn_time(): """Trả về thời gian hiện tại theo đúng múi giờ Việt Nam (UTC+7).""" return datetime.datetime.now(VN_TIMEZONE) # --- CẤU HÌNH ZEROGPU CHO HUGGING FACE --- try: import spaces has_zerogpu = True except ImportError: has_zerogpu = False def gpu_decorator(func): if has_zerogpu: return spaces.GPU(func) return func # ------------------------------------------------------------- # ============ KHỞI TẠO NHIỀU API KEY (TỰ CHUYỂN KEY KHI KEY 1 QUÁ TẢI) ============ API_KEYS = [ k for k in [ os.environ.get("GEMINI_API_KEY"), os.environ.get("GEMINI_API_KEY_2"), ] if k ] # Mỗi key một client riêng: [("KEY_1", client1), ("KEY_2", client2)] GEMINI_CLIENTS = [] for _i, _k in enumerate(API_KEYS): try: GEMINI_CLIENTS.append((f"KEY_{_i + 1}", genai.Client(api_key=_k))) except Exception as e: print(f"❌ Không khởi tạo được KEY_{_i + 1}: {e}") if GEMINI_CLIENTS: print(f"🎉 Khởi tạo máy chủ Gemini AI thành công với {len(GEMINI_CLIENTS)} API key!") else: print("❌ Lỗi cấu hình AI: không có API key Gemini hợp lệ nào.") client = GEMINI_CLIENTS[0][1] if GEMINI_CLIENTS else None TARGET_MODEL = "gemini-3.5-flash-lite" # ============================================================================ # ============ CẢNH BÁO TELEGRAM ============ TELEGRAM_BOT_TOKEN = os.environ.get("TELEGRAM_BOT_TOKEN") TELEGRAM_CHAT_ID = os.environ.get("TELEGRAM_CHAT_ID") ALERT_COOLDOWN = 0 # giây: cùng loại lỗi chỉ báo lại sau 5 phút (tránh spam) _last_alert_time = {} def classify_error(err): msg = str(err).upper() if "429" in msg or "RESOURCE_EXHAUSTED" in msg or "QUOTA" in msg: return "429 - HẾT QUOTA / QUÁ NHIỀU YÊU CẦU" if "503" in msg or "UNAVAILABLE" in msg or "OVERLOADED" in msg or "HIGH DEMAND" in msg: return "503 - MÁY CHỦ GEMINI QUÁ TẢI" return "LỖI KHÁC - KHÔNG TRẢ LỜI ĐƯỢC" def _send_telegram(text): try: requests.post( f"https://api.telegram.org/bot{TELEGRAM_BOT_TOKEN}/sendMessage", json={"chat_id": TELEGRAM_CHAT_ID, "text": text}, timeout=10, ) except Exception as e: print(f"⚠️ Gửi Telegram thất bại: {e}") def notify_telegram(error_type, detail=""): """Gửi cảnh báo ở luồng riêng, có chống spam theo loại lỗi.""" if not TELEGRAM_BOT_TOKEN or not TELEGRAM_CHAT_ID: return now = time.time() if now - _last_alert_time.get(error_type, 0) < ALERT_COOLDOWN: return _last_alert_time[error_type] = now text = ( f"🚨 AgriHospital - CHATBOT AI LỖI\n" f"⏱️ {get_vn_time().strftime('%Y-%m-%d %H:%M:%S')}\n" f"❗ Loại lỗi: {error_type}\n" f"📝 Chi tiết: {detail[:600]}" ) threading.Thread(target=_send_telegram, args=(text,), daemon=True).start() # ============ BOT TELEGRAM THỨ 2: BÁO CHUYÊN GIA KHI CÓ CÂU HỎI TỪ NHÀ NÔNG ============ EXPERT_BOT_TOKEN = os.environ.get("EXPERT_BOT_TOKEN") EXPERT_CHAT_ID = os.environ.get("EXPERT_CHAT_ID") def _send_expert_telegram(text, image_path=None): """Gửi tin cho chuyên gia; có ảnh lá thì gửi kèm ảnh, lỗi ảnh thì gửi chữ.""" base = f"https://api.telegram.org/bot{EXPERT_BOT_TOKEN}" try: if image_path and os.path.exists(image_path): try: with open(image_path, "rb") as f: r = requests.post( f"{base}/sendPhoto", data={"chat_id": EXPERT_CHAT_ID, "caption": text[:1000]}, files={"photo": f}, timeout=20, ) if r.ok: return print(f"⚠️ Telegram chuyên gia (gửi ảnh) trả lỗi: {r.status_code} {r.text[:200]}") except Exception as e: print(f"⚠️ Telegram chuyên gia (gửi ảnh) thất bại: {e}") r = requests.post( f"{base}/sendMessage", json={"chat_id": EXPERT_CHAT_ID, "text": text}, timeout=10, ) if not r.ok: print(f"⚠️ Telegram chuyên gia trả lỗi: {r.status_code} {r.text[:200]}") except Exception as e: print(f"⚠️ Gửi Telegram chuyên gia thất bại: {e}") def _dispatch_expert_telegram(text, image_path=None): if not EXPERT_BOT_TOKEN or not EXPERT_CHAT_ID: return threading.Thread(target=_send_expert_telegram, args=(text, image_path), daemon=True).start() def notify_expert_new_question(ticket): """Nhà nông vừa gửi câu hỏi MỚI vào hộp thư chờ chuyên gia.""" context_text = str(ticket.get("context", ""))[:300] text = ( f"📩 CÂU HỎI MỚI TỪ NHÀ NÔNG\n" f"📌 Mã yêu cầu: #{ticket.get('id')}\n" f"⏱️ {ticket.get('time')}\n" f"🌱 Loại cây: {ticket.get('plant')}\n" f"💬 Câu hỏi: {ticket.get('user_query')}\n" f"🔬 Kết quả quét gần nhất: {context_text}\n\n" f"👉 Đăng nhập hệ thống bằng tài khoản chuyên gia, vào 'Xem Lại Lịch Sử Bệnh Án' để trả lời." ) _dispatch_expert_telegram(text, ticket.get("image_path")) def notify_expert_followup(ticket, followup_text): """Nhà nông hỏi THÊM trong một yêu cầu đã có.""" text = ( f"🔄 NHÀ NÔNG HỎI THÊM\n" f"📌 Mã yêu cầu: #{ticket.get('id')}\n" f"⏱️ {get_vn_time().strftime('%Y-%m-%d %H:%M:%S')}\n" f"🌱 Loại cây: {ticket.get('plant')}\n" f"💬 Nội dung hỏi thêm: {followup_text}\n\n" f"👉 Đăng nhập hệ thống bằng tài khoản chuyên gia, vào 'Xem Lại Lịch Sử Bệnh Án' để trả lời." ) _dispatch_expert_telegram(text) # ========================================================================================= # ========================================== current_detected_disease_context = "Chưa thực hiện quét mẫu bệnh phẩm." model_path = "best_tomato.pt" model = YOLO(model_path) ROBOFLOW_YAML_NAMES = [ 'Tomato Bacterial Spot', 'Tomato Early blight', 'Tomato Late blight', 'Tomato Leaf Mold', 'Tomato Septoria leaf spot', 'Tomato Spider mites Two-spotted spider mite', 'Tomato Target Spot', 'Tomato Yellow Leaf Curl Virus', 'Tomato healthy', 'Tomato mosaic virus' ] PLANT_DISEASES_DB = { "Cây lúa": { "Rice__BacterialLeafBlight": {"no_accent": "Benh bac la (chay bia la vi khuan)", "accent": "Bệnh bạc lá do vi khuẩn (cháy bìa lá)"}, "Rice__BrownSpot": {"no_accent": "Benh dom nau", "accent": "Bệnh đốm nâu hại lúa"}, "Rice__Healthy": {"no_accent": "Cay lua khoe manh", "accent": "Cây lúa khỏe mạnh không có bệnh"}, "Rice__Hispa": {"no_accent": "Sau gai an la lua", "accent": "Sâu gai ăn lá lúa (Hispa)"}, "Rice__LeafBlast": {"no_accent": "Benh dao on la", "accent": "Bệnh đạo ôn hại lá lúa"}, "Rice__LeafScald": {"no_accent": "Benh thoi be / chay vien la", "accent": "Bệnh thối bẹ lá / cháy viền lá (Leaf Scald)"}, "Rice__LeafSmut": {"no_accent": "Benh than den la lua", "accent": "Bệnh than đen lá lúa"}, "Rice__NarrowBrownLeafSpot": {"no_accent": "Benh dom nau hep", "accent": "Bệnh đốm nâu hẹp gây hại"}, "Rice__NeckBlast": {"no_accent": "Benh dao on co bong", "accent": "Bệnh đạo ôn cổ bông"} }, "Cây ớt": { "bercak daun serkospora": {"no_accent": "Benh dom la Cercospora", "accent": "Bệnh đốm lá Cercospora"}, "buah cabai sehat": {"no_accent": "Qua ot khoe manh", "accent": "Quả ớt khỏe mạnh không có bệnh"}, "busuk buah antraknosa": {"no_accent": "Benh than thu thoi qua", "accent": "Bệnh thán thư thối quả ớt"}, "daun cabai sehat": {"no_accent": "La ot khoe manh", "accent": "Lá ớt khỏe mạnh không có bệnh"}, "virus kuning": {"no_accent": "Benh virus vang la", "accent": "Bệnh virus vàng lá hại ớt"} }, "Cây cà chua": { "tomato bacterial spot": {"no_accent": "Benh dom vi khuan", "accent": "Bệnh đốm vi khuẩn"}, "tomato early blight": {"no_accent": "Benh ua som (dom vong)", "accent": "Bệnh úa sớm (đốm vòng)"}, "tomato late blight": {"no_accent": "Benh suong mai (ua muon)", "accent": "Bệnh sương mai (úa muộn)"}, "tomato leaf mold": {"no_accent": "Benh nam moc la", "accent": "Bệnh nấm mốc lá"}, "tomato septoria leaf spot": {"no_accent": "Benh dom la Septoria", "accent": "Bệnh đốm lá Septoria"}, "tomato spider mites two-spotted spider mite": {"no_accent": "Benh nhen do hai cham", "accent": "Bệnh nhện đỏ hai chấm gây hại"}, "tomato target spot": {"no_accent": "Benh dom hinh bia ban", "accent": "Bệnh đốm hình bia bắn"}, "tomato yellow leaf curl virus": {"no_accent": "Benh xoan lun vang la", "accent": "Bệnh virus xoăn lùn vàng la"}, "tomato healthy": {"no_accent": "Cay khoe manh", "accent": "Cây khỏe mạnh không có bệnh"}, "tomato mosaic virus": {"no_accent": "Benh kham virus", "accent": "Bệnh khảm virus"} }, "Cây dâu tây": { "angular leafspot": {"no_accent": "Benh dom la goc canh (do vi khuan)", "accent": "Bệnh đốm lá góc cạnh (do vi khuẩn)"}, "anthracnose fruit rot": {"no_accent": "Benh thoi trai anthracnose (than thu)", "accent": "Bệnh thối trái Anthracnose (thán thư)"}, "blossom blight": {"no_accent": "Benh thoi hoa (thoi nu)", "accent": "Bệnh thối hoa (thối nụ)"}, "gray mold": {"no_accent": "Benh moc xam", "accent": "Bệnh mốc xám"}, "leaf spot": {"no_accent": "Benh dom la (do nam)", "accent": "Bệnh đốm lá (do nấm)"}, "powdery mildew fruit": {"no_accent": "Benh phan trang tren qua", "accent": "Bệnh phấn trắng trên quả"}, "powdery mildew leaf": {"no_accent": "Benh phan trang tren la", "accent": "Bệnh phấn trắng trên lá"} }, "Cây cà phê": { "algal spot": {"no_accent": "Benh dom tao", "accent": "Bệnh đốm tảo"}, "brown eye spot": {"no_accent": "Benh dom mat cua", "accent": "Bệnh đốm mắt cua"}, "healthy": {"no_accent": "Cay khoe manh", "accent": "Cây khỏe mạnh không có bệnh"}, "miner": {"no_accent": "Sau ve bua", "accent": "Sâu vẽ bùa gây hại"}, "phoma": {"no_accent": "Benh do nam Phoma", "accent": "Bệnh do nấm Phoma"}, "powdery mildew": {"no_accent": "Benh phan trang", "accent": "Bệnh phấn trắng"} }, "Cây ngô (Bắp)": { "blight": {"no_accent": "Benh chay la ngo", "accent": "Bệnh cháy lá ngô"}, "common rust": {"no_accent": "Benh ri sat hai bap", "accent": "Bệnh rỉ sắt hại bắp"}, "gray spot": {"no_accent": "Benh dom xam la ngo", "accent": "Bệnh đốm xám lá ngô"}, "health": {"no_accent": "Cay ngo khoe manh", "accent": "Cây ngô khỏe mạnh không có bệnh"} }, "Cây nho": { "grape black rot": {"no_accent": "Benh thoi den (Black Rot)", "accent": "Bệnh thối đen (Black Rot)"}, "grape esca": {"no_accent": "Benh Esca (thoi go nho)", "accent": "Bệnh Esca (thối gỗ nho)"}, "grape healthy": {"no_accent": "Cay nho khoe manh", "accent": "Cây nho khỏe mạnh không có bệnh"}, "grape leaf blight": {"no_accent": "Benh chay la nho", "accent": "Bệnh cháy lá nho"} } } # ============================================================================= # CƠ SỞ DỮ LIỆU TÀI LIỆU CỨU NGUY DỰ PHÒNG KHI API GEMINI QUÁ TẢI (7 LOÀI CÂY) # Trích xuất từ Giáo trình Bệnh cây chuyên khoa, Đại cương & Cẩm nang ACIAR # ============================================================================= PLANT_EMERGENCY_DOCS = { "Cây lúa": """ ### 🌾 HƯỚNG DẪN ĐIỀU TRỊ DỰ PHÒNG CẤP BÁCH CHO CÂY LÚA *(Trích xuất từ Giáo trình Bệnh cây chuyên khoa (Đại học Nông Lâm Tp.HCM) & Cẩm nang chẩn đoán bệnh cây ở Việt Nam (ACIAR))* #### 1. Bệnh Đạo ôn (Pyricularia oryzae / P. grisea) * **Triệu chứng:** Vết bệnh hình thoi, tâm xám nhạt, viền nâu đậm; vết bệnh ở cổ bông làm hạt lép, bạc lửng hoặc gãy cổ bông. * **Biện pháp khẩn cấp:** - Ngừng ngay bón thúc đạm, không phun phân bón lá có đạm. - Phun trừ sớm bằng các thuốc hóa học đặc trị: **Fuji-one 40EC** (1 lít/ha), **Beam 75WP / Triozol 20WP (Tricyclazole)** (1 kg/ha), **Kitazin 50EC** (1 - 1.5 lít/ha), hoặc **Kasai 21.2WP** (1 - 1.5 kg/ha). #### 2. Bệnh Khô vằn (Rhizoctonia solani) * **Triệu chứng:** Vết vằn da hổ, dạng vân mây loang lổ lan từ bẹ lá già sát mặt nước lên các lá phía trên; có hạch nấm màu nâu tròn dẹt. * **Biện pháp khẩn cấp:** - Rút bớt nước mặt ruộng để hạ độ ẩm tán lá. - Phun tiếp xúc tầng lá dưới gốc bằng: **Validamycin (Vida 3SC / Validacin 5SL / Anlicin 3SL)** liều 1 - 1.5 lít/ha, **Tilt 250ND** (0.3 - 0.5 lít/ha), hoặc **Anvil 5SC (Hexaconazole)** (50 - 100g a.i/ha). #### 3. Bệnh Bạc lá vi khuẩn (Xanthomonas oryzae) * **Triệu chứng:** Vết cháy bìa lá gợn sóng màu vàng tái từ chóp lá lan xuống, sáng sớm có giọt dịch keo vi khuẩn đọng lại. * **Biện pháp khẩn cấp:** - Rút nước giữ ruộng khô 2 - 3 ngày để hạn chế vi khuẩn truyền lan theo nước. - Rắc vôi bột (60 - 80 kg/ha) lúc sáng sớm hoặc phun thuốc gốc kháng sinh/đồng: **Starner 20WP (Oxolinic acid)** nồng độ 0.1 - 0.2%, **Kasuran** (1 - 2 kg/ha). """, "Cây cà chua": """ ### 🍅 HƯỚNG DẪN ĐIỀU TRỊ DỰ PHÒNG CẤP BÁCH CHO CÂY CÀ CHUA *(Trích xuất từ Giáo trình Bệnh cây chuyên khoa (Đại học Nông Lâm Tp.HCM) & Cẩm nang chẩn đoán bệnh cây ở Việt Nam (ACIAR))* #### 1. Bệnh Mốc sương / Sương mai (Phytophthora infestans) * **Triệu chứng:** Vết úng nước màu xanh tối chuyển nâu đen ở chóp/mép lá, mặt dưới lá có mốc trắng xốp như sương muối; thân thâm đen dễ gãy gục. * **Biện pháp khẩn cấp:** - Vệ sinh ruộng, bấm tỉa lá già sát gốc. - Phun kịp thời khi trời râm mát: **Ridomil Gold 68WP / Rhidomil MZ 72** (nồng độ 0.2%), **Aliette 80WP (Fosetyl-aluminium)** (0.2 - 0.3%), hoặc **Mancozeb 80WP (Dithane M45)** (2 - 2.5 kg/ha). #### 2. Bệnh Đốm vòng (Alternaria solani) * **Triệu chứng:** Vết bệnh tròn có vòng đồng tâm màu nâu đen viền quầng vàng, cuống lá gãy gục, quả có quầng đen mượt như nhung. * **Biện pháp khẩn cấp:** - Phun: **Score 250EC (Difenoconazole)** (0.3 - 0.5 lít/ha), **Rovral 50WP (Iprodione)** (1.5 - 1.7 kg/ha), hoặc **Mirage 50WP (Prochloraz)** (0.15 - 0.2%). #### 3. Bệnh Héo xanh vi khuẩn (Ralstonia solanacearum) * **Triệu chứng:** Lá héo rũ xanh đột ngột vào ban ngày; cắt ngang gốc cắm vào cốc nước thấy dòng dịch vi khuẩn màu trắng sữa chảy ra. * **Biện pháp khẩn cấp:** - Nhổ bỏ ngay cả gốc rễ cây bệnh đem tiêu hủy, rắc vôi bột khử trùng hốc đất. - Tuyệt đối không tưới rãnh tràn lan; tưới gốc bằng chế phẩm sinh học đối kháng **Bacillus subtilis** hoặc **Trichoderma**. """, "Cây ớt": """ ### 🌶️ HƯỚNG DẪN ĐIỀU TRỊ DỰ PHÒNG CẤP BÁCH CHO CÂY ỚT *(Trích xuất từ Giáo trình Bệnh cây chuyên khoa (Đại học Nông Lâm Tp.HCM) & Cẩm nang chẩn đoán bệnh cây ở Việt Nam (ACIAR))* #### 1. Bệnh Thán thư thối quả (Colletotrichum capsici / C. nigrum) * **Triệu chứng:** Đốm lõm hình bầu dục ướt trên quả chín, vết bệnh xuất hiện các vòng tròn đồng tâm chứa chấm đen li ti (đĩa cành). * **Biện pháp khẩn cấp:** - Thu gom toàn bộ quả bệnh trên cây và dưới đất đem chôn sâu. - Phun ướt đều tán và chùm quả: **Score 250ND (Difenoconazole)** (0.5 lít/ha), **Topsin M 70WP** (0.4 - 0.6 kg/ha), hoặc **Antracol 70WP (Propineb)** (0.3 - 0.4%). #### 2. Bệnh Thối rễ / Héo gốc (Phytophthora capsici / Pythium spp.) * **Triệu chứng:** Cổ rễ sát mặt đất ủng nước thâm nâu, cây héo rũ nhanh chóng sau mưa to, vỏ rễ tuột ra. * **Biện pháp khẩn cấp:** - Lên luống cao ít nhất 30cm, tạo rãnh thoát nước sâu không để ứ đọng. - Tưới hoặc phun gốc bằng: **Aliette 80WP** (0.25 - 0.3%) hoặc **Ridomil Gold 68WP** (0.2%). """, "Cây ngô (Bắp)": """ ### 🌽 HƯỚNG DẪN ĐIỀU TRỊ DỰ PHÒNG CẤP BÁCH CHO CÂY NGÔ *(Trích xuất từ Giáo trình Bệnh cây chuyên khoa (Đại học Nông Lâm Tp.HCM) & Cẩm nang chẩn đoán bệnh cây ở Việt Nam (ACIAR))* #### 1. Bệnh Khô vằn (Rhizoctonia solani) * **Triệu chứng:** Vết loang lổ hình mây xám tro, vằn da hổ từ bẹ gốc lan lên áo bắp và bông cờ làm thối khô bắp. * **Biện pháp khẩn cấp:** - Bóc tỉa bớt lá già khô bệnh ở dưới gốc để ruộng thông thoáng. - Phun: **Validacin 5SL** (1.5 lít/ha), **Tilt Super 300ND** (0.4 lít/ha), hoặc **Rovral 50WP** (1.5 kg/ha). #### 2. Bệnh Gỉ sắt hại ngô (Puccinia maydis) * **Triệu chứng:** Xuất hiện các ổ nổi bột màu nâu đỏ gạch non dày đặc trên cả 2 mặt phiến lá, cuối vụ chuyển màu đen. * **Biện pháp khẩn cấp:** - Phun: **Tilt 250EC** (0.3 - 0.5 lít/ha), **Score 250ND** (0.3 - 0.5 lít/ha), hoặc **Bayfidan 15WP / Samet 15WP**. #### 3. Bệnh Đốm lá lớn & Đốm lá nhỏ (Bipolaris maydis / B. turcica) * **Triệu chứng:** Vết bệnh sọc hình thoi dài màu nâu xám, gây khô táp và rách tươm ở chóp lá. * **Biện pháp khẩn cấp:** Phun **Dithane M45 80WP** (1.5 kg/ha), **Tilt 250EC**, hoặc dung dịch **Boocđô 1%**. """, "Cây cà phê": """ ### ☕ HƯỚNG DẪN ĐIỀU TRỊ DỰ PHÒNG CẤP BÁCH CHO CÂY CÀ PHÊ *(Trích xuất từ Giáo trình Bệnh cây chuyên khoa (Đại học Nông Lâm Tp.HCM) & Cẩm nang chẩn đoán bệnh cây ở Việt Nam (ACIAR))* #### 1. Bệnh Gỉ sắt cà phê (Hemileia vastatrix) * **Triệu chứng:** Mặt dưới lá phủ lớp bột xốp màu vàng da cam (nấm vàng da cam), sau cháy khô nâu và gây rụng lá hàng loạt. * **Biện pháp khẩn cấp:** - Cắt tỉa cành sâu bệnh, làm sạch cỏ quanh bồn gốc. - Phun thuốc chặn trước cao điểm phát bệnh (tháng 8 - 9): **Tilt 250EC** (0.75 - 1 lít/ha), **Anvil 5SC** (0.2%), **Bayleton 250EC** (250 - 500 g/ha), hoặc **Score 250ND**. #### 2. Tuyến trùng rễ (Pratylenchus coffeae) phối hợp nấm Fusarium * **Triệu chứng:** Rễ tơ bị thối đen, vỏ rễ tuột, lá biến vàng, cành teo tóp còi cọc. * **Biện pháp khẩn cấp:** - Bón phân chuồng hoai mục kết hợp nấm đối kháng **Trichoderma viride**. - Xử lý đất bằng hoạt chất tuyến trùng: **Nemacur**, **Temic** hoặc dội nước nóng nếu ở vườn ươm. """, "Cây nho": """ ### 🍇 HƯỚNG DẪN ĐIỀU TRỊ DỰ PHÒNG CẤP BÁCH CHO CÂY NHO *(Trích xuất từ Giáo trình Bệnh cây chuyên khoa (Đại học Nông Lâm Tp.HCM) & Cẩm nang chẩn đoán bệnh cây ở Việt Nam (ACIAR))* #### 1. Bệnh Sương mai nho (Plasmopara viticola) * **Triệu chứng:** Mặt trên lá có đốm dầu vàng nâu góc cạnh, mặt dưới phủ lớp mốc trắng mịn như sương muối; chùm quả non teo khô. * **Biện pháp khẩn cấp:** - Cắt tỉa cành lá thông gió, thu gom lá bệnh rụng đem đốt. - Phun ngừa sớm khi có mưa phùn, ẩm độ cao: **Boocđô 1%**, **Aliette 80WP**, **Zineb 80WP**, hoặc **Ridomil MZ 72** (0.2%). #### 2. Bệnh Gỉ sắt nho (Phakopsora vitis) * **Triệu chứng:** Mặt dưới lá xuất hiện các ổ bào tử màu nâu gỉ sắt rách nứt biểu bì làm lá vàng khô rụng sớm. * **Biện pháp khẩn cấp:** Phun **Tilt 250EC** (0.1 - 0.2 lít/ha), **Baycor 25WP**, hoặc **Score 250ND**. #### 3. Bệnh Phấn trắng nho (Uncinula necator) * **Triệu chứng:** Lớp bụi phấn màu trắng xám bao trùm lá non và quả non. * **Biện pháp khẩn cấp:** Phun bột lưu huỳnh **Kumulus 80WP** (0.4 - 0.8%) hoặc **Anvil 5SC**. """, "Cây dâu tây": """ ### 🍓 HƯỚNG DẪN ĐIỀU TRỊ DỰ PHÒNG CẤP BÁCH CHO CÂY DÂU TÂY *(Trích xuất từ Giáo trình Bệnh cây chuyên khoa (Đại học Nông Lâm Tp.HCM) & Cẩm nang chẩn đoán bệnh cây ở Việt Nam (ACIAR))* #### 1. Bệnh Thối mốc xám (Botrytis cinerea) * **Triệu chứng:** Quả chín mềm nhũn ủng nước, bao phủ lớp mốc xám mịn như lông tơ; cuống hoa và nụ bị thối đen. * **Biện pháp khẩn cấp:** - Tỉa bớt lá già mục, cách ly quả không tiếp xúc trực tiếp với đất ẩm. - Phun: **Rovral 50WP (Iprodione)** (1 - 1.5 kg/ha) hoặc **Topsin M 70WP** (chú ý thời gian cách ly thu hoạch). #### 2. Bệnh Đốm lá nấm (Septoria / Mycosphaerella) * **Triệu chứng:** Đốm tròn màu tím viền nâu xám trên lá, làm giảm khả năng quang hợp và cây còi cọc. * **Biện pháp khẩn cấp:** Phun **Score 250EC**, **Daconil 75WP**, hoặc **Antracol 70WP**. #### 3. Bệnh Thối rễ / Thối thân (Phytophthora cactorum / Pythium spp.) * **Triệu chứng:** Cây còi cọc, vàng rũ, chóp rễ tơ thối nâu đen. * **Biện pháp khẩn cấp:** Sử dụng giá thể sạch bệnh, tưới ngừa bằng **Aliette 80WP** (0.2%) hoặc **Ridomil Gold**. """ } def get_emergency_doc_for_plant(plant_name): """Trích xuất tài liệu cứu nguy đúng cho loại cây được chọn.""" return PLANT_EMERGENCY_DOCS.get( plant_name, f"### 📖 TÀI LIỆU DỰ PHÒNG: {plant_name}\n\nHiện chưa có tài liệu cứu nguy sẵn có cho loại cây này." ) def handle_emergency_button_click(selected_plant): """Xử lý sự kiện bấm nút cứu nguy: bung nội dung tài liệu theo đúng loại cây.""" content = get_emergency_doc_for_plant(selected_plant) return gr.update(visible=True, value=content) # ------------------------------------------------------------- def translate_disease(english_name, plant_type, with_accent=True): plant_db = PLANT_DISEASES_DB.get(plant_type, PLANT_DISEASES_DB["Cây cà chua"]) # 1. Tra trực tiếp tên gốc (cho Cây lúa có chứa định dạng PascalCase / Rice__...) disease_info = plant_db.get(english_name, None) # 2. Tra tên đã chuẩn hóa chữ thường (cho Cà chua, Ớt, Ngô...) if not disease_info: clean_name = english_name.lower().replace("_", " ").strip() disease_info = plant_db.get(clean_name, None) if disease_info: return disease_info["accent"] if with_accent else disease_info["no_accent"] return english_name new_names_dict = {} for idx, name in enumerate(ROBOFLOW_YAML_NAMES): new_names_dict[idx] = translate_disease(name, "Cây cà chua", with_accent=False) model.model.names = new_names_dict HISTORY_DIR = "he_thong_lich_su" TICKET_IMG_DIR = os.path.join(HISTORY_DIR, "ticket_images") os.makedirs(HISTORY_DIR, exist_ok=True) os.makedirs(TICKET_IMG_DIR, exist_ok=True) EXPERT_DB_PATH = os.path.join(HISTORY_DIR, "expert_tickets.json") def load_expert_tickets(): if os.path.exists(EXPERT_DB_PATH): try: with open(EXPERT_DB_PATH, "r", encoding="utf-8") as f: tickets = json.load(f) for t in tickets: if "deleted_by_admin" not in t: t["deleted_by_admin"] = False if "deleted_by_user" not in t: t["deleted_by_user"] = False return tickets except Exception: return [] return [] def save_expert_tickets(tickets): try: with open(EXPERT_DB_PATH, "w", encoding="utf-8") as f: json.dump(tickets, f, ensure_ascii=False, indent=2) except Exception as e: print(f"⚠️ Lỗi lưu hồ sơ tư vấn chuyên gia: {e}") def load_diagnose_history(): log_path = os.path.join(HISTORY_DIR, "lich_su_chan_doan.txt") if os.path.exists(log_path): with open(log_path, "r", encoding="utf-8") as f: return f.read() return "Chưa có dữ liệu lịch sử chẩn đoán." def load_chat_history(): log_path = os.path.join(HISTORY_DIR, "lich_su_chat.txt") if os.path.exists(log_path): with open(log_path, "r", encoding="utf-8") as f: return f.read() return "Chưa có dữ liệu lịch sử hội thoại." def save_diagnose_log(plant, result_text): try: log_path = os.path.join(HISTORY_DIR, "lich_su_chan_doan.txt") now = get_vn_time().strftime("%Y-%m-%d %H:%M:%S") with open(log_path, "a", encoding="utf-8") as f: f.write(f"\n{'='*60}\n⏱️ THỜI GIAN: {now}\n🌱 ĐỐI TƯỢNG: {plant}\n{result_text}\n") except Exception as e: print(f"⚠️ Không thể lưu lịch sử chẩn đoán: {e}") def save_chat_log(user_msg, ai_reply): try: log_path = os.path.join(HISTORY_DIR, "lich_su_chat.txt") now = get_vn_time().strftime("%Y-%m-%d %H:%M:%S") with open(log_path, "a", encoding="utf-8") as f: f.write(f"\n⏱️ [{now}]\n👤 Nhà nông: {user_msg}\n🤖 Bác sĩ AI: {ai_reply}\n") except Exception as e: print(f"⚠️ Không thể lưu lịch sử chat: {e}") def clear_diagnose_history_fn(): log_path = os.path.join(HISTORY_DIR, "lich_su_chan_doan.txt") if os.path.exists(log_path): os.remove(log_path) return "Chưa có dữ liệu lịch sử chẩn đoán." def clear_chat_history_fn(): log_path = os.path.join(HISTORY_DIR, "lich_su_chat.txt") if os.path.exists(log_path): os.remove(log_path) return "Chưa có dữ liệu lịch sử hội thoại." def extract_text_content(msg_data): if isinstance(msg_data, dict): content = msg_data.get("content", "") if isinstance(content, dict): return content.get("text", "") return str(content) if hasattr(msg_data, "content"): content_attr = getattr(msg_data, "content") if isinstance(content_attr, dict): return content_attr.get("text", "") return str(content_attr) return str(msg_data) ACCOUNTS = { "admin": {"password": "123", "role": "admin"}, "user": {"password": "456", "role": "user"} } def login_auth(username, password): user_info = ACCOUNTS.get(username) if user_info and user_info["password"] == password: user_role = user_info["role"] is_admin = (user_role == "admin") is_user = (user_role == "user") return ( gr.update(visible=False), gr.update(visible=True), "", gr.update(visible=is_admin), gr.update(visible=is_user), gr.update(visible=is_user), gr.update(visible=is_user), user_role ) else: error_msg = '

❌ Mã người dùng hoặc Mật khẩu hệ thống không chính xác!

' return gr.update(visible=True), gr.update(visible=False), error_msg, gr.update(visible=False), gr.update(visible=False), gr.update(visible=False), gr.update(visible=False), "user" def apply_role_visibility(role): """Áp lại hiển thị các khung theo đúng vai trò (admin / user). Gọi sau khi đăng nhập để đảm bảo các khung của user không bị lộ ra ở tài khoản admin.""" is_admin = (role == "admin") is_user = (role == "user") return ( gr.update(visible=is_user), # user_expert_section gr.update(visible=is_admin), # admin_control_panel gr.update(visible=is_user), # user_followup_panel gr.update(visible=is_user), # user_diagnose_col gr.update(visible=is_user) # user_chat_col ) def logout_fn(): global current_detected_disease_context current_detected_disease_context = "Chưa thực hiện quét mẫu bệnh phẩm." return ( gr.update(visible=True), gr.update(visible=False), gr.update(value="Cây cà chua"), None, None, "", "", "", None, 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!"}]), "", gr.update(visible=False), gr.update(visible=False), "user", # Ẩn toàn bộ các khung theo vai trò khi đăng xuất để lần đăng nhập sau không bị lẫn khung của tài khoản trước gr.update(visible=False), # user_expert_section gr.update(visible=False), # admin_control_panel gr.update(visible=False), # user_followup_panel gr.update(visible=False), # user_diagnose_col gr.update(visible=False) # user_chat_col ) def get_ticket_status_display(ticket): """Xác định nhãn trạng thái hiển thị rõ ràng: 1. 🔵 Chưa trả lời 2. 🟡 Hỏi thêm 3. 🔴 Đã trả lời """ messages = ticket.get("messages", []) has_admin_replied_before = any(m.get("sender") == "ADMIN" for m in messages) or bool(ticket.get("admin_reply")) if ticket.get("status") == "PENDING": if has_admin_replied_before: return "🟡 Hỏi thêm", 1 else: return "🔵 Chưa trả lời", 0 else: return "🔴 Đã trả lời", 2 def get_admin_tickets_list(selected_value=None, role="user"): tickets = load_expert_tickets() is_user = (role == "user") if role == "admin": visible_tickets = [t for t in tickets if not t.get("deleted_by_admin", False)] else: visible_tickets = [t for t in tickets if not t.get("deleted_by_user", False)] if not visible_tickets: 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) # Sắp xếp ưu tiên: Chưa trả lời -> Có hỏi thêm -> Đã trả lời. Trong cùng nhóm sắp xếp thời gian mới nhất lên đầu. def sort_key(t): status_label, priority = get_ticket_status_display(t) return (priority, -t['id']) sorted_tickets = sorted(visible_tickets, key=sort_key) choices = [] ticket_map = {} for t in sorted_tickets: status_label, _ = get_ticket_status_display(t) choice_str = f"#{t['id']} - {t['plant']} - {t['time']} - [{status_label}]" choices.append(choice_str) ticket_map[choice_str] = t target_choice = choices[0] target_ticket = ticket_map[choices[0]] if selected_value and selected_value in choices: target_choice = selected_value target_ticket = ticket_map[selected_value] first_img = target_ticket.get('image_path', None) header_info, conversation_info = format_ticket_detail(target_ticket) return gr.update(choices=choices, value=target_choice), header_info, conversation_info, first_img, gr.update(visible=is_user) def delete_current_ticket(selected_option, role="user"): if not selected_option: dropdown_up, h_info, c_info, img_p, followup_vis = get_admin_tickets_list(None, role) return "⚠️ Chưa chọn câu hỏi nào để xóa!", dropdown_up, h_info, c_info, img_p, followup_vis ticket_id = int(selected_option.split(" - ")[0].replace("#", "")) tickets = load_expert_tickets() new_tickets_list = [] for t in tickets: if t['id'] == ticket_id: if role == "admin": t["deleted_by_admin"] = True else: t["deleted_by_user"] = True if not (t.get("deleted_by_admin", False) and t.get("deleted_by_user", False)): new_tickets_list.append(t) else: new_tickets_list.append(t) save_expert_tickets(new_tickets_list) dropdown_up, h_info, c_info, img_p, followup_vis = get_admin_tickets_list(None, role) return "🗑️ Đã xóa hội thoại thành công ở phía bạn!", dropdown_up, h_info, c_info, img_p, followup_vis def format_ticket_detail(ticket): status_label, status_priority = get_ticket_status_display(ticket) if status_priority == 0: status_str = "⏳ ĐANG CHỜ CHUYÊN GIA TRẢ LỜI" status_color = "#2980b9" elif status_priority == 1: status_str = "🔄 NHÀ NÔNG ĐÃ HỎI THÊM (CHỜ PHẢN HỒI)" status_color = "#d35400" else: status_str = "✅ ĐÃ ĐƯỢC CHUYÊN GIA TRẢ LỜI" status_color = "#c0392b" reply_str = ticket.get('admin_reply', 'Chưa có phản hồi.') header_html = f"""
📌 MÃ YÊU CẦU: #{ticket['id']} | ⏱️ Thời gian: {ticket['time']}
🌱 Loại cây: {ticket['plant']}
💬 Câu hỏi từ nhà nông: {ticket['user_query']}
""" history_conversation = "" if "messages" in ticket and isinstance(ticket["messages"], list): for msg in ticket["messages"]: sender = msg.get("sender", "") time_stamp = msg.get("time", "") text = msg.get("text", "") if sender == "USER": history_conversation += f"""
👤 Nhà nông ({time_stamp}): {text}
""" else: history_conversation += f"""
👨‍⚕️ Chuyên gia ({time_stamp}): {text}
""" if not history_conversation: history_conversation = f"""
{reply_str}
""" conversation_html = f"""
🚥 Trạng thái: {status_str}
👨‍⚕️ Nội dung trao đổi với Chuyên gia:
{history_conversation}
""" return header_html, conversation_html def on_select_admin_ticket(selected_option, role="user"): is_user = (role == "user") if not selected_option: return "", "", None, gr.update(visible=is_user) ticket_id = int(selected_option.split(" - ")[0].replace("#", "")) tickets = load_expert_tickets() for t in tickets: if t['id'] == ticket_id: img_p = t.get('image_path', None) h_info, c_info = format_ticket_detail(t) return h_info, c_info, img_p, gr.update(visible=is_user) return "", "", None, gr.update(visible=is_user) def submit_admin_reply(selected_option, reply_text, role="user"): if not selected_option or not reply_text.strip(): dropdown_up, h_info, c_info, img_p, followup_vis = get_admin_tickets_list(selected_option, role) 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, gr.update() ticket_id = int(selected_option.split(" - ")[0].replace("#", "")) tickets = load_expert_tickets() updated = False now = get_vn_time().strftime("%Y-%m-%d %H:%M:%S") target_ticket = None for t in tickets: if t['id'] == ticket_id: t['status'] = "ANSWERED" t['admin_reply'] = reply_text.strip() t['deleted_by_user'] = False if "messages" not in t: t["messages"] = [ {"sender": "USER", "text": t["user_query"], "time": t["time"]} ] t["messages"].append({"sender": "ADMIN", "text": reply_text.strip(), "time": now}) updated = True target_ticket = t break if updated: save_expert_tickets(tickets) status_label, _ = get_ticket_status_display(target_ticket) updated_option_str = f"#{ticket_id} - {target_ticket['plant']} - {target_ticket['time']} - [{status_label}]" dropdown_update, h_info, c_info, img_p, followup_vis = get_admin_tickets_list(updated_option_str, role) return "🎉 Đã gửi câu trả lời cho nhà nông thành công!", dropdown_update, h_info, c_info, img_p, followup_vis, "" dropdown_up, h_info, c_info, img_p, followup_vis = get_admin_tickets_list(selected_option, role) return "❌ Lỗi không tìm thấy yêu cầu!", dropdown_up, h_info, c_info, img_p, followup_vis, gr.update() def submit_user_followup(selected_option, followup_text, role="user"): if not selected_option or not followup_text.strip(): dropdown_up, h_info, c_info, img_p, followup_vis = get_admin_tickets_list(selected_option, role) return dropdown_up, h_info, c_info, img_p, followup_vis, "" ticket_id = int(selected_option.split(" - ")[0].replace("#", "")) tickets = load_expert_tickets() now = get_vn_time().strftime("%Y-%m-%d %H:%M:%S") updated = False target_ticket = None for t in tickets: if t['id'] == ticket_id: t['status'] = "PENDING" t['deleted_by_admin'] = False if "messages" not in t: t["messages"] = [ {"sender": "USER", "text": t["user_query"], "time": t["time"]} ] if t.get("admin_reply"): t["messages"].append({"sender": "ADMIN", "text": t.get("admin_reply", ""), "time": t["time"]}) t["messages"].append({"sender": "USER", "text": followup_text.strip(), "time": now}) updated = True target_ticket = t break if updated: save_expert_tickets(tickets) notify_expert_followup(target_ticket, followup_text.strip()) status_label, _ = get_ticket_status_display(target_ticket) updated_option_str = f"#{ticket_id} - {target_ticket['plant']} - {target_ticket['time']} - [{status_label}]" dropdown_update, h_info, c_info, img_p, followup_vis = get_admin_tickets_list(updated_option_str, role) return dropdown_update, h_info, c_info, img_p, followup_vis, "" def check_user_expert_status(): tickets = load_expert_tickets() user_tickets = [t for t in tickets if not t.get("deleted_by_user", False)] if not user_tickets: return "Hệ thống chưa ghi nhận câu hỏi hỗ trợ nào từ bạn.", None last_ticket = user_tickets[-1] img_p = last_ticket.get('image_path', None) h_info, c_info = format_ticket_detail(last_ticket) return h_info + "


" + c_info, img_p def submit_expert_request(user_question, selected_plant, input_image): global current_detected_disease_context if not user_question.strip(): txt, img_p = check_user_expert_status() 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 tickets = load_expert_tickets() new_id = len(tickets) + 1 now = get_vn_time().strftime("%Y-%m-%d %H:%M:%S") saved_img_path = None if input_image is not None: try: img_filename = f"ticket_{new_id}_{int(datetime.datetime.now().timestamp())}.jpg" saved_img_path = os.path.join(TICKET_IMG_DIR, img_filename) input_bgr = cv2.cvtColor(input_image, cv2.COLOR_RGB2BGR) cv2.imwrite(saved_img_path, input_bgr) except Exception as e: print(f"⚠️ Lỗi lưu ảnh ticket: {e}") new_ticket = { "id": new_id, "time": now, "plant": selected_plant if selected_plant else "Cây trồng", "context": current_detected_disease_context, "user_query": user_question.strip(), "status": "PENDING", "admin_reply": "", "image_path": saved_img_path, "deleted_by_admin": False, "deleted_by_user": False, "messages": [ {"sender": "USER", "text": user_question.strip(), "time": now} ] } tickets.append(new_ticket) save_expert_tickets(tickets) notify_expert_new_question(new_ticket) h_info, c_info = format_ticket_detail(new_ticket) return "📩 Đã gửi câu hỏi đến Hộp thư chờ Chuyên gia! Chuyên gia sẽ sớm xem xét và trả lời.", h_info + "


" + c_info, saved_img_path def go_to_history_panel(role="user"): dropdown_update, h_info, c_info, img_p, followup_vis = get_admin_tickets_list(None, role) is_admin = (role == "admin") is_user = (role == "user") return ( gr.update(visible=False), gr.update(visible=True), load_diagnose_history(), load_chat_history(), dropdown_update, h_info, c_info, img_p, gr.update(visible=is_admin), gr.update(visible=is_user), gr.update(visible=is_user), gr.update(visible=is_user) ) def go_back_to_main_panel(role="user"): # Trả lại màn hình chính và áp lại đúng hiển thị khung "Hỗ trợ tư vấn từ chuyên gia" (chỉ dành cho nhà nông) is_user = (role == "user") return gr.update(visible=True), gr.update(visible=False), gr.update(visible=is_user) @gpu_decorator def analyze_leaf(selected_plant, input_image): global current_detected_disease_context if input_image is None: 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() if selected_plant == "Cây lúa": current_model_path = "best_rice.pt" current_yaml_names = [ 'Rice__BacterialLeafBlight', 'Rice__BrownSpot', 'Rice__Healthy', 'Rice__Hispa', 'Rice__LeafBlast', 'Rice__LeafScald', 'Rice__LeafSmut', 'Rice__NarrowBrownLeafSpot', 'Rice__NeckBlast' ] elif selected_plant == "Cây ớt": current_model_path = "best_chilli.pt" current_yaml_names = [ 'Bercak Daun Serkospora', 'Buah Cabai Sehat', 'Busuk Buah Antraknosa', 'Daun Cabai Sehat', 'Virus Kuning' ] elif selected_plant == "Cây dâu tây": current_model_path = "best_strawberry.pt" current_yaml_names = [ 'Angular Leafspot', 'Anthracnose Fruit Rot', 'Blossom Blight', 'Gray Mold', 'Leaf Spot', 'Powdery Mildew Fruit', 'Powdery Mildew Leaf' ] elif selected_plant == "Cây cà chua": current_model_path = "best_tomato.pt" current_yaml_names = ROBOFLOW_YAML_NAMES elif selected_plant == "Cây cà phê": current_model_path = "best_coffee.pt" current_yaml_names = [ 'algal_spot', 'brown_eye_spot', 'healthy', 'miner', 'phoma', 'powdery_mildew' ] elif selected_plant == "Cây ngô (Bắp)": current_model_path = "best_corn.pt" current_yaml_names = ['blight', 'common_rust', 'gray_spot', 'health'] elif selected_plant == "Cây nho": current_model_path = "best_grape.pt" current_yaml_names = ['Grape Black Rot', 'Grape Esca', 'Grape Healthy', 'Grape Leaf Blight'] else: return None, f"⚠️ THÔNG BÁO: Phân khoa điều trị hiện tại chưa được kích hoạt phác đồ xử lý cho loại thực vật: {selected_plant}.", [{"role": "assistant", "content": "❌ Loại cây này hiện chưa được hỗ trợ tư vấn chuyên sâu."}], load_diagnose_history() local_model = YOLO(current_model_path) input_bgr = cv2.cvtColor(input_image, cv2.COLOR_RGB2BGR) dynamic_names = {} for idx, name in enumerate(current_yaml_names): dynamic_names[idx] = translate_disease(name, selected_plant, with_accent=False) local_model.model.names = dynamic_names results = local_model.predict(source=input_bgr, conf=0.35, imgsz=1024) annotated_bgr = results[0].plot(line_width=3, labels=True, conf=True) annotated_rgb = cv2.cvtColor(annotated_bgr, cv2.COLOR_BGR2RGB) detected_diseases_vi = [] raw_names_vi = [] for box in results[0].boxes: cls_id = int(box.cls[0]) english_name = current_yaml_names[cls_id] vietnamese_accent_name = translate_disease(english_name, selected_plant, with_accent=True) box_conf = float(box.conf[0]) * 100 detected_diseases_vi.append(f"🧬 {vietnamese_accent_name} ➔ Mức độ biểu hiện: {box_conf:.1f}%") raw_names_vi.append(vietnamese_accent_name) if len(detected_diseases_vi) == 0: current_detected_disease_context = f"Đối tượng kiểm tra là {selected_plant}. Hiện tại trạng thái của cây khỏe mạnh hoàn toàn, không có dấu hiệu bệnh hại bộc phát." result_text = f"✨ KẾT LUẬN TOÀN DIỆN TỪ HỘI ĐỒNG BÁC SĨ AI:\n\n🔬 Trạng thái: HOÀN TOÀN KHỎE MẠNH\n🎉 Chúc mừng! Thuật toán quét sâu bề mặt không phát hiện bất kỳ dấu hiệu bệnh lý nào trên {selected_plant}." else: unique_raw = list(set(raw_names_vi)) if selected_plant == "Cây lúa" and "Cây lúa khỏe mạnh không có bệnh" in unique_raw and len(unique_raw) > 1: unique_raw.remove("Cây lúa khỏe mạnh không có bệnh") current_detected_disease_context = f"Đối tượng kiểm tra là {selected_plant}. Qua phân tích cấu trúc mô lá, ghi nhận cây đang bị nhiễm cùng lúc: {', '.join(unique_raw)}." unique_diseases = sorted(list(set(detected_diseases_vi)), reverse=True) result_text = f"📋 BIÊN BẢN CHẨN ĐOÁN LÂM SÀNG BỆNH ÁN ({selected_plant.upper()}):\n\n" + "\n".join(unique_diseases) + "\n\n🚨 HỆ THỐNG ĐÃ KÍCH HOẠT TRỢ LÝ AI: Bà con có thể hỏi phác đồ bón thuốc trực tiếp ở khung chat bên dưới!" clear_chat_history = [ {"role": "assistant", "content": f"🤖 Chào bà con! Tôi đã nhận hồ sơ điện tử từ bộ phận quét ảnh. Ngữ cảnh ghi nhận: **{current_detected_disease_context}**. Bà con cần tôi tư vấn loại thuốc đặc trị hay cách xử lý đất, phân bón nào cho tình trạng này không?"} ] save_diagnose_log(selected_plant, result_text) return annotated_rgb, result_text, clear_chat_history, load_diagnose_history() def is_overload_error(err): """Nhận biết lỗi quá tải / hết quota để quyết định chuyển sang key khác.""" msg = str(err).upper() return any(c in msg for c in [ "503", "UNAVAILABLE", "429", "RESOURCE_EXHAUSTED", "QUOTA", "HIGH DEMAND", "OVERLOADED" ]) def chatbot_response(user_message, history, selected_plant): global current_detected_disease_context global client if history is None: history = [] if not user_message.strip(): return "", history, gr.update(visible=False), gr.update(visible=False) active_context = current_detected_disease_context if len(history) > 0: first_msg = history[0] first_content = extract_text_content(first_msg) if "Ngữ cảnh ghi nhận:" in first_content: try: extracted = first_content.split("Ngữ cảnh ghi nhận: **")[1].split("**.")[0] if extracted.strip(): active_context = extracted.strip() except Exception: pass msg_lower = user_message.lower() if "hoàng sa" in msg_lower or "trường sa" in msg_lower: ai_reply = "Quần đảo Hoàng Sa và Trường Sa là của Việt Nam 🇻🇳!" history.append({"role": "user", "content": user_message}) history.append({"role": "assistant", "content": ai_reply}) save_chat_log(user_message, ai_reply) return "", history, gr.update(visible=False), gr.update(visible=False) if not GEMINI_CLIENTS: notify_telegram("KHÔNG CÓ API KEY", "Biến GEMINI_API_KEY chưa được cấu hình hoặc khởi tạo lỗi.") history.append({"role": "user", "content": user_message}) history.append({"role": "assistant", "content": f"❌ Mất kết nối API với máy chủ Gemini AI. Bà con hãy bấm nút '🆘 XEM TÀI LIỆU CỨU NGUY' bên dưới để đọc tài liệu điều trị dự phòng cho {selected_plant}!"}) return "", history, gr.update(visible=True), gr.update(visible=False) system_instruction_text = f"""Bạn là một chuyên gia bảo vệ thực vật hàng đầu, tích hợp trong phần mềm AgriHospital-Bệnh Viện Cây Trồng. NGỮ CẢNH BẮT BUỘC TỪ HỆ THỐNG: {active_context} QUY TẮC PHẢI TUÂN THỦ: 1. Bạn giới thiệu mình ai, ĐÃ BIẾT rõ loại cây trồng mục tiêu và tình trạng bệnh lý hiện tại dựa trên trường NGỮ CẢNH phía trên. Tuyệt đối KHÔNG hỏi lại những câu thừa thãi như: 'Cây của bạn là cây gì?', 'Bạn đang trồng cây gì?' hoặc 'Cây đang bị bệnh gì?'. 2. Hãy tập trung đưa ra giải pháp cụ thể: Phác đồ cách ly cây bệnh, tên hoạt chất thuốc BVTV tương thích, liều lượng phun bón tra theo đúng chuẩn chỉ định cho phép theo Cục trồng trọt và bảo vệ thực vật thuộc Bộ nông nghiệp và phát triển nông thôn và Phải Nói cho người dùng biết thuốc đó theo đúng chuẩn được phép tại Việt Nam (hoặc CHỈ KHI NÀO người nông dân còn có vẻ nghi ngờ về độ chính xác thì khuyên người dân bấm vào nút "GỬI YÊU CẦU CHO CHUYÊN GIA" ở bên dưới là những chuyên gia kỹ sư thật để nhờ tư vấn) hoặc hướng xử lý nông học an toàn cho loại cây và loại bệnh được nhắc tới trong ngữ cảnh. 3. Nếu người nông dân đặt câu hỏi lạc đề, không liên quan đến loại cây và tình trạng bệnh đang hiển thị trong NGỮ CẢNH (Ví dụ: Hỏi về công thức toán, code python, ca sĩ,...), bạn phải từ chối ngay lập tức: 'Tôi là trợ lý chuyên khoa thuộc AgriHospital-Bệnh Viện Cây Trồng. Hiện tại tôi đang phụ trách hỗ trợ xử lý cho: {active_context}. Do đó, tôi xin phép từ chối giải đáp các câu hỏi ngoài luồng chuyên môn này. Mời bà con đặt câu hỏi tập trung vào tình trạng bệnh hiện tại của cây để tôi kê đơn thuốc chính xác!' 5. Trả lời bằng tiếng Việt thân thiện, súc tích, dễ hiểu với nhà nông. Luôn xưng 'Tôi' và gọi người dùng là 'Bà con'.""" gemini_history_contents = [] for turn in history[1:]: role_type = turn.get("role", "") if isinstance(turn, dict) else getattr(turn, "role", "") content_text = extract_text_content(turn) if content_text.strip(): role = "user" if role_type == "user" else "model" gemini_history_contents.append( types.Content( role=role, parts=[types.Part.from_text(text=content_text)] ) ) gemini_history_contents.append( types.Content( role="user", parts=[types.Part.from_text(text=str(user_message))] ) ) # ============ THỬ LẦN LƯỢT CÁC API KEY: KEY 1 LỖI THÌ CHUYỂN SANG KEY 2 NGAY ============ config = types.GenerateContentConfig( system_instruction=system_instruction_text, temperature=0.25, ) ai_reply = None last_error = None key_errors = [] for key_name, key_client in GEMINI_CLIENTS: for attempt in range(2): # mỗi key thử tối đa 2 lần try: response = key_client.models.generate_content( model=TARGET_MODEL, contents=gemini_history_contents, config=config, ) ai_reply = response.text.strip() print(f"✅ Trả lời bằng {key_name}") break except Exception as e: last_error = e key_errors.append(f"{key_name}: {str(e)[:150]}") if is_overload_error(e) and attempt < 1: print(f"⏳ {key_name} quá tải/hết quota, thử lại lần {attempt + 1}...") time.sleep(1.5) continue print(f"❌ {key_name} lỗi: {str(e)[:120]}") break # lỗi không chờ lại được -> chuyển sang key kế tiếp if ai_reply is not None: break # key này đã trả lời được, không cần thử key sau if ai_reply is not None: if key_errors: notify_telegram("KEY 1 LỖI (đã chuyển key dự phòng)", "\n".join(key_errors)) history.append({"role": "user", "content": user_message}) history.append({"role": "assistant", "content": ai_reply}) save_chat_log(user_message, ai_reply) return "", history, gr.update(visible=False), gr.update(visible=False) # Cả hai key đều thất bại -> báo lỗi và hiện nút tài liệu cứu nguy notify_telegram( classify_error(last_error), f"Cây: {selected_plant}\n" + "\n".join(key_errors) ) if last_error is not None and is_overload_error(last_error): ai_reply = f"🚨 HỆ THỐNG AI ĐANG QUÁ TẢI DO LƯỢNG TRUY CẬP CÙNG LÚC ĐÔNG!\n\n👉 Để không làm gián đoạn việc cứu cây, bà con hãy bấm nút màu cam **'🆘 XEM TÀI LIỆU CỨU NGUY ĐẶC TRỊ'** ngay dưới đây để xem phác đồ điều trị trích xuất từ tài liệu chính thức cho **{selected_plant}**!" else: ai_reply = f"🚨 Lỗi kết nối AI: {last_error}\n\n👉 Bà con hãy bấm nút **'🆘 XEM TÀI LIỆU CỨU NGUY ĐẶC TRỊ'** ngay dưới đây để xem tài liệu phác đồ điều trị dự phòng cho **{selected_plant}**!" history.append({"role": "user", "content": user_message}) history.append({"role": "assistant", "content": ai_reply}) save_chat_log(user_message, ai_reply) return "", history, gr.update(visible=True), gr.update(visible=False) LEAF_HERO_HEAD = r""" """ custom_css = """ .gradio-container { background: linear-gradient(180deg, #eff5f3 0%, #e1ebe7 100%) !important; font-family: 'Inter', system-ui, sans-serif !important; } #login_wrapper { padding: 0 !important; } .login-card { background: #ffffff !important; border-radius: 24px !important; padding: 45px 40px !important; box-shadow: 0 20px 45px rgba(0, 60, 40, 0.06) !important; border: 1px solid rgba(0, 129, 112, 0.1) !important; } .logo-container { display: flex; justify-content: center; align-items: center; margin-bottom: 25px; position: relative; height: 70px; gap: 12px; } /* CẤU HÌNH LOGO BÔNG LÚA ĐỨNG IM VÀ HƯỚNG RA NGOÀI */ .rice-icon-left, .rice-icon-right { font-size: 38px; line-height: 1; display: inline-block; filter: drop-shadow(0 2px 4px rgba(0,0,0,0.15)); } .rice-icon-left { transform: scaleX(-1); } .rice-icon-right { transform: scaleX(1); } .medical-cross-css { width: 46px; height: 46px; background: #007965; position: relative; border-radius: 10px; z-index: 2; box-shadow: 0 4px 12px rgba(0, 121, 101, 0.25); animation: pulseGlow 2.5s infinite ease-in-out; } .medical-cross-css::before, .medical-cross-css::after { content: ""; position: absolute; background: white; border-radius: 2px; } .medical-cross-css::before { top: 19px; left: 9px; width: 28px; height: 8px; } .medical-cross-css::after { top: 9px; left: 19px; width: 8px; height: 28px; } .main-title-layout { display: flex; align-items: center; justify-content: center; gap: 15px; margin: 0 auto; width: fit-content; } .medical-cross-red { width: 42px; height: 42px; background: #e74c3c; position: relative; border-radius: 8px; flex-shrink: 0; box-shadow: 0 4px 12px rgba(231, 76, 60, 0.35); display: inline-block; vertical-align: middle; animation: pulseGlow 2.5s infinite ease-in-out; } .medical-cross-red::before, .medical-cross-red::after { content: ""; position: absolute; background: white; border-radius: 2px; } .medical-cross-red::before { top: 17px; left: 8px; width: 26px; height: 8px; } .medical-cross-red::after { top: 8px; left: 17px; width: 8px; height: 26px; } .app-main-title { color: #004b39 !important; font-weight: 800 !important; font-size: 28px !important; text-align: center !important; margin: 0 0 8px 0 !important; } .app-sub-title { color: #557067 !important; font-size: 14px !important; text-align: center !important; margin: 0 0 30px 0 !important; font-weight: 500 !important; } .hospital-header-center { text-align: center !important; width: 100%; } .hospital-header-center .title-wrapper-h1 { display: inline-flex; align-items: center; justify-content: center; gap: 16px; text-align: center; margin: 0 auto; } .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; } .hospital-header-center p { text-align: center !important; margin: 8px auto 0 auto !important; color: #b2dfdb !important; font-size: 14px !important; } .scan-btn { background: linear-gradient(135deg, #007965, #00bfa5) !important; color: white !important; font-weight: 700 !important; border: none !important; border-radius: 12px !important; box-shadow: 0 5px 15px rgba(0, 121, 101, 0.2) !important; height: 48px; cursor: pointer; transition: all 0.25s ease !important; } .scan-btn:hover { filter: brightness(1.05); transform: translateY(-1px); box-shadow: 0 6px 20px rgba(0, 191, 165, 0.35) !important; } /* CSS NỔI BẬT NÚT GỬI YÊU CẦU CHO CHUYÊN GIA & NÚT CỨU NGUY */ .expert-send-btn { background: linear-gradient(135deg, #d35400 0%, #e67e22 50%, #e74c3c 100%) !important; color: white !important; font-weight: 800 !important; font-size: 15px !important; border: none !important; border-radius: 12px !important; height: 48px !important; cursor: pointer !important; box-shadow: 0 6px 18px rgba(211, 84, 0, 0.4) !important; transition: all 0.25s ease !important; margin-top: 10px !important; } .expert-send-btn:hover { filter: brightness(1.1) !important; transform: translateY(-2px) !important; box-shadow: 0 8px 24px rgba(230, 126, 34, 0.55) !important; } .inline-history-btn { background: #ffffff !important; color: #007965 !important; border: 1.5px solid #007965 !important; font-weight: 700 !important; border-radius: 8px !important; padding: 0px 14px !important; height: 32px !important; font-size: 13px !important; cursor: pointer; transition: all 0.2s ease !important; box-shadow: 0 2px 5px rgba(0, 0, 0, 0.05) !important; display: inline-flex !important; align-items: center; justify-content: center; } .inline-history-btn:hover { background: #007965 !important; color: #ffffff !important; box-shadow: 0 4px 10px rgba(0,121,101,0.15) !important; } /* TÙY CHỈNH NÚT ĐĂNG XUẤT CHO RỘNG RÃI TRỌN CHỮ */ .logout-btn-style { background: linear-gradient(135deg, #e74c3c, #c0392b) !important; color: white !important; font-weight: 700 !important; border: none !important; border-radius: 10px !important; cursor: pointer; height: 45px !important; min-width: 210px !important; padding: 0 18px !important; font-size: 14px !important; box-shadow: 0 4px 10px rgba(231, 76, 60, 0.2) !important; transition: all 0.2s ease !important; margin-top: 5px; display: flex !important; align-items: center !important; justify-content: center !important; white-space: nowrap !important; } .logout-btn-style:hover { filter: brightness(1.1); transform: translateY(-1px); box-shadow: 0 5px 15px rgba(192, 57, 43, 0.4) !important; } /* CẮN CHỈNH BẰNG CAO HOÀN TOÀN VỚI KHUNG TRẮNG CỦA DROPDOWN (BAO GỒM CẢ LABEL TRÊN) */ .delete-btn-style { background: linear-gradient(135deg, #e74c3c, #c0392b) !important; color: white !important; font-weight: 700 !important; font-size: 14px !important; border: 1.5px solid #a93226 !important; border-radius: 10px !important; cursor: pointer !important; height: 100% !important; min-height: 82px !important; margin: 0 !important; box-shadow: 0 4px 12px rgba(231, 76, 60, 0.25) !important; transition: all 0.25s ease !important; display: flex !important; align-items: center !important; justify-content: center !important; } .delete-btn-style:hover { filter: brightness(1.1) !important; transform: translateY(-1px) !important; box-shadow: 0 6px 18px rgba(192, 57, 43, 0.4) !important; } .history-back-btn-style { background: linear-gradient(135deg, #f39c12, #d35400) !important; color: white !important; font-weight: 700 !important; border: none !important; border-radius: 12px !important; cursor: pointer; height: 48px !important; box-shadow: 0 5px 15px rgba(243, 156, 18, 0.3) !important; transition: all 0.25s ease !important; } .history-back-btn-style:hover { filter: brightness(1.05); transform: translateY(-1px); box-shadow: 0 6px 20px rgba(211, 84, 0, 0.45) !important; } .hospital-header { background: linear-gradient(135deg, #004b39 0%, #007965 60%, #00bfa5 100%); color: white; padding: 25px; border-radius: 20px; margin-bottom: 15px; } .gr-group { border: 1px solid #d4deda !important; background: #ffffff !important; border-radius: 16px !important; margin-bottom: 12px !important; } #prescription_col .textbox_custom { border-left: 6px solid #007965 !important; background-color: #f7faf9 !important; border-radius: 12px !important; } #chatbot_col { background: #ffffff !important; border: 1px solid #d4deda !important; border-radius: 16px !important; padding: 15px !important; margin-top: 10px !important; } #chatbot_col .chatbot_custom { border-left: 6px solid #3498db !important; background-color: #f2f7fa !important; border-radius: 12px !important; } .chatbot-title-container { display: flex; justify-content: space-between; align-items: center; width: 100%; margin-bottom: 8px; } .footer-text { text-align: center; margin-top: 25px; color: #728681; font-size: 13px; font-weight: 500; } @keyframes pulseGlow { 0%, 100% { transform: scale(1); filter: drop-shadow(0 2px 5px rgba(0,129,112,0.2)); } 50% { transform: scale(1.04); filter: drop-shadow(0 4px 12px rgba(0,191,165,0.4)); } } /* ===================== LEAF HERO LOGIN (v4) ===================== */ #leaf-bg { position: fixed; inset: 0; width: 100vw; height: 100vh; z-index: 0; opacity: 0; pointer-events: none; transition: opacity 0.6s ease; } body.leaf-on #leaf-bg { opacity: 1; } body.leaf-on { background: #e8f5d6 !important; margin: 0; padding: 0; height: 100vh; overflow: hidden !important; font-family: "Be Vietnam Pro", -apple-system, "Segoe UI", Roboto, Helvetica, Arial, sans-serif; } html:has(body.leaf-on) { overflow: hidden !important; } body:not(.leaf-on) { overflow-y: auto !important; height: auto !important; } html:not(:has(body.leaf-on)) { overflow-y: auto !important; } body.leaf-on .gradio-container { background: transparent !important; padding: 0 !important; min-height: 0 !important; max-width: none !important; font-family: "Be Vietnam Pro", -apple-system, "Segoe UI", Roboto, Helvetica, Arial, sans-serif !important; } body.leaf-on footer { display: none !important; } #login_wrapper h1, #login_wrapper p, #login_wrapper label, #login_wrapper label span, #login_wrapper input, #login_wrapper textarea, #login_wrapper button { font-family: "Be Vietnam Pro", -apple-system, "Segoe UI", Roboto, Helvetica, Arial, sans-serif !important; } #login_wrapper { position: relative; z-index: 2; padding: 0 !important; margin: 0 !important; min-height: 0 !important; height: auto !important; } #login_wrapper.hide { display: none !important; } #login_content_col { position: fixed !important; top: 0 !important; bottom: 0 !important; left: 13vw !important; right: auto !important; z-index: 20 !important; width: 31rem !important; max-width: 84vw !important; margin: 0 !important; padding: 0 !important; box-sizing: border-box !important; display: flex !important; flex-direction: column !important; justify-content: center !important; gap: 8px !important; flex-wrap: nowrap !important; justify-content: safe center !important; overflow-y: auto !important; scrollbar-width: none !important; -ms-overflow-style: none !important; background: transparent !important; border: none !important; box-shadow: none !important; -webkit-backdrop-filter: none !important; backdrop-filter: none !important; } #login_content_col::-webkit-scrollbar { width: 0 !important; height: 0 !important; display: none !important; } #login_content_col > * { flex-shrink: 0 !important; } #login_wrapper .block, #login_wrapper .form { margin: 0 !important; } #login_error { margin: 0 !important; min-height: 0 !important; padding: 0 !important; } #login_error:empty { display: none !important; } @media (max-width: 767px) { #login_content_col { left: 5vw !important; right: 5vw !important; width: auto !important; max-width: none !important; justify-content: flex-start !important; padding-top: 10vh !important; } } .lv4-head { display: flex; align-items: center; gap: .9rem; margin-bottom: .2rem; } .lv4-badge { width: 48px; height: 48px; flex: 0 0 48px; border-radius: 15px; margin-top: 3px; display: grid; place-items: center; background: radial-gradient(circle at 35% 30%, #8fcb5e, #2f8b1c); box-shadow: 0 8px 20px -8px rgba(45,122,18,0.7), inset 0 1px 0 rgba(255,255,255,0.5); } .lv4-badge svg { width: 25px; height: 25px; } .lv4-heart { transform-origin: center; animation: lv4-beat 1.05s ease-in-out infinite; } .lv4-copy { min-width: 0; } .lv4-title { margin: 0; font-weight: 800; line-height: 1.12; letter-spacing: -.02em; font-size: clamp(1.65rem, 2.86vw, 2.31rem); color: #16281a; } .lv4-accent { background: linear-gradient(120deg, #34d399, #059669 55%, #2d7a12); -webkit-background-clip: text; background-clip: text; -webkit-text-fill-color: transparent; color: transparent; } .lv4-sub { margin: .3rem 0 0; font-size: 1.01rem; color: #3d5233; } @keyframes lv4-beat { 0%,100%{transform:scale(1);} 6%{transform:scale(1.22);} 12%{transform:scale(1);} 26%{transform:scale(1.13);} 34%{transform:scale(1);} } @media (prefers-reduced-motion: reduce){ .lv4-heart{ animation: none; } } #login_wrapper .gr-form, #login_wrapper .block, #login_wrapper .form { background: transparent !important; border: none !important; box-shadow: none !important; } #login_wrapper label span, #login_wrapper .gr-box label { color: #3d5233 !important; font-size: 14.3px !important; font-weight: 600 !important; letter-spacing: .01em !important; } #login_wrapper input[type="text"], #login_wrapper input[type="password"] { background: rgba(255,255,255,0.55) !important; border: 1px solid rgba(90,110,70,0.32) !important; border-radius: 14px !important; color: #16281a !important; font-size: 16.5px !important; min-height: 55px !important; padding: 0 17px !important; -webkit-backdrop-filter: blur(6px) !important; backdrop-filter: blur(6px) !important; transition: all 0.2s ease !important; } #login_wrapper input::placeholder { color: #5f7255 !important; } #login_wrapper input:hover { border-color: rgba(16,185,129,0.45) !important; } #login_wrapper input:focus, #login_wrapper input:focus-visible { border-color: #10b981 !important; background: rgba(255,255,255,0.9) !important; outline: none !important; box-shadow: 0 0 0 4px rgba(16,185,129,0.35) !important; } #login_wrapper .scan-btn { border-radius: 14px !important; min-height: 59px !important; margin-top: 2px !important; width: 100% !important; font-size: 16.5px !important; font-weight: 800 !important; letter-spacing: .08em !important; text-transform: uppercase !important; color: #fff !important; border: none !important; cursor: pointer; background: linear-gradient(135deg, #10b981, #047857) !important; box-shadow: 0 16px 34px -14px rgba(5,150,105,0.75), inset 0 1px 0 rgba(255,255,255,0.25) !important; transition: all 0.2s ease !important; } #login_wrapper .scan-btn:hover { transform: translateY(-1px); filter: brightness(1.05); box-shadow: 0 20px 40px -14px rgba(5,150,105,0.85) !important; } #login_wrapper .scan-btn:active { transform: translateY(0); } .lv4-demo { margin-top: .55rem; font-size: .88rem; color: #5f7255; } .lv4-demo-title { display: block; margin-bottom: .35rem; font-weight: 600; color: #3d5233; } .lv4-demo-row { display: flex; align-items: center; gap: .5rem; } .lv4-chip { font-family: ui-monospace, "SF Mono", Menlo, Consolas, monospace !important; font-size: .86rem; font-weight: 600; color: #047857; background: rgba(16,185,129,0.14); border: 1px solid rgba(16,185,129,0.28); padding: .22rem .6rem; border-radius: .5rem; } .sp-error { margin-top: 12px; padding: 12px 16px; border-radius: 12px; background: rgba(231,76,60,0.1); border: 1px solid rgba(231,76,60,0.4); color: #c0392b; font-size: 13.5px; font-weight: 600; display: flex; align-items: center; gap: 10px; } /* =================== END LEAF HERO LOGIN =================== */ /* ============ ĐỒNG BỘ MÀN LÀM VIỆC VỚI MÀN ĐĂNG NHẬP ============ */ :root { --lf-bg1:#eef8e1; --lf-bg2:#e3f2d0; --lf-ink:#16281a; --lf-ink2:#3d5233; --lf-muted:#5f7255; --lf-em:#10b981; --lf-em-d:#047857; --lf-em-dd:#065f46; --lf-card:rgba(255,255,255,0.86); --lf-bd:rgba(90,110,70,0.22); --lf-r:16px; --lf-amber:#d97706; --lf-danger:#dc2626; --lf-leaves:url("data:image/svg+xml;utf8,"); } .gradio-container { background-color: #eef8e1 !important; background-image: url("data:image/svg+xml;utf8,"), linear-gradient(180deg, #eef8e1 0%, #e3f2d0 100%) !important; background-attachment: fixed, fixed !important; background-repeat: repeat, no-repeat !important; font-family: "Be Vietnam Pro", -apple-system, "Segoe UI", Roboto, Helvetica, Arial, sans-serif !important; color: var(--lf-ink); } .gradio-container * { font-family: "Be Vietnam Pro", -apple-system, "Segoe UI", Roboto, Helvetica, Arial, sans-serif; } .hospital-header { background: linear-gradient(120deg, rgba(255,255,255,0.80), rgba(240,253,244,0.60)) !important; border: 1px solid var(--lf-bd) !important; border-radius: 20px !important; padding: 16px 20px !important; -webkit-backdrop-filter: blur(10px); backdrop-filter: blur(10px); box-shadow: 0 12px 32px -22px rgba(6,95,70,0.45) !important; color: var(--lf-ink) !important; } .hospital-header-center h1 { color: var(--lf-ink) !important; font-size: clamp(17px, 1.9vw, 23px) !important; line-height: 1.2 !important; letter-spacing: -0.015em !important; } .hospital-header-center p { color: var(--lf-muted) !important; font-size: 13px !important; } .history_panel_head h1, #root .hospital-header h1 { color: var(--lf-ink) !important; } .hospital-header p { color: var(--lf-muted) !important; } .medical-cross-red, .medical-cross-css { background: radial-gradient(circle at 35% 30%, #8fcb5e, #2f8b1c) !important; border-radius: 13px !important; box-shadow: 0 8px 20px -8px rgba(45,122,18,0.65) !important; } .gr-group, #chatbot_col { background: var(--lf-card) !important; border: 1px solid var(--lf-bd) !important; border-radius: var(--lf-r) !important; box-shadow: 0 10px 28px -22px rgba(6,95,70,0.5) !important; } .gr-group .gr-group { background: transparent !important; border: none !important; box-shadow: none !important; -webkit-backdrop-filter: none !important; backdrop-filter: none !important; } .lf-img { border-color: rgba(16,185,129,0.45) !important; border-width: 2px !important; } .lf-img:hover { border-color: rgba(16,185,129,0.75) !important; } .sec-head { display: flex !important; align-items: center; gap: 9px; margin: 10px 12px !important; font-size: 15px !important; font-weight: 700 !important; color: var(--lf-em-dd) !important; letter-spacing: .005em; } .sec-head svg { width: 19px; height: 19px; flex: 0 0 19px; stroke: var(--lf-em-d); } .sec-head .sec-n { display: inline-grid; place-items: center; width: 20px; height: 20px; flex: 0 0 20px; border-radius: 7px; background: rgba(16,185,129,0.16); color: var(--lf-em-dd); font-size: 11px; font-weight: 800; } .sec-desc { font-size: 13px !important; color: var(--lf-muted) !important; margin: 0 12px 8px !important; } .gradio-container .scan-btn { background: linear-gradient(135deg, var(--lf-em), var(--lf-em-d)) !important; color: #fff !important; border: none !important; border-radius: 14px !important; min-height: 48px !important; font-weight: 800 !important; letter-spacing: .05em !important; box-shadow: 0 14px 30px -16px rgba(5,150,105,0.8) !important; transition: transform .18s ease, box-shadow .18s ease, filter .18s ease !important; } .gradio-container .scan-btn:hover { transform: translateY(-1px); filter: brightness(1.05); } .logout-btn-style, .inline-history-btn, .history-back-btn-style { background: rgba(255,255,255,0.72) !important; color: var(--lf-em-dd) !important; border: 1.5px solid rgba(16,185,129,0.42) !important; border-radius: 12px !important; box-shadow: none !important; font-weight: 700 !important; transition: all .18s ease !important; } .logout-btn-style { height: 48px !important; min-width: 0 !important; } .history-back-btn-style { height: 48px !important; } .inline-history-btn { height: 38px !important; font-size: 13px !important; } .logout-btn-style:hover, .inline-history-btn:hover, .history-back-btn-style:hover { background: #fff !important; border-color: var(--lf-em) !important; color: var(--lf-em-dd) !important; box-shadow: 0 8px 20px -14px rgba(5,150,105,0.9) !important; filter: none !important; transform: translateY(-1px); } .expert-send-btn { background: linear-gradient(135deg, #f59e0b, var(--lf-amber)) !important; border-radius: 12px !important; height: 48px !important; box-shadow: 0 12px 26px -16px rgba(217,119,6,0.85) !important; } .delete-btn-style { background: linear-gradient(135deg, #ef4444, var(--lf-danger)) !important; border: none !important; border-radius: 12px !important; box-shadow: 0 12px 26px -16px rgba(220,38,38,0.8) !important; } .gradio-container input[type="text"], .gradio-container textarea, .gradio-container .wrap-inner { background: rgba(255,255,255,0.62) !important; border-radius: 12px !important; color: var(--lf-ink) !important; } .gradio-container input:focus, .gradio-container textarea:focus { border-color: var(--lf-em) !important; box-shadow: 0 0 0 4px rgba(16,185,129,0.28) !important; outline: none !important; } .gradio-container label span { color: var(--lf-ink2) !important; font-weight: 600 !important; } #prescription_col .textbox_custom { border-left: 5px solid var(--lf-em) !important; background-color: rgba(240,253,244,0.66) !important; border-radius: 12px !important; } #chatbot_col .chatbot_custom { border-left: 5px solid var(--lf-em-d) !important; background-color: rgba(240,253,244,0.5) !important; border-radius: 12px !important; } .footer-text { color: var(--lf-muted) !important; } .lf-img, .lf-chat { transition: height .3s cubic-bezier(.4,0,.2,1) !important; } .textbox_custom textarea { transition: height .3s cubic-bezier(.4,0,.2,1) !important; } .lf-img:has(.upload-container), .lf-img:has(.empty) { height: 230px !important; } .lf-img:has(.image-container img) { height: 420px !important; } .textbox_custom:has(textarea:placeholder-shown) textarea { height: 74px !important; } .lf-chat:not(:has(.message-row ~ .message-row)) { height: 340px !important; } .lf-chat:has(.message-row ~ .message-row) { height: 560px !important; } @media (max-width: 767px) { .gradio-container { font-size: 16px !important; } .gradio-container .scan-btn, .logout-btn-style, .expert-send-btn, .history-back-btn-style { min-height: 50px !important; } .inline-history-btn { min-height: 46px !important; height: auto !important; } .hospital-header { padding: 14px 16px !important; } .lf-img:has(.image-container img) { height: 330px !important; } .lf-chat:has(.message-row ~ .message-row) { height: 460px !important; } } @media (prefers-reduced-motion: reduce) { .lf-img, .lf-chat, .textbox_custom textarea, .gradio-container .scan-btn { transition: none !important; } .medical-cross-red, .medical-cross-css { animation: none !important; } } .gradio-container .scan-btn::before, .logout-btn-style::before, .inline-history-btn::before, .history-back-btn-style::before, .expert-send-btn::before, .delete-btn-style::before { content: ""; width: 18px; height: 18px; flex: 0 0 18px; margin-right: 9px; background-color: currentColor; -webkit-mask-repeat: no-repeat; mask-repeat: no-repeat; -webkit-mask-position: center; mask-position: center; -webkit-mask-size: contain; mask-size: contain; } .gradio-container .scan-btn, .logout-btn-style, .inline-history-btn, .history-back-btn-style, .expert-send-btn, .delete-btn-style { display: inline-flex !important; align-items: center !important; justify-content: center !important; } .gradio-container .scan-btn::before { -webkit-mask-image: url("data:image/svg+xml;utf8,"); mask-image: url("data:image/svg+xml;utf8,"); } .logout-btn-style::before { -webkit-mask-image: url("data:image/svg+xml;utf8,"); mask-image: url("data:image/svg+xml;utf8,"); } .inline-history-btn::before { -webkit-mask-image: url("data:image/svg+xml;utf8,"); mask-image: url("data:image/svg+xml;utf8,"); } .history-back-btn-style::before { -webkit-mask-image: url("data:image/svg+xml;utf8,"); mask-image: url("data:image/svg+xml;utf8,"); } .expert-send-btn::before { -webkit-mask-image: url("data:image/svg+xml;utf8,"); mask-image: url("data:image/svg+xml;utf8,"); } .delete-btn-style::before { -webkit-mask-image: url("data:image/svg+xml;utf8,"); mask-image: url("data:image/svg+xml;utf8,"); } #login_wrapper .scan-btn::before { content: none !important; display: none !important; } .gradio-container button.stop, .gradio-container .stop { background: linear-gradient(135deg, #ef4444, var(--lf-danger)) !important; border: none !important; border-radius: 12px !important; color: #fff !important; min-height: 48px !important; font-weight: 700 !important; } .logout-btn-style { background: linear-gradient(135deg, #fecaca, #fca5a5) !important; color: #7f1d1d !important; border: 1.5px solid rgba(220,38,38,0.35) !important; } .logout-btn-style:hover { background: linear-gradient(135deg, #fca5a5, #f87171) !important; color: #7f1d1d !important; border-color: rgba(220,38,38,0.5) !important; box-shadow: 0 8px 20px -14px rgba(220,38,38,0.6) !important; } #chatbot_col { background: rgba(219,234,254,0.55) !important; } .inline-history-btn:hover { background: linear-gradient(135deg, var(--lf-em), var(--lf-em-d)) !important; color: #ffffff !important; border-color: transparent !important; box-shadow: 0 14px 30px -16px rgba(5,150,105,0.8) !important; } .history-back-btn-style:hover { background: linear-gradient(135deg, #fb923c, #ea580c) !important; color: #ffffff !important; border-color: transparent !important; box-shadow: 0 14px 30px -16px rgba(234,88,12,0.8) !important; } .hospital-header { position: relative !important; overflow: hidden !important; background-color: var(--lf-em-d) !important; background-image: linear-gradient(135deg, var(--lf-em), var(--lf-em-d)), url("data:image/svg+xml;utf8,") !important; background-repeat: no-repeat, repeat !important; background-size: cover, 150px 150px !important; animation: hh-leaves-drift 16s linear infinite !important; border: 1px solid rgba(255,255,255,0.28) !important; } @keyframes hh-leaves-drift { 0% { background-position: 0 0, 0 0; } 100% { background-position: 0 0, 150px 150px; } } @media (prefers-reduced-motion: reduce) { .hospital-header { animation: none !important; } } .hospital-header h1 { color: #ffffff !important; text-shadow: 0 2px 6px rgba(0,0,0,0.25) !important; } .hospital-header p { color: rgba(255,255,255,0.92) !important; } .hospital-header > * { position: relative !important; z-index: 2 !important; } .hospital-header::before, .hospital-header::after { content: ""; position: absolute; top: -45%; left: -45%; width: 190%; height: 190%; pointer-events: none; z-index: 0; background-repeat: repeat; } .hospital-header::before { background-image: url("data:image/svg+xml;utf8,"); background-size: 130px 130px; animation: hh-leaves-fly-1 11s linear infinite; } .hospital-header::after { background-image: url("data:image/svg+xml;utf8,"); background-size: 170px 170px; animation: hh-leaves-fly-2 17s linear infinite reverse; } @keyframes hh-leaves-fly-1 { 0% { transform: translate(0, 0); } 100% { transform: translate(-130px, 130px); } } @keyframes hh-leaves-fly-2 { 0% { transform: translate(0, 0); } 100% { transform: translate(170px, -170px); } } @media (prefers-reduced-motion: reduce) { .hospital-header::before, .hospital-header::after { animation: none !important; } } .lf-img { position: relative !important; } .lf-img .source-selection { display: flex !important; gap: 7px !important; padding: 7px 9px !important; height: auto !important; border-top: 1px solid rgba(90,110,70,0.16) !important; background: rgba(255,255,255,0.55) !important; } .lf-img .source-selection button { flex: 1 1 0 !important; min-width: 0 !important; width: auto !important; min-height: 42px !important; height: auto !important; display: inline-flex !important; align-items: center !important; justify-content: center !important; gap: 6px !important; padding: 0 7px !important; border-radius: 11px !important; background: rgba(255,255,255,0.92) !important; border: 1px solid rgba(16,185,129,0.32) !important; color: var(--lf-em-dd) !important; font-family: "Be Vietnam Pro", -apple-system, "Segoe UI", Roboto, Helvetica, Arial, sans-serif !important; font-size: 11.7px !important; font-weight: 700 !important; white-space: nowrap !important; cursor: pointer !important; transition: all .18s ease !important; box-shadow: none !important; } .lf-img .source-selection button svg { width: 16px !important; height: 16px !important; flex: 0 0 16px !important; } .lf-img .source-selection button:hover { background: #fff !important; border-color: var(--lf-em) !important; } .lf-img .source-selection button:focus-visible { outline: 3px solid rgba(16,185,129,.45) !important; outline-offset: 2px !important; } .lf-img .source-selection button:nth-child(1)::after { content: "Tải ảnh"; } .lf-img .source-selection button:nth-child(2)::after { content: "Chụp ảnh"; } .lf-img .source-selection button:nth-child(3)::after { content: "Dán ảnh"; } .lf-img .source-selection button.selected { background: linear-gradient(135deg, var(--lf-em), var(--lf-em-d)) !important; border-color: transparent !important; color: #fff !important; box-shadow: 0 8px 18px -12px rgba(5,150,105,0.9) !important; } .lf-img .source-selection button.selected:hover { background: linear-gradient(135deg, var(--lf-em), var(--lf-em-d)) !important; filter: brightness(1.06) !important; border-color: transparent !important; } .lf-cam-switch { position: absolute !important; left: 10px !important; right: 10px !important; top: 44px !important; z-index: 26 !important; display: flex !important; flex-direction: column !important; align-items: center !important; gap: 6px !important; pointer-events: none !important; } .lf-cam-cap, .lf-cam-msg { font-family: "Be Vietnam Pro", -apple-system, "Segoe UI", Roboto, Helvetica, Arial, sans-serif !important; color: #fff !important; background: rgba(6,95,70,0.78) !important; padding: 3px 10px !important; border-radius: 999px !important; -webkit-backdrop-filter: blur(6px); backdrop-filter: blur(6px); } .lf-cam-cap { font-size: 11.5px !important; font-weight: 700 !important; letter-spacing: .06em !important; text-transform: uppercase !important; } .lf-cam-msg { font-size: 12px !important; font-weight: 600 !important; } .lf-cam-msg:empty { display: none !important; } .lf-cam-msg.is-err { background: rgba(190,18,60,0.9) !important; } .lf-cam-seg { display: flex !important; gap: 6px !important; padding: 5px !important; background: rgba(6,95,70,0.78) !important; border-radius: 14px !important; -webkit-backdrop-filter: blur(8px); backdrop-filter: blur(8px); pointer-events: auto !important; box-shadow: 0 14px 30px -18px rgba(0,0,0,0.85) !important; } .lf-cam-opt { display: inline-flex !important; align-items: center !important; justify-content: center !important; gap: 7px !important; min-height: 44px !important; padding: 0 14px !important; border: none !important; border-radius: 10px !important; background: transparent !important; color: rgba(255,255,255,0.88) !important; font-family: "Be Vietnam Pro", -apple-system, "Segoe UI", Roboto, Helvetica, Arial, sans-serif !important; font-size: 13.5px !important; font-weight: 700 !important; white-space: nowrap !important; cursor: pointer !important; transition: all .18s ease !important; } .lf-cam-opt svg { width: 18px !important; height: 18px !important; flex: 0 0 18px !important; } .lf-cam-opt:hover { background: rgba(255,255,255,0.16) !important; color: #fff !important; } .lf-cam-opt.is-on { background: #fff !important; color: var(--lf-em-dd) !important; box-shadow: 0 4px 12px -6px rgba(0,0,0,0.55) !important; } .lf-cam-opt:focus-visible { outline: 3px solid #a7f3d0 !important; outline-offset: 2px !important; } .lf-cam-switch.is-busy .lf-cam-opt { opacity: .55 !important; pointer-events: none !important; } @media (max-width: 767px) { .lf-img .source-selection button { min-height: 44px !important; font-size: 11.5px !important; } .lf-cam-opt { min-height: 48px !important; font-size: 14px !important; } } @media (prefers-reduced-motion: reduce) { .lf-img .source-selection button, .lf-cam-opt { transition: none !important; } } .lf-chat.lf-it-tin.lf-it-tin.lf-it-tin { height: 340px !important; } .lf-chat.lf-nhieu-tin.lf-nhieu-tin.lf-nhieu-tin { height: 560px !important; } .lf-img.lf-trong.lf-trong.lf-trong { height: 230px !important; } .lf-img.lf-co-anh.lf-co-anh.lf-co-anh { height: 420px !important; } .textbox_custom.lf-chua-nhap.lf-chua-nhap.lf-chua-nhap textarea { height: 74px !important; } @media (max-width: 767px) { .lf-img.lf-co-anh.lf-co-anh.lf-co-anh { height: 330px !important; } .lf-chat.lf-nhieu-tin.lf-nhieu-tin.lf-nhieu-tin { height: 460px !important; } } html:root.lf-khoa-cuon.lf-khoa-cuon { overflow: hidden !important; } html:root:not(.lf-khoa-cuon):not(.lf-khoa-cuon) { overflow-y: auto !important; } .lf-chat.lf-chat.lf-chat.lf-chat.lf-chat, .lf-img.lf-img.lf-img.lf-img.lf-img, .textbox_custom.textbox_custom.textbox_custom.textbox_custom.textbox_custom textarea { transition: none !important; } .lf-img.fullscreen.fullscreen.fullscreen.fullscreen.fullscreen { position: fixed !important; top: 0 !important; left: 0 !important; width: 100% !important; height: 100% !important; max-width: none !important; max-height: none !important; min-width: 0 !important; min-height: 0 !important; margin: 0 !important; padding: 0 !important; border-radius: 0 !important; z-index: 1000 !important; overflow: hidden !important; background: rgba(8,20,14,0.94) !important; display: flex !important; align-items: center !important; justify-content: center !important; transition: none !important; } .lf-img.fullscreen.fullscreen.fullscreen.fullscreen.fullscreen .image-container, .lf-img.fullscreen.fullscreen.fullscreen.fullscreen.fullscreen .image-frame { width: 100% !important; height: 100% !important; max-width: none !important; max-height: none !important; } .lf-img.fullscreen.fullscreen.fullscreen.fullscreen.fullscreen .image-frame img { width: 100% !important; height: 100% !important; max-width: none !important; max-height: none !important; object-fit: contain !important; } .block.fullscreen .image-frame img { object-fit: contain !important; } """ initial_ticket_text, initial_ticket_img = check_user_expert_status() 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: role_state = gr.State("user") with gr.Row(visible=True, elem_id="login_wrapper") as login_panel: with gr.Column(elem_id="login_content_col"): gr.HTML("""

Trung tâm Chẩn đoán & Điều trị Bệnh Cây trồng Công nghệ cao

Cổng kết nối Trợ lý Bác sĩ AI xét nghiệm tế bào lá.

""") username_input = gr.Textbox(label="Tên đăng nhập", placeholder="Nhập tên đăng nhập", max_lines=1) password_input = gr.Textbox(label="Mật khẩu", type="password", placeholder="••••••••", max_lines=1) error_output = gr.HTML("", elem_id="login_error") btn_login = gr.Button("Kích hoạt phiên xét nghiệm", variant="primary", elem_classes="scan-btn") gr.HTML("""
Tài khoản thử nghiệm
Nhà nông: user / 456
""") with gr.Column(visible=False) as main_panel: with gr.Row(elem_classes="hospital-header"): with gr.Column(scale=10, elem_classes="hospital-header-center"): gr.HTML("""

TRUNG TÂM CHẨN ĐOÁN & ĐIỀU TRỊ BỆNH CÂY TRỒNG CÔNG NGHỆ CAO

Hệ thống tự động phân tích thị giác học sâu v8, phát hiện mầm bệnh thực vật và kết xuất phác đồ điều trị thời gian thực

""") with gr.Column(scale=2, min_width=210): with gr.Row(): btn_logout = gr.Button("ĐĂNG XUẤT HỆ THỐNG", elem_classes="logout-btn-style") with gr.Row(): with gr.Column(scale=10): with gr.Group(elem_classes="gr-group"): gr.Markdown("""

1TIẾP NHẬN MẪU XÉT NGHIỆM

""") plant_dropdown = gr.Dropdown( choices=["Cây dâu tây", "Cây lúa", "Cây ớt", "Cây cà chua", "Cây cà phê", "Cây ngô (Bắp)", "Cây nho"], value="Cây dâu tây", label="Lựa chọn phân khoa điều trị thực vật" ) with gr.Group(elem_classes="gr-group"): image_input = gr.Image(type="numpy", label="Ảnh quét tế bào bề mặt lá", height=370, elem_classes="lf-img") gr.HTML("
") btn_analyze = gr.Button("TIẾN HÀNH QUÉT & CHẨN ĐOÁN LÂM SÀNG", variant="primary", elem_classes="scan-btn") gr.HTML("
") with gr.Column(scale=11, elem_id="prescription_col"): with gr.Group(elem_classes="gr-group"): gr.Markdown("""

2KẾT QUẢ QUÉT THỊ GIÁC HỌC SÂU (AI DETECT)

""") image_output = gr.Image(type="numpy", label="Bản đồ nội soi vi vị trí: Khoanh vùng khu trú ổ bệnh", height=370, elem_classes="lf-img") gr.Markdown("""

3ĐƠN THUỐC LÂM SÀNG SƠ BỘ

""") text_output = gr.Textbox( label="Hồ sơ bệnh án điện tử xuất từ thuật toán", lines=5, placeholder="Hồ sơ bệnh án sơ bộ sẽ tự động xuất ra tại đây...", elem_classes="textbox_custom" ) with gr.Column(scale=12, elem_id="chatbot_col"): with gr.Row(elem_classes="chatbot-title-container"): gr.Markdown("""

4HỘI ĐỒNG TƯ VẤN THUỐC BẢO VỆ THỰC VẬT (CHATBOT AI)

""") btn_history_nav = gr.Button("Xem Lại Lịch Sử Bệnh Án", elem_classes="inline-history-btn") chatbot = gr.Chatbot( 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!"}], height=550, label="Trò chuyện trực tiếp với Chuyên gia Bảo vệ Thực vật AI", elem_classes=["chatbot_custom", "lf-chat"] ) with gr.Row(elem_id="chat_input_row"): chat_msg = gr.Textbox( placeholder="Hỏi chuyên gia AI 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...", scale=8, max_lines=1, label="Câu hỏi của bà con" ) btn_send = gr.Button("GỬI AI", scale=1, variant="primary", elem_classes="scan-btn") # --- NÚT CỨU NGUY VÀ KHUNG TÀI LIỆU DỰ PHÒNG KHI API QUÁ TẢI --- btn_emergency_docs = gr.Button( "🆘 HỆ THỐNG QUÁ TẢI: BẤM VÀO ĐÂY ĐỂ XEM TÀI LIỆU CỨU NGUY ĐẶC TRỊ", variant="primary", elem_classes="expert-send-btn", visible=False ) emergency_doc_box = gr.Markdown( value="", visible=False, elem_classes=["gr-group", "textbox_custom"] ) with gr.Group(elem_classes="gr-group", visible=True) as user_expert_section: gr.Markdown("""

HỖ TRỢ TƯ VẤN TỪ CHUYÊN GIA

""") gr.Markdown("""

Nghi ngờ AI đoán sai hoặc muốn hỏi chi tiết cách điều trị? Gửi câu hỏi tại đây, chỉ Chuyên gia mới xem và trả lời trực tiếp cho bạn!

""") expert_user_query = gr.Textbox(label="Thắc mắc về tình trạng lá cây / nghi ngờ bệnh:", placeholder="Ví dụ: AI đoán cháy bìa lá nhưng tui nghi là đốm vằn, nhờ chuyên gia xem kỹ lại...", lines=2) btn_send_expert = gr.Button("GỬI YÊU CẦU CHO CHUYÊN GIA (HỘP THƯ CHỜ)", elem_classes="expert-send-btn") expert_status_box = gr.HTML(value=initial_ticket_text) 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) gr.HTML("") with gr.Column(visible=False) as history_panel: with gr.Row(elem_classes="hospital-header"): with gr.Column(scale=10): gr.HTML("""

KHO LƯU TRỮ HỒ SƠ & LỊCH SỬ HỆ THỐNG

Xem lại toàn bộ nhật ký quét mô bệnh học thực vật, lịch sử hội thoại và Quản lý Hàng chờ Chuyên gia

""") with gr.Column(scale=2, min_width=150): btn_back_to_clinic = gr.Button("QUAY LẠI PHÒNG KHÁM", elem_classes="history-back-btn-style") with gr.Row(): with gr.Column(visible=True) as user_diagnose_col: gr.Markdown("""

NHẬT KÝ CHẨN ĐOÁN ẢNH

""") history_diagnose_box = gr.Textbox( value=load_diagnose_history(), label="Lịch sử các ca bệnh đã quét", lines=15, interactive=False ) btn_clear_diagnose = gr.Button("XÓA NHẬT KÝ CHẨN ĐOÁN", variant="stop") with gr.Column(visible=True) as user_chat_col: gr.Markdown("""

NHẬT KÝ HỘI THOẠI VỚI AI

""") history_chat_box = gr.Textbox( value=load_chat_history(), label="Lịch sử chat kê đơn thuốc", lines=15, interactive=False ) btn_clear_chat = gr.Button("XÓA NHẬT KÝ CHAT", variant="stop") gr.HTML("
") with gr.Group(elem_classes="gr-group"): gr.Markdown("""

HỘP THƯ TƯ VẤN CHUYÊN GIA (LỊCH SỬ HỎI ĐÁP)

""") with gr.Row(elem_id="expert_select_row"): admin_ticket_select = gr.Dropdown(label="Danh sách các câu hỏi hỗ trợ:", choices=[], value=None, scale=8) btn_delete_ticket = gr.Button("XÓA CÂU HỎI / HỘI THOẠI NÀY", elem_classes="delete-btn-style", scale=2) with gr.Row(): with gr.Column(scale=1): admin_ticket_detail = gr.HTML(value="Hiện chưa có yêu cầu hỗ trợ nào.") with gr.Column(scale=1): admin_ticket_img_display = gr.Image(label="Mẫu lá bệnh do nhà nông gửi lên:", height=300, interactive=False) with gr.Row(): admin_ticket_conversation = gr.HTML(value="", elem_id="full_width_conversation") with gr.Row(): with gr.Column(scale=1, visible=False) as admin_control_panel: gr.Markdown("
") gr.Markdown("""

GỬI PHẢN HỒI BỆNH ÁN TỪ CHUYÊN GIA

""") admin_reply_input = gr.Textbox(label="Nhập phản hồi chuyên gia / Phác đồ điều trị chuẩn:", placeholder="Gõ câu trả lời của Admin/Chuyên gia tại đây...", lines=4) btn_submit_admin_reply = gr.Button("GỬI CÂU TRẢ LỜI CHO NHÀ NÔNG", variant="primary", elem_classes="scan-btn") admin_reply_status = gr.Markdown("") with gr.Group(visible=True) as user_followup_panel: gr.Markdown("
") gr.Markdown("""

BẠN VẪN CHƯA RÕ? HỎI TIẾP CHUYÊN GIA VỀ VẤN ĐỀ NÀY

""") user_followup_input = gr.Textbox(label="Nội dung câu hỏi thêm:", placeholder="Ví dụ: Cảm ơn chuyên gia, nhưng cho tôi hỏi thêm là phun thuốc này vào buổi sáng hay chiều thì tốt hơn...", lines=2) btn_send_followup = gr.Button("GỬI CÂU HỎI TIẾP TỤC CHO CHUYÊN GIA", variant="primary") btn_login.click( login_auth, inputs=[username_input, password_input], outputs=[login_panel, main_panel, error_output, admin_control_panel, user_followup_panel, user_expert_section, user_diagnose_col, role_state] ).then( # Áp lại hiển thị theo vai trò sau khi role_state đã được cập nhật (tránh lộ khung của user ở tài khoản admin) apply_role_visibility, inputs=[role_state], outputs=[user_expert_section, admin_control_panel, user_followup_panel, user_diagnose_col, user_chat_col] ) btn_logout.click( logout_fn, outputs=[ login_panel, main_panel, plant_dropdown, image_input, image_output, text_output, expert_user_query, expert_status_box, expert_ticket_img_view, chatbot, chat_msg, btn_emergency_docs, emergency_doc_box, role_state, user_expert_section, admin_control_panel, user_followup_panel, user_diagnose_col, user_chat_col ] ) btn_history_nav.click( go_to_history_panel, inputs=[role_state], 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] ) btn_back_to_clinic.click( go_back_to_main_panel, inputs=[role_state], outputs=[main_panel, history_panel, user_expert_section] ).then( apply_role_visibility, inputs=[role_state], outputs=[user_expert_section, admin_control_panel, user_followup_panel, user_diagnose_col, user_chat_col] ) btn_analyze.click(analyze_leaf, inputs=[plant_dropdown, image_input], outputs=[image_output, text_output, chatbot, history_diagnose_box]) btn_send.click(chatbot_response, inputs=[chat_msg, chatbot, plant_dropdown], outputs=[chat_msg, chatbot, btn_emergency_docs, emergency_doc_box]) chat_msg.submit(chatbot_response, inputs=[chat_msg, chatbot, plant_dropdown], outputs=[chat_msg, chatbot, btn_emergency_docs, emergency_doc_box]) btn_emergency_docs.click( handle_emergency_button_click, inputs=[plant_dropdown], outputs=[emergency_doc_box] ) btn_clear_diagnose.click(clear_diagnose_history_fn, outputs=[history_diagnose_box]) btn_clear_chat.click(clear_chat_history_fn, outputs=[history_chat_box]) btn_send_expert.click( submit_expert_request, inputs=[expert_user_query, plant_dropdown, image_input], outputs=[expert_user_query, expert_status_box, expert_ticket_img_view] ) admin_ticket_select.change( on_select_admin_ticket, inputs=[admin_ticket_select, role_state], outputs=[admin_ticket_detail, admin_ticket_conversation, admin_ticket_img_display, user_followup_panel] ) btn_submit_admin_reply.click( submit_admin_reply, inputs=[admin_ticket_select, admin_reply_input, role_state], outputs=[admin_reply_status, admin_ticket_select, admin_ticket_detail, admin_ticket_conversation, admin_ticket_img_display, user_followup_panel, admin_reply_input] ) btn_send_followup.click( submit_user_followup, inputs=[admin_ticket_select, user_followup_input, role_state], outputs=[admin_ticket_select, admin_ticket_detail, admin_ticket_conversation, admin_ticket_img_display, user_followup_panel, user_followup_input] ) btn_delete_ticket.click( delete_current_ticket, inputs=[admin_ticket_select, role_state], outputs=[admin_reply_status, admin_ticket_select, admin_ticket_detail, admin_ticket_conversation, admin_ticket_img_display, user_followup_panel] ) if __name__ == "__main__": demo.launch()