make789 commited on
Commit
5b68dcf
·
verified ·
1 Parent(s): 80cd8b7

Upload ocr_service.py

Browse files
Files changed (1) hide show
  1. ocr_service.py +101 -39
ocr_service.py CHANGED
@@ -126,42 +126,65 @@ _ocr_tokenizer = None
126
  _model_lock = asyncio.Lock()
127
 
128
 
129
- def _patch_deepseek_model_for_m4():
130
  """
131
- Patch DeepSeek-OCR model code to fix LlamaFlashAttention2 import error on M4 Mac.
132
- This is needed because transformers 4.57.1 doesn't have LlamaFlashAttention2,
133
- but DeepSeek-OCR's model code tries to import it.
134
  """
135
  from pathlib import Path
 
136
 
137
- cache_dir = Path.home() / ".cache" / "huggingface"
138
- model_files = list(cache_dir.glob("**/modeling_deepseekv2.py"))
 
 
 
 
 
 
 
 
 
 
 
 
 
 
139
 
140
  if not model_files:
 
141
  return # Model not downloaded yet, will patch on first load
142
 
143
  model_file = model_files[0]
 
144
 
145
  # Check if already patched
146
  try:
147
- with open(model_file, 'r') as f:
148
  content = f.read()
149
  if "LlamaFlashAttention2 = LlamaAttention" in content:
 
150
  return # Already patched
151
- except:
152
- pass
 
153
 
154
- # Original import pattern
155
- original_import = """from transformers.models.llama.modeling_llama import (
 
156
  LlamaAttention,
157
  LlamaFlashAttention2
158
- )"""
 
 
 
159
 
160
  # Patched version with fallback
161
  patched_import = """from transformers.models.llama.modeling_llama import (
162
  LlamaAttention,
163
- )
164
- # Patch for M4 Mac: LlamaFlashAttention2 not available in transformers 4.57.1
165
  # Use LlamaAttention as fallback when flash attention unavailable
166
  try:
167
  from transformers.models.llama.modeling_llama import LlamaFlashAttention2
@@ -169,33 +192,69 @@ except ImportError:
169
  # Fallback: Use LlamaAttention when flash attention not available
170
  LlamaFlashAttention2 = LlamaAttention"""
171
 
 
 
 
 
 
 
 
172
  try:
173
- if original_import in content:
174
- # Create backup
175
- backup_file = model_file.with_suffix('.py.backup')
176
- try:
177
- with open(backup_file, 'w') as f:
178
- f.write(content)
179
- except:
180
- pass
181
-
182
- # Apply patch
183
- content = content.replace(original_import, patched_import)
184
- with open(model_file, 'w') as f:
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
185
  f.write(content)
186
- print(f"✅ Patched DeepSeek model for M4 Mac compatibility")
 
 
 
 
 
 
 
 
187
  except Exception as e:
188
- print(f"⚠️ Could not patch model file: {e}")
 
 
189
 
190
 
191
  async def get_ocr_model():
192
- """Lazy load DeepSeek-OCR model with M4 Mac compatibility patching"""
193
  global _ocr_model, _ocr_tokenizer
194
  if _ocr_model is None or _ocr_tokenizer is None:
195
  async with _model_lock:
196
  if _ocr_model is None or _ocr_tokenizer is None:
197
- # Patch DeepSeek model code for M4 Mac compatibility BEFORE loading
198
- _patch_deepseek_model_for_m4()
 
199
 
200
  # Lazy import dependencies
201
  AutoModel, AutoTokenizer = _get_transformers()
@@ -208,21 +267,18 @@ async def get_ocr_model():
208
  _ocr_tokenizer = AutoTokenizer.from_pretrained(
209
  MODEL_NAME, trust_remote_code=True
210
  )
211
- # Load model with Apple Silicon (M4) optimized settings
212
- # M4 Mac: Use SDPA (not flash_attention_2) - flash attention doesn't work on Apple Silicon
213
  load_kwargs = {
214
  "trust_remote_code": True,
215
- "use_safetensors": False, # Avoid safetensors issues on M4
 
216
  }
217
 
218
- # Force SDPA attention for Apple Silicon compatibility
219
- # This avoids LlamaFlashAttention2 import errors on M4 Mac
220
  if IS_APPLE_SILICON:
221
- load_kwargs["_attn_implementation"] = "sdpa"
222
  print(" - Using SDPA attention (Apple Silicon/M4 optimized)")
223
  else:
224
- # For non-Apple Silicon, let model choose
225
- pass
226
 
227
  try:
228
  _ocr_model = AutoModel.from_pretrained(MODEL_NAME, **load_kwargs)
@@ -649,7 +705,13 @@ async def ocr_options():
649
  """Handle CORS preflight requests (required by HuggingFace Spaces)"""
650
  return {"message": "OK"}
651
 
 
 
 
 
 
652
  @app.post("/ocr")
 
