Spaces:
Running
Running
File size: 3,534 Bytes
cc8e96c | 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 | import re
import gc
import torch
from PIL import Image
from transformers import (
AutoProcessor,
AutoModelForImageTextToText
)
MODEL_ID = "PaddlePaddle/PaddleOCR-VL-1.5"
DEVICE = (
"cuda"
if torch.cuda.is_available()
else "cpu"
)
ocr_processor = AutoProcessor.from_pretrained(
MODEL_ID
)
ocr_model = AutoModelForImageTextToText.from_pretrained(
MODEL_ID,
torch_dtype=(
torch.bfloat16
if torch.cuda.is_available()
else torch.float32
)
).to(DEVICE).eval()
def extract_text_with_paddleocr_vl_spotting(image):
image = image.convert("RGB")
original_width, original_height = image.size
if (
original_width < 1500
and original_height < 1500
):
image = image.resize(
(
original_width * 2,
original_height * 2
),
Image.Resampling.LANCZOS
)
max_pixels = 2048 * 28 * 28
image_processor = (
ocr_processor.image_processor
)
if hasattr(
image_processor,
"size"
):
size_config = image_processor.size
if isinstance(
size_config,
dict
):
min_pixels = size_config.get(
"shortest_edge",
28 * 28 * 130
)
else:
min_pixels = 28 * 28 * 130
else:
min_pixels = 28 * 28 * 130
messages = [
{
"role": "user",
"content": [
{
"type": "image",
"image": image
},
{
"type": "text",
"text": "Spotting:"
}
]
}
]
inputs = ocr_processor.apply_chat_template(
messages,
add_generation_prompt=True,
tokenize=True,
return_dict=True,
return_tensors="pt",
images_kwargs={
"size": {
"shortest_edge": min_pixels,
"longest_edge": max_pixels
}
}
)
inputs = {
key: value.to(ocr_model.device)
if hasattr(value, "to")
else value
for key, value in inputs.items()
}
with torch.inference_mode():
outputs = ocr_model.generate(
**inputs,
max_new_tokens=512,
do_sample=False
)
input_length = inputs[
"input_ids"
].shape[-1]
generated_tokens = outputs[
0,
input_length:
]
raw_result = ocr_processor.decode(
generated_tokens,
skip_special_tokens=True
).strip()
lines = []
for line in raw_result.splitlines():
line = line.strip()
if not line:
continue
line = re.sub(
r"<\|LOC_\d+\|>",
"",
line
)
line = line.strip()
if line:
lines.append(line)
cleaned_lines = []
for line in lines:
if (
not cleaned_lines
or line != cleaned_lines[-1]
):
cleaned_lines.append(line)
del inputs
del outputs
gc.collect()
if torch.cuda.is_available():
torch.cuda.empty_cache()
return cleaned_lines |