sunbv56 commited on
Commit
a18913a
·
verified ·
1 Parent(s): e9a7925

Update app.py

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