prithivMLmods commited on
Commit
f748f14
·
verified ·
1 Parent(s): 7a1eb34

Upload Callisto_OCR3_2B_Instruct.ipynb

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