Spaces:
Paused
Paused
Update app.py
Browse files
app.py
CHANGED
|
@@ -1,17 +1,13 @@
|
|
| 1 |
import gradio as gr
|
| 2 |
-
import spaces
|
| 3 |
from transformers import Qwen2VLForConditionalGeneration, AutoProcessor, TextIteratorStreamer
|
| 4 |
from transformers.image_utils import load_image
|
| 5 |
from threading import Thread
|
| 6 |
import time
|
| 7 |
import torch
|
| 8 |
-
|
| 9 |
-
import uuid
|
| 10 |
-
import io
|
| 11 |
-
import os
|
| 12 |
|
| 13 |
# Fine-tuned for OCR-based tasks from Qwen's [ Qwen/Qwen2-VL-2B-Instruct ]
|
| 14 |
-
MODEL_ID = "prithivMLmods/Qwen2-VL-OCR-2B-Instruct"
|
| 15 |
processor = AutoProcessor.from_pretrained(MODEL_ID, trust_remote_code=True)
|
| 16 |
model = Qwen2VLForConditionalGeneration.from_pretrained(
|
| 17 |
MODEL_ID,
|
|
@@ -19,78 +15,25 @@ model = Qwen2VLForConditionalGeneration.from_pretrained(
|
|
| 19 |
torch_dtype=torch.float16
|
| 20 |
).to("cuda").eval()
|
| 21 |
|
| 22 |
-
# Supported media extensions
|
| 23 |
-
image_extensions = Image.registered_extensions()
|
| 24 |
-
video_extensions = ("avi", "mp4", "mov", "mkv", "flv", "wmv", "mjpeg", "wav", "gif", "webm", "m4v", "3gp")
|
| 25 |
-
|
| 26 |
-
def identify_and_save_blob(blob_path):
|
| 27 |
-
"""Identifies if the blob is an image or video and saves it accordingly."""
|
| 28 |
-
try:
|
| 29 |
-
with open(blob_path, 'rb') as file:
|
| 30 |
-
blob_content = file.read()
|
| 31 |
-
|
| 32 |
-
# Try to identify if it's an image
|
| 33 |
-
try:
|
| 34 |
-
Image.open(io.BytesIO(blob_content)).verify() # Check if it's a valid image
|
| 35 |
-
extension = ".png" # Default to PNG for saving
|
| 36 |
-
media_type = "image"
|
| 37 |
-
except (IOError, SyntaxError):
|
| 38 |
-
# If it's not a valid image, assume it's a video
|
| 39 |
-
extension = ".mp4" # Default to MP4 for saving
|
| 40 |
-
media_type = "video"
|
| 41 |
-
|
| 42 |
-
# Create a unique filename
|
| 43 |
-
filename = f"temp_{uuid.uuid4()}_media{extension}"
|
| 44 |
-
with open(filename, "wb") as f:
|
| 45 |
-
f.write(blob_content)
|
| 46 |
-
|
| 47 |
-
return filename, media_type
|
| 48 |
-
|
| 49 |
-
except FileNotFoundError:
|
| 50 |
-
raise ValueError(f"The file {blob_path} was not found.")
|
| 51 |
-
except Exception as e:
|
| 52 |
-
raise ValueError(f"An error occurred while processing the file: {e}")
|
| 53 |
-
|
| 54 |
-
def process_vision_info(messages):
|
| 55 |
-
"""Processes vision inputs (images and videos) from messages."""
|
| 56 |
-
image_inputs = []
|
| 57 |
-
video_inputs = []
|
| 58 |
-
for message in messages:
|
| 59 |
-
for content in message["content"]:
|
| 60 |
-
if content["type"] == "image":
|
| 61 |
-
image_inputs.append(load_image(content["image"]))
|
| 62 |
-
elif content["type"] == "video":
|
| 63 |
-
video_inputs.append(content["video"])
|
| 64 |
-
return image_inputs, video_inputs
|
| 65 |
-
|
| 66 |
@spaces.GPU
|
| 67 |
def model_inference(input_dict, history):
|
| 68 |
text = input_dict["text"]
|
| 69 |
files = input_dict["files"]
|
| 70 |
|
| 71 |
-
#
|
| 72 |
-
|
| 73 |
-
|
| 74 |
-
|
| 75 |
-
|
| 76 |
-
|
| 77 |
-
|
| 78 |
-
media_type = "video"
|
| 79 |
-
else:
|
| 80 |
-
try:
|
| 81 |
-
file, media_type = identify_and_save_blob(file)
|
| 82 |
-
except Exception as e:
|
| 83 |
-
gr.Error(f"Unsupported media type: {e}")
|
| 84 |
-
return
|
| 85 |
-
media_paths.append(file)
|
| 86 |
-
media_types.append(media_type)
|
| 87 |
|
| 88 |
# Validate input
|
| 89 |
-
if text == "" and not
|
| 90 |
-
gr.Error("Please input a query and optionally image(s)
|
| 91 |
return
|
| 92 |
-
if text == "" and
|
| 93 |
-
gr.Error("Please input a text query along with the image(s)
|
| 94 |
return
|
| 95 |
|
| 96 |
# Prepare messages for the model
|
|
@@ -98,7 +41,7 @@ def model_inference(input_dict, history):
|
|
| 98 |
{
|
| 99 |
"role": "user",
|
| 100 |
"content": [
|
| 101 |
-
*[{"type":
|
| 102 |
{"type": "text", "text": text},
|
| 103 |
],
|
| 104 |
}
|
|
@@ -106,18 +49,9 @@ def model_inference(input_dict, history):
|
|
| 106 |
|
| 107 |
# Apply chat template and process inputs
|
| 108 |
prompt = processor.apply_chat_template(messages, tokenize=False, add_generation_prompt=True)
|
| 109 |
-
|
| 110 |
-
# Process vision inputs (images and videos)
|
| 111 |
-
image_inputs, video_inputs = process_vision_info(messages)
|
| 112 |
-
|
| 113 |
-
# Ensure video_inputs is not empty
|
| 114 |
-
if not video_inputs:
|
| 115 |
-
video_inputs = None
|
| 116 |
-
|
| 117 |
inputs = processor(
|
| 118 |
text=[prompt],
|
| 119 |
-
images=
|
| 120 |
-
videos=video_inputs if video_inputs else None,
|
| 121 |
return_tensors="pt",
|
| 122 |
padding=True,
|
| 123 |
).to("cuda")
|
|
@@ -142,7 +76,7 @@ def model_inference(input_dict, history):
|
|
| 142 |
|
| 143 |
# Example inputs
|
| 144 |
examples = [
|
| 145 |
-
|
| 146 |
[{"text": "Extract JSON from the image", "files": ["example_images/document.jpg"]}],
|
| 147 |
[{"text": "summarize the letter", "files": ["examples/1.png"]}],
|
| 148 |
[{"text": "Describe the photo", "files": ["examples/3.png"]}],
|
|
@@ -153,16 +87,17 @@ examples = [
|
|
| 153 |
[{"text": "Can you describe this image?", "files": ["example_images/newyork.jpg"]}],
|
| 154 |
[{"text": "Can you describe this image?", "files": ["example_images/dogs.jpg"]}],
|
| 155 |
[{"text": "Where do the severe droughts happen according to this diagram?", "files": ["example_images/examples_weather_events.png"]}],
|
|
|
|
| 156 |
]
|
| 157 |
|
| 158 |
demo = gr.ChatInterface(
|
| 159 |
fn=model_inference,
|
| 160 |
description="# **Multimodal OCR**",
|
| 161 |
examples=examples,
|
| 162 |
-
textbox=gr.MultimodalTextbox(label="Query Input", file_types=["image"
|
| 163 |
stop_btn="Stop Generation",
|
| 164 |
multimodal=True,
|
| 165 |
cache_examples=False,
|
| 166 |
)
|
| 167 |
|
| 168 |
-
demo.launch(debug=True
|
|
|
|
| 1 |
import gradio as gr
|
|
|
|
| 2 |
from transformers import Qwen2VLForConditionalGeneration, AutoProcessor, TextIteratorStreamer
|
| 3 |
from transformers.image_utils import load_image
|
| 4 |
from threading import Thread
|
| 5 |
import time
|
| 6 |
import torch
|
| 7 |
+
import spaces
|
|
|
|
|
|
|
|
|
|
| 8 |
|
| 9 |
# Fine-tuned for OCR-based tasks from Qwen's [ Qwen/Qwen2-VL-2B-Instruct ]
|
| 10 |
+
MODEL_ID = "prithivMLmods/Qwen2-VL-OCR-2B-Instruct"
|
| 11 |
processor = AutoProcessor.from_pretrained(MODEL_ID, trust_remote_code=True)
|
| 12 |
model = Qwen2VLForConditionalGeneration.from_pretrained(
|
| 13 |
MODEL_ID,
|
|
|
|
| 15 |
torch_dtype=torch.float16
|
| 16 |
).to("cuda").eval()
|
| 17 |
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 18 |
@spaces.GPU
|
| 19 |
def model_inference(input_dict, history):
|
| 20 |
text = input_dict["text"]
|
| 21 |
files = input_dict["files"]
|
| 22 |
|
| 23 |
+
# Load images if provided
|
| 24 |
+
if len(files) > 1:
|
| 25 |
+
images = [load_image(image) for image in files]
|
| 26 |
+
elif len(files) == 1:
|
| 27 |
+
images = [load_image(files[0])]
|
| 28 |
+
else:
|
| 29 |
+
images = []
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 30 |
|
| 31 |
# Validate input
|
| 32 |
+
if text == "" and not images:
|
| 33 |
+
gr.Error("Please input a query and optionally image(s).")
|
| 34 |
return
|
| 35 |
+
if text == "" and images:
|
| 36 |
+
gr.Error("Please input a text query along with the image(s).")
|
| 37 |
return
|
| 38 |
|
| 39 |
# Prepare messages for the model
|
|
|
|
| 41 |
{
|
| 42 |
"role": "user",
|
| 43 |
"content": [
|
| 44 |
+
*[{"type": "image", "image": image} for image in images],
|
| 45 |
{"type": "text", "text": text},
|
| 46 |
],
|
| 47 |
}
|
|
|
|
| 49 |
|
| 50 |
# Apply chat template and process inputs
|
| 51 |
prompt = processor.apply_chat_template(messages, tokenize=False, add_generation_prompt=True)
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 52 |
inputs = processor(
|
| 53 |
text=[prompt],
|
| 54 |
+
images=images if images else None,
|
|
|
|
| 55 |
return_tensors="pt",
|
| 56 |
padding=True,
|
| 57 |
).to("cuda")
|
|
|
|
| 76 |
|
| 77 |
# Example inputs
|
| 78 |
examples = [
|
| 79 |
+
|
| 80 |
[{"text": "Extract JSON from the image", "files": ["example_images/document.jpg"]}],
|
| 81 |
[{"text": "summarize the letter", "files": ["examples/1.png"]}],
|
| 82 |
[{"text": "Describe the photo", "files": ["examples/3.png"]}],
|
|
|
|
| 87 |
[{"text": "Can you describe this image?", "files": ["example_images/newyork.jpg"]}],
|
| 88 |
[{"text": "Can you describe this image?", "files": ["example_images/dogs.jpg"]}],
|
| 89 |
[{"text": "Where do the severe droughts happen according to this diagram?", "files": ["example_images/examples_weather_events.png"]}],
|
| 90 |
+
|
| 91 |
]
|
| 92 |
|
| 93 |
demo = gr.ChatInterface(
|
| 94 |
fn=model_inference,
|
| 95 |
description="# **Multimodal OCR**",
|
| 96 |
examples=examples,
|
| 97 |
+
textbox=gr.MultimodalTextbox(label="Query Input", file_types=["image"], file_count="multiple"),
|
| 98 |
stop_btn="Stop Generation",
|
| 99 |
multimodal=True,
|
| 100 |
cache_examples=False,
|
| 101 |
)
|
| 102 |
|
| 103 |
+
demo.launch(debug=True)
|