Update app.py
Browse files
app.py
CHANGED
|
@@ -31,22 +31,16 @@ def load_image_as_bytes(image_path):
|
|
| 31 |
except UnidentifiedImageError:
|
| 32 |
print(f"❌ Lỗi: Không thể mở file {image_path} (định dạng không hợp lệ)")
|
| 33 |
return None
|
| 34 |
-
|
| 35 |
except Exception as e:
|
| 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
|
| 40 |
-
"""Gửi request và nhận kết quả từ Gemini API (Xử lý lỗi 429
|
| 41 |
-
|
| 42 |
-
while attempt < max_retries:
|
| 43 |
try:
|
| 44 |
image_parts = [types.Part(inline_data=types.Blob(data=img, mime_type="image/jpeg")) for img in image_bytes_list if img]
|
| 45 |
-
|
| 46 |
-
contents = [text_input] + (
|
| 47 |
-
[image_parts] if len(image_parts) == 1 else
|
| 48 |
-
sum([[f"Image {idx+1}:", part] for idx, part in enumerate(image_parts)], []) if len(image_parts) == 2 else []
|
| 49 |
-
)
|
| 50 |
|
| 51 |
response = await asyncio.to_thread(
|
| 52 |
client.models.generate_content,
|
|
@@ -56,9 +50,8 @@ async def generate_image(image_bytes_list, text_input, max_retries=5):
|
|
| 56 |
)
|
| 57 |
|
| 58 |
if not response or not response.candidates or not response.candidates[0].content:
|
| 59 |
-
|
| 60 |
-
|
| 61 |
-
continue # Thử lại ngay lập tức
|
| 62 |
|
| 63 |
images = []
|
| 64 |
for part in response.candidates[0].content.parts:
|
|
@@ -67,37 +60,33 @@ async def generate_image(image_bytes_list, text_input, max_retries=5):
|
|
| 67 |
img = Image.open(BytesIO(part.inline_data.data))
|
| 68 |
images.append(img)
|
| 69 |
except Exception as e:
|
| 70 |
-
|
| 71 |
-
return images
|
| 72 |
|
| 73 |
except Exception as e:
|
| 74 |
error_message = str(e)
|
| 75 |
-
if "RESOURCE_EXHAUSTED" in error_message:
|
| 76 |
try:
|
| 77 |
# Trích xuất retryDelay từ JSON lỗi
|
| 78 |
error_json = json.loads(error_message.split("RESOURCE_EXHAUSTED. ")[1])
|
| 79 |
retry_delay = int(error_json["error"]["details"][-1]["retryDelay"][:-1]) # Lấy số giây từ '2s'
|
| 80 |
|
| 81 |
-
|
| 82 |
-
|
| 83 |
-
# Đếm ngược
|
| 84 |
for i in range(retry_delay, 0, -1):
|
| 85 |
-
|
| 86 |
time.sleep(1)
|
| 87 |
|
| 88 |
-
|
| 89 |
-
|
| 90 |
-
continue # Thử lại sau thời gian chờ
|
| 91 |
|
| 92 |
except Exception as parse_error:
|
| 93 |
-
|
| 94 |
|
| 95 |
-
|
| 96 |
return []
|
| 97 |
|
| 98 |
-
gr.Error("❌ Đã thử lại nhiều lần nhưng vẫn thất bại!")
|
| 99 |
-
return []
|
| 100 |
-
|
| 101 |
async def process_request(images, text, num_requests):
|
| 102 |
"""Chạy nhiều request song song"""
|
| 103 |
image_bytes_list = [load_image_as_bytes(image) if image else None for image in images]
|
|
@@ -110,14 +99,13 @@ async def process_request(images, text, num_requests):
|
|
| 110 |
generated_images = [img for result in results for img in result]
|
| 111 |
|
| 112 |
# Resize ảnh giữ nguyên tỷ lệ chiều cao
|
| 113 |
-
resized_images = [img.resize((
|
| 114 |
print("num_requests", num_requests)
|
| 115 |
print("tasks", len(tasks))
|
| 116 |
print("generated_images", len(generated_images))
|
| 117 |
print("resized_images", len(resized_images))
|
| 118 |
|
| 119 |
-
|
| 120 |
-
return resized_images
|
| 121 |
|
| 122 |
def gradio_interface(image1, image2, text, num_requests):
|
| 123 |
"""Hàm Gradio xử lý yêu cầu và trả về ảnh"""
|
|
@@ -134,8 +122,8 @@ demo = gr.Interface(
|
|
| 134 |
gr.Slider(minimum=1, maximum=8, step=1, value=4, label="Số lượng ảnh cần tạo") # Tăng lên 8
|
| 135 |
],
|
| 136 |
outputs=gr.Gallery(label="Kết quả chỉnh sửa", columns=4),
|
| 137 |
-
title="Chỉnh sửa ảnh bằng Gemini AI +
|
| 138 |
-
description="Upload tối đa 2 ảnh và nhập yêu cầu chỉnh sửa. Hiển thị ảnh gốc từ API và đã qua
|
| 139 |
)
|
| 140 |
|
| 141 |
demo.launch()
|
|
|
|
| 31 |
except UnidentifiedImageError:
|
| 32 |
print(f"❌ Lỗi: Không thể mở file {image_path} (định dạng không hợp lệ)")
|
| 33 |
return None
|
|
|
|
| 34 |
except Exception as e:
|
| 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):
|
| 39 |
+
"""Gửi request và nhận kết quả từ Gemini API (Xử lý lỗi 429)"""
|
| 40 |
+
while True:
|
|
|
|
| 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 |
+
contents = [text_input, image_parts] if image_parts else [text_input]
|
|
|
|
|
|
|
|
|
|
|
|
|
| 44 |
|
| 45 |
response = await asyncio.to_thread(
|
| 46 |
client.models.generate_content,
|
|
|
|
| 50 |
)
|
| 51 |
|
| 52 |
if not response or not response.candidates or not response.candidates[0].content:
|
| 53 |
+
print("❌ Lỗi: Phản hồi API không hợp lệ")
|
| 54 |
+
return []
|
|
|
|
| 55 |
|
| 56 |
images = []
|
| 57 |
for part in response.candidates[0].content.parts:
|
|
|
|
| 60 |
img = Image.open(BytesIO(part.inline_data.data))
|
| 61 |
images.append(img)
|
| 62 |
except Exception as e:
|
| 63 |
+
print(f"❌ Lỗi khi hiển thị ảnh: {e}")
|
| 64 |
+
return images
|
| 65 |
|
| 66 |
except Exception as e:
|
| 67 |
error_message = str(e)
|
| 68 |
+
if "429" in error_message and "RESOURCE_EXHAUSTED" in error_message:
|
| 69 |
try:
|
| 70 |
# Trích xuất retryDelay từ JSON lỗi
|
| 71 |
error_json = json.loads(error_message.split("RESOURCE_EXHAUSTED. ")[1])
|
| 72 |
retry_delay = int(error_json["error"]["details"][-1]["retryDelay"][:-1]) # Lấy số giây từ '2s'
|
| 73 |
|
| 74 |
+
print(f"⚠️ Đã vượt quá hạn mức! Chờ {retry_delay} giây trước khi thử lại...")
|
| 75 |
+
|
| 76 |
+
# Đếm ngược
|
| 77 |
for i in range(retry_delay, 0, -1):
|
| 78 |
+
print(f"⏳ Thử lại sau {i} giây...", end="\r")
|
| 79 |
time.sleep(1)
|
| 80 |
|
| 81 |
+
print("\n🔄 Đang thử lại...")
|
| 82 |
+
continue # Thử lại request
|
|
|
|
| 83 |
|
| 84 |
except Exception as parse_error:
|
| 85 |
+
print(f"❌ Lỗi khi phân tích retryDelay: {parse_error}")
|
| 86 |
|
| 87 |
+
print(f"❌ Lỗi khi gọi API Gemini: {e}")
|
| 88 |
return []
|
| 89 |
|
|
|
|
|
|
|
|
|
|
| 90 |
async def process_request(images, text, num_requests):
|
| 91 |
"""Chạy nhiều request song song"""
|
| 92 |
image_bytes_list = [load_image_as_bytes(image) if image else None for image in images]
|
|
|
|
| 99 |
generated_images = [img for result in results for img in result]
|
| 100 |
|
| 101 |
# Resize ảnh giữ nguyên tỷ lệ chiều cao
|
| 102 |
+
resized_images = [img.resize((2560, int(img.height * (2560 / img.width))), Image.LANCZOS) for img in generated_images]
|
| 103 |
print("num_requests", num_requests)
|
| 104 |
print("tasks", len(tasks))
|
| 105 |
print("generated_images", len(generated_images))
|
| 106 |
print("resized_images", len(resized_images))
|
| 107 |
|
| 108 |
+
return generated_images + resized_images
|
|
|
|
| 109 |
|
| 110 |
def gradio_interface(image1, image2, text, num_requests):
|
| 111 |
"""Hàm Gradio xử lý yêu cầu và trả về ảnh"""
|
|
|
|
| 122 |
gr.Slider(minimum=1, maximum=8, step=1, value=4, label="Số lượng ảnh cần tạo") # Tăng lên 8
|
| 123 |
],
|
| 124 |
outputs=gr.Gallery(label="Kết quả chỉnh sửa", columns=4),
|
| 125 |
+
title="Chỉnh sửa ảnh bằng Gemini AI + SRCNN",
|
| 126 |
+
description="Upload tối đa 2 ảnh và nhập yêu cầu chỉnh sửa. Hiển thị ảnh gốc từ API và ảnh đã qua SRCNN.",
|
| 127 |
)
|
| 128 |
|
| 129 |
demo.launch()
|