Upload app.py
Browse files
app.py
ADDED
@@ -0,0 +1,154 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
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 |
+
**📝 Mô 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)
|