File size: 12,908 Bytes
41874b0
 
 
 
 
a6e0a2f
41874b0
 
 
 
 
 
 
 
a6e0a2f
 
41874b0
 
 
 
 
 
a6e0a2f
 
41874b0
be74ad9
41874b0
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
be74ad9
41874b0
 
 
 
 
 
be74ad9
41874b0
be74ad9
 
41874b0
 
 
 
 
be74ad9
41874b0
 
 
 
 
 
 
be74ad9
41874b0
 
be74ad9
 
41874b0
 
 
eb490cd
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
be74ad9
41874b0
 
 
 
 
 
 
 
be74ad9
41874b0
be74ad9
 
41874b0
 
 
 
 
be74ad9
 
41874b0
 
 
 
eb490cd
be74ad9
41874b0
 
be74ad9
41874b0
 
be74ad9
41874b0
 
be74ad9
41874b0
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
be74ad9
41874b0
 
 
 
 
 
 
be74ad9
41874b0
5d13714
 
41874b0
be74ad9
41874b0
 
 
 
 
be74ad9
41874b0
 
 
 
 
 
 
 
 
 
 
 
 
 
be74ad9
41874b0
 
 
 
be74ad9
41874b0
 
 
 
 
 
 
be74ad9
41874b0
 
 
 
 
 
 
 
 
 
 
 
 
be74ad9
41874b0
 
 
 
 
be74ad9
41874b0
 
 
 
 
 
 
 
 
 
 
 
 
 
be74ad9
41874b0
 
 
 
 
 
 
 
 
 
be74ad9
41874b0
 
 
 
 
 
 
be74ad9
41874b0
 
be74ad9
eb490cd
be74ad9
 
41874b0
 
 
 
be74ad9
41874b0
b251882
b71fb29
 
 
41874b0
 
be74ad9
41874b0
 
 
 
 
be74ad9
41874b0
5d13714
41874b0
 
 
 
 
be74ad9
 
41874b0
 
 
be74ad9
41874b0
 
 
 
 
 
 
 
 
 
be74ad9
41874b0
 
 
 
 
 
be74ad9
41874b0
 
 
 
 
 
 
 
 
 
 
 
be74ad9
41874b0
 
 
be74ad9
83ce815
 
 
 
 
 
 
 
 
 
 
 
 
41874b0
83ce815
 
 
41874b0
83ce815
 
 
 
 
 
 
 
41874b0
83ce815
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
be74ad9
41874b0
 
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
# Main One
import json
import os
import re
from datetime import datetime

import fitz  # PyMuPDF
import gradio as gr
import spaces
import torch
from gradio.themes.base import Base
from PIL import Image
from qwen_vl_utils import process_vision_info
from transformers import AutoProcessor, Qwen2VLForConditionalGeneration


# 1. Custom Theme Definition
class CustomTheme(Base):
    def __init__(self):
        super().__init__()
        self.primary_hue = "blue"
        self.secondary_hue = "sky"


custom_theme = CustomTheme()

DESCRIPTION = "A powerful vision-language model that can understand images and text to provide detailed analysis."


# 2. Safely Downscale & Save Image to prevent CUDA OOM
def prepare_and_save_image(image_filepath, max_width=1250, max_height=1750):
    if not image_filepath or not os.path.exists(image_filepath):
        raise ValueError("Image file not found.")

    img = Image.open(image_filepath).convert("RGB")
    width, height = img.size

    # Re-calculate dimensions while locking aspect ratio
    if width > max_width or height > max_height:
        aspect_ratio = width / height
        if width > max_width:
            width = max_width
            height = int(width / aspect_ratio)
        if height > max_height:
            height = max_height
            width = int(height * aspect_ratio)

        img = img.resize((width, height), Image.Resampling.LANCZOS)

    # We MUST save the resized image to a new path so the GPU actually reads the small version
    timestamp = datetime.now().strftime("%Y%m%d_%H%M%S_%f")
    temp_filename = os.path.abspath(f"temp_downscaled_{timestamp}.png")
    img.save(temp_filename, "PNG")

    return temp_filename, width, height


# 3. PDF Page Extractor
def convert_pdf_to_images(pdf_path):
    image_paths = []
    doc = fitz.open(pdf_path)
    base_name = os.path.splitext(os.path.basename(pdf_path))[0]

    for i, page in enumerate(doc):
        # dpi=150 is the sweet spot for 7B models to read fine text without blowing out VRAM
        pix = page.get_pixmap(dpi=150)
        timestamp = datetime.now().strftime("%Y%m%d_%H%M%S")
        image_path = os.path.abspath(f"{base_name}_page_{i + 1}_{timestamp}.png")
        pix.save(image_path)
        image_paths.append(image_path)

    doc.close()
    return image_paths


