vithacocf commited on
Commit
b6ea73c
·
verified ·
1 Parent(s): 30ad4b1

Update app.py

Browse files
Files changed (1) hide show
  1. app.py +25 -5
app.py CHANGED
@@ -5,6 +5,7 @@ import re
5
  import gradio as gr
6
  import google.generativeai as genai
7
  import random
 
8
 
9
  print("Google Generative AI SDK version:", genai.__version__)
10
 
@@ -70,15 +71,34 @@ def process_image(image, prompt):
70
  # print("(Info) RAG store exists:", e)
71
 
72
  # Create temp file
73
- with tempfile.NamedTemporaryFile(delete=False, suffix=".png") as tmp:
 
 
 
 
 
 
74
  if hasattr(image, "save"):
75
- image.save(tmp.name)
76
- elif isinstance(image, str):
77
- with open(image, "rb") as f:
78
- tmp.write(f.read())
 
79
  else:
 
80
  raise ValueError(f"Unsupported image type: {type(image)}")
 
 
 
 
 
 
 
 
 
 
81
  temp_file = tmp.name
 
82
  print("Temp file:", temp_file)
83
 
84
  # Upload file
 
5
  import gradio as gr
6
  import google.generativeai as genai
7
  import random
8
+ from PIL import Image # Thêm dòng này
9
 
10
  print("Google Generative AI SDK version:", genai.__version__)
11
 
 
71
  # print("(Info) RAG store exists:", e)
72
 
73
  # Create temp file
74
+ COMPRESSION_QUALITY = 80
75
+
76
+ # === KHỐI CODE THAY THẾ ===
77
+ # Tạo tệp tạm thời với suffix là .jpeg
78
+ with tempfile.NamedTemporaryFile(delete=False, suffix=".jpeg") as tmp:
79
+
80
+ # 1. Mở hình ảnh bằng Pillow (xử lý các loại input khác nhau)
81
  if hasattr(image, "save"):
82
+ # Trường hợp input đã là đối tượng Pillow Image
83
+ img = image
84
+ elif isinstance(image, str) and os.path.exists(image):
85
+ # Trường hợp input là đường dẫn tệp
86
+ img = Image.open(image)
87
  else:
88
+ # Trường hợp input không được hỗ trợ
89
  raise ValueError(f"Unsupported image type: {type(image)}")
90
+
91
+ # 2. Giảm Chất Lượng (quality=80) và Lưu tệp vào tệp tạm thời
92
+ # Lưu dưới định dạng JPEG để tối ưu hóa việc nén
93
+ img.save(
94
+ tmp.name,
95
+ format='JPEG',
96
+ optimize=True,
97
+ quality=COMPRESSION_QUALITY
98
+ )
99
+
100
  temp_file = tmp.name
101
+ # ===========================
102
  print("Temp file:", temp_file)
103
 
104
  # Upload file