Update app.py
Browse files
app.py
CHANGED
|
@@ -47,32 +47,74 @@ client = genai.Client(api_key=api_key)
|
|
| 47 |
# return output_image
|
| 48 |
|
| 49 |
def load_image_as_bytes(image_path):
|
| 50 |
-
"""Chuyển ảnh thành dữ liệu nhị phân"""
|
| 51 |
-
|
| 52 |
-
|
| 53 |
-
|
| 54 |
-
|
| 55 |
-
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 56 |
|
| 57 |
async def generate_image(image_bytes_list, text_input):
|
| 58 |
-
"""Gửi request và nhận kết quả từ Gemini API"""
|
| 59 |
-
|
| 60 |
-
|
| 61 |
-
|
| 62 |
-
|
| 63 |
-
|
| 64 |
-
|
| 65 |
-
|
| 66 |
-
|
| 67 |
-
|
| 68 |
-
|
| 69 |
-
|
| 70 |
-
|
| 71 |
-
|
| 72 |
-
|
| 73 |
-
|
| 74 |
-
|
| 75 |
-
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 76 |
|
| 77 |
async def process_request(images, text, num_requests):
|
| 78 |
"""Chạy nhiều request song song"""
|
|
@@ -87,10 +129,11 @@ async def process_request(images, text, num_requests):
|
|
| 87 |
|
| 88 |
# Resize ảnh giữ nguyên tỷ lệ chiều cao
|
| 89 |
resized_images = [img.resize((2560, int(img.height * (2560 / img.width))), Image.LANCZOS) for img in generated_images]
|
| 90 |
-
print("num_requests",num_requests)
|
| 91 |
-
print("tasks",len(tasks))
|
| 92 |
-
print("generated_images",len(generated_images))
|
| 93 |
-
print("resized_images",len(resized_images))
|
|
|
|
| 94 |
return generated_images + resized_images
|
| 95 |
|
| 96 |
def gradio_interface(image1, image2, text, num_requests):
|
|
@@ -98,14 +141,14 @@ def gradio_interface(image1, image2, text, num_requests):
|
|
| 98 |
images = [img for img in [image1, image2] if img]
|
| 99 |
return asyncio.run(process_request(images, text, num_requests))
|
| 100 |
|
| 101 |
-
# Tạo giao diện Gradio
|
| 102 |
demo = gr.Interface(
|
| 103 |
fn=gradio_interface,
|
| 104 |
inputs=[
|
| 105 |
gr.Image(type='filepath', label="Upload hình ảnh 1"),
|
| 106 |
gr.Image(type='filepath', label="Upload hình ảnh 2"),
|
| 107 |
gr.Textbox(label="Nhập yêu cầu chỉnh sửa hình ảnh"),
|
| 108 |
-
gr.Slider(minimum=1, maximum=
|
| 109 |
],
|
| 110 |
outputs=gr.Gallery(label="Kết quả chỉnh sửa", columns=4),
|
| 111 |
title="Chỉnh sửa ảnh bằng Gemini AI + SRCNN",
|
|
|
|
| 47 |
# return output_image
|
| 48 |
|
| 49 |
def load_image_as_bytes(image_path):
|
| 50 |
+
"""Chuyển ảnh thành dữ liệu nhị phân với kiểm tra lỗi"""
|
| 51 |
+
try:
|
| 52 |
+
with Image.open(image_path) as img:
|
| 53 |
+
img = img.convert("RGB") # Đảm bảo ảnh là RGB
|
| 54 |
+
img_bytes = BytesIO()
|
| 55 |
+
img.save(img_bytes, format="JPEG") # Lưu ảnh vào buffer
|
| 56 |
+
return img_bytes.getvalue() # Lấy dữ liệu nhị phân
|
| 57 |
+
except FileNotFoundError:
|
| 58 |
+
print(f"❌ Lỗi: Không tìm thấy file {image_path}")
|
| 59 |
+
return None
|
| 60 |
+
except UnidentifiedImageError:
|
| 61 |
+
print(f"❌ Lỗi: Không thể mở file {image_path} (định dạng không hợp lệ)")
|
| 62 |
+
return None
|
| 63 |
+
except Exception as e:
|
| 64 |
+
print(f"❌ Lỗi khi đọc ảnh {image_path}: {e}")
|
| 65 |
+
return None
|
| 66 |
|
| 67 |
async def generate_image(image_bytes_list, text_input):
|
| 68 |
+
"""Gửi request và nhận kết quả từ Gemini API (Xử lý lỗi 429)"""
|
| 69 |
+
while True:
|
| 70 |
+
try:
|
| 71 |
+
image_parts = [types.Part(inline_data=types.Blob(data=img, mime_type="image/jpeg")) for img in image_bytes_list if img]
|
| 72 |
+
contents = [text_input, image_parts] if image_parts else [text_input]
|
| 73 |
+
|
| 74 |
+
response = await asyncio.to_thread(
|
| 75 |
+
client.models.generate_content,
|
| 76 |
+
model="gemini-2.0-flash-exp-image-generation",
|
| 77 |
+
contents=contents,
|
| 78 |
+
config=types.GenerateContentConfig(response_modalities=['Text', 'Image'])
|
| 79 |
+
)
|
| 80 |
+
|
| 81 |
+
if not response or not response.candidates or not response.candidates[0].content:
|
| 82 |
+
print("❌ Lỗi: Phản hồi API không hợp lệ")
|
| 83 |
+
return []
|
| 84 |
+
|
| 85 |
+
images = []
|
| 86 |
+
for part in response.candidates[0].content.parts:
|
| 87 |
+
if part.inline_data is not None:
|
| 88 |
+
try:
|
| 89 |
+
img = Image.open(BytesIO(part.inline_data.data))
|
| 90 |
+
images.append(img)
|
| 91 |
+
except Exception as e:
|
| 92 |
+
print(f"❌ Lỗi khi hiển thị ảnh: {e}")
|
| 93 |
+
return images
|
| 94 |
+
|
| 95 |
+
except Exception as e:
|
| 96 |
+
error_message = str(e)
|
| 97 |
+
if "429" in error_message and "RESOURCE_EXHAUSTED" in error_message:
|
| 98 |
+
try:
|
| 99 |
+
# Trích xuất retryDelay từ JSON lỗi
|
| 100 |
+
error_json = json.loads(error_message.split("RESOURCE_EXHAUSTED. ")[1])
|
| 101 |
+
retry_delay = int(error_json["error"]["details"][-1]["retryDelay"][:-1]) # Lấy số giây từ '2s'
|
| 102 |
+
|
| 103 |
+
print(f"⚠️ Đã vượt quá hạn mức! Chờ {retry_delay} giây trước khi thử lại...")
|
| 104 |
+
|
| 105 |
+
# Đếm ngược
|
| 106 |
+
for i in range(retry_delay, 0, -1):
|
| 107 |
+
print(f"⏳ Thử lại sau {i} giây...", end="\r")
|
| 108 |
+
time.sleep(1)
|
| 109 |
+
|
| 110 |
+
print("\n🔄 Đang thử lại...")
|
| 111 |
+
continue # Thử lại request
|
| 112 |
+
|
| 113 |
+
except Exception as parse_error:
|
| 114 |
+
print(f"❌ Lỗi khi phân tích retryDelay: {parse_error}")
|
| 115 |
+
|
| 116 |
+
print(f"❌ Lỗi khi gọi API Gemini: {e}")
|
| 117 |
+
return []
|
| 118 |
|
| 119 |
async def process_request(images, text, num_requests):
|
| 120 |
"""Chạy nhiều request song song"""
|
|
|
|
| 129 |
|
| 130 |
# Resize ảnh giữ nguyên tỷ lệ chiều cao
|
| 131 |
resized_images = [img.resize((2560, int(img.height * (2560 / img.width))), Image.LANCZOS) for img in generated_images]
|
| 132 |
+
print("num_requests", num_requests)
|
| 133 |
+
print("tasks", len(tasks))
|
| 134 |
+
print("generated_images", len(generated_images))
|
| 135 |
+
print("resized_images", len(resized_images))
|
| 136 |
+
|
| 137 |
return generated_images + resized_images
|
| 138 |
|
| 139 |
def gradio_interface(image1, image2, text, num_requests):
|
|
|
|
| 141 |
images = [img for img in [image1, image2] if img]
|
| 142 |
return asyncio.run(process_request(images, text, num_requests))
|
| 143 |
|
| 144 |
+
# Tạo giao diện Gradio với slider từ 1 đến 8
|
| 145 |
demo = gr.Interface(
|
| 146 |
fn=gradio_interface,
|
| 147 |
inputs=[
|
| 148 |
gr.Image(type='filepath', label="Upload hình ảnh 1"),
|
| 149 |
gr.Image(type='filepath', label="Upload hình ảnh 2"),
|
| 150 |
gr.Textbox(label="Nhập yêu cầu chỉnh sửa hình ảnh"),
|
| 151 |
+
gr.Slider(minimum=1, maximum=8, step=1, value=4, label="Số lượng ảnh cần tạo") # Tăng lên 8
|
| 152 |
],
|
| 153 |
outputs=gr.Gallery(label="Kết quả chỉnh sửa", columns=4),
|
| 154 |
title="Chỉnh sửa ảnh bằng Gemini AI + SRCNN",
|