Spaces:
Sleeping
Sleeping
Download models/ocr_model.py from seed-image-ai/image_ai: direct link, hf CLI and curl.
- Browser
- Download file 4.08 kB
-
https://huggingface.co/spaces/seed-image-ai/image_ai/resolve/main/models/ocr_model.py
- Command line
-
hf download hf://spaces/seed-image-ai/image_ai/models/ocr_model.py
-
curl -L -o ocr_model.py https://huggingface.co/spaces/seed-image-ai/image_ai/resolve/main/models/ocr_model.py
4.08 kB
| import gc | |
| import re | |
| import torch | |
| from PIL import Image | |
| class OCRModel: | |
| def __init__( | |
| self, | |
| processor, | |
| model, | |
| device=None | |
| ): | |
| self.processor = processor | |
| self.model = model | |
| self.device = device or ( | |
| "cuda" | |
| if torch.cuda.is_available() | |
| else "cpu" | |
| ) | |
| self.model.to(self.device) | |
| self.model.eval() | |
| def extract_text( | |
| self, | |
| image, | |
| max_pixels=2048 * 28 * 28, | |
| max_new_tokens=512 | |
| ): | |
| """ | |
| Extract visible text from a PIL image | |
| using PaddleOCR-VL-1.5. | |
| """ | |
| image = image.convert("RGB") | |
| original_width, original_height = image.size | |
| # Upscale relatively small images | |
| if ( | |
| original_width < 1500 | |
| and original_height < 1500 | |
| ): | |
| image = image.resize( | |
| ( | |
| original_width * 2, | |
| original_height * 2 | |
| ), | |
| Image.Resampling.LANCZOS | |
| ) | |
| # Get processor image settings | |
| image_processor = ( | |
| self.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 | |
| # PaddleOCR-VL spotting prompt | |
| messages = [ | |
| { | |
| "role": "user", | |
| "content": [ | |
| { | |
| "type": "image", | |
| "image": image | |
| }, | |
| { | |
| "type": "text", | |
| "text": "Spotting:" | |
| } | |
| ] | |
| } | |
| ] | |
| # Prepare model inputs | |
| inputs = self.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 | |
| } | |
| } | |
| ) | |
| # Move tensors to device | |
| inputs = { | |
| key: value.to(self.device) | |
| if hasattr(value, "to") | |
| else value | |
| for key, value in inputs.items() | |
| } | |
| # Generate OCR result | |
| with torch.inference_mode(): | |
| outputs = self.model.generate( | |
| **inputs, | |
| max_new_tokens=max_new_tokens, | |
| do_sample=False | |
| ) | |
| # Remove prompt tokens | |
| input_length = ( | |
| inputs["input_ids"].shape[-1] | |
| ) | |
| generated_tokens = outputs[ | |
| 0, | |
| input_length: | |
| ] | |
| # Decode | |
| raw_result = self.processor.decode( | |
| generated_tokens, | |
| skip_special_tokens=True | |
| ).strip() | |
| # Remove location tokens | |
| 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) | |
| # Remove consecutive duplicates | |
| cleaned_lines = [] | |
| for line in lines: | |
| if ( | |
| not cleaned_lines | |
| or line != cleaned_lines[-1] | |
| ): | |
| cleaned_lines.append(line) | |
| # Free temporary memory | |
| del inputs | |
| del outputs | |
| gc.collect() | |
| if torch.cuda.is_available(): | |
| torch.cuda.empty_cache() | |
| return cleaned_lines |