nguyentantoan commited on
Commit
5f21563
·
verified ·
1 Parent(s): cb8d367

Update app.py

Browse files
Files changed (1) hide show
  1. app.py +29 -109
app.py CHANGED
@@ -7,12 +7,6 @@ from PIL import Image
7
  import base64
8
  import io
9
  import time
10
- import logging
11
- import warnings
12
-
13
- # Suppress warnings
14
- warnings.filterwarnings("ignore")
15
- logging.getLogger("transformers").setLevel(logging.ERROR)
16
 
17
  # Setup
18
  device = "cpu" # HF Spaces miễn phí chỉ có CPU
@@ -58,27 +52,20 @@ def load_model():
58
  return False
59
 
60
  def analyze_image(image):
61
- """
62
- Analyze image with proper error handling
63
- """
64
  if model is None:
65
  return "❌ Model chưa được tải. Vui lòng chờ..."
66
 
67
- if image is None:
68
- return "❌ Không có ảnh để phân tích."
69
-
70
  try:
71
  start_time = time.time()
72
 
73
- # Ensure image is PIL Image
74
- if not isinstance(image, Image.Image):
75
- return "❌ Định dạng ảnh không hợp lệ."
76
-
77
- # Convert to RGB if needed
78
- if image.mode != 'RGB':
79
- image = image.convert('RGB')
80
-
81
  # Preprocess image
 
 
 
 
 
 
 
82
  image_tensor = transform(image).unsqueeze(0).to(device)
83
 
84
  with torch.no_grad():
@@ -97,8 +84,7 @@ def analyze_image(image):
97
  )
98
  )
99
 
100
- # Get objects with error handling
101
- objects_str = "Không có"
102
  try:
103
  object_query = "Liệt kê các đối tượng chính:"
104
  objects_text = model.chat(
@@ -109,14 +95,13 @@ def analyze_image(image):
109
  )
110
  objects = [obj.strip() for obj in objects_text.replace(',', ' ').split() if len(obj.strip()) > 2][:5]
111
  objects_str = ", ".join(objects) if objects else "Không có"
112
- except Exception as obj_error:
113
- print(f"Warning: Object detection failed: {obj_error}")
114
  objects_str = "Không có"
115
 
116
  processing_time = time.time() - start_time
117
 
118
- # Format response
119
- result = f"""**📝 Mô tả từ Vintern AI:**
120
  {description}
121
 
122
  **🔍 Đối tượng nhận diện:**
@@ -124,111 +109,46 @@ def analyze_image(image):
124
 
125
  **⚡ Thời gian xử lý:** {processing_time:.2f}s
126
  **🤖 Model:** Vintern-1B-v3.5 (Hugging Face Spaces)
127
- **📡 API Status:** ✅ Hoạt động bình thường"""
128
-
129
- return result
130
 
131
  except Exception as e:
132
- error_msg = f"❌ Lỗi phân tích: {str(e)}"
133
- print(f"Analysis error: {e}")
134
- return error_msg
135
 
136
  # Load model khi khởi động
137
  print("🚀 Initializing Vintern-1B-v3.5...")
138
  model_loaded = load_model()
139
 
140
- # Custom CSS để ẩn một số warnings
141
- custom_css = """
142
- .gradio-container {
143
- max-width: 1200px !important;
144
- }
145
- footer {
146
- visibility: hidden;
147
- }
148
- """
149
-
150
- # Gradio interface với error handling tốt hơn
151
- with gr.Blocks(
152
- title="Vintern-1B-v3.5 Video Recognition",
153
- css=custom_css,
154
- theme=gr.themes.Soft()
155
- ) as demo:
156
- gr.Markdown("""
157
- # 🎥 Vintern-1B-v3.5 - Nhận Diện Ảnh Tiếng Việt
158
- Upload ảnh để nhận diện nội dung bằng AI Vintern-1B-v3.5
159
-
160
- **🔧 API Ready:** Sử dụng `/api/predict` endpoint cho ứng dụng web của bạn!
161
- """)
162
 
163
  if not model_loaded:
164
- gr.Markdown("⚠️ **Model đang được tải...** Vui lòng chờ vài phút và refresh trang.")
165
 
166
  with gr.Row():
167
  with gr.Column():
168
- image_input = gr.Image(
169
- type="pil",
170
- label="📤 Upload Ảnh",
171
- sources=["upload", "webcam", "clipboard"]
172
- )
173
- analyze_btn = gr.Button(
174
- "🔍 Phân Tích",
175
- variant="primary",
176
- size="lg"
177
- )
178
 
179
  with gr.Column():
180
- result_output = gr.Textbox(
181
- label="📋 Kết Quả",
182
- lines=12,
183
- max_lines=20,
184
- show_copy_button=True
185
- )
186
-
187
- # Event handlers với error handling
188
- def safe_analyze(image):
189
- try:
190
- return analyze_image(image)
191
- except Exception as e:
192
- return f"❌ Lỗi hệ thống: {str(e)}"
193
 
194
  analyze_btn.click(
195
- fn=safe_analyze,
196
  inputs=image_input,
197
- outputs=result_output,
198
- show_progress=True
199
- )
200
-
201
- # Auto-analyze on image upload
202
- image_input.change(
203
- fn=safe_analyze,
204
- inputs=image_input,
205
- outputs=result_output,
206
- show_progress=True
207
  )
