Spaces:
Running
Running
File size: 9,423 Bytes
8959aae |
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 207 208 209 210 211 212 213 214 215 216 217 218 219 220 221 222 223 224 225 226 227 228 229 230 231 232 233 234 235 236 237 238 239 240 241 242 243 244 245 246 247 248 249 250 251 252 253 254 255 256 257 258 259 260 261 262 263 264 265 266 267 268 269 270 271 272 273 274 275 276 277 278 |
"""
DeepSeek OCR Service Module
Handles OCR text extraction using DeepSeek-OCR model
"""
import os
import torch
from PIL import Image
from transformers import AutoModelForCausalLM, AutoTokenizer
from typing import Optional, Dict, Any
import logging
from pathlib import Path
from dotenv import load_dotenv
# Load environment variables
load_dotenv()
# Configure logging
logging.basicConfig(level=logging.INFO)
logger = logging.getLogger(__name__)
class DeepSeekOCRService:
"""
Service class for DeepSeek OCR text extraction
"""
def __init__(self, model_name: str = None):
"""
Initialize the DeepSeek OCR service
Args:
model_name (str): Hugging Face model name for DeepSeek OCR
"""
self.model_name = model_name or os.getenv('DEEPSEEK_OCR_MODEL', 'deepseek-ai/DeepSeek-OCR')
self.model = None
self.tokenizer = None
# Device configuration - optimized for CPU
device_config = os.getenv('DEEPSEEK_OCR_DEVICE', 'cpu')
if device_config == 'auto':
self.device = "cuda" if torch.cuda.is_available() else "cpu"
else:
self.device = device_config
logger.info(f"Initializing DeepSeek OCR on device: {self.device}")
def load_model(self):
"""
Load the DeepSeek OCR model and tokenizer
"""
try:
logger.info(f"Loading DeepSeek OCR model: {self.model_name}")
self.tokenizer = AutoTokenizer.from_pretrained(
self.model_name,
trust_remote_code=True
)
# CPU-optimized model loading
if self.device == "cpu":
self.model = AutoModelForCausalLM.from_pretrained(
self.model_name,
trust_remote_code=True,
torch_dtype=torch.float32, # Use float32 for CPU
low_cpu_mem_usage=True, # Reduce memory usage
device_map="cpu" # Force CPU usage
)
else:
self.model = AutoModelForCausalLM.from_pretrained(
self.model_name,
trust_remote_code=True,
torch_dtype=torch.float16 if self.device == "cuda" else torch.float32
)
self.model.to(self.device)
logger.info("DeepSeek OCR model loaded successfully")
except Exception as e:
logger.error(f"Failed to load DeepSeek OCR model: {str(e)}")
raise e
def extract_text_from_image(self, image_path: str, prompt: str = None) -> Dict[str, Any]:
"""
Extract text from an image using DeepSeek OCR
Args:
image_path (str): Path to the image file
prompt (str, optional): Custom prompt for OCR processing
Returns:
Dict containing extracted text and metadata
"""
if self.model is None or self.tokenizer is None:
self.load_model()
try:
# Load and preprocess the image
image = Image.open(image_path)
if image.mode != 'RGB':
image = image.convert('RGB')
# Use default prompt if none provided
if prompt is None:
prompt = "<|grounding|>Extract all text from this image."
# Prepare inputs
inputs = self.tokenizer(
prompt,
image,
return_tensors="pt"
).to(self.device)
# Get configuration from environment - CPU optimized defaults
max_tokens = int(os.getenv('DEEPSEEK_OCR_MAX_TOKENS', '256')) # Reduced for CPU
temperature = float(os.getenv('DEEPSEEK_OCR_TEMPERATURE', '0.1'))
# Generate text extraction
with torch.no_grad():
outputs = self.model.generate(
**inputs,
max_new_tokens=max_tokens,
do_sample=False,
temperature=temperature,
pad_token_id=self.tokenizer.eos_token_id
)
# Decode the output
extracted_text = self.tokenizer.decode(
outputs[0],
skip_special_tokens=True
)
# Clean up the extracted text
extracted_text = extracted_text.replace(prompt, "").strip()
return {
"success": True,
"extracted_text": extracted_text,
"image_path": image_path,
"model_used": self.model_name,
"device": self.device
}
except Exception as e:
logger.error(f"Error extracting text from image {image_path}: {str(e)}")
return {
"success": False,
"error": str(e),
"image_path": image_path
}
def extract_text_with_grounding(self, image_path: str, target_text: str = None) -> Dict[str, Any]:
"""
Extract text with grounding capabilities (locate specific text)
Args:
image_path (str): Path to the image file
target_text (str, optional): Specific text to locate in the image
Returns:
Dict containing extracted text and location information
"""
if self.model is None or self.tokenizer is None:
self.load_model()
try:
image = Image.open(image_path)
if image.mode != 'RGB':
image = image.convert('RGB')
if target_text:
prompt = f"<|grounding|>Locate <|ref|>{target_text}<|/ref|> in the image."
else:
prompt = "<|grounding|>Extract all text from this image with location information."
inputs = self.tokenizer(
prompt,
image,
return_tensors="pt"
).to(self.device)
with torch.no_grad():
outputs = self.model.generate(
**inputs,
max_new_tokens=512,
do_sample=False,
temperature=0.1,
pad_token_id=self.tokenizer.eos_token_id
)
extracted_text = self.tokenizer.decode(
outputs[0],
skip_special_tokens=True
)
extracted_text = extracted_text.replace(prompt, "").strip()
return {
"success": True,
"extracted_text": extracted_text,
"grounding_info": target_text if target_text else "all_text",
"image_path": image_path,
"model_used": self.model_name
}
except Exception as e:
logger.error(f"Error in grounding extraction from {image_path}: {str(e)}")
return {
"success": False,
"error": str(e),
"image_path": image_path
}
def convert_to_markdown(self, image_path: str) -> Dict[str, Any]:
"""
Convert document image to markdown format
Args:
image_path (str): Path to the image file
Returns:
Dict containing markdown formatted text
"""
if self.model is None or self.tokenizer is None:
self.load_model()
try:
image = Image.open(image_path)
if image.mode != 'RGB':
image = image.convert('RGB')
prompt = "<|grounding|>Convert the document to markdown format."
inputs = self.tokenizer(
prompt,
image,
return_tensors="pt"
).to(self.device)
with torch.no_grad():
outputs = self.model.generate(
**inputs,
max_new_tokens=1024,
do_sample=False,
temperature=0.1,
pad_token_id=self.tokenizer.eos_token_id
)
markdown_text = self.tokenizer.decode(
outputs[0],
skip_special_tokens=True
)
markdown_text = markdown_text.replace(prompt, "").strip()
return {
"success": True,
"markdown_text": markdown_text,
"image_path": image_path,
"model_used": self.model_name
}
except Exception as e:
logger.error(f"Error converting to markdown from {image_path}: {str(e)}")
return {
"success": False,
"error": str(e),
"image_path": image_path
}
# Global OCR service instance
ocr_service = DeepSeekOCRService()
def get_ocr_service() -> DeepSeekOCRService:
"""
Get the global OCR service instance
Returns:
DeepSeekOCRService: The OCR service instance
"""
return ocr_service
|