File size: 14,808 Bytes
d7da47f
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
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
{
  "cells": [
    {
      "cell_type": "markdown",
      "metadata": {
        "id": "-b4-SW1aGOcF"
      },
      "source": [
        "# **Open R1 Reasoning Exp**\n",
        "\n",
        "Qwen2VLForConditionalGeneration"
      ]
    },
    {
      "cell_type": "code",
      "execution_count": null,
      "metadata": {
        "id": "oDmd1ZObGSel"
      },
      "outputs": [],
      "source": [
        "!pip install gradio spaces transformers accelerate numpy requests torch torchvision qwen-vl-utils av ipython reportlab fpdf python-docx pillow huggingface_hub"
      ]
    },
    {
      "cell_type": "code",
      "execution_count": null,
      "metadata": {
        "id": "ovBSsRFhGbs2"
      },
      "outputs": [],
      "source": [
        "# Authenticate with Hugging Face\n",
        "from huggingface_hub import login\n",
        "\n",
        "# Log in to Hugging Face using the provided token\n",
        "hf_token = '---xxxxx---'\n",
        "login(hf_token)\n",
        "\n",
        "#Demo\n",
        "import gradio as gr\n",
        "import spaces\n",
        "from transformers import Qwen2VLForConditionalGeneration, AutoProcessor, TextIteratorStreamer\n",
        "from qwen_vl_utils import process_vision_info\n",
        "import torch\n",
        "from PIL import Image\n",
        "import os\n",
        "import uuid\n",
        "import io\n",
        "from threading import Thread\n",
        "from reportlab.lib.pagesizes import A4\n",
        "from reportlab.lib.styles import getSampleStyleSheet\n",
        "from reportlab.lib import colors\n",
        "from reportlab.platypus import SimpleDocTemplate, Image as RLImage, Paragraph, Spacer\n",
        "from reportlab.lib.units import inch\n",
        "from reportlab.pdfbase import pdfmetrics\n",
        "from reportlab.pdfbase.ttfonts import TTFont\n",
        "import docx\n",
        "from docx.enum.text import WD_ALIGN_PARAGRAPH\n",
        "\n",
        "# Define model options\n",
        "MODEL_OPTIONS = {\n",
        "    \"OpenR1\": \"prithivMLmods/Open-R1-Mini-Experimental\",\n",
        "}\n",
        "\n",
        "# Preload models and processors into CUDA\n",
        "models = {}\n",
        "processors = {}\n",
        "for name, model_id in MODEL_OPTIONS.items():\n",
        "    print(f\"Loading {name}...\")\n",
        "    models[name] = Qwen2VLForConditionalGeneration.from_pretrained(\n",
        "        model_id,\n",
        "        trust_remote_code=True,\n",
        "        torch_dtype=torch.float16\n",
        "    ).to(\"cuda\").eval()\n",
        "    processors[name] = AutoProcessor.from_pretrained(model_id, trust_remote_code=True)\n",
        "\n",
        "image_extensions = Image.registered_extensions()\n",
        "\n",
        "def identify_and_save_blob(blob_path):\n",
        "    \"\"\"Identifies if the blob is an image and saves it.\"\"\"\n",
        "    try:\n",
        "        with open(blob_path, 'rb') as file:\n",
        "            blob_content = file.read()\n",
        "            try:\n",
        "                Image.open(io.BytesIO(blob_content)).verify()  # Check if it's a valid image\n",
        "                extension = \".png\"  # Default to PNG for saving\n",
        "                media_type = \"image\"\n",
        "            except (IOError, SyntaxError):\n",
        "                raise ValueError(\"Unsupported media type. Please upload a valid image.\")\n",
        "\n",
        "            filename = f\"temp_{uuid.uuid4()}_media{extension}\"\n",
        "            with open(filename, \"wb\") as f:\n",
        "                f.write(blob_content)\n",
        "\n",
        "            return filename, media_type\n",
        "\n",
        "    except FileNotFoundError:\n",
        "        raise ValueError(f\"The file {blob_path} was not found.\")\n",
        "    except Exception as e:\n",
        "        raise ValueError(f\"An error occurred while processing the file: {e}\")\n",
        "\n",
        "@spaces.GPU\n",
        "def qwen_inference(model_name, media_input, text_input=None):\n",
        "    \"\"\"Handles inference for the selected model.\"\"\"\n",
        "    model = models[model_name]\n",
        "    processor = processors[model_name]\n",
        "\n",
        "    if isinstance(media_input, str):\n",
        "        media_path = media_input\n",
        "        if media_path.endswith(tuple([i for i in image_extensions.keys()])):\n",
        "            media_type = \"image\"\n",
        "        else:\n",
        "            try:\n",
        "                media_path, media_type = identify_and_save_blob(media_input)\n",
        "            except Exception as e:\n",
        "                raise ValueError(\"Unsupported media type. Please upload a valid image.\")\n",
        "\n",
        "    messages = [\n",
        "        {\n",
        "            \"role\": \"user\",\n",
        "            \"content\": [\n",
        "                {\n",
        "                    \"type\": media_type,\n",
        "                    media_type: media_path\n",
        "                },\n",
        "                {\"type\": \"text\", \"text\": text_input},\n",
        "            ],\n",
        "        }\n",
        "    ]\n",
        "\n",
        "    text = processor.apply_chat_template(\n",
        "        messages, tokenize=False, add_generation_prompt=True\n",
        "    )\n",
        "    image_inputs, _ = process_vision_info(messages)\n",
        "    inputs = processor(\n",
        "        text=[text],\n",
        "        images=image_inputs,\n",
        "        padding=True,\n",
        "        return_tensors=\"pt\",\n",
        "    ).to(\"cuda\")\n",
        "\n",
        "    streamer = TextIteratorStreamer(\n",
        "        processor.tokenizer, skip_prompt=True, skip_special_tokens=True\n",
        "    )\n",
        "    generation_kwargs = dict(inputs, streamer=streamer, max_new_tokens=1024)\n",
        "\n",
        "    thread = Thread(target=model.generate, kwargs=generation_kwargs)\n",
        "    thread.start()\n",
        "\n",
        "    buffer = \"\"\n",
        "    for new_text in streamer:\n",
        "        buffer += new_text\n",
        "        # Remove <|im_end|> or similar tokens from the output\n",
        "        buffer = buffer.replace(\"<|im_end|>\", \"\")\n",
        "        yield buffer\n",
        "\n",
        "def format_plain_text(output_text):\n",
        "    \"\"\"Formats the output text as plain text without LaTeX delimiters.\"\"\"\n",
        "    # Remove LaTeX delimiters and convert to plain text\n",
        "    plain_text = output_text.replace(\"\\\\(\", \"\").replace(\"\\\\)\", \"\").replace(\"\\\\[\", \"\").replace(\"\\\\]\", \"\")\n",
        "    return plain_text\n",
        "\n",
        "def generate_document(media_path, output_text, file_format, font_size, line_spacing, alignment, image_size):\n",
        "    \"\"\"Generates a document with the input image and plain text output.\"\"\"\n",
        "    plain_text = format_plain_text(output_text)\n",
        "    if file_format == \"pdf\":\n",
        "        return generate_pdf(media_path, plain_text, font_size, line_spacing, alignment, image_size)\n",
        "    elif file_format == \"docx\":\n",
        "        return generate_docx(media_path, plain_text, font_size, line_spacing, alignment, image_size)\n",
        "\n",
        "def generate_pdf(media_path, plain_text, font_size, line_spacing, alignment, image_size):\n",
        "    \"\"\"Generates a PDF document.\"\"\"\n",
        "    filename = f\"output_{uuid.uuid4()}.pdf\"\n",
        "    doc = SimpleDocTemplate(\n",
        "        filename,\n",
        "        pagesize=A4,\n",
        "        rightMargin=inch,\n",
        "        leftMargin=inch,\n",
        "        topMargin=inch,\n",
        "        bottomMargin=inch\n",
        "    )\n",
        "    styles = getSampleStyleSheet()\n",
        "    styles[\"Normal\"].fontSize = int(font_size)\n",
        "    styles[\"Normal\"].leading = int(font_size) * line_spacing\n",
        "    styles[\"Normal\"].alignment = {\n",
        "        \"Left\": 0,\n",
        "        \"Center\": 1,\n",
        "        \"Right\": 2,\n",
        "        \"Justified\": 4\n",
        "    }[alignment]\n",
        "\n",
        "    story = []\n",
        "\n",
        "    # Add image with size adjustment\n",
        "    image_sizes = {\n",
        "        \"Small\": (200, 200),\n",
        "        \"Medium\": (400, 400),\n",
        "        \"Large\": (600, 600)\n",
        "    }\n",
        "    img = RLImage(media_path, width=image_sizes[image_size][0], height=image_sizes[image_size][1])\n",
        "    story.append(img)\n",
        "    story.append(Spacer(1, 12))\n",
        "\n",
        "    # Add plain text output\n",
        "    text = Paragraph(plain_text, styles[\"Normal\"])\n",
        "    story.append(text)\n",
        "\n",
        "    doc.build(story)\n",
        "    return filename\n",
        "\n",
        "def generate_docx(media_path, plain_text, font_size, line_spacing, alignment, image_size):\n",
        "    \"\"\"Generates a DOCX document.\"\"\"\n",
        "    filename = f\"output_{uuid.uuid4()}.docx\"\n",
        "    doc = docx.Document()\n",
        "\n",
        "    # Add image with size adjustment\n",
        "    image_sizes = {\n",
        "        \"Small\": docx.shared.Inches(2),\n",
        "        \"Medium\": docx.shared.Inches(4),\n",
        "        \"Large\": docx.shared.Inches(6)\n",
        "    }\n",
        "    doc.add_picture(media_path, width=image_sizes[image_size])\n",
        "    doc.add_paragraph()\n",
        "\n",
        "    # Add plain text output\n",
        "    paragraph = doc.add_paragraph()\n",
        "    paragraph.paragraph_format.line_spacing = line_spacing\n",
        "    paragraph.paragraph_format.alignment = {\n",
        "        \"Left\": WD_ALIGN_PARAGRAPH.LEFT,\n",
        "        \"Center\": WD_ALIGN_PARAGRAPH.CENTER,\n",
        "        \"Right\": WD_ALIGN_PARAGRAPH.RIGHT,\n",
        "        \"Justified\": WD_ALIGN_PARAGRAPH.JUSTIFY\n",
        "    }[alignment]\n",
        "    run = paragraph.add_run(plain_text)\n",
        "    run.font.size = docx.shared.Pt(int(font_size))\n",
        "\n",
        "    doc.save(filename)\n",
        "    return filename\n",
        "\n",
        "# CSS for output styling\n",
        "css = \"\"\"\n",
        "  #output {\n",
        "    height: 500px;\n",
        "    overflow: auto;\n",
        "    border: 1px solid #ccc;\n",
        "  }\n",
        ".submit-btn {\n",
        "    background-color: #cf3434  !important;\n",
        "    color: white !important;\n",
        "}\n",
        ".submit-btn:hover {\n",
        "    background-color: #ff2323 !important;\n",
        "}\n",
        ".download-btn {\n",
        "    background-color: #35a6d6 !important;\n",
        "    color: white !important;\n",
        "}\n",
        ".download-btn:hover {\n",
        "    background-color: #22bcff !important;\n",
        "}\n",
        "\"\"\"\n",
        "\n",
        "# Gradio app setup\n",
        "with gr.Blocks(css=css) as demo:\n",
        "    gr.Markdown(\"# Open R1 Reasoning Exp\")\n",
        "\n",
        "    with gr.Tab(label=\"Image Input\"):\n",
        "\n",
        "        with gr.Row():\n",
        "            with gr.Column():\n",
        "                model_choice = gr.Dropdown(\n",
        "                    label=\"Model Selection\",\n",
        "                    choices=list(MODEL_OPTIONS.keys()),\n",
        "                    value=\"OpenR1\"\n",
        "                )\n",
        "                input_media = gr.File(\n",
        "                    label=\"Upload Image\", type=\"filepath\"\n",
        "                )\n",
        "                text_input = gr.Textbox(label=\"Question\", placeholder=\"Ask a question about the image...\")\n",
        "                submit_btn = gr.Button(value=\"Submit\", elem_classes=\"submit-btn\")\n",
        "\n",
        "            with gr.Column():\n",
        "                output_text = gr.Textbox(label=\"Output Text\", lines=10)\n",
        "                plain_text_output = gr.Textbox(label=\"Standardized Plain Text\", lines=10)\n",
        "\n",
        "        submit_btn.click(\n",
        "            qwen_inference, [model_choice, input_media, text_input], [output_text]\n",
        "        ).then(\n",
        "            lambda output_text: format_plain_text(output_text), [output_text], [plain_text_output]\n",
        "        )\n",
        "\n",
        "        # Add examples directly usable by clicking\n",
        "        with gr.Row():\n",
        "            with gr.Column():\n",
        "                line_spacing = gr.Dropdown(\n",
        "                    choices=[0.5, 1.0, 1.15, 1.5, 2.0, 2.5, 3.0],\n",
        "                    value=1.5,\n",
        "                    label=\"Line Spacing\"\n",
        "                )\n",
        "                font_size = gr.Dropdown(\n",
        "                    choices=[\"8\", \"10\", \"12\", \"14\", \"16\", \"18\", \"20\", \"22\", \"24\"],\n",
        "                    value=\"18\",\n",
        "                    label=\"Font Size\"\n",
        "                )\n",
        "                alignment = gr.Dropdown(\n",
        "                    choices=[\"Left\", \"Center\", \"Right\", \"Justified\"],\n",
        "                    value=\"Justified\",\n",
        "                    label=\"Text Alignment\"\n",
        "                )\n",
        "                image_size = gr.Dropdown(\n",
        "                    choices=[\"Small\", \"Medium\", \"Large\"],\n",
        "                    value=\"Small\",\n",
        "                    label=\"Image Size\"\n",
        "                )\n",
        "                file_format = gr.Radio([\"pdf\", \"docx\"], label=\"File Format\", value=\"pdf\")\n",
        "                get_document_btn = gr.Button(value=\"Get Document\", elem_classes=\"download-btn\")\n",
        "\n",
        "        get_document_btn.click(\n",
        "            generate_document, [input_media, output_text, file_format, font_size, line_spacing, alignment, image_size], gr.File(label=\"Download Document\")\n",
        "        )\n",
        "\n",
        "demo.launch(debug=True)"
      ]
    }
  ],
  "metadata": {
    "accelerator": "GPU",
    "colab": {
      "gpuType": "T4",
      "provenance": []
    },
    "kernelspec": {
      "display_name": "Python 3",
      "name": "python3"
    },
    "language_info": {
      "name": "python"
    }
  },
  "nbformat": 4,
  "nbformat_minor": 0
}