File size: 5,013 Bytes
93ab632 |
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 |
import gradio as gr
import torch
from transformers import AutoModel, AutoTokenizer
import torchvision.transforms as T
from torchvision.transforms.functional import InterpolationMode
from PIL import Image
import base64
import io
import time
# Setup
device = "cpu" # HF Spaces miễn phí chỉ có CPU
model = None
tokenizer = None
transform = None
def load_model():
global model, tokenizer, transform
try:
print("🤖 Loading Vintern-1B-v3.5...")
model_name = "5CD-AI/Vintern-1B-v3_5"
tokenizer = AutoTokenizer.from_pretrained(
model_name,
trust_remote_code=True
)
model = AutoModel.from_pretrained(
model_name,
torch_dtype=torch.float32,
trust_remote_code=True,
low_cpu_mem_usage=True
)
# Image transform
IMAGENET_MEAN = (0.485, 0.456, 0.406)
IMAGENET_STD = (0.229, 0.224, 0.225)
transform = T.Compose([
T.Lambda(lambda img: img.convert('RGB') if img.mode != 'RGB' else img),
T.Resize((448, 448), interpolation=InterpolationMode.BICUBIC),
T.ToTensor(),
T.Normalize(mean=IMAGENET_MEAN, std=IMAGENET_STD)
])
print("✅ Model loaded successfully!")
return True
except Exception as e:
print(f"❌ Error loading model: {e}")
return False
def analyze_image(image):
if model is None:
return "❌ Model chưa được tải. Vui lòng chờ..."
try:
start_time = time.time()
# Preprocess image
if isinstance(image, str):
# Base64 image
if image.startswith('data:image'):
image = image.split(',')[1]
image_bytes = base64.b64decode(image)
image = Image.open(io.BytesIO(image_bytes)).convert('RGB')
image_tensor = transform(image).unsqueeze(0).to(device)
with torch.no_grad():
query = "Mô tả chi tiết những gì bạn thấy trong hình ảnh này:"
description = model.chat(
tokenizer,
image_tensor,
query,
generation_config=dict(
max_new_tokens=200,
do_sample=True,
temperature=0.7,
top_p=0.9,
repetition_penalty=1.1
)
)
# Get objects
try:
object_query = "Liệt kê các đối tượng chính:"
objects_text = model.chat(
tokenizer,
image_tensor,
object_query,
generation_config=dict(max_new_tokens=100, temperature=0.5)
)
objects = [obj.strip() for obj in objects_text.replace(',', ' ').split() if len(obj.strip()) > 2][:5]
objects_str = ", ".join(objects) if objects else "Không có"
except:
objects_str = "Không có"
processing_time = time.time() - start_time
return f"""
**📝 Mô tả từ Vintern AI:**
{description}
**🔍 Đối tượng nhận diện:**
{objects_str}
**⚡ Thời gian xử lý:** {processing_time:.2f}s
**🤖 Model:** Vintern-1B-v3.5 (Hugging Face Spaces)
"""
except Exception as e:
return f"❌ Lỗi phân tích: {str(e)}"
# Load model khi khởi động
print("🚀 Initializing Vintern-1B-v3.5...")
model_loaded = load_model()
# Gradio interface
with gr.Blocks(title="Vintern-1B-v3.5 Video Recognition") as demo:
gr.Markdown("# 🎥 Vintern-1B-v3.5 - Nhận Diện Ảnh Tiếng Việt")
gr.Markdown("Upload ảnh để nhận diện nội dung bằng AI Vintern-1B-v3.5")
if not model_loaded:
gr.Markdown("⚠️ **Model đang được tải...** Vui lòng chờ vài phút.")
with gr.Row():
with gr.Column():
image_input = gr.Image(type="pil", label="📤 Upload Ảnh")
analyze_btn = gr.Button("🔍 Phân Tích", variant="primary")
with gr.Column():
result_output = gr.Textbox(label="📋 Kết Quả", lines=10, max_lines=15)
analyze_btn.click(
fn=analyze_image,
inputs=image_input,
outputs=result_output
)
gr.Markdown("""
---
**💡 Hướng dẫn:**
1. Upload ảnh từ máy tính hoặc webcam
2. Nhấn "Phân Tích" để nhận diện
3. Xem kết quả mô tả tiếng Việt
**🔗 API Endpoint:** Sử dụng URL của Space này trong trangchu.html
""")
if __name__ == "__main__":
demo.launch(server_name="0.0.0.0", server_port=7860) |