prithivMLmods commited on
Commit
c9d4765
·
verified ·
1 Parent(s): 2362df8

Upload the demo notebook [supports T4 GPUs with load_in_4bit=True]. (#1)

Browse files

- Upload the demo notebook [supports T4 GPUs with load_in_4bit=True]. (f96ed8dcc709661fa10c4467627f0fe96161798e)

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