prithivMLmods commited on
Commit
f11a1ed
·
verified ·
1 Parent(s): 972e85d

Upload TokenizerOCR.ipynb

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