Update app.py
Browse files
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
|
| 40 |
-
attempt
|
| 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 |
-
|
| 59 |
-
|
| 60 |
-
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 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 |
-
|
| 70 |
-
return images
|
| 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 |
-
|
| 79 |
|
| 80 |
-
|
| 81 |
-
|
| 82 |
-
|
| 83 |
-
|
| 84 |
-
gr.Info(f"⏳ Thử lại sau {i} giây...")
|
| 85 |
time.sleep(1)
|
| 86 |
|
| 87 |
-
|
| 88 |
-
|
| 89 |
-
continue # Thử lại sau thời gian chờ
|
| 90 |
|
| 91 |
except Exception as parse_error:
|
| 92 |
-
|
| 93 |
|
| 94 |
-
|
| 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 và 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]
|