sunbv56 commited on
Commit
cae7746
·
verified ·
1 Parent(s): 9bf5f5a

Update app.py

Browse files
Files changed (1) hide show
  1. app.py +23 -25
app.py CHANGED
@@ -35,10 +35,9 @@ def load_image_as_bytes(image_path):
35
  print(f"❌ Lỗi khi đọc ảnh {image_path}: {e}")
36
  return None
37
 
38
- async def generate_image(image_bytes_list, text_input, max_retries=5):
39
- """Gửi request và nhận kết quả từ Gemini API (Xử lý lỗi 429 với popup thông báo)"""
40
- attempt = 0 # Đếm số lần thử lại
41
- while attempt < max_retries:
42
  try:
43
  image_parts = [types.Part(inline_data=types.Blob(data=img, mime_type="image/jpeg")) for img in image_bytes_list if img]
44
 
@@ -55,9 +54,14 @@ async def generate_image(image_bytes_list, text_input, max_retries=5):
55
  )
56
 
57
  if not response or not response.candidates or not response.candidates[0].content:
58
- attempt += 1
59
- gr.Warning(f"⚠️ API trả về dữ liệu không hợp lệ (thử {attempt}/{max_retries}). Đang thử lại...")
60
- continue # Thử lại ngay lập tức
 
 
 
 
 
61
 
62
  images = []
63
  for part in response.candidates[0].content.parts:
@@ -66,37 +70,31 @@ async def generate_image(image_bytes_list, text_input, max_retries=5):
66
  img = Image.open(BytesIO(part.inline_data.data))
67
  images.append(img)
68
  except Exception as e:
69
- gr.Error(f"❌ Lỗi khi hiển thị ảnh: {e}")
70
- return images # Thành công, trả về ảnh ngay lập tức
71
 
72
  except Exception as e:
73
  error_message = str(e)
74
- if "RESOURCE_EXHAUSTED" in error_message:
75
  try:
76
- # Trích xuất retryDelay từ JSON lỗi
77
  error_json = json.loads(error_message.split("RESOURCE_EXHAUSTED. ")[1])
78
- retry_delay = int(error_json["error"]["details"][-1]["retryDelay"][:-1]) # Lấy số giây từ '2s'
79
 
80
- gr.Warning(f"⚠️ API quá tải! Sẽ thử lại sau {retry_delay} giây...")
81
-
82
- # Đếm ngược thời gian chờ (có popup)
83
- for i in range(retry_delay, 0, -1):
84
- gr.Info(f"⏳ Thử lại sau {i} giây...")
85
  time.sleep(1)
86
 
87
- gr.Info("🔄 Đang thử lại...")
88
- attempt += 1
89
- continue # Thử lại sau thời gian chờ
90
 
91
  except Exception as parse_error:
92
- gr.Error(f"❌ Lỗi khi phân tích retryDelay: {parse_error}")
93
 
94
- gr.Error(f"❌ Lỗi khi gọi API Gemini: {e}")
95
  return []
96
 
97
- gr.Error("❌ Đã thử lại nhiều lần nhưng vẫn thất bại!")
98
- return []
99
-
100
  async def process_request(images, text, num_requests):
101
  """Chạy nhiều request song song"""
102
  image_bytes_list = [load_image_as_bytes(image) if image else None for image in images]
 
35
  print(f"❌ Lỗi khi đọc ảnh {image_path}: {e}")
36
  return None
37
 
38
+ async def generate_image(image_bytes_list, text_input, max_retries=5, retry_delay=2):
39
+ """Gửi request và nhận kết quả từ Gemini API (Xử lý lỗi 429 lỗi phản hồi không hợp lệ)"""
40
+ for attempt in range(1, max_retries + 1):
 
41
  try:
42
  image_parts = [types.Part(inline_data=types.Blob(data=img, mime_type="image/jpeg")) for img in image_bytes_list if img]
43
 
 
54
  )
55
 
56
  if not response or not response.candidates or not response.candidates[0].content:
57
+ print(f"⚠️ Phản hồi API không hợp lệ (thử {attempt}/{max_retries})")
58
+ if attempt < max_retries:
59
+ print(f"🔄 Đang thử lại sau {retry_delay} giây...")
60
+ time.sleep(retry_delay)
61
+ continue
62
+ else:
63
+ print("❌ Đã thử lại nhiều lần nhưng vẫn thất bại!")
64
+ return []
65
 
66
  images = []
67
  for part in response.candidates[0].content.parts:
 
70
  img = Image.open(BytesIO(part.inline_data.data))
71
  images.append(img)
72
  except Exception as e:
73
+ print(f"❌ Lỗi khi hiển thị ảnh: {e}")
74
+ return images
75
 
76
  except Exception as e:
77
  error_message = str(e)
78
+ if "429" in error_message and "RESOURCE_EXHAUSTED" in error_message:
79
  try:
 
80
  error_json = json.loads(error_message.split("RESOURCE_EXHAUSTED. ")[1])
81
+ retry_seconds = int(error_json["error"]["details"][-1]["retryDelay"][:-1]) # Lấy số giây từ '2s'
82
 
83
+ print(f"⚠️ Quá tải API! Chờ {retry_seconds} giây trước khi thử lại...")
84
+
85
+ for i in range(retry_seconds, 0, -1):
86
+ print(f"⏳ Thử lại sau {i} giây...", end="\r")
 
87
  time.sleep(1)
88
 
89
+ print("\n🔄 Đang thử lại...")
90
+ continue
 
91
 
92
  except Exception as parse_error:
93
+ print(f"❌ Lỗi khi phân tích retryDelay: {parse_error}")
94
 
95
+ print(f"❌ Lỗi khi gọi API Gemini: {e}")
96
  return []
97
 
 
 
 
98
  async def process_request(images, text, num_requests):
99
  """Chạy nhiều request song song"""
100
  image_bytes_list = [load_image_as_bytes(image) if image else None for image in images]