653
  async def ocr_page(
654
  file: UploadFile,
655
  _: None = Depends(enforce_rate_limit),
 
126
  _model_lock = asyncio.Lock()
127
 
128
 
129
+ def _patch_deepseek_model_for_compatibility():
130
  """
131
+ Patch DeepSeek-OCR model code to fix LlamaFlashAttention2 import error.
132
+ Works on HuggingFace Spaces (CPU) and M4 Macs (Apple Silicon).
133
+ Tries multiple cache locations and handles permission errors gracefully.
134
  """
135
  from pathlib import Path
136
+ import os
137
 
138
+ # Try multiple cache locations (HuggingFace Spaces uses different paths)
139
+ possible_cache_dirs = [
140
+ Path.home() / ".cache" / "huggingface",
141
+ Path("/home/user/.cache/huggingface"), # HuggingFace Spaces default
142
+ Path(os.getenv("HF_HOME", "")) / ".cache" / "huggingface" if os.getenv("HF_HOME") else None,
143
+ Path(os.getenv("TRANSFORMERS_CACHE", "")) / "hub" if os.getenv("TRANSFORMERS_CACHE") else None,
144
+ ]
145
+
146
+ model_files = []
147
+ for cache_dir in possible_cache_dirs:
148
+ if cache_dir and cache_dir.exists():
149
+ try:
150
+ found = list(cache_dir.glob("**/modeling_deepseekv2.py"))
151
+ model_files.extend(found)
152
+ except Exception:
153
+ continue
154
 
155
  if not model_files:
156
+ print("⚠️ Model file not found yet - will patch on first model load")
157
  return # Model not downloaded yet, will patch on first load
158
 
159
  model_file = model_files[0]
160
+ print(f"🔍 Found model file: {model_file}")
161
 
162
  # Check if already patched
163
  try:
164
+ with open(model_file, 'r', encoding='utf-8') as f:
165
  content = f.read()
166
  if "LlamaFlashAttention2 = LlamaAttention" in content:
167
+ print("✅ Model already patched")
168
  return # Already patched
169
+ except Exception as e:
170
+ print(f"⚠️ Could not read model file to check patch status: {e}")
171
+ return
172
 
173
+ # Original import patterns (try multiple variations)
174
+ original_patterns = [
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
  # Patched version with fallback
184
  patched_import = """from transformers.models.llama.modeling_llama import (
185
  LlamaAttention,
186
+ )
187
+ # Patch: LlamaFlashAttention2 not available in transformers <5.0.0
188
  # Use LlamaAttention as fallback when flash attention unavailable
189
  try:
190
  from transformers.models.llama.modeling_llama import LlamaFlashAttention2
 
192
  # Fallback: Use LlamaAttention when flash attention not available
193
  LlamaFlashAttention2 = LlamaAttention"""
194
 
195
+ patched_single_import = """# Patch: LlamaFlashAttention2 import with fallback
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(f"🔧 Applied patch pattern (multiline={is_multiline})")
229
+ break
230
+
231
+ if patched:
232
+ with open(model_file, 'w', encoding='utf-8') as f:
233
  f.write(content)
234
+ print(f"✅ Successfully patched DeepSeek model file: {model_file}")
235
+ else:
236
+ print(f"⚠️ Could not find import pattern to patch in {model_file}")
237
+ print(f" File size: {len(content)} chars, first 500 chars:")
238
+ print(content[:500])
239
+ except PermissionError as e:
240
+ print(f"❌ Permission denied - cannot patch model file: {e}")
241
+ print(f" File: {model_file}")
242
+ print(f" Try running with write permissions or patch manually")
243
  except Exception as e:
244
+ print(f"⚠️ Could not patch model file {model_file}: {e}")
245
+ import traceback
246
+ traceback.print_exc()
247
 
248
 
249
  async def get_ocr_model():
250
+ """Lazy load DeepSeek-OCR model with compatibility patching"""
251
  global _ocr_model, _ocr_tokenizer
252
  if _ocr_model is None or _ocr_tokenizer is None:
253
  async with _model_lock:
254
  if _ocr_model is None or _ocr_tokenizer is None:
255
+ # Patch DeepSeek model code for compatibility BEFORE loading
256
+ # Works on HuggingFace Spaces (CPU) and M4 Macs (Apple Silicon)
257
+ _patch_deepseek_model_for_compatibility()
258
 
259
  # Lazy import dependencies
260
  AutoModel, AutoTokenizer = _get_transformers()
 
267
  _ocr_tokenizer = AutoTokenizer.from_pretrained(
268
  MODEL_NAME, trust_remote_code=True
269
  )
270
+ # Load model with compatibility settings
271
+ # Use SDPA attention to avoid LlamaFlashAttention2 import errors
272
  load_kwargs = {
273
  "trust_remote_code": True,
274
+ "use_safetensors": False, # Avoid safetensors issues
275
+ "_attn_implementation": "sdpa", # Force SDPA (works on HuggingFace Spaces and Apple Silicon)
276
  }
277
 
 
 
278
  if IS_APPLE_SILICON:
 
279
  print(" - Using SDPA attention (Apple Silicon/M4 optimized)")
280
  else:
281
+ print(" - Using SDPA attention (HuggingFace Spaces/CPU optimized)")
 
282
 
283
  try:
284
  _ocr_model = AutoModel.from_pretrained(MODEL_NAME, **load_kwargs)
 
705
  """Handle CORS preflight requests (required by HuggingFace Spaces)"""
706
  return {"message": "OK"}
707
 
708
+ @app.options("/api/predict")
709
+ async def predict_options():
710
+ """Handle CORS preflight for HuggingFace Spaces auto-routing"""
711
+ return {"message": "OK"}
712
+
713
  @app.post("/ocr")
714
+ @app.post("/api/predict") # HuggingFace Spaces may auto-route POST requests here
715
  async def ocr_page(
716
  file: UploadFile,
717
  _: None = Depends(enforce_rate_limit),