File size: 2,747 Bytes
5038429
 
 
 
3f49fe4
5038429
 
 
3f49fe4
dc2ea44
101c1f1
5038429
 
3f49fe4
5038429
3f49fe4
 
dc2ea44
3f49fe4
5038429
 
 
 
 
 
 
3f49fe4
5038429
3f49fe4
 
 
 
5038429
3f49fe4
 
5038429
3f49fe4
 
 
 
 
 
 
5038429
3f49fe4
dc2ea44
5038429
 
3f49fe4
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
5038429
dc2ea44
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
import gradio as gr
from transformers import AutoModelForCausalLM, AutoTokenizer
import torch
from PIL import Image
import re  # Importando o módulo de expressões regulares
import requests
from io import BytesIO

# Carregar o modelo Qwen-VL e o tokenizer
tokenizer = AutoTokenizer.from_pretrained("Qwen/Qwen-VL-Chat-Int4", trust_remote_code=True)
model = AutoModelForCausalLM.from_pretrained("Qwen/Qwen-VL-Chat-Int4", device_map="auto", trust_remote_code=True).eval()

def generate_predictions(image_input, text_input):
    # Inverter a imagem para corrigir o negativo
    user_image_path = "/tmp/user_input_test_image.jpg"
    Image.fromarray((255 - (image_input * 255).astype('uint8'))).save(user_image_path)
    
    
    # Preparar as entradas
    query = tokenizer.from_list_format([
        {'image': user_image_path},
        {'text': text_input},
    ])
    inputs = tokenizer(query, return_tensors='pt')
    inputs = inputs.to(model.device)
    
    # Gerar a legenda
    pred = model.generate(**inputs)
    full_response = tokenizer.decode(pred.cpu()[0], skip_special_tokens=False)
    
    # Remover o texto de input e outras partes indesejadas da resposta completa
    frontend_response = re.sub(r'Picture \d+:|<.*?>|\/tmp\/.*\.jpg', '', full_response).replace(text_input, '').strip()
    
    # Desenhar caixas delimitadoras, se houver
    image_with_boxes = tokenizer.draw_bbox_on_latest_picture(full_response)
    
    # Salvar e recarregar a imagem para garantir que seja uma imagem PIL
    if image_with_boxes:
        temp_path = "/tmp/image_with_boxes.jpg"
        image_with_boxes.save(temp_path)
        image_with_boxes = Image.open(temp_path)
    
    return image_with_boxes, frontend_response  # Retornando a resposta formatada para o frontend

# Criar interface Gradio
# Create Gradio interface
iface = gr.Interface(
    fn=generate_predictions, 
    inputs=[
        gr.inputs.Image(label="Image Input"), 
        gr.inputs.Textbox(default="Generate a caption for that image with grounding:", label="Prompt")
    ], 
    outputs=[
        gr.outputs.Image(type='pil', label="Image"),  # Explicitly set type to 'pil'
        gr.outputs.Textbox(label="Generated")
    ],
    title="Qwen-VL Demonstration",
    description = """
## Qwen-VL: A Multimodal Large Vision Language Model by Alibaba Cloud
**Space by [@Artificialguybr](https://twitter.com/artificialguybr)**
    
### Key Features:
- **Strong Performance**: Surpasses existing LVLMs on multiple English benchmarks including Zero-shot Captioning and VQA.
- **Multi-lingual Support**: Supports English, Chinese, and multi-lingual conversation.
- **High Resolution**: Utilizes 448*448 resolution for fine-grained recognition and understanding.
""",
)
iface.launch()