ThreeT2105 commited on
Commit
bb48539
·
verified ·
1 Parent(s): 512b4d2

Update app.py

Browse files
Files changed (1) hide show
  1. app.py +77 -29
app.py CHANGED
@@ -7,6 +7,7 @@ from google.genai import types
7
  import datetime
8
  import json
9
  import numpy as np
 
10
 
11
  VN_TIMEZONE = datetime.timezone(datetime.timedelta(hours=7))
12
 
@@ -27,14 +28,30 @@ def gpu_decorator(func):
27
  return func
28
  # -------------------------------------------------------------
29
 
30
- API_KEY = os.environ.get("GEMINI_API_KEY")
31
- TARGET_MODEL = "gemini-3.8-flash"
32
- try:
33
- client = genai.Client(api_key=API_KEY)
34
- print("🎉 Khởi tạo máy chủ Gemini AI thành công!")
35
- except Exception as e:
36
- client = None
37
- print(f"❌ Lỗi cấu hình AI: {e}")
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
38
 
39
  current_detected_disease_context = "Chưa thực hiện quét mẫu bệnh phẩm."
40
  model_path = "best_tomato.pt"
@@ -769,6 +786,13 @@ def analyze_leaf(selected_plant, input_image):
769
  save_diagnose_log(selected_plant, result_text)
770
  return annotated_rgb, result_text, clear_chat_history, load_diagnose_history()
771
 
 
 
 
 
 
 
 
772
  def chatbot_response(user_message, history, selected_plant):
773
  global current_detected_disease_context
774
  global client
@@ -794,7 +818,7 @@ def chatbot_response(user_message, history, selected_plant):
794
  history.append({"role": "assistant", "content": ai_reply})
795
  save_chat_log(user_message, ai_reply)
796
  return "", history, gr.update(visible=False), gr.update(visible=False)
797
- if client is None:
798
  history.append({"role": "user", "content": user_message})
799
  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}!"})
800
  return "", history, gr.update(visible=True), gr.update(visible=False)
@@ -821,29 +845,52 @@ QUY TẮC PHẢI TUÂN THỦ:
821
  role="user",
822
  parts=[types.Part.from_text(text=str(user_message))]
823
  ) )
824
- try:
825
- config = types.GenerateContentConfig(
826
- system_instruction=system_instruction_text,
827
- temperature=0.25, )
828
- response = client.models.generate_content(
829
- model=TARGET_MODEL,
830
- contents=gemini_history_contents,
831
- config=config )
832
- ai_reply = response.text.strip()
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
833
  history.append({"role": "user", "content": user_message})
834
  history.append({"role": "assistant", "content": ai_reply})
835
  save_chat_log(user_message, ai_reply)
836
  return "", history, gr.update(visible=False), gr.update(visible=False)
837
- except Exception as e:
838
- err_msg = str(e).lower()
839
- if "429" in err_msg or "resource_exhausted" in err_msg or "quota" in err_msg:
840
- 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}**!"
841
- else:
842
- ai_reply = f"🚨 Lỗi kết nối AI: {e}\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}**!"
843
- history.append({"role": "user", "content": user_message})
844
- history.append({"role": "assistant", "content": ai_reply})
845
- save_chat_log(user_message, ai_reply)
846
- return "", history, gr.update(visible=True), gr.update(visible=False)
847
 
848
  LEAF_HERO_HEAD = r"""
849
  <link rel="preconnect" href="https://fonts.googleapis.com">
@@ -1573,7 +1620,7 @@ custom_css = """
1573
  }