# 4. Bulletproof JSON Extractor
def extract_json_from_text(raw_text):
    # Target 1: Look inside markdown json fences
    if "```json" in raw_text:
        start = raw_text.find("```json") + 7
        end = raw_text.find("```", start)
        if end != -1:
            try:
                return json.loads(raw_text[start:end].strip())
            except json.JSONDecodeError:
                pass
    elif "```" in raw_text:
        start = raw_text.find("```") + 3
        end = raw_text.find("```", start)
        if end != -1:
            try:
                return json.loads(raw_text[start:end].strip())
            except json.JSONDecodeError:
                pass

    # Target 2: Fallback to raw bracket math
    try:
        start = raw_text.find("{")
        end = raw_text.rfind("}") + 1
        if start != -1 and end > start:
            return json.loads(raw_text[start:end])
    except json.JSONDecodeError:
        pass

    return None


# 5. Global Model Init (Optimized with SDPA & bfloat16)
model = Qwen2VLForConditionalGeneration.from_pretrained(
    "Qwen/Qwen2-VL-7B-Instruct", torch_dtype=torch.bfloat16, attn_implementation="sdpa"
)
processor = AutoProcessor.from_pretrained("Qwen/Qwen2-VL-7B-Instruct")


@spaces.GPU(duration=180)
def run_inference(uploaded_files, text_input):
    if not uploaded_files:
        err = json.dumps({"error": "No file uploaded."}, indent=4)
        return err, gr.update(interactive=False)

    results = []
    files_to_delete_from_disk = []

    # Standardize incoming Gradio file objects to raw string paths
    raw_paths = [getattr(f, "path", getattr(f, "name", str(f))) for f in uploaded_files]

    images_to_process = []
    unsupported = []

    # Sort files into PDFs vs standard images
    for f_path in raw_paths:
        ext = os.path.splitext(f_path)[1].lower()
        if ext == ".pdf":
            try:
                generated_pngs = convert_pdf_to_images(f_path)
                images_to_process.extend(generated_pngs)
                files_to_delete_from_disk.extend(generated_pngs)
            except Exception as e:
                results.append(
                    json.dumps(
                        {"error": f"Corrupt PDF: {os.path.basename(f_path)}"},
                        indent=4,
                    )
                )
        elif ext in [".png", ".jpg", ".jpeg", ".bmp", ".gif", ".webp"]:
            images_to_process.append(f_path)
        else:
            unsupported.append(os.path.basename(f_path))

    if unsupported:
        results.append(
            json.dumps(
                {"warning": f"Ignored unknown files: {', '.join(unsupported)}"},
                indent=4,
            )
        )

    system_json_injection = (
        f"{text_input}\n\nBased on the image and the query, respond ONLY with a single, valid JSON object. "
        "This object should be well-structured, using nested objects and arrays to logically represent the information."
    )

    for original_img in images_to_process:
        downscaled_img = None
        try:
            downscaled_img, w, h = prepare_and_save_image(original_img)
            files_to_delete_from_disk.append(downscaled_img)

            messages = [
                {
                    "role": "user",
                    "content": [
                        {
                            "type": "image",
                            "image": downscaled_img,
                            "resized_height": h,
                            "resized_width": w,
                        },
                        {"type": "text", "text": system_json_injection},
                    ],
                }
            ]

            text = processor.apply_chat_template(
                messages, tokenize=False, add_generation_prompt=True
            )
            image_inputs, video_inputs = process_vision_info(messages)

            inputs = processor(
                text=[text],
                images=image_inputs,
                videos=video_inputs,
                padding=True,
                return_tensors="pt",
            ).to("cuda")

            # Optimized generation parameters (Faster + Better JSON)
            generated_ids = model.generate(
                **inputs, max_new_tokens=2048, do_sample=False, use_cache=True
            )
            trimmed = [
                out[len(in_ids) :]
                for in_ids, out in zip(inputs.input_ids, generated_ids)
            ]
            raw_output = processor.batch_decode(
                trimmed,
                skip_special_tokens=True,
                clean_up_tokenization_spaces=True,
            )[0]

            # Format clean output
            parsed_json = extract_json_from_text(raw_output)
            clean_source_name = re.sub(
                r"_\d{8}_\d{6}\.png$", "", os.path.basename(original_img)
            )

            if parsed_json:
                parsed_json["_source_document"] = clean_source_name
                results.append(json.dumps(parsed_json, indent=4))
            else:
                results.append(
                    json.dumps(
                        {
                            "error": "Model failed to format valid JSON",
                            "source": clean_source_name,
                            "raw_text": raw_output[:250] + "...",
                        },
                        indent=4,
                    )
                )

        except Exception as e:
            results.append(
                json.dumps(
                    {
                        "error": f"Inference failed on {os.path.basename(original_img)}",
                        "trace": str(e),
                    },
                    indent=4,
                )
            )

    # Rigorous disk sweep: Delete all generated temp files
    for filepath in set(files_to_delete_from_disk):
        if filepath and os.path.exists(filepath):
            try:
                os.remove(filepath)
            except OSError:
                pass

    final_payload = "\n\n".join(results)
    is_failed = '"error":' in final_payload

    return final_payload, gr.update(interactive=not is_failed)


