Spaces:
Sleeping
Sleeping
Upload ocr_service.py
Browse files- ocr_service.py +206 -46
ocr_service.py
CHANGED
|
@@ -170,20 +170,57 @@ def _patch_deepseek_model_for_compatibility():
|
|
| 170 |
print(f"⚠️ Could not read model file to check patch status: {e}")
|
| 171 |
return
|
| 172 |
|
| 173 |
-
#
|
| 174 |
-
|
| 175 |
-
("""from transformers.models.llama.modeling_llama import (
|
| 176 |
-
LlamaAttention,
|
| 177 |
-
LlamaFlashAttention2
|
| 178 |
-
)""", True),
|
| 179 |
-
("""from transformers.models.llama.modeling_llama import (LlamaAttention, LlamaFlashAttention2)""", True),
|
| 180 |
-
("""from transformers.models.llama.modeling_llama import LlamaFlashAttention2""", False),
|
| 181 |
-
]
|
| 182 |
|
| 183 |
-
|
| 184 |
-
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 185 |
LlamaAttention,
|
| 186 |
-
|
| 187 |
# Patch: LlamaFlashAttention2 not available in transformers <5.0.0
|
| 188 |
# Use LlamaAttention as fallback when flash attention unavailable
|
| 189 |
try:
|
|
@@ -191,51 +228,174 @@ try:
|
|
| 191 |
except ImportError:
|
| 192 |
# Fallback: Use LlamaAttention when flash attention not available
|
| 193 |
LlamaFlashAttention2 = LlamaAttention"""
|
| 194 |
-
|
| 195 |
-
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 196 |
try:
|
| 197 |
from transformers.models.llama.modeling_llama import LlamaFlashAttention2
|
| 198 |
except ImportError:
|
| 199 |
from transformers.models.llama.modeling_llama import LlamaAttention
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 200 |
LlamaFlashAttention2 = LlamaAttention"""
|
| 201 |
-
|
| 202 |
-
try:
|
| 203 |
-
patched = False
|
| 204 |
-
for original_import, is_multiline in original_patterns:
|
| 205 |
-
if original_import in content:
|
| 206 |
-
# Create backup
|
| 207 |
-
backup_file = model_file.with_suffix('.py.backup')
|
| 208 |
-
try:
|
| 209 |
-
import shutil
|
| 210 |
-
shutil.copy2(model_file, backup_file)
|
| 211 |
-
print(f"📋 Created backup: {backup_file}")
|
| 212 |
-
except Exception as backup_err:
|
| 213 |
-
print(f"⚠️ Could not create backup: {backup_err}")
|
| 214 |
-
|
| 215 |
-
# Apply patch
|
| 216 |
-
if is_multiline:
|
| 217 |
-
content = content.replace(original_import, patched_import)
|
| 218 |
-
else:
|
| 219 |
-
# For single-line imports, add after the import
|
| 220 |
-
lines = content.split('\n')
|
| 221 |
-
for i, line in enumerate(lines):
|
| 222 |
-
if original_import in line:
|
| 223 |
-
lines[i] = patched_single_import
|
| 224 |
-
content = '\n'.join(lines)
|
| 225 |
-
break
|
| 226 |
|
|
|
|
| 227 |
patched = True
|
| 228 |
-
print(
|
| 229 |
-
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 230 |
|
| 231 |
if patched:
|
| 232 |
-
|
| 233 |
-
f.write(content)
|
| 234 |
print(f"✅ Successfully patched DeepSeek model file: {model_file}")
|
| 235 |
else:
|
| 236 |
-
print(f"⚠️ Could not find import
|
| 237 |
-
|
| 238 |
-
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 239 |
except PermissionError as e:
|
| 240 |
print(f"❌ Permission denied - cannot patch model file: {e}")
|
| 241 |
print(f" File: {model_file}")
|
|
|
|
| 170 |
print(f"⚠️ Could not read model file to check patch status: {e}")
|
| 171 |
return
|
| 172 |
|
| 173 |
+
# More flexible approach: find and replace any import containing LlamaFlashAttention2
|
| 174 |
+
import re
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 175 |
|
| 176 |
+
try:
|
| 177 |
+
# Pattern 1: Multi-line import with parentheses
|
| 178 |
+
# Matches: from transformers.models.llama.modeling_llama import (\n ...\n LlamaFlashAttention2\n )
|
| 179 |
+
multiline_pattern = r'from transformers\.models\.llama\.modeling_llama import\s*\([^)]*LlamaFlashAttention2[^)]*\)'
|
| 180 |
+
|
| 181 |
+
# Pattern 2: Single-line import with parentheses
|
| 182 |
+
singleline_parentheses_pattern = r'from transformers\.models\.llama\.modeling_llama import\s*\([^)]*LlamaFlashAttention2[^)]*\)'
|
| 183 |
+
|
| 184 |
+
# Pattern 3: Direct import without parentheses
|
| 185 |
+
direct_import_pattern = r'from transformers\.models\.llama\.modeling_llama import[^;]*LlamaFlashAttention2[^;\n]*'
|
| 186 |
+
|
| 187 |
+
patched = False
|
| 188 |
+
|
| 189 |
+
# Try multiline replacement first (most common)
|
| 190 |
+
if re.search(multiline_pattern, content, re.MULTILINE | re.DOTALL):
|
| 191 |
+
# Create backup
|
| 192 |
+
backup_file = model_file.with_suffix('.py.backup')
|
| 193 |
+
try:
|
| 194 |
+
import shutil
|
| 195 |
+
shutil.copy2(model_file, backup_file)
|
| 196 |
+
print(f"📋 Created backup: {backup_file}")
|
| 197 |
+
except Exception as backup_err:
|
| 198 |
+
print(f"⚠️ Could not create backup: {backup_err}")
|
| 199 |
+
|
| 200 |
+
# Extract what else is being imported (besides LlamaFlashAttention2)
|
| 201 |
+
match = re.search(r'from transformers\.models\.llama\.modeling_llama import\s*\(([^)]*)\)', content, re.MULTILINE | re.DOTALL)
|
| 202 |
+
if match:
|
| 203 |
+
imports_text = match.group(1)
|
| 204 |
+
# Remove LlamaFlashAttention2 from imports, keep others
|
| 205 |
+
other_imports = [imp.strip() for imp in imports_text.split(',') if 'LlamaFlashAttention2' not in imp.strip()]
|
| 206 |
+
other_imports_str = ',\n '.join(other_imports) if other_imports else ''
|
| 207 |
+
|
| 208 |
+
# Build replacement
|
| 209 |
+
if other_imports_str:
|
| 210 |
+
replacement = f"""from transformers.models.llama.modeling_llama import (
|
| 211 |
+
{other_imports_str}
|
| 212 |
+
)
|
| 213 |
+
# Patch: LlamaFlashAttention2 not available in transformers <5.0.0
|
| 214 |
+
# Use LlamaAttention as fallback when flash attention unavailable
|
| 215 |
+
try:
|
| 216 |
+
from transformers.models.llama.modeling_llama import LlamaFlashAttention2
|
| 217 |
+
except ImportError:
|
| 218 |
+
# Fallback: Use LlamaAttention when flash attention not available
|
| 219 |
+
LlamaFlashAttention2 = LlamaAttention"""
|
| 220 |
+
else:
|
| 221 |
+
replacement = """from transformers.models.llama.modeling_llama import (
|
| 222 |
LlamaAttention,
|
| 223 |
+
)
|
| 224 |
# Patch: LlamaFlashAttention2 not available in transformers <5.0.0
|
| 225 |
# Use LlamaAttention as fallback when flash attention unavailable
|
| 226 |
try:
|
|
|
|
| 228 |
except ImportError:
|
| 229 |
# Fallback: Use LlamaAttention when flash attention not available
|
| 230 |
LlamaFlashAttention2 = LlamaAttention"""
|
| 231 |
+
|
| 232 |
+
content = re.sub(multiline_pattern, replacement, content, flags=re.MULTILINE | re.DOTALL)
|
| 233 |
+
patched = True
|
| 234 |
+
print("🔧 Applied multiline import patch")
|
| 235 |
+
|
| 236 |
+
# Try single-line parentheses pattern
|
| 237 |
+
elif re.search(singleline_parentheses_pattern, content):
|
| 238 |
+
# Create backup
|
| 239 |
+
backup_file = model_file.with_suffix('.py.backup')
|
| 240 |
+
try:
|
| 241 |
+
import shutil
|
| 242 |
+
shutil.copy2(model_file, backup_file)
|
| 243 |
+
print(f"📋 Created backup: {backup_file}")
|
| 244 |
+
except Exception as backup_err:
|
| 245 |
+
print(f"⚠️ Could not create backup: {backup_err}")
|
| 246 |
+
|
| 247 |
+
# Extract other imports
|
| 248 |
+
match = re.search(r'from transformers\.models\.llama\.modeling_llama import\s*\(([^)]*)\)', content)
|
| 249 |
+
if match:
|
| 250 |
+
imports_text = match.group(1)
|
| 251 |
+
other_imports = [imp.strip() for imp in imports_text.split(',') if 'LlamaFlashAttention2' not in imp.strip()]
|
| 252 |
+
other_imports_str = ', '.join(other_imports) if other_imports else ''
|
| 253 |
+
|
| 254 |
+
replacement = f"""from transformers.models.llama.modeling_llama import ({other_imports_str})
|
| 255 |
+
# Patch: LlamaFlashAttention2 import with fallback
|
| 256 |
try:
|
| 257 |
from transformers.models.llama.modeling_llama import LlamaFlashAttention2
|
| 258 |
except ImportError:
|
| 259 |
from transformers.models.llama.modeling_llama import LlamaAttention
|
| 260 |
+
LlamaFlashAttention2 = LlamaAttention""" if other_imports_str else """from transformers.models.llama.modeling_llama import LlamaAttention
|
| 261 |
+
# Patch: LlamaFlashAttention2 import with fallback
|
| 262 |
+
try:
|
| 263 |
+
from transformers.models.llama.modeling_llama import LlamaFlashAttention2
|
| 264 |
+
except ImportError:
|
| 265 |
LlamaFlashAttention2 = LlamaAttention"""
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 266 |
|
| 267 |
+
content = re.sub(singleline_parentheses_pattern, replacement, content)
|
| 268 |
patched = True
|
| 269 |
+
print("🔧 Applied single-line parentheses import patch")
|
| 270 |
+
|
| 271 |
+
# Try direct import pattern (no parentheses)
|
| 272 |
+
elif re.search(direct_import_pattern, content):
|
| 273 |
+
# Create backup
|
| 274 |
+
backup_file = model_file.with_suffix('.py.backup')
|
| 275 |
+
try:
|
| 276 |
+
import shutil
|
| 277 |
+
shutil.copy2(model_file, backup_file)
|
| 278 |
+
print(f"📋 Created backup: {backup_file}")
|
| 279 |
+
except Exception as backup_err:
|
| 280 |
+
print(f"⚠️ Could not create backup: {backup_err}")
|
| 281 |
+
|
| 282 |
+
replacement = """# Patch: LlamaFlashAttention2 import with fallback
|
| 283 |
+
try:
|
| 284 |
+
from transformers.models.llama.modeling_llama import LlamaFlashAttention2
|
| 285 |
+
except ImportError:
|
| 286 |
+
from transformers.models.llama.modeling_llama import LlamaAttention
|
| 287 |
+
LlamaFlashAttention2 = LlamaAttention"""
|
| 288 |
+
|
| 289 |
+
content = re.sub(direct_import_pattern, replacement, content)
|
| 290 |
+
patched = True
|
| 291 |
+
print("🔧 Applied direct import patch")
|
| 292 |
+
|
| 293 |
+
# Last resort: find any line containing LlamaFlashAttention2 import and replace
|
| 294 |
+
if not patched:
|
| 295 |
+
lines = content.split('\n')
|
| 296 |
+
for i, line in enumerate(lines):
|
| 297 |
+
if 'LlamaFlashAttention2' in line and 'from transformers.models.llama.modeling_llama' in line:
|
| 298 |
+
# Create backup on first match
|
| 299 |
+
if not patched:
|
| 300 |
+
backup_file = model_file.with_suffix('.py.backup')
|
| 301 |
+
try:
|
| 302 |
+
import shutil
|
| 303 |
+
shutil.copy2(model_file, backup_file)
|
| 304 |
+
print(f"📋 Created backup: {backup_file}")
|
| 305 |
+
except Exception as backup_err:
|
| 306 |
+
print(f"⚠️ Could not create backup: {backup_err}")
|
| 307 |
+
|
| 308 |
+
# Replace the import line(s)
|
| 309 |
+
# Handle multiline imports
|
| 310 |
+
if '(' in line:
|
| 311 |
+
# Find closing paren
|
| 312 |
+
j = i
|
| 313 |
+
import_block = [lines[j]]
|
| 314 |
+
while ')' not in lines[j] and j < len(lines) - 1:
|
| 315 |
+
j += 1
|
| 316 |
+
import_block.append(lines[j])
|
| 317 |
+
|
| 318 |
+
# Replace with patched version
|
| 319 |
+
replacement_lines = [
|
| 320 |
+
"# Patch: LlamaFlashAttention2 not available - using fallback",
|
| 321 |
+
"try:",
|
| 322 |
+
" from transformers.models.llama.modeling_llama import LlamaFlashAttention2",
|
| 323 |
+
"except ImportError:",
|
| 324 |
+
" from transformers.models.llama.modeling_llama import LlamaAttention",
|
| 325 |
+
" LlamaFlashAttention2 = LlamaAttention"
|
| 326 |
+
]
|
| 327 |
+
|
| 328 |
+
# Replace the block
|
| 329 |
+
lines[i:j+1] = replacement_lines
|
| 330 |
+
content = '\n'.join(lines)
|
| 331 |
+
patched = True
|
| 332 |
+
print(f"🔧 Applied line-by-line patch (lines {i}-{j})")
|
| 333 |
+
break
|
| 334 |
+
else:
|
| 335 |
+
# Single line import
|
| 336 |
+
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"
|
| 337 |
+
content = '\n'.join(lines)
|
| 338 |
+
patched = True
|
| 339 |
+
print(f"🔧 Applied single-line patch (line {i})")
|
| 340 |
+
break
|
| 341 |
+
|
| 342 |
+
# Last resort: find any line containing LlamaFlashAttention2 import and add fallback
|
| 343 |
+
if not patched:
|
| 344 |
+
lines_for_fallback = content.split('\n')
|
| 345 |
+
for i, line in enumerate(lines_for_fallback):
|
| 346 |
+
if 'LlamaFlashAttention2' in line and 'from transformers.models.llama.modeling_llama' in line:
|
| 347 |
+
print(f" Found import line {i}, attempting fallback insertion...")
|
| 348 |
+
# Create backup
|
| 349 |
+
backup_file = model_file.with_suffix('.py.backup')
|
| 350 |
+
try:
|
| 351 |
+
import shutil
|
| 352 |
+
if not backup_file.exists():
|
| 353 |
+
shutil.copy2(model_file, backup_file)
|
| 354 |
+
print(f"📋 Created backup: {backup_file}")
|
| 355 |
+
except Exception as backup_err:
|
| 356 |
+
print(f"⚠️ Could not create backup: {backup_err}")
|
| 357 |
+
|
| 358 |
+
# Add fallback after the import line
|
| 359 |
+
new_lines = lines_for_fallback[:i+1]
|
| 360 |
+
new_lines.extend([
|
| 361 |
+
"",
|
| 362 |
+
"# Patch: LlamaFlashAttention2 fallback for compatibility",
|
| 363 |
+
"try:",
|
| 364 |
+
" pass # LlamaFlashAttention2 already imported",
|
| 365 |
+
"except NameError:",
|
| 366 |
+
" try:",
|
| 367 |
+
" from transformers.models.llama.modeling_llama import LlamaFlashAttention2",
|
| 368 |
+
" except ImportError:",
|
| 369 |
+
" from transformers.models.llama.modeling_llama import LlamaAttention",
|
| 370 |
+
" LlamaFlashAttention2 = LlamaAttention"
|
| 371 |
+
])
|
| 372 |
+
new_lines.extend(lines_for_fallback[i+1:])
|
| 373 |
+
content = '\n'.join(new_lines)
|
| 374 |
+
with open(model_file, 'w', encoding='utf-8') as f:
|
| 375 |
+
f.write(content)
|
| 376 |
+
print(f"✅ Added fallback import block after line {i}")
|
| 377 |
+
patched = True
|
| 378 |
+
break
|
| 379 |
|
| 380 |
if patched:
|
| 381 |
+
# File already written if patched via fallback, but print success message
|
|
|
|
| 382 |
print(f"✅ Successfully patched DeepSeek model file: {model_file}")
|
| 383 |
else:
|
| 384 |
+
print(f"⚠️ Could not find LlamaFlashAttention2 import to patch in {model_file}")
|
| 385 |
+
# Show a snippet around potential import lines for debugging
|
| 386 |
+
lines = content.split('\n')
|
| 387 |
+
for i, line in enumerate(lines):
|
| 388 |
+
if 'LlamaFlashAttention2' in line or ('llama.modeling_llama' in line and i < 200):
|
| 389 |
+
start = max(0, i - 2)
|
| 390 |
+
end = min(len(lines), i + 3)
|
| 391 |
+
snippet = '\n'.join(f"{j:4d}: {lines[j]}" for j in range(start, end))
|
| 392 |
+
print(f" Found potential import around line {i}:")
|
| 393 |
+
print(f" {snippet}")
|
| 394 |
+
|
| 395 |
+
# Show more context for debugging
|
| 396 |
+
if 'LlamaFlashAttention2' in line:
|
| 397 |
+
print(f" Full line {i}: {line[:200]}")
|
| 398 |
+
break
|
| 399 |
except PermissionError as e:
|
| 400 |
print(f"❌ Permission denied - cannot patch model file: {e}")
|
| 401 |
print(f" File: {model_file}")
|