prithivMLmods commited on
Commit
bd5b8ca
·
verified ·
1 Parent(s): 2cd02e7

colab demo

Browse files
Lumian2-VLR-7B-Thinking-Demo-Notebook/Lumian2_VLR_7B_Thinking.ipynb ADDED
@@ -0,0 +1,378 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ {
2
+ "cells": [
3
+ {
4
+ "cell_type": "markdown",
5
+ "metadata": {
6
+ "id": "uFovmijgUV1Z"
7
+ },
8
+ "source": [
9
+ "***Multimodal Thinking ReportLab : Lumian2-VLR-7B-Thinking***\n",
10
+ "\n",
11
+ "\n",
12
+ "*explicit grounded reasoning* ~*notebook by : [prithivMLmods](https://huggingface.co/prithivMLmods)🤗 x ❤️*"
13
+ ]
14
+ },
15
+ {
16
+ "cell_type": "markdown",
17
+ "metadata": {
18
+ "id": "RugX4SGZV-8O"
19
+ },
20
+ "source": [
21
+ "***Installing all necessary packages***"
22
+ ]
23
+ },
24
+ {
25
+ "cell_type": "code",
26
+ "execution_count": null,
27
+ "metadata": {
28
+ "id": "l-NtFtjSpuJQ"
29
+ },
30
+ "outputs": [],
31
+ "source": [
32
+ "%%capture\n",
33
+ "!pip install gradio transformers transformers-stream-generator qwen-vl-utils\n",
34
+ "!pip install torchvision torch huggingface_hub spaces accelerate ipython\n",
35
+ "!pip install pillow av python-docx requests numpy reportlab fpdf hf_xet\n",
36
+ "#Hold tight, this will take around 3-5 minutes."
37
+ ]
38
+ },
39
+ {
40
+ "cell_type": "markdown",
41
+ "source": [
42
+ "\n",
43
+ "*Model Folder:* [Lumian2-VLR-7B-Thinking](https://huggingface.co/prithivMLmods/Lumian2-VLR-7B-Thinking/)\n"
44
+ ],
45
+ "metadata": {
46
+ "id": "g3TKo5gpEROZ"
47
+ }
48
+ },
49
+ {
50
+ "cell_type": "markdown",
51
+ "metadata": {
52
+ "id": "mvoSnRZcVBu4"
53
+ },
54
+ "source": [
55
+ "***Run app***"
56
+ ]
57
+ },
58
+ {
59
+ "cell_type": "code",
60
+ "execution_count": null,
61
+ "metadata": {
62
+ "id": "tElKr2Fkp1bO"
63
+ },
64
+ "outputs": [],
65
+ "source": [
66
+ "# ================================================\n",
67
+ "# Model Configuration\n",
68
+ "# ================================================\n",
69
+ "\n",
70
+ "# Model used in the app:\n",
71
+ "# https://huggingface.co/prithivMLmods/Lumian2-VLR-7B-Thinking\n",
72
+ "\n",
73
+ "import gradio as gr\n",
74
+ "import spaces\n",
75
+ "from transformers import Qwen2_5_VLForConditionalGeneration, AutoProcessor, TextIteratorStreamer\n",
76
+ "from qwen_vl_utils import process_vision_info\n",
77
+ "import torch\n",
78
+ "from PIL import Image\n",
79
+ "import os\n",
80
+ "import uuid\n",
81
+ "import io\n",
82
+ "from threading import Thread\n",
83
+ "from reportlab.lib.pagesizes import A4\n",
84
+ "from reportlab.lib.styles import getSampleStyleSheet\n",
85
+ "from reportlab.lib import colors\n",
86
+ "from reportlab.platypus import SimpleDocTemplate, Image as RLImage, Paragraph, Spacer\n",
87
+ "from reportlab.lib.units import inch\n",
88
+ "from reportlab.pdfbase import pdfmetrics\n",
89
+ "from reportlab.pdfbase.ttfonts import TTFont\n",
90
+ "import docx\n",
91
+ "from docx.enum.text import WD_ALIGN_PARAGRAPH\n",
92
+ "\n",
93
+ "# Define model options\n",
94
+ "MODEL_OPTIONS = {\n",
95
+ " \"Lumian2-VLR-7B-Thinking\": \"prithivMLmods/Lumian2-VLR-7B-Thinking\",\n",
96
+ "}\n",
97
+ "\n",
98
+ "# Preload models and processors into CUDA\n",
99
+ "models = {}\n",
100
+ "processors = {}\n",
101
+ "for name, model_id in MODEL_OPTIONS.items():\n",
102
+ " print(f\"Loading {name}🤗. Hold tight, this will take around 4-6 minutes..\")\n",
103
+ " models[name] = Qwen2_5_VLForConditionalGeneration.from_pretrained(\n",
104
+ " model_id,\n",
105
+ " trust_remote_code=True,\n",
106
+ " torch_dtype=torch.float16\n",
107
+ " ).to(\"cuda\").eval()\n",
108
+ " processors[name] = AutoProcessor.from_pretrained(model_id, trust_remote_code=True)\n",
109
+ "\n",
110
+ "image_extensions = Image.registered_extensions()\n",
111
+ "\n",
112
+ "def identify_and_save_blob(blob_path):\n",
113
+ " \"\"\"Identifies if the blob is an image and saves it.\"\"\"\n",
114
+ " try:\n",
115
+ " with open(blob_path, 'rb') as file:\n",
116
+ " blob_content = file.read()\n",
117
+ " try:\n",
118
+ " Image.open(io.BytesIO(blob_content)).verify() # Check if it's a valid image\n",
119
+ " extension = \".png\" # Default to PNG for saving\n",
120
+ " media_type = \"image\"\n",
121
+ " except (IOError, SyntaxError):\n",
122
+ " raise ValueError(\"Unsupported media type. Please upload a valid image.\")\n",
123
+ "\n",
124
+ " filename = f\"temp_{uuid.uuid4()}_media{extension}\"\n",
125
+ " with open(filename, \"wb\") as f:\n",
126
+ " f.write(blob_content)\n",
127
+ "\n",
128
+ " return filename, media_type\n",
129
+ "\n",
130
+ " except FileNotFoundError:\n",
131
+ " raise ValueError(f\"The file {blob_path} was not found.\")\n",
132
+ " except Exception as e:\n",
133
+ " raise ValueError(f\"An error occurred while processing the file: {e}\")\n",
134
+ "\n",
135
+ "@spaces.GPU\n",
136
+ "def qwen_inference(model_name, media_input, text_input=None):\n",
137
+ " \"\"\"Handles inference for the selected model.\"\"\"\n",
138
+ " model = models[model_name]\n",
139
+ " processor = processors[model_name]\n",
140
+ "\n",
141
+ " if isinstance(media_input, str):\n",
142
+ " media_path = media_input\n",
143
+ " if media_path.endswith(tuple([i for i in image_extensions.keys()])):\n",
144
+ " media_type = \"image\"\n",
145
+ " else:\n",
146
+ " try:\n",
147
+ " media_path, media_type = identify_and_save_blob(media_input)\n",
148
+ " except Exception as e:\n",
149
+ " raise ValueError(\"Unsupported media type. Please upload a valid image.\")\n",
150
+ "\n",
151
+ " messages = [\n",
152
+ " {\n",
153
+ " \"role\": \"user\",\n",
154
+ " \"content\": [\n",
155
+ " {\n",
156
+ " \"type\": media_type,\n",
157
+ " media_type: media_path\n",
158
+ " },\n",
159
+ " {\"type\": \"text\", \"text\": text_input},\n",
160
+ " ],\n",
161
+ " }\n",
162
+ " ]\n",
163
+ "\n",
164
+ " text = processor.apply_chat_template(\n",
165
+ " messages, tokenize=False, add_generation_prompt=True\n",
166
+ " )\n",
167
+ " image_inputs, _ = process_vision_info(messages)\n",
168
+ " inputs = processor(\n",
169
+ " text=[text],\n",
170
+ " images=image_inputs,\n",
171
+ " padding=True,\n",
172
+ " return_tensors=\"pt\",\n",
173
+ " ).to(\"cuda\")\n",
174
+ "\n",
175
+ " streamer = TextIteratorStreamer(\n",
176
+ " processor.tokenizer, skip_prompt=True, skip_special_tokens=True\n",
177
+ " )\n",
178
+ " generation_kwargs = dict(inputs, streamer=streamer, max_new_tokens=1024)\n",
179
+ "\n",
180
+ " thread = Thread(target=model.generate, kwargs=generation_kwargs)\n",
181
+ " thread.start()\n",
182
+ "\n",
183
+ " buffer = \"\"\n",
184
+ " for new_text in streamer:\n",
185
+ " buffer += new_text\n",
186
+ " # Remove <|im_end|> or similar tokens from the output\n",
187
+ " buffer = buffer.replace(\"<|im_end|>\", \"\")\n",
188
+ " yield buffer\n",
189
+ "\n",
190
+ "def format_plain_text(output_text):\n",
191
+ " \"\"\"Formats the output text as plain text without LaTeX delimiters.\"\"\"\n",
192
+ " # Remove LaTeX delimiters and convert to plain text\n",
193
+ " plain_text = output_text.replace(\"\\\\(\", \"\").replace(\"\\\\)\", \"\").replace(\"\\\\[\", \"\").replace(\"\\\\]\", \"\")\n",
194
+ " return plain_text\n",
195
+ "\n",
196
+ "def generate_document(media_path, output_text, file_format, font_size, line_spacing, alignment, image_size):\n",
197
+ " \"\"\"Generates a document with the input image and plain text output.\"\"\"\n",
198
+ " plain_text = format_plain_text(output_text)\n",
199
+ " if file_format == \"pdf\":\n",
200
+ " return generate_pdf(media_path, plain_text, font_size, line_spacing, alignment, image_size)\n",
201
+ " elif file_format == \"docx\":\n",
202
+ " return generate_docx(media_path, plain_text, font_size, line_spacing, alignment, image_size)\n",
203
+ "\n",
204
+ "def generate_pdf(media_path, plain_text, font_size, line_spacing, alignment, image_size):\n",
205
+ " \"\"\"Generates a PDF document.\"\"\"\n",
206
+ " filename = f\"output_{uuid.uuid4()}.pdf\"\n",
207
+ " doc = SimpleDocTemplate(\n",
208
+ " filename,\n",
209
+ " pagesize=A4,\n",
210
+ " rightMargin=inch,\n",
211
+ " leftMargin=inch,\n",
212
+ " topMargin=inch,\n",
213
+ " bottomMargin=inch\n",
214
+ " )\n",
215
+ " styles = getSampleStyleSheet()\n",
216
+ " styles[\"Normal\"].fontSize = int(font_size)\n",
217
+ " styles[\"Normal\"].leading = int(font_size) * line_spacing\n",
218
+ " styles[\"Normal\"].alignment = {\n",
219
+ " \"Left\": 0,\n",
220
+ " \"Center\": 1,\n",
221
+ " \"Right\": 2,\n",
222
+ " \"Justified\": 4\n",
223
+ " }[alignment]\n",
224
+ "\n",
225
+ " story = []\n",
226
+ "\n",
227
+ " # Add image with size adjustment\n",
228
+ " image_sizes = {\n",
229
+ " \"Small\": (200, 200),\n",
230
+ " \"Medium\": (400, 400),\n",
231
+ " \"Large\": (600, 600)\n",
232
+ " }\n",
233
+ " img = RLImage(media_path, width=image_sizes[image_size][0], height=image_sizes[image_size][1])\n",
234
+ " story.append(img)\n",
235
+ " story.append(Spacer(1, 12))\n",
236
+ "\n",
237
+ " # Add plain text output\n",
238
+ " text = Paragraph(plain_text, styles[\"Normal\"])\n",
239
+ " story.append(text)\n",
240
+ "\n",
241
+ " doc.build(story)\n",
242
+ " return filename\n",
243
+ "\n",
244
+ "def generate_docx(media_path, plain_text, font_size, line_spacing, alignment, image_size):\n",
245
+ " \"\"\"Generates a DOCX document.\"\"\"\n",
246
+ " filename = f\"output_{uuid.uuid4()}.docx\"\n",
247
+ " doc = docx.Document()\n",
248
+ "\n",
249
+ " # Add image with size adjustment\n",
250
+ " image_sizes = {\n",
251
+ " \"Small\": docx.shared.Inches(2),\n",
252
+ " \"Medium\": docx.shared.Inches(4),\n",
253
+ " \"Large\": docx.shared.Inches(6)\n",
254
+ " }\n",
255
+ " doc.add_picture(media_path, width=image_sizes[image_size])\n",
256
+ " doc.add_paragraph()\n",
257
+ "\n",
258
+ " # Add plain text output\n",
259
+ " paragraph = doc.add_paragraph()\n",
260
+ " paragraph.paragraph_format.line_spacing = line_spacing\n",
261
+ " paragraph.paragraph_format.alignment = {\n",
262
+ " \"Left\": WD_ALIGN_PARAGRAPH.LEFT,\n",
263
+ " \"Center\": WD_ALIGN_PARAGRAPH.CENTER,\n",
264
+ " \"Right\": WD_ALIGN_PARAGRAPH.RIGHT,\n",
265
+ " \"Justified\": WD_ALIGN_PARAGRAPH.JUSTIFY\n",
266
+ " }[alignment]\n",
267
+ " run = paragraph.add_run(plain_text)\n",
268
+ " run.font.size = docx.shared.Pt(int(font_size))\n",
269
+ "\n",
270
+ " doc.save(filename)\n",
271
+ " return filename\n",
272
+ "\n",
273
+ "# CSS for output styling\n",
274
+ "css = \"\"\"\n",
275
+ " #output {\n",
276
+ " height: 500px;\n",
277
+ " overflow: auto;\n",
278
+ " border: 1px solid #ccc;\n",
279
+ " }\n",
280
+ ".submit-btn {\n",
281
+ " background-color: #cf3434 !important;\n",
282
+ " color: white !important;\n",
283
+ "}\n",
284
+ ".submit-btn:hover {\n",
285
+ " background-color: #ff2323 !important;\n",
286
+ "}\n",
287
+ ".download-btn {\n",
288
+ " background-color: #35a6d6 !important;\n",
289
+ " color: white !important;\n",
290
+ "}\n",
291
+ ".download-btn:hover {\n",
292
+ " background-color: #22bcff !important;\n",
293
+ "}\n",
294
+ "\"\"\"\n",
295
+ "\n",
296
+ "# Gradio app setup\n",
297
+ "with gr.Blocks(css=css, theme=\"bethecloud/storj_theme\") as demo:\n",
298
+ " gr.Markdown(\"# **Multimodal-Thinking : Lumian2-VLR-7B-Thinking**\")\n",
299
+ "\n",
300
+ " with gr.Tab(label=\"Image Input\"):\n",
301
+ "\n",
302
+ " with gr.Row():\n",
303
+ " with gr.Column():\n",
304
+ " model_choice = gr.Dropdown(\n",
305
+ " label=\"Model Selection\",\n",
306
+ " choices=list(MODEL_OPTIONS.keys()),\n",
307
+ " value=\"Lumian2-VLR-7B-Thinking\"\n",
308
+ " )\n",
309
+ " input_media = gr.File(\n",
310
+ " label=\"Upload Image\", type=\"filepath\"\n",
311
+ " )\n",
312
+ " text_input = gr.Textbox(label=\"Question\", value=\"OCR the image precisely.\")\n",
313
+ " submit_btn = gr.Button(value=\"Submit\", elem_classes=\"submit-btn\")\n",
314
+ "\n",
315
+ " with gr.Column():\n",
316
+ " output_text = gr.Textbox(label=\"Output Text\", lines=7)\n",
317
+ "\n",
318
+ " with gr.Accordion(\"Plain Text\", open=False):\n",
319
+ " plain_text_output = gr.Textbox(label=\"Standardized Plain Text\", lines=10)\n",
320
+ "\n",
321
+ " submit_btn.click(\n",
322
+ " qwen_inference, [model_choice, input_media, text_input], [output_text]\n",
323
+ " ).then(\n",
324
+ " lambda output_text: format_plain_text(output_text), [output_text], [plain_text_output]\n",
325
+ " )\n",
326
+ "\n",
327
+ " with gr.Accordion(\"Docx/PDF Settings\", open=False):\n",
328
+ " with gr.Row():\n",
329
+ " with gr.Column():\n",
330
+ " line_spacing = gr.Dropdown(\n",
331
+ " choices=[0.5, 1.0, 1.15, 1.5, 2.0, 2.5, 3.0],\n",
332
+ " value=1.5,\n",
333
+ " label=\"Line Spacing\"\n",
334
+ " )\n",
335
+ " font_size = gr.Dropdown(\n",
336
+ " choices=[\"8\", \"10\", \"12\", \"14\", \"16\", \"18\", \"20\", \"22\", \"24\"],\n",
337
+ " value=\"16\",\n",
338
+ " label=\"Font Size\"\n",
339
+ " )\n",
340
+ " alignment = gr.Dropdown(\n",
341
+ " choices=[\"Left\", \"Center\", \"Right\", \"Justified\"],\n",
342
+ " value=\"Justified\",\n",
343
+ " label=\"Text Alignment\"\n",
344
+ " )\n",
345
+ " image_size = gr.Dropdown(\n",
346
+ " choices=[\"Small\", \"Medium\", \"Large\"],\n",
347
+ " value=\"Medium\",\n",
348
+ " label=\"Image Size\"\n",
349
+ " )\n",
350
+ " file_format = gr.Radio([\"pdf\", \"docx\"], label=\"File Format\", value=\"pdf\")\n",
351
+ "\n",
352
+ " get_document_btn = gr.Button(value=\"Get Document\", elem_classes=\"download-btn\")\n",
353
+ "\n",
354
+ " get_document_btn.click(\n",
355
+ " generate_document, [input_media, output_text, file_format, font_size, line_spacing, alignment, image_size], gr.File(label=\"Download Document\")\n",
356
+ " )\n",
357
+ "\n",
358
+ "demo.launch(debug=True)"
359
+ ]
360
+ }
361
+ ],
362
+ "metadata": {
363
+ "accelerator": "GPU",
364
+ "colab": {
365
+ "gpuType": "T4",
366
+ "provenance": []
367
+ },
368
+ "kernelspec": {
369
+ "display_name": "Python 3",
370
+ "name": "python3"
371
+ },
372
+ "language_info": {
373
+ "name": "python"
374
+ }
375
+ },
376
+ "nbformat": 4,
377
+ "nbformat_minor": 0
378
+ }