208
 
209
  gr.Markdown("""
210
  ---
211
- **💡 Hướng dẫn sử dụng:**
212
- 1. 📤 Upload ảnh từ máy tính, webcam hoặc clipboard
213
- 2. 🔍 Nhấn "Phân Tích" hoặc tự động phân tích khi upload
214
- 3. 📋 Xem kết quả mô tả tiếng Việt chi tiết
215
-
216
- **🔗 API Usage:**
217
- - **Endpoint:** `{space_url}/api/predict`
218
- - **Method:** POST
219
- - **Format:** FormData với image file
220
 
221
- **⚡ Hiệu suất:** CPU-optimized cho Hugging Face Spaces miễn phí
222
  """)
223
 
224
- # Launch với cấu hình tối ưu
225
  if __name__ == "__main__":
226
- demo.launch(
227
- server_name="0.0.0.0",
228
- server_port=7860,
229
- show_error=True,
230
- quiet=False, # Show logs for debugging
231
- show_tips=False,
232
- enable_queue=True, # Handle multiple requests
233
- max_threads=2 # Limit threads for free tier
234
- )
 
7
  import base64
8
  import io
9
  import time
 
 
 
 
 
 
10
 
11
  # Setup
12
  device = "cpu" # HF Spaces miễn phí chỉ có CPU
 
52
  return False
53
 
54
  def analyze_image(image):
 
 
 
55
  if model is None:
56
  return "❌ Model chưa được tải. Vui lòng chờ..."
57
 
 
 
 
58
  try:
59
  start_time = time.time()
60
 
 
 
 
 
 
 
 
 
61
  # Preprocess image
62
+ if isinstance(image, str):
63
+ # Base64 image
64
+ if image.startswith('data:image'):
65
+ image = image.split(',')[1]
66
+ image_bytes = base64.b64decode(image)
67
+ image = Image.open(io.BytesIO(image_bytes)).convert('RGB')
68
+
69
  image_tensor = transform(image).unsqueeze(0).to(device)
70
 
71
  with torch.no_grad():
 
84
  )
85
  )
86
 
87
+ # Get objects
 
88
  try:
89
  object_query = "Liệt kê các đối tượng chính:"
90
  objects_text = model.chat(
 
95
  )
96
  objects = [obj.strip() for obj in objects_text.replace(',', ' ').split() if len(obj.strip()) > 2][:5]
97
  objects_str = ", ".join(objects) if objects else "Không có"
98
+ except:
 
99
  objects_str = "Không có"
100
 
101
  processing_time = time.time() - start_time
102
 
103
+ return f"""
104
+ **📝 Mô tả từ Vintern AI:**
105
  {description}
106
 
107
  **🔍 Đối tượng nhận diện:**
 
109
 
110
  **⚡ Thời gian xử lý:** {processing_time:.2f}s
111
  **🤖 Model:** Vintern-1B-v3.5 (Hugging Face Spaces)
112
+ """
 
 
113
 
114
  except Exception as e:
115
+ return f"❌ Lỗi phân tích: {str(e)}"
 
 
116
 
117
  # Load model khi khởi động
118
  print("🚀 Initializing Vintern-1B-v3.5...")
119
  model_loaded = load_model()
120
 
121
+ # Gradio interface
122
+ with gr.Blocks(title="Vintern-1B-v3.5 Video Recognition") as demo:
123
+ gr.Markdown("# 🎥 Vintern-1B-v3.5 - Nhận Diện Ảnh Tiếng Việt")
124
+ gr.Markdown("Upload ảnh để nhận diện nội dung bằng AI Vintern-1B-v3.5")
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
125
 
126
  if not model_loaded:
127
+ gr.Markdown("⚠️ **Model đang được tải...** Vui lòng chờ vài phút.")
128
 
129
  with gr.Row():
130
  with gr.Column():
131
+ image_input = gr.Image(type="pil", label="📤 Upload Ảnh")
132
+ analyze_btn = gr.Button("🔍 Phân Tích", variant="primary")
 
 
 
 
 
 
 
 
133
 
134
  with gr.Column():
135
+ result_output = gr.Textbox(label="📋 Kết Quả", lines=10, max_lines=15)
 
 
 
 
 
 
 
 
 
 
 
 
136
 
137
  analyze_btn.click(
138
+ fn=analyze_image,
139
  inputs=image_input,
140
+ outputs=result_output
 
 
 
 
 
 
 
 
 
141
  )
142
 
143
  gr.Markdown("""
144
  ---
145
+ **💡 Hướng dẫn:**
146
+ 1. Upload ảnh từ máy tính hoặc webcam
147
+ 2. Nhấn "Phân Tích" để nhận diện
148
+ 3. Xem kết quả mô tả tiếng Việt
 
 
 
 
 
149
 
150
+ **🔗 API Endpoint:** Sử dụng URL của Space này trong trangchu.html
151
  """)
152
 
 
153
  if __name__ == "__main__":
154
+ demo.launch(server_name="0.0.0.0", server_port=7860)