lycaoduong commited on
Commit
3eecb30
Β·
1 Parent(s): c4d4142

added application

Browse files
Files changed (13) hide show
  1. app.py +213 -0
  2. demo/P0.jpg +0 -0
  3. demo/P1.jpg +0 -0
  4. demo/P10.jpg +0 -0
  5. demo/P2.jpg +0 -0
  6. demo/P3.jpg +0 -0
  7. demo/P4.jpg +0 -0
  8. demo/P5.jpg +0 -0
  9. demo/P6.jpg +0 -0
  10. demo/P7.jpg +0 -0
  11. demo/P8.jpg +0 -0
  12. demo/P9.jpg +0 -0
  13. requirements.txt +13 -0
app.py ADDED
@@ -0,0 +1,213 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ import gradio as gr
2
+ import torch
3
+ from transformers import AutoModelForCausalLM, AutoTokenizer, TextIteratorStreamer, StoppingCriteria
4
+ import gradio as gr
5
+ import torch
6
+ import numpy as np
7
+ import torch
8
+ import torchvision.transforms as T
9
+ from PIL import Image
10
+ from torchvision.transforms.functional import InterpolationMode
11
+ from transformers import AutoModel, AutoTokenizer
12
+ import os
13
+ from threading import Thread
14
+ import re
15
+ import time
16
+ from PIL import Image
17
+ import torch
18
+ import spaces
19
+ import subprocess
20
+ from time import sleep
21
+ import base64
22
+ from io import BytesIO
23
+
24
+ subprocess.run('pip install flash-attn --no-build-isolation', env={'FLASH_ATTENTION_SKIP_CUDA_BUILD': "TRUE"}, shell=True)
25
+
26
+ # torch.set_default_device('cuda')
27
+
28
+ IMAGENET_MEAN = (0.485, 0.456, 0.406)
29
+ IMAGENET_STD = (0.229, 0.224, 0.225)
30
+
31
+ def build_transform(input_size):
32
+ MEAN, STD = IMAGENET_MEAN, IMAGENET_STD
33
+ transform = T.Compose([
34
+ T.Lambda(lambda img: img.convert('RGB') if img.mode != 'RGB' else img),
35
+ T.Resize((input_size, input_size), interpolation=InterpolationMode.BICUBIC),
36
+ T.ToTensor(),
37
+ T.Normalize(mean=MEAN, std=STD)
38
+ ])
39
+ return transform
40
+
41
+ def find_closest_aspect_ratio(aspect_ratio, target_ratios, width, height, image_size):
42
+ best_ratio_diff = float('inf')
43
+ best_ratio = (1, 1)
44
+ area = width * height
45
+ for ratio in target_ratios:
46
+ target_aspect_ratio = ratio[0] / ratio[1]
47
+ ratio_diff = abs(aspect_ratio - target_aspect_ratio)
48
+ if ratio_diff < best_ratio_diff:
49
+ best_ratio_diff = ratio_diff
50
+ best_ratio = ratio
51
+ elif ratio_diff == best_ratio_diff:
52
+ if area > 0.5 * image_size * image_size * ratio[0] * ratio[1]:
53
+ best_ratio = ratio
54
+ return best_ratio
55
+
56
+ def dynamic_preprocess(image, min_num=1, max_num=12, image_size=448, use_thumbnail=False):
57
+ orig_width, orig_height = image.size
58
+ aspect_ratio = orig_width / orig_height
59
+
60
+ # calculate the existing image aspect ratio
61
+ target_ratios = set(
62
+ (i, j) for n in range(min_num, max_num + 1) for i in range(1, n + 1) for j in range(1, n + 1) if
63
+ i * j <= max_num and i * j >= min_num)
64
+ target_ratios = sorted(target_ratios, key=lambda x: x[0] * x[1])
65
+
66
+ # find the closest aspect ratio to the target
67
+ target_aspect_ratio = find_closest_aspect_ratio(
68
+ aspect_ratio, target_ratios, orig_width, orig_height, image_size)
69
+
70
+ # calculate the target width and height
71
+ target_width = image_size * target_aspect_ratio[0]
72
+ target_height = image_size * target_aspect_ratio[1]
73
+ blocks = target_aspect_ratio[0] * target_aspect_ratio[1]
74
+
75
+ # resize the image
76
+ resized_img = image.resize((target_width, target_height))
77
+ processed_images = []
78
+ for i in range(blocks):
79
+ box = (
80
+ (i % (target_width // image_size)) * image_size,
81
+ (i // (target_width // image_size)) * image_size,
82
+ ((i % (target_width // image_size)) + 1) * image_size,
83
+ ((i // (target_width // image_size)) + 1) * image_size
84
+ )
85
+ # split the image
86
+ split_img = resized_img.crop(box)
87
+ processed_images.append(split_img)
88
+ assert len(processed_images) == blocks
89
+ if use_thumbnail and len(processed_images) != 1:
90
+ thumbnail_img = image.resize((image_size, image_size))
91
+ processed_images.append(thumbnail_img)
92
+ return processed_images
93
+
94
+ def load_image(image_file, input_size=448, max_num=12):
95
+ if isinstance(image_file, str): # Check if it's a file path
96
+ image = Image.open(image_file).convert('RGB')
97
+ else: # Assume it's a base64 string
98
+ image_data = base64.b64decode(image_file)
99
+ image = Image.open(BytesIO(image_data)).convert('RGB')
100
+
101
+ transform = build_transform(input_size=input_size)
102
+ images = dynamic_preprocess(image, image_size=input_size, use_thumbnail=True, max_num=max_num)
103
+ pixel_values = [transform(image) for image in images]
104
+ pixel_values = torch.stack(pixel_values)
105
+ return pixel_values
106
+
107
+ model_name = "lycaoduong/KLPintern-v2-1B"
108
+
109
+ access_token = os.getenv("LPInternVL21B")
110
+
111
+ model = AutoModel.from_pretrained(
112
+ model_name,
113
+ torch_dtype=torch.bfloat16,
114
+ low_cpu_mem_usage=True,
115
+ trust_remote_code=True,
116
+ token=access_token
117
+ ).eval()
118
+
119
+ tokenizer = AutoTokenizer.from_pretrained(model_name, trust_remote_code=True, use_fast=False, token=access_token)
120
+
121
+
122
+ @spaces.GPU
123
+ def chat(message, history):
124
+ # print(history)
125
+ # print(message)
126
+ model.to('cuda')
127
+
128
+ test_image = message["files"][0]
129
+
130
+ pixel_values = load_image(test_image, max_num=12).to(torch.bfloat16).cuda()
131
+ generation_config = dict(max_new_tokens= 1024, do_sample=True, num_beams = 3, repetition_penalty=2.5)
132
+
133
+ question = '<image>\n'+message["text"]
134
+ response, conv_history = model.chat(tokenizer, pixel_values, question, generation_config, history=None, return_history=True)
135
+
136
+ # print(f'User: {question}\nAssistant: {response}')
137
+
138
+ txt_stream = ''
139
+ for c in response:
140
+ sleep(0.01)
141
+ txt_stream = txt_stream + c
142
+ yield txt_stream
143
+
144
+ # return response
145
+
146
+
147
+ CSS ="""
148
+ # @media only screen and (max-width: 600px){
149
+ # #component-3 {
150
+ # height: 90dvh !important;
151
+ # transform-origin: top; /* Ensure that the element expands from top to bottom. */
152
+ # border-style: solid;
153
+ # overflow: hidden;
154
+ # flex-grow: 1;
155
+ # min-width: min(160px, 100%);
156
+ # border-width: var(--block-border-width);
157
+ # }
158
+ # }
159
+ #component-3 {
160
+ height: 50dvh !important;
161
+ transform-origin: top; /* Ensure that the element expands from top to bottom. */
162
+ border-style: solid;
163
+ overflow: hidden;
164
+ flex-grow: 1;
165
+ min-width: min(160px, 100%);
166
+ border-width: var(--block-border-width);
167
+ }
168
+ /* Ensure that the image inside the button is displayed correctly for buttons with a specified aria-label. */
169
+ button.svelte-1lcyrx4[aria-label="user's message: a file of type image/jpeg, "] img.svelte-1pijsyv {
170
+ width: 100%;
171
+ object-fit: contain;
172
+ height: 100%;
173
+ border-radius: 13px; /* Add rounded corners to the image. */
174
+ max-width: 50vw; /* Limit the image width. */
175
+ }
176
+ /* Set the height for the button and allow text selection only for buttons with a specified aria-label. */
177
+ button.svelte-1lcyrx4[aria-label="user's message: a file of type image/jpeg, "] {
178
+ user-select: text;
179
+ text-align: left;
180
+ height: 300px;
181
+ }
182
+ /* Add border-radius and limit the width for images that do not belong to the avatar container. */
183
+ .message-wrap.svelte-1lcyrx4 > div.svelte-1lcyrx4 .svelte-1lcyrx4:not(.avatar-container) img {
184
+ border-radius: 13px;
185
+ max-width: 50vw;
186
+ }
187
+ .message-wrap.svelte-1lcyrx4 .message.svelte-1lcyrx4 img {
188
+ margin: var(--size-2);
189
+ max-height: 500px;
190
+ }
191
+ """
192
+
193
+
194
+ demo = gr.ChatInterface(
195
+ fn=chat,
196
+ description="Test Korean License Plate OCR VLMs in this demo.",
197
+ examples=[{"text": "Extract LPR information, return in JSON format.", "files":["./demo/P0.jpg"]},
198
+ {"text": "Extract LPR information.", "files":["./demo/P1.jpg"]},
199
+ {"text": "Extract LPR information.", "files":["./demo/P2.jpg"]},
200
+ {"text": "Extract LPR information.", "files":["./demo/P3.jpg"]},
201
+ {"text": "Extract LPR information.", "files":["./demo/P4.jpg"]},
202
+ {"text": "Extract LPR information.", "files":["./demo/P5.jpg"]},
203
+ {"text": "Extract LPR information.", "files":["./demo/P6.jpg"]},
204
+ {"text": "Extract LPR information.", "files":["./demo/P7.jpg"]},
205
+ {"text": "Extract LPR information.", "files":["./demo/P8.jpg"]},
206
+ {"text": "Extract LPR information.", "files":["./demo/P9.jpg"]},
207
+ {"text": "Extract LPR information.", "files":["./demo/P10.jpg"]},
208
+ ],
209
+ title="❄️ InternVL2-1B fine-tuned for Korean License Plate recognition.❄️",
210
+ multimodal=True,
211
+ css=CSS
212
+ )
213
+ demo.queue().launch()
demo/P0.jpg ADDED
demo/P1.jpg ADDED
demo/P10.jpg ADDED
demo/P2.jpg ADDED
demo/P3.jpg ADDED
demo/P4.jpg ADDED
demo/P5.jpg ADDED
demo/P6.jpg ADDED
demo/P7.jpg ADDED
demo/P8.jpg ADDED
demo/P9.jpg ADDED
requirements.txt ADDED
@@ -0,0 +1,13 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ torch
2
+ # git+https://github.com/huggingface/transformers.git
3
+ spaces
4
+ pillow
5
+ accelerate
6
+ pypandoc
7
+ fastapi
8
+ wheel
9
+ torchvision
10
+ imageio
11
+ timm
12
+ transformers==4.44.2
13
+ gradio==4.44.1