prithivMLmods commited on
Commit
dfae74e
·
verified ·
1 Parent(s): d15c2f6

Delete app.py

Browse files
Files changed (1) hide show
  1. app.py +0 -225
app.py DELETED
@@ -1,225 +0,0 @@
1
- import os
2
- import time
3
- from threading import Thread
4
- import re
5
- from PIL import Image, ImageDraw
6
-
7
- import gradio as gr
8
- import spaces
9
- import torch
10
-
11
- from transformers import (
12
- Qwen2_5_VLForConditionalGeneration,
13
- AutoProcessor,
14
- TextIteratorStreamer,
15
- )
16
-
17
- # Constants for text generation
18
- MAX_MAX_NEW_TOKENS = 2048
19
- DEFAULT_MAX_NEW_TOKENS = 1024
20
- MAX_INPUT_TOKEN_LENGTH = int(os.getenv("MAX_INPUT_TOKEN_LENGTH", "4096"))
21
-
22
- device = torch.device("cuda:0" if torch.cuda.is_available() else "cpu")
23
-
24
- # Load Lumian2-VLR-7B-Thinking
25
- MODEL_ID_Y = "prithivMLmods/Lumian2-VLR-7B-Thinking"
26
- processor = AutoProcessor.from_pretrained(MODEL_ID_Y, trust_remote_code=True)
27
- model = Qwen2_5_VLForConditionalGeneration.from_pretrained(
28
- MODEL_ID_Y,
29
- trust_remote_code=True,
30
- torch_dtype=torch.float16
31
- ).to(device).eval()
32
-
33
- def parse_model_output(text: str):
34
- """
35
- Parses the model output to extract the answer and bounding box coordinates.
36
- """
37
- # Extract coordinates from the <think> block
38
- think_match = re.search(r"<think>(.*?)</think>", text, re.DOTALL)
39
- coordinates = []
40
- if think_match:
41
- think_content = think_match.group(1)
42
- # Find all occurrences of (x, y) coordinates
43
- coords_raw = re.findall(r'\((\d+),\s*(\d+)\)', think_content)
44
- coordinates = [(int(x), int(y)) for x, y in coords_raw]
45
-
46
- # Extract the answer from the <answer> block
47
- answer_match = re.search(r"<answer>(.*?)</answer>", text, re.DOTALL)
48
- answer = answer_match.group(1).strip() if answer_match else text
49
-
50
- return answer, coordinates
51
-
52
- def draw_bounding_boxes(image: Image.Image, coordinates: list, box_size: int = 60, use_dotted_style: bool = False):
53
- """
54
- Draws square bounding boxes on the image at the given coordinates.
55
- """
56
- if not coordinates:
57
- return image
58
-
59
- img_with_boxes = image.copy()
60
- draw = ImageDraw.Draw(img_with_boxes, "RGBA")
61
-
62
- half_box = box_size // 2
63
-
64
- for (x, y) in coordinates:
65
- # Define the bounding box corners
66
- x1 = x - half_box
67
- y1 = y - half_box
68
- x2 = x + half_box
69
- y2 = y + half_box
70
-
71
- if use_dotted_style:
72
- # "Dotted like seaborn" - a semi-transparent fill with a solid outline
73
- fill_color = (0, 100, 255, 60) # Light blue, semi-transparent
74
- outline_color = (0, 0, 255) # Solid blue
75
- draw.rectangle([x1, y1, x2, y2], fill=fill_color, outline=outline_color, width=2)
76
- else:
77
- # Default solid box
78
- outline_color = (255, 0, 0) # Red
79
- draw.rectangle([x1, y1, x2, y2], outline=outline_color, width=3)
80
-
81
- return img_with_boxes
82
-
83
- @spaces.GPU
84
- def generate_image(text: str, image: Image.Image,
85
- max_new_tokens: int,
86
- temperature: float,
87
- top_p: float,
88
- top_k: int,
89
- repetition_penalty: float,
90
- draw_boxes: bool,
91
- use_dotted_style: bool):
92
- """
93
- Generates responses and draws bounding boxes based on model output.
94
- Yields raw text, markdown-formatted text, and the processed image.
95
- """
96
- if image is None:
97
- yield "Please upload an image.", "Please upload an image.", None
98
- return
99
-
100
- # Yield the original image immediately for the output display
101
- yield "", "", image
102
-
103
- messages = [{
104
- "role": "user",
105
- "content": [
106
- {"type": "image", "image": image},
107
- {"type": "text", "text": text},
108
- ]
109
- }]
110
- prompt_full = processor.apply_chat_template(messages, tokenize=False, add_generation_prompt=True)
111
- inputs = processor(
112
- text=[prompt_full],
113
- images=[image],
114
- return_tensors="pt",
115
- padding=True,
116
- truncation=False,
117
- max_length=MAX_INPUT_TOKEN_LENGTH
118
- ).to(device)
119
- streamer = TextIteratorStreamer(processor, skip_prompt=True, skip_special_tokens=True)
120
- generation_kwargs = {
121
- **inputs,
122
- "streamer": streamer,
123
- "max_new_tokens": max_new_tokens,
124
- "temperature": temperature,
125
- "top_p": top_p,
126
- "top_k": top_k,
127
- "repetition_penalty": repetition_penalty,
128
- "do_sample": True
129
- }
130
- thread = Thread(target=model.generate, kwargs=generation_kwargs)
131
- thread.start()
132
-
133
- buffer = ""
134
- for new_text in streamer:
135
- buffer += new_text
136
- time.sleep(0.01)
137
- # During generation, yield text updates but keep the original image
138
- yield buffer, buffer, image
139
-
140
- # After generation is complete, parse the output and draw boxes
141
- final_answer, coordinates = parse_model_output(buffer)
142
-
143
- output_image = image
144
- if draw_boxes and coordinates:
145
- output_image = draw_bounding_boxes(image, coordinates, use_dotted_style=use_dotted_style)
146
-
147
- # Yield the final result with the processed image
148
- yield buffer, final_answer, output_image
149
-
150
- # Define examples for image inference
151
- image_examples = [
152
- ["Explain the content in detail.", "images/D.jpg"],
153
- ["Explain the content (ocr).", "images/O.jpg"],
154
- ["What is the core meaning of the poem?", "images/S.jpg"],
155
- ["Provide a detailed caption for the image.", "images/A.jpg"],
156
- ["Explain the pie-chart in detail.", "images/2.jpg"],
157
- ["Jsonify Data.", "images/1.jpg"],
158
- ]
159
-
160
- css = """
161
- .submit-btn {
162
- background-color: #2980b9 !important;
163
- color: white !important;
164
- }
165
- .submit-btn:hover {
166
- background-color: #3498db !important;
167
- }
168
- .canvas-output {
169
- border: 2px solid #4682B4;
170
- border-radius: 10px;
171
- padding: 20px;
172
- }
173
- """
174
-
175
- # Create the Gradio Interface
176
- with gr.Blocks(css=css, theme="bethecloud/storj_theme") as demo:
177
- gr.Markdown("# **Lumian2-VLR-7B-Thinking Image Inference**")
178
- with gr.Row():
179
- with gr.Column(scale=1):
180
- gr.Markdown("## Image Inference")
181
- image_query = gr.Textbox(label="Query Input", placeholder="Enter your query here...")
182
- image_upload = gr.Image(type="pil", label="Image")
183
- image_submit = gr.Button("Submit", elem_classes="submit-btn")
184
-
185
- with gr.Accordion("Advanced options", open=False):
186
- max_new_tokens = gr.Slider(label="Max new tokens", minimum=1, maximum=MAX_MAX_NEW_TOKENS, step=1, value=DEFAULT_MAX_NEW_TOKENS)
187
- temperature = gr.Slider(label="Temperature", minimum=0.1, maximum=4.0, step=0.1, value=0.6)
188
- top_p = gr.Slider(label="Top-p (nucleus sampling)", minimum=0.05, maximum=1.0, step=0.05, value=0.9)
189
- top_k = gr.Slider(label="Top-k", minimum=1, maximum=1000, step=1, value=50)
190
- repetition_penalty = gr.Slider(label="Repetition penalty", minimum=1.0, maximum=2.0, step=0.05, value=1.2)
191
-
192
- gr.Examples(
193
- examples=image_examples,
194
- inputs=[image_query, image_upload]
195
- )
196
-
197
- with gr.Column(scale=2):
198
- gr.Markdown("## Output")
199
- with gr.Tabs():
200
- with gr.TabItem("Image with Bounding Box"):
201
- image_output = gr.Image(label="Processed Image")
202
- with gr.TabItem("Raw Text"):
203
- output = gr.Textbox(label="Raw Model Output", interactive=False, lines=10)
204
- with gr.TabItem("Parsed Answer"):
205
- markdown_output = gr.Markdown(label="Parsed Answer")
206
-
207
- gr.Markdown("**Model Info 💻** | [Report Bug](https://huggingface.co/spaces/prithivMLmods/Qwen2.5-VL/discussions)")
208
-
209
- gr.Markdown(
210
- """> [Lumian2-VLR-7B-Thinking](https://huggingface.co/prithivMLmods/Lumian2-VLR-7B-Thinking): The Lumian2-VLR-7B-Thinking model is a high-fidelity vision-language reasoning (experimental model) system designed for fine-grained multimodal understanding. Built on Qwen2.5-VL-7B-Instruct, this model enhances image captioning, and document comprehension through explicit grounded reasoning. It produces structured reasoning traces aligned with visual coordinates, enabling explainable multimodal reasoning."""
211
- )
212
-
213
- with gr.Row():
214
- draw_boxes_checkbox = gr.Checkbox(label="Draw Bounding Boxes", value=True)
215
- dotted_style_checkbox = gr.Checkbox(label="Use Dotted Style for Boxes", value=False)
216
-
217
-
218
- image_submit.click(
219
- fn=generate_image,
220
- inputs=[image_query, image_upload, max_new_tokens, temperature, top_p, top_k, repetition_penalty, draw_boxes_checkbox, dotted_style_checkbox],
221
- outputs=[output, markdown_output, image_output]
222
- )
223
-
224
- if __name__ == "__main__":
225
- demo.queue(max_size=50).launch(share=True)