Spaces:
Runtime error
Runtime error
Commit
·
5be3d23
1
Parent(s):
c55296e
Add application file
Browse files- qwen_gradio.py +63 -0
qwen_gradio.py
ADDED
|
@@ -0,0 +1,63 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
import gradio as gr
|
| 2 |
+
from transformers import Qwen2VLForConditionalGeneration, AutoProcessor
|
| 3 |
+
from qwen_vl_utils import process_vision_info
|
| 4 |
+
import torch
|
| 5 |
+
|
| 6 |
+
# Specify the local cache path for models
|
| 7 |
+
local_path = "/root/.cache/huggingface/hub/models--Qwen--Qwen2-VL-7B-Instruct/snapshots/a28a094eb66a9f2ac70eef346f040d8a79977472"
|
| 8 |
+
|
| 9 |
+
# Load model and processor
|
| 10 |
+
model = Qwen2VLForConditionalGeneration.from_pretrained(
|
| 11 |
+
local_path, torch_dtype="auto", device_map="auto"
|
| 12 |
+
)
|
| 13 |
+
|
| 14 |
+
processor = AutoProcessor.from_pretrained(local_path)
|
| 15 |
+
|
| 16 |
+
# Function to process image and text and generate the output
|
| 17 |
+
def generate_output(image, text, button_click):
|
| 18 |
+
# Prepare input data
|
| 19 |
+
messages = [
|
| 20 |
+
{
|
| 21 |
+
"role": "user",
|
| 22 |
+
"content": [
|
| 23 |
+
{"type": "image", "image": image},
|
| 24 |
+
{"type": "text", "text": text},
|
| 25 |
+
],
|
| 26 |
+
}
|
| 27 |
+
]
|
| 28 |
+
|
| 29 |
+
# Prepare inputs for the model
|
| 30 |
+
text_input = processor.apply_chat_template(messages, tokenize=False, add_generation_prompt=True)
|
| 31 |
+
image_inputs, video_inputs = process_vision_info(messages)
|
| 32 |
+
inputs = processor(
|
| 33 |
+
text=[text_input],
|
| 34 |
+
images=image_inputs,
|
| 35 |
+
videos=video_inputs,
|
| 36 |
+
padding=True,
|
| 37 |
+
return_tensors="pt",
|
| 38 |
+
)
|
| 39 |
+
inputs = inputs.to("cuda")
|
| 40 |
+
|
| 41 |
+
# Generate the output
|
| 42 |
+
generated_ids = model.generate(**inputs, max_new_tokens=128)
|
| 43 |
+
generated_ids_trimmed = [
|
| 44 |
+
out_ids[len(in_ids):] for in_ids, out_ids in zip(inputs.input_ids, generated_ids)
|
| 45 |
+
]
|
| 46 |
+
output_text = processor.batch_decode(
|
| 47 |
+
generated_ids_trimmed, skip_special_tokens=True, clean_up_tokenization_spaces=False
|
| 48 |
+
)
|
| 49 |
+
return output_text[0]
|
| 50 |
+
|
| 51 |
+
# Create Gradio interface
|
| 52 |
+
iface = gr.Interface(
|
| 53 |
+
fn=generate_output,
|
| 54 |
+
inputs=[
|
| 55 |
+
gr.Image(type="pil", label="Upload Image"),
|
| 56 |
+
gr.Textbox(lines=2, placeholder="Enter a question related to the image", label="Input Text"),
|
| 57 |
+
|
| 58 |
+
],
|
| 59 |
+
outputs=gr.Textbox(label="Model Output"),
|
| 60 |
+
)
|
| 61 |
+
|
| 62 |
+
# Launch the Gradio interface
|
| 63 |
+
iface.launch()
|