Spaces:
Running
on
Zero
Running
on
Zero
Added Video Support
Browse files
app.py
CHANGED
@@ -5,98 +5,59 @@ from qwen_vl_utils import process_vision_info
|
|
5 |
import torch
|
6 |
from PIL import Image
|
7 |
import subprocess
|
8 |
-
from datetime import datetime
|
9 |
import numpy as np
|
10 |
import os
|
11 |
|
|
|
|
|
12 |
|
13 |
-
#
|
14 |
-
|
15 |
-
|
16 |
-
|
17 |
-
|
18 |
-
# }
|
19 |
-
def array_to_image_path(image_array):
|
20 |
-
# Convert numpy array to PIL Image
|
21 |
-
img = Image.fromarray(np.uint8(image_array))
|
22 |
-
|
23 |
-
# Generate a unique filename using timestamp
|
24 |
-
timestamp = datetime.now().strftime("%Y%m%d_%H%M%S")
|
25 |
-
filename = f"image_{timestamp}.png"
|
26 |
-
|
27 |
-
# Save the image
|
28 |
-
img.save(filename)
|
29 |
-
|
30 |
-
# Get the full path of the saved image
|
31 |
-
full_path = os.path.abspath(filename)
|
32 |
-
|
33 |
-
return full_path
|
34 |
-
|
35 |
-
models = {
|
36 |
-
"Qwen/Qwen2-VL-2B-Instruct": Qwen2VLForConditionalGeneration.from_pretrained("Qwen/Qwen2-VL-2B-Instruct", trust_remote_code=True, torch_dtype="auto").cuda().eval()
|
37 |
-
|
38 |
-
}
|
39 |
-
|
40 |
-
processors = {
|
41 |
-
"Qwen/Qwen2-VL-2B-Instruct": AutoProcessor.from_pretrained("Qwen/Qwen2-VL-2B-Instruct", trust_remote_code=True)
|
42 |
-
}
|
43 |
|
44 |
DESCRIPTION = "[Qwen2-VL-2B Demo](https://huggingface.co/Qwen/Qwen2-VL-2B-Instruct)"
|
45 |
|
46 |
-
kwargs = {}
|
47 |
-
kwargs['torch_dtype'] = torch.bfloat16
|
48 |
-
|
49 |
-
user_prompt = '<|user|>\n'
|
50 |
-
assistant_prompt = '<|assistant|>\n'
|
51 |
-
prompt_suffix = "<|end|>\n"
|
52 |
-
|
53 |
@spaces.GPU
|
54 |
-
def
|
55 |
-
image_path = array_to_image_path(image)
|
56 |
-
|
57 |
-
print(image_path)
|
58 |
-
model = models[model_id]
|
59 |
-
processor = processors[model_id]
|
60 |
|
61 |
-
|
62 |
-
|
|
|
|
|
|
|
|
|
|
|
|
|
63 |
messages = [
|
64 |
-
|
65 |
"role": "user",
|
66 |
"content": [
|
67 |
{
|
68 |
-
"type":
|
69 |
-
|
|
|
70 |
},
|
71 |
{"type": "text", "text": text_input},
|
72 |
],
|
73 |
}
|
74 |
]
|
75 |
-
|
76 |
-
|
77 |
-
|
78 |
-
messages, tokenize=False, add_generation_prompt=True
|
79 |
-
)
|
80 |
-
image_inputs, video_inputs = process_vision_info(messages)
|
81 |
inputs = processor(
|
82 |
text=[text],
|
83 |
images=image_inputs,
|
84 |
videos=video_inputs,
|
85 |
padding=True,
|
86 |
return_tensors="pt",
|
87 |
-
)
|
88 |
-
|
89 |
-
|
90 |
-
|
91 |
-
|
92 |
-
generated_ids_trimmed = [
|
93 |
-
out_ids[len(in_ids) :] for in_ids, out_ids in zip(inputs.input_ids, generated_ids)
|
94 |
-
]
|
95 |
-
output_text = processor.batch_decode(
|
96 |
-
generated_ids_trimmed, skip_special_tokens=True, clean_up_tokenization_spaces=False
|
97 |
-
)
|
98 |
|
99 |
-
return output_text
|
100 |
|
101 |
css = """
|
102 |
#output {
|
@@ -108,17 +69,16 @@ css = """
|
|
108 |
|
109 |
with gr.Blocks(css=css) as demo:
|
110 |
gr.Markdown(DESCRIPTION)
|
111 |
-
|
|
|
112 |
with gr.Row():
|
113 |
with gr.Column():
|
114 |
-
|
115 |
-
model_selector = gr.Dropdown(choices=list(models.keys()), label="Model", value="Qwen/Qwen2-VL-2B-Instruct")
|
116 |
text_input = gr.Textbox(label="Question")
|
117 |
submit_btn = gr.Button(value="Submit")
|
118 |
with gr.Column():
|
119 |
output_text = gr.Textbox(label="Output Text")
|
120 |
|
121 |
-
submit_btn.click(
|
122 |
|
123 |
-
demo.queue(api_open=False)
|
124 |
demo.launch(debug=True)
|
|
|
5 |
import torch
|
6 |
from PIL import Image
|
7 |
import subprocess
|
|
|
8 |
import numpy as np
|
9 |
import os
|
10 |
|
11 |
+
# Install flash-attn
|
12 |
+
subprocess.run('pip install flash-attn --no-build-isolation', env={'FLASH_ATTENTION_SKIP_CUDA_BUILD': "TRUE"}, shell=True)
|
13 |
|
14 |
+
# Model and Processor Loading (Done once at startup)
|
15 |
+
MODEL_ID = "Qwen/Qwen2-VL-2B-Instruct"
|
16 |
+
model = Qwen2VLForConditionalGeneration.from_pretrained(MODEL_ID, trust_remote_code=True, torch_dtype=torch.float16).to("cuda").eval()
|
17 |
+
processor = AutoProcessor.from_pretrained(MODEL_ID, trust_remote_code=True)
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
18 |
|
19 |
DESCRIPTION = "[Qwen2-VL-2B Demo](https://huggingface.co/Qwen/Qwen2-VL-2B-Instruct)"
|
20 |
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
21 |
@spaces.GPU
|
22 |
+
def qwen_inference(media_path, text_input=None):
|
|
|
|
|
|
|
|
|
|
|
23 |
|
24 |
+
image_extensions = Image.registered_extensions()
|
25 |
+
if media_path.endswith(tuple([i for i, f in image_extensions.items()])):
|
26 |
+
media_type = "image"
|
27 |
+
elif media_path.endswith(("avi", "mp4", "mov", "mkv", "flv", "wmv", "mjpeg", "wav", "gif", "webm", "m4v", "3gp")): # Check if it's a video path
|
28 |
+
media_type = "video"
|
29 |
+
else:
|
30 |
+
raise ValueError("Unsupported media type. Please upload an image or video.")
|
31 |
+
|
32 |
messages = [
|
33 |
+
{
|
34 |
"role": "user",
|
35 |
"content": [
|
36 |
{
|
37 |
+
"type": media_type,
|
38 |
+
media_type: media_path,
|
39 |
+
**({"fps": 8.0} if media_type == "video" else {}),
|
40 |
},
|
41 |
{"type": "text", "text": text_input},
|
42 |
],
|
43 |
}
|
44 |
]
|
45 |
+
|
46 |
+
text = processor.apply_chat_template(messages, tokenize=False, add_generation_prompt=True)
|
47 |
+
image_inputs, video_inputs = process_vision_info(messages)
|
|
|
|
|
|
|
48 |
inputs = processor(
|
49 |
text=[text],
|
50 |
images=image_inputs,
|
51 |
videos=video_inputs,
|
52 |
padding=True,
|
53 |
return_tensors="pt",
|
54 |
+
).to("cuda")
|
55 |
+
|
56 |
+
generated_ids = model.generate(**inputs, max_new_tokens=1024)
|
57 |
+
generated_ids_trimmed = [out_ids[len(in_ids):] for in_ids, out_ids in zip(inputs.input_ids, generated_ids)]
|
58 |
+
output_text = processor.batch_decode(generated_ids_trimmed, skip_special_tokens=True, clean_up_tokenization_spaces=False)[0]
|
|
|
|
|
|
|
|
|
|
|
|
|
59 |
|
60 |
+
return output_text
|
61 |
|
62 |
css = """
|
63 |
#output {
|
|
|
69 |
|
70 |
with gr.Blocks(css=css) as demo:
|
71 |
gr.Markdown(DESCRIPTION)
|
72 |
+
|
73 |
+
with gr.Tab(label="Image/Video Input"):
|
74 |
with gr.Row():
|
75 |
with gr.Column():
|
76 |
+
input_media = gr.File(label="Upload Image or Video", type="filepath")
|
|
|
77 |
text_input = gr.Textbox(label="Question")
|
78 |
submit_btn = gr.Button(value="Submit")
|
79 |
with gr.Column():
|
80 |
output_text = gr.Textbox(label="Output Text")
|
81 |
|
82 |
+
submit_btn.click(qwen_inference, [input_media, text_input], [output_text])
|
83 |
|
|
|
84 |
demo.launch(debug=True)
|