nguyentantoan commited on
Commit
cb8d367
·
verified ·
1 Parent(s): 63fea4e

Update app.py

Browse files
Files changed (1) hide show
  1. app.py +234 -154
app.py CHANGED
@@ -1,154 +1,234 @@
1
- import gradio as gr
2
- import torch
3
- from transformers import AutoModel, AutoTokenizer
4
- import torchvision.transforms as T
5
- from torchvision.transforms.functional import InterpolationMode
6
- from PIL import Image
7
- import base64
8
- import io
9
- import time
10
-
11
- # Setup
12
- device = "cpu" # HF Spaces miễn phí chỉ có CPU
13
- model = None
14
- tokenizer = None
15
- transform = None
16
-
17
- def load_model():
18
- global model, tokenizer, transform
19
- try:
20
- print("🤖 Loading Vintern-1B-v3.5...")
21
-
22
- model_name = "5CD-AI/Vintern-1B-v3_5"
23
-
24
- tokenizer = AutoTokenizer.from_pretrained(
25
- model_name,
26
- trust_remote_code=True
27
- )
28
-
29
- model = AutoModel.from_pretrained(
30
- model_name,
31
- torch_dtype=torch.float32,
32
- trust_remote_code=True,
33
- low_cpu_mem_usage=True
34
- )
35
-
36
- # Image transform
37
- IMAGENET_MEAN = (0.485, 0.456, 0.406)
38
- IMAGENET_STD = (0.229, 0.224, 0.225)
39
-
40
- transform = T.Compose([
41
- T.Lambda(lambda img: img.convert('RGB') if img.mode != 'RGB' else img),
42
- T.Resize((448, 448), interpolation=InterpolationMode.BICUBIC),
43
- T.ToTensor(),
44
- T.Normalize(mean=IMAGENET_MEAN, std=IMAGENET_STD)
45
- ])
46
-
47
- print("✅ Model loaded successfully!")
48
- return True
49
-
50
- except Exception as e:
51
- print(f"❌ Error loading model: {e}")
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():
72
- query = "Mô tả chi tiết những gì bạn thấy trong hình ảnh này:"
73
-
74
- description = model.chat(
75
- tokenizer,
76
- image_tensor,
77
- query,
78
- generation_config=dict(
79
- max_new_tokens=200,
80
- do_sample=True,
81
- temperature=0.7,
82
- top_p=0.9,
83
- repetition_penalty=1.1
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(
91
- tokenizer,
92
- image_tensor,
93
- object_query,
94
- generation_config=dict(max_new_tokens=100, temperature=0.5)
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
- **📝 tả từ Vintern AI:**
105
- {description}
106
-
107
- **🔍 Đối tượng nhận diện:**
108
- {objects_str}
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)
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ import gradio as gr
2
+ import torch
3
+ from transformers import AutoModel, AutoTokenizer
4
+ import torchvision.transforms as T
5
+ from torchvision.transforms.functional import InterpolationMode
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
19
+ model = None
20
+ tokenizer = None
21
+ transform = None
22
+
23
+ def load_model():
24
+ global model, tokenizer, transform
25
+ try:
26
+ print("🤖 Loading Vintern-1B-v3.5...")
27
+
28
+ model_name = "5CD-AI/Vintern-1B-v3_5"
29
+
30
+ tokenizer = AutoTokenizer.from_pretrained(
31
+ model_name,
32
+ trust_remote_code=True
33
+ )
34
+
35
+ model = AutoModel.from_pretrained(
36
+ model_name,
37
+ torch_dtype=torch.float32,
38
+ trust_remote_code=True,
39
+ low_cpu_mem_usage=True
40
+ )
41
+
42
+ # Image transform
43
+ IMAGENET_MEAN = (0.485, 0.456, 0.406)
44
+ IMAGENET_STD = (0.229, 0.224, 0.225)
45
+
46
+ transform = T.Compose([
47
+ T.Lambda(lambda img: img.convert('RGB') if img.mode != 'RGB' else img),
48
+ T.Resize((448, 448), interpolation=InterpolationMode.BICUBIC),
49
+ T.ToTensor(),
50
+ T.Normalize(mean=IMAGENET_MEAN, std=IMAGENET_STD)
51
+ ])
52
+
53
+ print("✅ Model loaded successfully!")
54
+ return True
55
+
56
+ except Exception as e:
57
+ print(f"❌ Error loading model: {e}")
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():
85
+ query = "Mô tả chi tiết những gì bạn thấy trong hình ảnh này:"
86
+
87
+ description = model.chat(
88
+ tokenizer,
89
+ image_tensor,
90
+ query,
91
+ generation_config=dict(
92
+ max_new_tokens=200,
93
+ do_sample=True,
94
+ temperature=0.7,
95
+ top_p=0.9,
96
+ repetition_penalty=1.1
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(
105
+ tokenizer,
106
+ image_tensor,
107
+ object_query,
108
+ generation_config=dict(max_new_tokens=100, temperature=0.5)
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:**
123
+ {objects_str}
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
+ )