Spaces:
Build error
Build error
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",load_in_4bit=True, 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() |