1574
  .inline-history-btn:hover { background: #007965 !important; color: #ffffff !important; box-shadow: 0 4px 10px rgba(0,121,101,0.15) !important; }
1575
 
1576
- /* TÙY CHỈNH NÚT ĐĂNG XUẤT */
1577
  .logout-btn-style {
1578
  background: linear-gradient(135deg, #e74c3c, #c0392b) !important; color: white !important; font-weight: 700 !important;
1579
  border: none !important; border-radius: 10px !important; cursor: pointer; height: 45px !important; min-width: 210px !important; padding: 0 18px !important;
@@ -1583,6 +1630,7 @@ custom_css = """
1583
  }
1584
  .logout-btn-style:hover { filter: brightness(1.1); transform: translateY(-1px); box-shadow: 0 5px 15px rgba(192, 57, 43, 0.4) !important; }
1585
 
 
1586
  .delete-btn-style {
1587
  background: linear-gradient(135deg, #e74c3c, #c0392b) !important;
1588
  color: white !important;
 
7
  import datetime
8
  import json
9
  import numpy as np
10
+ import time
11
 
12
  VN_TIMEZONE = datetime.timezone(datetime.timedelta(hours=7))
13
 
 
28
  return func
29
  # -------------------------------------------------------------
30
 
31
+ # ============ KHỞI TẠO NHIỀU API KEY (TỰ CHUYỂN KEY KHI KEY 1 QUÁ TẢI) ============
32
+ API_KEYS = [
33
+ k for k in [
34
+ os.environ.get("GEMINI_API_KEY"),
35
+ os.environ.get("GEMINI_API_KEY_2"),
36
+ ] if k
37
+ ]
38
+
39
+ # Mỗi key một client riêng: [("KEY_1", client1), ("KEY_2", client2)]
40
+ GEMINI_CLIENTS = []
41
+ for _i, _k in enumerate(API_KEYS):
42
+ try:
43
+ GEMINI_CLIENTS.append((f"KEY_{_i + 1}", genai.Client(api_key=_k)))
44
+ except Exception as e:
45
+ print(f"❌ Không khởi tạo được KEY_{_i + 1}: {e}")
46
+
47
+ if GEMINI_CLIENTS:
48
+ print(f"🎉 Khởi tạo máy chủ Gemini AI thành công với {len(GEMINI_CLIENTS)} API key!")
49
+ else:
50
+ print("❌ Lỗi cấu hình AI: không có API key Gemini hợp lệ nào.")
51
+
52
+ client = GEMINI_CLIENTS[0][1] if GEMINI_CLIENTS else None
53
+ TARGET_MODEL = "gemini-3.1-flash-lite"
54
+ # ============================================================================
55
 
56
  current_detected_disease_context = "Chưa thực hiện quét mẫu bệnh phẩm."
57
  model_path = "best_tomato.pt"
 
786
  save_diagnose_log(selected_plant, result_text)
787
  return annotated_rgb, result_text, clear_chat_history, load_diagnose_history()
788
 
789
+ def is_overload_error(err):
790
+ """Nhận biết lỗi quá tải / hết quota để quyết định chuyển sang key khác."""
791
+ msg = str(err).upper()
792
+ return any(c in msg for c in [
793
+ "503", "UNAVAILABLE", "429", "RESOURCE_EXHAUSTED", "QUOTA", "HIGH DEMAND", "OVERLOADED"
794
+ ])
795
+
796
  def chatbot_response(user_message, history, selected_plant):
797
  global current_detected_disease_context
798
  global client
 
818
  history.append({"role": "assistant", "content": ai_reply})
819
  save_chat_log(user_message, ai_reply)
820
  return "", history, gr.update(visible=False), gr.update(visible=False)
821
+ if not GEMINI_CLIENTS:
822
  history.append({"role": "user", "content": user_message})
823
  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}!"})
824
  return "", history, gr.update(visible=True), gr.update(visible=False)
 
845
  role="user",
846
  parts=[types.Part.from_text(text=str(user_message))]
847
  ) )
848
+
849
+ # ============ THỬ LẦN LƯỢT CÁC API KEY: KEY 1 LỖI THÌ CHUYỂN SANG KEY 2 NGAY ============
850
+ config = types.GenerateContentConfig(
851
+ system_instruction=system_instruction_text,
852
+ temperature=0.25,
853
+ )
854
+ ai_reply = None
855
+ last_error = None
856
+
857
+ for key_name, key_client in GEMINI_CLIENTS:
858
+ for attempt in range(2): # mỗi key thử tối đa 2 lần
859
+ try:
860
+ response = key_client.models.generate_content(
861
+ model=TARGET_MODEL,
862
+ contents=gemini_history_contents,
863
+ config=config,
864
+ )
865
+ ai_reply = response.text.strip()
866
+ print(f"✅ Trả lời bằng {key_name}")
867
+ break
868
+ except Exception as e:
869
+ last_error = e
870
+ if is_overload_error(e) and attempt < 1:
871
+ print(f"⏳ {key_name} quá tải/hết quota, thử lại lần {attempt + 1}...")
872
+ time.sleep(1.5)
873
+ continue
874
+ print(f"❌ {key_name} lỗi: {str(e)[:120]}")
875
+ break # lỗi không chờ lại được -> chuyển sang key kế tiếp
876
+ if ai_reply is not None:
877
+ break # key này đã trả lời được, không cần thử key sau
878
+
879
+ if ai_reply is not None:
880
  history.append({"role": "user", "content": user_message})
881
  history.append({"role": "assistant", "content": ai_reply})
882
  save_chat_log(user_message, ai_reply)
883
  return "", history, gr.update(visible=False), gr.update(visible=False)
884
+
885
+ # Cả hai key đều thất bại -> báo lỗi và hiện nút tài liệu cứu nguy
886
+ if last_error is not None and is_overload_error(last_error):
887
+ 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}**!"
888
+ else:
889
+ 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}**!"
890
+ history.append({"role": "user", "content": user_message})
891
+ history.append({"role": "assistant", "content": ai_reply})
892
+ save_chat_log(user_message, ai_reply)
893
+ return "", history, gr.update(visible=True), gr.update(visible=False)
894
 
895
  LEAF_HERO_HEAD = r"""
896
  <link rel="preconnect" href="https://fonts.googleapis.com">
 
1620
  }
1621
  .inline-history-btn:hover { background: #007965 !important; color: #ffffff !important; box-shadow: 0 4px 10px rgba(0,121,101,0.15) !important; }
1622
 
1623
+ /* TÙY CHỈNH NÚT ĐĂNG XUẤT CHO RỘNG RÃI TRỌN CHỮ */
1624
  .logout-btn-style {
1625
  background: linear-gradient(135deg, #e74c3c, #c0392b) !important; color: white !important; font-weight: 700 !important;
1626
  border: none !important; border-radius: 10px !important; cursor: pointer; height: 45px !important; min-width: 210px !important; padding: 0 18px !important;
 
1630
  }
1631
  .logout-btn-style:hover { filter: brightness(1.1); transform: translateY(-1px); box-shadow: 0 5px 15px rgba(192, 57, 43, 0.4) !important; }
1632
 
1633
+ /* 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) */
1634
  .delete-btn-style {
1635
  background: linear-gradient(135deg, #e74c3c, #c0392b) !important;
1636
  color: white !important;