Spaces:
Sleeping
Sleeping
Upload ocr_service.py
Browse files- ocr_service.py +3 -296
ocr_service.py
CHANGED
|
@@ -131,302 +131,9 @@ _ocr_tokenizer = None
|
|
| 131 |
_model_lock = asyncio.Lock()
|
| 132 |
|
| 133 |
|
| 134 |
-
|
| 135 |
-
|
| 136 |
-
|
| 137 |
-
Works on HuggingFace Spaces (CPU) and M4 Macs (Apple Silicon).
|
| 138 |
-
Tries multiple cache locations and handles permission errors gracefully.
|
| 139 |
-
"""
|
| 140 |
-
from pathlib import Path
|
| 141 |
-
import os
|
| 142 |
-
|
| 143 |
-
# Try multiple cache locations (HuggingFace Spaces uses different paths)
|
| 144 |
-
possible_cache_dirs = [
|
| 145 |
-
Path.home() / ".cache" / "huggingface",
|
| 146 |
-
Path("/home/user/.cache/huggingface"), # HuggingFace Spaces default
|
| 147 |
-
Path(os.getenv("HF_HOME", "")) / ".cache" / "huggingface" if os.getenv("HF_HOME") else None,
|
| 148 |
-
Path(os.getenv("TRANSFORMERS_CACHE", "")) / "hub" if os.getenv("TRANSFORMERS_CACHE") else None,
|
| 149 |
-
]
|
| 150 |
-
|
| 151 |
-
# Patch ALL files that might import LlamaFlashAttention2
|
| 152 |
-
model_files = []
|
| 153 |
-
for cache_dir in possible_cache_dirs:
|
| 154 |
-
if cache_dir and cache_dir.exists():
|
| 155 |
-
try:
|
| 156 |
-
# Find all Python files in the DeepSeek-OCR model directory
|
| 157 |
-
found = list(cache_dir.glob(f"**/models--deepseek-ai--DeepSeek-OCR/**/*.py"))
|
| 158 |
-
# Filter for the files that might import LlamaFlashAttention2
|
| 159 |
-
relevant_files = [
|
| 160 |
-
f for f in found
|
| 161 |
-
if any(pattern in f.name for pattern in [
|
| 162 |
-
'modeling_deepseekv2.py',
|
| 163 |
-
'modeling_deepseekocr.py',
|
| 164 |
-
'modeling_llama.py' # In case it's in a nested location
|
| 165 |
-
])
|
| 166 |
-
]
|
| 167 |
-
model_files.extend(relevant_files)
|
| 168 |
-
except Exception:
|
| 169 |
-
continue
|
| 170 |
-
|
| 171 |
-
if not model_files:
|
| 172 |
-
print("⚠️ Model files not found yet - will patch on first model load")
|
| 173 |
-
return # Model not downloaded yet, will patch on first load
|
| 174 |
-
|
| 175 |
-
# Patch all found files
|
| 176 |
-
print(f"🔍 Found {len(model_files)} model file(s) to patch")
|
| 177 |
-
for model_file in model_files:
|
| 178 |
-
print(f" - {model_file.name}")
|
| 179 |
-
|
| 180 |
-
# Patch each file
|
| 181 |
-
import re
|
| 182 |
-
|
| 183 |
-
for model_file in model_files:
|
| 184 |
-
print(f"\n🔧 Patching: {model_file.name}")
|
| 185 |
-
patched_this_file = False
|
| 186 |
-
|
| 187 |
-
# Check if already patched
|
| 188 |
-
try:
|
| 189 |
-
with open(model_file, 'r', encoding='utf-8') as f:
|
| 190 |
-
content = f.read()
|
| 191 |
-
if "LlamaFlashAttention2 = LlamaAttention" in content:
|
| 192 |
-
print(f" ✅ Already patched, skipping")
|
| 193 |
-
continue # Already patched, move to next file
|
| 194 |
-
original_content = content # Save original for comparison
|
| 195 |
-
except Exception as e:
|
| 196 |
-
print(f" ⚠️ Could not read model file to check patch status: {e}")
|
| 197 |
-
continue # Skip this file, try next
|
| 198 |
-
|
| 199 |
-
# More flexible approach: find and replace any import containing LlamaFlashAttention2
|
| 200 |
-
try:
|
| 201 |
-
# Pattern 1: Multi-line import with parentheses
|
| 202 |
-
# Matches: from transformers.models.llama.modeling_llama import (\n ...\n LlamaFlashAttention2\n )
|
| 203 |
-
multiline_pattern = r'from transformers\.models\.llama\.modeling_llama import\s*\([^)]*LlamaFlashAttention2[^)]*\)'
|
| 204 |
-
|
| 205 |
-
# Pattern 2: Single-line import with parentheses
|
| 206 |
-
singleline_parentheses_pattern = r'from transformers\.models\.llama\.modeling_llama import\s*\([^)]*LlamaFlashAttention2[^)]*\)'
|
| 207 |
-
|
| 208 |
-
# Pattern 3: Direct import without parentheses
|
| 209 |
-
direct_import_pattern = r'from transformers\.models\.llama\.modeling_llama import[^;]*LlamaFlashAttention2[^;\n]*'
|
| 210 |
-
|
| 211 |
-
# Try multiline replacement first (most common)
|
| 212 |
-
if re.search(multiline_pattern, content, re.MULTILINE | re.DOTALL):
|
| 213 |
-
# Create backup
|
| 214 |
-
backup_file = model_file.with_suffix('.py.backup')
|
| 215 |
-
try:
|
| 216 |
-
import shutil
|
| 217 |
-
shutil.copy2(model_file, backup_file)
|
| 218 |
-
print(f"📋 Created backup: {backup_file}")
|
| 219 |
-
except Exception as backup_err:
|
| 220 |
-
print(f"⚠️ Could not create backup: {backup_err}")
|
| 221 |
-
|
| 222 |
-
# Extract what else is being imported (besides LlamaFlashAttention2)
|
| 223 |
-
match = re.search(r'from transformers\.models\.llama\.modeling_llama import\s*\(([^)]*)\)', content, re.MULTILINE | re.DOTALL)
|
| 224 |
-
if match:
|
| 225 |
-
imports_text = match.group(1)
|
| 226 |
-
# Remove LlamaFlashAttention2 from imports, keep others
|
| 227 |
-
other_imports = [imp.strip() for imp in imports_text.split(',') if 'LlamaFlashAttention2' not in imp.strip()]
|
| 228 |
-
other_imports_str = ',\n '.join(other_imports) if other_imports else ''
|
| 229 |
-
|
| 230 |
-
# Build replacement
|
| 231 |
-
if other_imports_str:
|
| 232 |
-
replacement = f"""from transformers.models.llama.modeling_llama import (
|
| 233 |
-
{other_imports_str}
|
| 234 |
-
)
|
| 235 |
-
# Patch: LlamaFlashAttention2 not available in transformers <5.0.0
|
| 236 |
-
# Use LlamaAttention as fallback when flash attention unavailable
|
| 237 |
-
try:
|
| 238 |
-
from transformers.models.llama.modeling_llama import LlamaFlashAttention2
|
| 239 |
-
except ImportError:
|
| 240 |
-
# Fallback: Use LlamaAttention when flash attention not available
|
| 241 |
-
LlamaFlashAttention2 = LlamaAttention"""
|
| 242 |
-
else:
|
| 243 |
-
replacement = """from transformers.models.llama.modeling_llama import (
|
| 244 |
-
LlamaAttention,
|
| 245 |
-
)
|
| 246 |
-
# Patch: LlamaFlashAttention2 not available in transformers <5.0.0
|
| 247 |
-
# Use LlamaAttention as fallback when flash attention unavailable
|
| 248 |
-
try:
|
| 249 |
-
from transformers.models.llama.modeling_llama import LlamaFlashAttention2
|
| 250 |
-
except ImportError:
|
| 251 |
-
# Fallback: Use LlamaAttention when flash attention not available
|
| 252 |
-
LlamaFlashAttention2 = LlamaAttention"""
|
| 253 |
-
|
| 254 |
-
content = re.sub(multiline_pattern, replacement, content, flags=re.MULTILINE | re.DOTALL)
|
| 255 |
-
patched_this_file = True
|
| 256 |
-
print(" 🔧 Applied multiline import patch")
|
| 257 |
-
|
| 258 |
-
# Try single-line parentheses pattern
|
| 259 |
-
elif re.search(singleline_parentheses_pattern, content):
|
| 260 |
-
# Create backup
|
| 261 |
-
backup_file = model_file.with_suffix('.py.backup')
|
| 262 |
-
try:
|
| 263 |
-
import shutil
|
| 264 |
-
shutil.copy2(model_file, backup_file)
|
| 265 |
-
print(f"📋 Created backup: {backup_file}")
|
| 266 |
-
except Exception as backup_err:
|
| 267 |
-
print(f"⚠️ Could not create backup: {backup_err}")
|
| 268 |
-
|
| 269 |
-
# Extract other imports
|
| 270 |
-
match = re.search(r'from transformers\.models\.llama\.modeling_llama import\s*\(([^)]*)\)', content)
|
| 271 |
-
if match:
|
| 272 |
-
imports_text = match.group(1)
|
| 273 |
-
other_imports = [imp.strip() for imp in imports_text.split(',') if 'LlamaFlashAttention2' not in imp.strip()]
|
| 274 |
-
other_imports_str = ', '.join(other_imports) if other_imports else ''
|
| 275 |
-
|
| 276 |
-
replacement = f"""from transformers.models.llama.modeling_llama import ({other_imports_str})
|
| 277 |
-
# Patch: LlamaFlashAttention2 import with fallback
|
| 278 |
-
try:
|
| 279 |
-
from transformers.models.llama.modeling_llama import LlamaFlashAttention2
|
| 280 |
-
except ImportError:
|
| 281 |
-
from transformers.models.llama.modeling_llama import LlamaAttention
|
| 282 |
-
LlamaFlashAttention2 = LlamaAttention""" if other_imports_str else """from transformers.models.llama.modeling_llama import LlamaAttention
|
| 283 |
-
# Patch: LlamaFlashAttention2 import with fallback
|
| 284 |
-
try:
|
| 285 |
-
from transformers.models.llama.modeling_llama import LlamaFlashAttention2
|
| 286 |
-
except ImportError:
|
| 287 |
-
LlamaFlashAttention2 = LlamaAttention"""
|
| 288 |
-
|
| 289 |
-
content = re.sub(singleline_parentheses_pattern, replacement, content)
|
| 290 |
-
patched_this_file = True
|
| 291 |
-
print(" 🔧 Applied single-line parentheses import patch")
|
| 292 |
-
|
| 293 |
-
# Try direct import pattern (no parentheses)
|
| 294 |
-
elif re.search(direct_import_pattern, content):
|
| 295 |
-
# Create backup
|
| 296 |
-
backup_file = model_file.with_suffix('.py.backup')
|
| 297 |
-
try:
|
| 298 |
-
import shutil
|
| 299 |
-
shutil.copy2(model_file, backup_file)
|
| 300 |
-
print(f"📋 Created backup: {backup_file}")
|
| 301 |
-
except Exception as backup_err:
|
| 302 |
-
print(f"⚠️ Could not create backup: {backup_err}")
|
| 303 |
-
|
| 304 |
-
replacement = """# Patch: LlamaFlashAttention2 import with fallback
|
| 305 |
-
try:
|
| 306 |
-
from transformers.models.llama.modeling_llama import LlamaFlashAttention2
|
| 307 |
-
except ImportError:
|
| 308 |
-
from transformers.models.llama.modeling_llama import LlamaAttention
|
| 309 |
-
LlamaFlashAttention2 = LlamaAttention"""
|
| 310 |
-
|
| 311 |
-
content = re.sub(direct_import_pattern, replacement, content)
|
| 312 |
-
patched_this_file = True
|
| 313 |
-
print(" 🔧 Applied direct import patch")
|
| 314 |
-
|
| 315 |
-
# Last resort: find any line containing LlamaFlashAttention2 import and replace
|
| 316 |
-
if not patched_this_file:
|
| 317 |
-
lines = content.split('\n')
|
| 318 |
-
for i, line in enumerate(lines):
|
| 319 |
-
if 'LlamaFlashAttention2' in line and 'from transformers.models.llama.modeling_llama' in line:
|
| 320 |
-
# Create backup on first match
|
| 321 |
-
backup_file = model_file.with_suffix('.py.backup')
|
| 322 |
-
try:
|
| 323 |
-
import shutil
|
| 324 |
-
shutil.copy2(model_file, backup_file)
|
| 325 |
-
print(f" 📋 Created backup: {backup_file.name}")
|
| 326 |
-
except Exception as backup_err:
|
| 327 |
-
print(f" ⚠️ Could not create backup: {backup_err}")
|
| 328 |
-
|
| 329 |
-
# Replace the import line(s)
|
| 330 |
-
# Handle multiline imports
|
| 331 |
-
if '(' in line:
|
| 332 |
-
# Find closing paren
|
| 333 |
-
j = i
|
| 334 |
-
import_block = [lines[j]]
|
| 335 |
-
while ')' not in lines[j] and j < len(lines) - 1:
|
| 336 |
-
j += 1
|
| 337 |
-
import_block.append(lines[j])
|
| 338 |
-
|
| 339 |
-
# Replace with patched version
|
| 340 |
-
replacement_lines = [
|
| 341 |
-
"# Patch: LlamaFlashAttention2 not available - using fallback",
|
| 342 |
-
"try:",
|
| 343 |
-
" from transformers.models.llama.modeling_llama import LlamaFlashAttention2",
|
| 344 |
-
"except ImportError:",
|
| 345 |
-
" from transformers.models.llama.modeling_llama import LlamaAttention",
|
| 346 |
-
" LlamaFlashAttention2 = LlamaAttention"
|
| 347 |
-
]
|
| 348 |
-
|
| 349 |
-
# Replace the block
|
| 350 |
-
lines[i:j+1] = replacement_lines
|
| 351 |
-
content = '\n'.join(lines)
|
| 352 |
-
patched_this_file = True
|
| 353 |
-
print(f" 🔧 Applied line-by-line patch (lines {i}-{j})")
|
| 354 |
-
break
|
| 355 |
-
else:
|
| 356 |
-
# Single line import
|
| 357 |
-
lines[i] = "# Patch: LlamaFlashAttention2 import with fallback\ntry:\n from transformers.models.llama.modeling_llama import LlamaFlashAttention2\nexcept ImportError:\n from transformers.models.llama.modeling_llama import LlamaAttention\n LlamaFlashAttention2 = LlamaAttention"
|
| 358 |
-
content = '\n'.join(lines)
|
| 359 |
-
patched_this_file = True
|
| 360 |
-
print(f" 🔧 Applied single-line patch (line {i})")
|
| 361 |
-
break
|
| 362 |
-
|
| 363 |
-
# Last resort: find any line containing LlamaFlashAttention2 import and add fallback
|
| 364 |
-
if not patched_this_file:
|
| 365 |
-
lines_for_fallback = content.split('\n')
|
| 366 |
-
for i, line in enumerate(lines_for_fallback):
|
| 367 |
-
if 'LlamaFlashAttention2' in line and 'from transformers.models.llama.modeling_llama' in line:
|
| 368 |
-
print(f" Found import line {i}, attempting fallback insertion...")
|
| 369 |
-
# Create backup
|
| 370 |
-
backup_file = model_file.with_suffix('.py.backup')
|
| 371 |
-
try:
|
| 372 |
-
import shutil
|
| 373 |
-
if not backup_file.exists():
|
| 374 |
-
shutil.copy2(model_file, backup_file)
|
| 375 |
-
print(f"📋 Created backup: {backup_file}")
|
| 376 |
-
except Exception as backup_err:
|
| 377 |
-
print(f"⚠️ Could not create backup: {backup_err}")
|
| 378 |
-
|
| 379 |
-
# Add fallback after the import line
|
| 380 |
-
new_lines = lines_for_fallback[:i+1]
|
| 381 |
-
new_lines.extend([
|
| 382 |
-
"",
|
| 383 |
-
"# Patch: LlamaFlashAttention2 fallback for compatibility",
|
| 384 |
-
"try:",
|
| 385 |
-
" pass # LlamaFlashAttention2 already imported",
|
| 386 |
-
"except NameError:",
|
| 387 |
-
" try:",
|
| 388 |
-
" from transformers.models.llama.modeling_llama import LlamaFlashAttention2",
|
| 389 |
-
" except ImportError:",
|
| 390 |
-
" from transformers.models.llama.modeling_llama import LlamaAttention",
|
| 391 |
-
" LlamaFlashAttention2 = LlamaAttention"
|
| 392 |
-
])
|
| 393 |
-
new_lines.extend(lines_for_fallback[i+1:])
|
| 394 |
-
content = '\n'.join(new_lines)
|
| 395 |
-
print(f" ✅ Added fallback import block after line {i}")
|
| 396 |
-
patched_this_file = True
|
| 397 |
-
break
|
| 398 |
-
|
| 399 |
-
if patched_this_file:
|
| 400 |
-
# Write file if content was modified
|
| 401 |
-
# (fallback already writes immediately, regex patterns modify content then write here)
|
| 402 |
-
with open(model_file, 'w', encoding='utf-8') as f:
|
| 403 |
-
f.write(content)
|
| 404 |
-
print(f" ✅ Successfully patched: {model_file.name}")
|
| 405 |
-
else:
|
| 406 |
-
print(f" ⚠️ Could not find LlamaFlashAttention2 import to patch in {model_file.name}")
|
| 407 |
-
# Show a snippet around potential import lines for debugging
|
| 408 |
-
lines = content.split('\n')
|
| 409 |
-
for i, line in enumerate(lines):
|
| 410 |
-
if 'LlamaFlashAttention2' in line or ('llama.modeling_llama' in line and i < 200):
|
| 411 |
-
start = max(0, i - 2)
|
| 412 |
-
end = min(len(lines), i + 3)
|
| 413 |
-
snippet = '\n'.join(f"{j:4d}: {lines[j]}" for j in range(start, end))
|
| 414 |
-
print(f" Found potential import around line {i}:")
|
| 415 |
-
print(f" {snippet}")
|
| 416 |
-
|
| 417 |
-
# Show more context for debugging
|
| 418 |
-
if 'LlamaFlashAttention2' in line:
|
| 419 |
-
print(f" Full line {i}: {line[:200]}")
|
| 420 |
-
break
|
| 421 |
-
except PermissionError as e:
|
| 422 |
-
print(f"❌ Permission denied - cannot patch model file: {e}")
|
| 423 |
-
print(f" File: {model_file}")
|
| 424 |
-
print(f" Try running with write permissions or patch manually")
|
| 425 |
-
except Exception as e:
|
| 426 |
-
print(f"⚠️ Could not patch model file {model_file}: {e}")
|
| 427 |
-
import traceback
|
| 428 |
-
traceback.print_exc()
|
| 429 |
-
|
| 430 |
|
| 431 |
async def get_ocr_model():
|
| 432 |
"""Lazy load DeepSeek-OCR model with compatibility patching"""
|
|
|
|
| 131 |
_model_lock = asyncio.Lock()
|
| 132 |
|
| 133 |
|
| 134 |
+
# NOTE: Patching function removed - version pinning (transformers==4.46.3)
|
| 135 |
+
# and model revision pinning solved the LlamaFlashAttention2 issue.
|
| 136 |
+
# No patching needed anymore!
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|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