@spaces.GPU(duration=180)
def generate_explanation(json_text):
    if not json_text or '"error":' in json_text:
        return "Cannot generate an explanation from an errored JSON payload."

    prompt = (
        "You are an expert data analyst. Carefully review the following JSON data.\n"
        "First, provide a detailed, comprehensive textual explanation of the JSON data you understood. Explain what this document represents and its key takeaways.\n"
        "Then, you MUST extract the actual data points from the JSON and format them into a CLEAN MARKDOWN TABLE or MARKDOWN LIST as appropriate for clarity.\n"
        "CRITICAL INSTRUCTION: Do NOT number your conversational paragraphs (e.g. do not start paragraphs with '1.' or '2.'). Write your textual explanation as normal unnumbered paragraphs. You may use bullet points or numbered lists ONLY when explicitly listing data items.\n\n"
        f"JSON Data:\n```json\n{json_text}\n```"
    )

    messages = [{"role": "user", "content": prompt}]
    text = processor.apply_chat_template(
        messages, tokenize=False, add_generation_prompt=True
    )
    inputs = processor(text=[text], return_tensors="pt").to("cuda")

    generated_ids = model.generate(
        **inputs, max_new_tokens=2048, do_sample=False, use_cache=True
    )
    trimmed = [
        out[len(in_ids) :] for in_ids, out in zip(inputs.input_ids, generated_ids)
    ]
    return processor.batch_decode(trimmed, skip_special_tokens=True)[0]


# 6. Gradio UI Assembly
css = """
  .gradio-container { font-family: 'IBM Plex Sans', sans-serif; }

  #output-code, #output-code pre, #output-code code {
    background-color: #f0f0f0;
    border: 1px solid #e0e0e0;
    border-radius: 7px;
    color: #333;
  }
  #output-code .token.punctuation { color: #393a34; }
  #output-code .token.property, #output-code .token.string { color: #0b7500; }
  #output-code .token.number { color: #2973b7; }
  #output-code .token.boolean { color: #9a050f; }

  #explanation-box {
    min-height: 200px;
    border: 1px solid #e0e0e0;
    padding: 15px;
    border-radius: 7px;
  }

  .dark #output-code, .dark #output-code pre, .dark #output-code code {
    background-color: #2b2b2b !important;
    border: 1px solid #444 !important;
    color: #f0f0f0 !important;
  }
  .dark #explanation-box { border: 1px solid #444 !important; }
  .dark #output-code code span { color: #f0f0f0 !important; }
  .dark #output-code .token.punctuation { color: #ccc !important; }
  .dark #output-code .token.property, .dark #output-code .token.string { color: #90ee90 !important; }
  .dark #output-code .token.number { color: #add8e6 !important; }
  .dark #output-code .token.boolean { color: #f08080 !important; }
"""

with gr.Blocks(theme=custom_theme, css=css) as demo:
    gr.Markdown("# Sparrow Qwen2-VL-7B Vision AI ๐Ÿ‘๏ธ")
    gr.Markdown(DESCRIPTION)

    with gr.Row():
        with gr.Column(scale=1):
            input_files = gr.Files(
                label="Upload Images or PDFs",
                file_types=[
                    ".pdf",
                    ".png",
                    ".jpg",
                    ".jpeg",
                    ".bmp",
                    ".gif",
                    ".webp",
                ],
            )
            text_input = gr.Textbox(
                label="Your Query",
                placeholder="e.g., Extract all line items into JSON.",
            )
            submit_btn = gr.Button("Analyze File(s)", variant="primary")

        with gr.Column(scale=2):
            output_text = gr.Code(
                label="Full JSON Response",
                language="json",
                elem_id="output-code",
                interactive=False,
            )
            explanation_btn = gr.Button(
                "๐Ÿ“„ Generate Detailed Explanation", interactive=False
            )
            explanation_output = gr.Markdown(
                label="Detailed Explanation", elem_id="explanation-box"
            )

    submit_btn.click(
        fn=run_inference,
        inputs=[input_files, text_input],
        outputs=[output_text, explanation_btn],
        api_name="analyze_document",
    )

    explanation_btn.click(
        fn=generate_explanation,
        inputs=[output_text],
        outputs=[explanation_output],
        api_name="generate_explanation",
    )

if __name__ == "__main__":
    demo.queue(api_open=True).launch(debug=True)