-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathocr_utils.py
More file actions
906 lines (772 loc) · 31.8 KB
/
Copy pathocr_utils.py
File metadata and controls
906 lines (772 loc) · 31.8 KB
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
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
"""
OCR utilities: Ollama/GLM, Mistral, Vision LLM, Groq, OpenRouter, and master dispatcher.
"""
from __future__ import annotations
import base64
import json
import logging
import mimetypes
import os
import tempfile
from collections.abc import Iterator
from typing import Any
import requests
from config import API_KEYS
logger = logging.getLogger(__name__)
_noop_progress = lambda *_a, **_kw: None
def run_ollama_ocr(filepath: str, model: str, host: str, progress: Any = None) -> Iterator[str]:
"""
Runs GLM-OCR via Ollama.
The Go backend handles resizing, so we just send the raw image.
"""
if progress is None:
progress = _noop_progress
logger.info(
"[OCR-GLM] run_ollama_ocr | file=%s | model=%s | host=%s",
os.path.basename(filepath),
model,
host,
)
# 1. Encode Image
progress(0.2, desc="Lade Bild...")
yield f"🔄 Lade Bild: {os.path.basename(filepath)}...\n\n"
try:
file_size = os.path.getsize(filepath) / (1024 * 1024)
with open(filepath, "rb") as f:
b64_img = base64.b64encode(f.read()).decode("utf-8")
logger.debug("[OCR-GLM] Image encoded: %.2f MB → %d base64 chars", file_size, len(b64_img))
except Exception as e:
logger.error("[OCR-GLM] Read error: %s", e)
yield f"❌ Lesefehler: {e}"
return
# 2. Setup Request
if not host.startswith("http"):
host = f"http://{host}"
url = f"{host}/api/chat"
payload = {
"model": model or "glm-ocr:q8_0",
"messages": [{"role": "user", "content": "Text Recognition:", "images": [b64_img]}],
"stream": True,
}
progress(0.4, desc=f"Sende an Ollama ({model})...")
yield f"🔄 Sende an Ollama ({model}) — Bitte warten, dies kann einige Sekunden dauern...\n\n"
logger.info(
"[OCR-GLM] Sending request to %s (model=%s, payload_size=%.2f MB)",
url,
model,
len(b64_img) * 3 / 4 / (1024 * 1024),
)
try:
with requests.post(url, json=payload, stream=True, timeout=300) as r:
logger.info("[OCR-GLM] Response status=%d", r.status_code)
r.raise_for_status()
full_text = ""
token_count = 0
for line in r.iter_lines():
if line:
body = json.loads(line)
if "message" in body and "content" in body["message"]:
chunk = body["message"]["content"]
full_text += chunk
token_count += 1
yield full_text
if body.get("done"):
eval_duration = body.get("eval_duration", 0) / 1e9
logger.info(
"[OCR-GLM] Done | tokens=%d | time=%.1fs | chars=%d",
token_count,
eval_duration,
len(full_text),
)
break
progress(1.0, desc="Fertig!")
except Exception as e:
logger.error("[OCR-GLM] Ollama API error: %s | host=%s", e, host, exc_info=True)
yield f"❌ Ollama API Fehler: {e!s}\nHost: {host}"
def run_mistral_ocr(
filepath: str, api_key: str, max_images: int = 10, progress: Any = None
) -> Iterator[str]:
"""
Uses Mistral's specialized OCR API with STREAMING results.
"""
if progress is None:
progress = _noop_progress
logger.info(
"[OCR-Mistral] Starting | file=%s | max_images=%d | key_present=%s",
os.path.basename(filepath),
max_images,
bool(api_key),
)
if not api_key:
logger.error("[OCR-Mistral] API key missing")
yield "❌ Fehler: Mistral API Key fehlt."
return
progress(0.1, desc="Bereite Datei vor...")
yield "🔄 Bereite Datei vor...\n\n"
url = "https://api.mistral.ai/v1/ocr"
headers = {"Authorization": f"Bearer {api_key}", "Content-Type": "application/json"}
mime_type, _ = mimetypes.guess_type(filepath)
if not mime_type:
ext = os.path.splitext(filepath)[1].lower()
if ext == ".pdf":
mime_type = "application/pdf"
elif ext in [".png", ".jpg", ".jpeg"]:
mime_type = "image/jpeg"
else:
yield f"❌ Dateityp nicht unterstützt: {ext}"
return
progress(0.3, desc="Lade Datei...")
yield "🔄 Lade Datei...\n\n"
try:
with open(filepath, "rb") as f:
encoded_string = base64.b64encode(f.read()).decode("utf-8")
except Exception as e:
yield f"❌ Fehler beim Lesen der Datei: {e}"
return
payload = {"model": "mistral-ocr-latest", "document": {}}
if "pdf" in mime_type:
payload["document"] = {
"type": "document_url",
"document_url": f"data:application/pdf;base64,{encoded_string}",
}
elif "image" in mime_type:
payload["document"] = {
"type": "image_url",
"image_url": f"data:{mime_type};base64,{encoded_string}",
}
else:
yield f"❌ Mistral OCR unterstützt nur Bilder und PDFs (Erkannt: {mime_type})"
return
progress(0.5, desc="Sende an Mistral OCR API...")
yield "🔄 Sende an Mistral OCR API...\n\n"
logger.info(
"[OCR-Mistral] Sending request | mime=%s | file=%s", mime_type, os.path.basename(filepath)
)
try:
response = requests.post(url, headers=headers, json=payload, timeout=120)
logger.info(
"[OCR-Mistral] Response status=%d | file=%s",
response.status_code,
os.path.basename(filepath),
)
if response.status_code != 200:
logger.error("[OCR-Mistral] Error %d: %s", response.status_code, response.text[:500])
yield f"❌ Mistral OCR Error {response.status_code}: {response.text}"
return
progress(0.8, desc="Verarbeite Antwort...")
yield "🔄 Verarbeite Antwort...\n\n"
data = response.json()
full_text = []
pages = data.get("pages", [])
total_pages = len(pages)
logger.info(
"[OCR-Mistral] Response parsed: %d total pages | processing up to %d",
total_pages,
max_images,
)
for idx, page in enumerate(pages[:max_images]):
md = page.get("markdown", "")
logger.debug("[OCR-Mistral] Page %d/%d: %d chars", idx + 1, total_pages, len(md))
full_text.append(md)
progress(
0.8 + (0.2 * (idx + 1) / min(total_pages, max_images)),
desc=f"Verarbeite Seite {idx + 1}/{min(total_pages, max_images)}",
)
yield "\n\n---\n\n".join(full_text)
progress(1.0, desc="Fertig!")
result = "\n\n---\n\n".join(full_text)
if total_pages > max_images:
result += f"\n\n---\n\n**ℹ️ Hinweis:** Nur die ersten {max_images} von {total_pages} Seiten wurden verarbeitet."
logger.info(
"[OCR-Mistral] Done | total_chars=%d | pages_processed=%d",
len(result),
min(total_pages, max_images),
)
yield result
except Exception as e:
logger.error("[OCR-Mistral] Connection error: %s", e, exc_info=True)
yield f"❌ Connection Error: {e}"
def run_ocr_vision_llm(
filepath: str,
provider: str,
model: str,
api_key: str,
max_images: int = 10,
progress: Any = None,
) -> Iterator[str]:
"""
Generic Vision LLM - Iterates through PDF pages with STREAMING results.
"""
if progress is None:
progress = _noop_progress
from chat import UniversalExtractor
from image_gen_utils import run_vision
progress(0, desc="Konvertiere Datei...")
yield "🔄 Konvertiere Datei in Bilder...\n\n"
images = UniversalExtractor.get_images_from_file(filepath, max_images=max_images)
if not images:
yield "❌ Konnte Datei nicht in Bilder umwandeln."
return
full_text = []
for i, (mime, b64) in enumerate(images):
page_num = i + 1
progress(i / len(images), desc=f"Vision OCR: Seite {page_num}/{len(images)}")
ext = ".jpg" if "jpeg" in mime else ".png"
with tempfile.NamedTemporaryFile(suffix=ext, delete=False) as tmp:
tmp.write(base64.b64decode(b64))
tmp_path = tmp.name
try:
ocr_prompt = (
"Transcribe the text in this image exactly. Do not chat. Output only Markdown."
)
dummy_state = {"id": "ocr", "is_admin": True}
page_text = run_vision(tmp_path, ocr_prompt, provider, model, api_key, 0, dummy_state)
page_result = f"## Seite {page_num}\n{page_text}"
full_text.append(page_result)
yield "\n\n---\n\n".join(full_text)
except Exception as e:
page_result = f"## Seite {page_num}\n[Fehler: {e}]"
full_text.append(page_result)
yield "\n\n---\n\n".join(full_text)
finally:
if os.path.exists(tmp_path):
os.remove(tmp_path)
progress(1.0, desc="Fertig!")
final_result = "\n\n---\n\n".join(full_text)
if len(images) == max_images:
final_result += (
f"\n\n---\n\n**ℹ️ Hinweis:** Nur die ersten {max_images} Seiten wurden verarbeitet."
)
yield final_result
def run_groq_ocr(
filepath: str, model: str, api_key: str, max_images: int = 10, progress: Any = None
) -> Iterator[str]:
"""
Uses Groq's Llama 4 Vision models with STREAMING results.
LIMITS: Base64 images max 4MB per image.
Now supports PDFs by converting to images first.
"""
if progress is None:
progress = _noop_progress
from chat import UniversalExtractor
if not api_key:
yield "❌ Fehler: Groq API Key fehlt."
return
url = "https://api.groq.com/openai/v1/chat/completions"
headers = {"Authorization": f"Bearer {api_key}", "Content-Type": "application/json"}
mime_type, _ = mimetypes.guess_type(filepath)
ext = os.path.splitext(filepath)[1].lower()
if ext == ".pdf":
logger.info("Groq: Converting PDF to images for processing...")
progress(0, desc="PDF wird in Bilder konvertiert...")
yield "🔄 PDF wird in Bilder konvertiert...\n\n"
images = UniversalExtractor.get_images_from_file(filepath, max_images=max_images)
if not images:
yield "❌ Konnte PDF nicht in Bilder konvertieren."
return
full_text = []
total_pages = len(images)
for i, (img_mime, b64_img) in enumerate(images):
page_num = i + 1
progress((i / total_pages), desc=f"Groq OCR: Seite {page_num}/{total_pages}")
logger.info(f"Groq: Processing page {page_num}/{total_pages}")
img_size_mb = len(b64_img) * 3 / 4 / (1024 * 1024)
if img_size_mb > 3.8:
page_result = (
f"## Seite {page_num}\n[⚠️ Übersprungen: Zu groß ({img_size_mb:.1f}MB)]"
)
full_text.append(page_result)
yield "\n\n---\n\n".join(full_text)
continue
payload = {
"model": model,
"messages": [
{
"role": "user",
"content": [
{
"type": "text",
"text": "Extract all text from this image. Preserve formatting using Markdown.",
},
{
"type": "image_url",
"image_url": {"url": f"data:{img_mime};base64,{b64_img}"},
},
],
}
],
"temperature": 0.1,
}
try:
resp = requests.post(url, headers=headers, json=payload, timeout=60)
if resp.status_code != 200:
page_result = f"## Seite {page_num}\n[❌ Error {resp.status_code}]"
full_text.append(page_result)
yield "\n\n---\n\n".join(full_text)
continue
result = resp.json()
page_text = result["choices"][0]["message"]["content"]
page_result = f"## Seite {page_num}\n{page_text}"
full_text.append(page_result)
yield "\n\n---\n\n".join(full_text)
except Exception as e:
page_result = f"## Seite {page_num}\n[❌ Fehler: {e!s}]"
full_text.append(page_result)
yield "\n\n---\n\n".join(full_text)
progress(1.0, desc="Fertig!")
final_result = "\n\n---\n\n".join(full_text)
if len(images) == max_images:
final_result += (
f"\n\n---\n\n**ℹ️ Hinweis:** Nur die ersten {max_images} Seiten wurden verarbeitet."
)
yield final_result
return
# Handle single images
progress(0.5, desc="Verarbeite Bild...")
yield "🔄 Verarbeite Bild...\n\n"
if not mime_type or not mime_type.startswith("image/"):
yield "❌ Groq Vision unterstützt nur Bilder und PDFs (JPG/PNG)."
return
file_size_mb = os.path.getsize(filepath) / (1024 * 1024)
if file_size_mb > 3.8:
yield f"❌ Datei zu groß für Groq Base64 ({file_size_mb:.1f}MB). Limit ist 4MB. Bitte Bild verkleinern."
return
try:
with open(filepath, "rb") as f:
b64_img = base64.b64encode(f.read()).decode("utf-8")
except Exception as e:
yield f"❌ Lesefehler: {e}"
return
payload = {
"model": model,
"messages": [
{
"role": "user",
"content": [
{
"type": "text",
"text": "Extract all text from this image. Preserve formatting (tables, headers) using Markdown.",
},
{
"type": "image_url",
"image_url": {"url": f"data:{mime_type};base64,{b64_img}"},
},
],
}
],
"temperature": 0.1,
}
try:
resp = requests.post(url, headers=headers, json=payload, timeout=60)
if resp.status_code != 200:
yield f"❌ Groq Error {resp.status_code}: {resp.text}"
return
result = resp.json()
progress(1.0, desc="Fertig!")
yield result["choices"][0]["message"]["content"]
except Exception as e:
yield f"❌ Groq Connection Error: {e}"
def run_openrouter_ocr(
filepath: str, model: str, pdf_engine: str, api_key: str, progress: Any = None
) -> Iterator[str]:
"""
Uses OpenRouter's 'file' support with STREAMING results.
"""
if progress is None:
progress = _noop_progress
if not api_key:
yield "❌ Fehler: OpenRouter API Key fehlt."
return
progress(0.1, desc="Bereite Datei vor...")
yield "🔄 Bereite Datei vor...\n\n"
url = "https://openrouter.ai/api/v1/chat/completions"
headers = {"Authorization": f"Bearer {api_key}", "Content-Type": "application/json"}
mime_type, _ = mimetypes.guess_type(filepath)
if not mime_type:
mime_type = "application/octet-stream"
progress(0.3, desc="Lade Datei...")
yield "🔄 Lade Datei...\n\n"
try:
with open(filepath, "rb") as f:
b64_data = base64.b64encode(f.read()).decode("utf-8")
except Exception as e:
yield f"❌ Lesefehler: {e}"
return
content = [
{
"type": "text",
"text": "Extract and transcribe the full content of this document perfectly into Markdown.",
}
]
if "pdf" in mime_type:
content.append(
{
"type": "file",
"file": {
"filename": os.path.basename(filepath),
"file_data": f"data:application/pdf;base64,{b64_data}",
},
}
)
elif mime_type.startswith("image/"):
content.append(
{"type": "image_url", "image_url": {"url": f"data:{mime_type};base64,{b64_data}"}}
)
else:
yield f"❌ OpenRouter OCR unterstützt nur PDF und Bilder (Typ: {mime_type})"
return
plugins = []
if "pdf" in mime_type:
plugins.append({"id": "file-parser", "pdf": {"engine": pdf_engine}})
payload = {
"model": model,
"messages": [{"role": "user", "content": content}],
"plugins": plugins,
}
progress(0.5, desc=f"Sende an OpenRouter ({pdf_engine})...")
yield f"🔄 Sende an OpenRouter ({pdf_engine})...\n\n"
try:
resp = requests.post(url, headers=headers, json=payload, timeout=120)
if resp.status_code != 200:
yield f"❌ OpenRouter Error {resp.status_code}: {resp.text}"
return
progress(0.9, desc="Verarbeite Antwort...")
yield "🔄 Verarbeite Antwort...\n\n"
result = resp.json()
if "error" in result:
yield f"❌ API Error: {result['error']}"
return
progress(1.0, desc="Fertig!")
yield result["choices"][0]["message"]["content"]
except Exception as e:
yield f"❌ OpenRouter Connection Error: {e}"
def run_ocr(
filepath: str | None,
engine: str,
vision_provider: str,
vision_model: str,
groq_model: str,
or_model: str,
or_engine: str,
max_images: int | str | None,
user_state: dict | None,
progress: Any = None,
) -> Iterator[str]:
"""
Master Dispatcher for OCR with STREAMING support
"""
if progress is None:
progress = _noop_progress
from chat import UniversalExtractor
# ── Auth ──────────────────────────────────────────────────────────
_uid = (user_state or {}).get("id")
_uname = (user_state or {}).get("username", "?")
logger.info(
"[OCR] run_ocr called — user_id=%s username=%s engine=%r filepath=%r",
_uid,
_uname,
engine,
filepath,
)
logger.debug("[OCR] user_state keys: %s", list((user_state or {}).keys()))
if not user_state or not user_state.get("id"):
logger.warning("[OCR] ⛔ Auth failed — user_state=%r", user_state)
yield "⛔ Nicht autorisiert. Bitte anmelden und Seite neu laden."
return
if not filepath:
logger.warning("[OCR] No filepath provided for user_id=%s", _uid)
yield "❌ Keine Datei ausgewählt."
return
try:
max_images = int(max_images) if max_images else 10
max_images = max(1, min(1000, max_images))
except (ValueError, TypeError):
max_images = 10
logger.warning("[OCR] Invalid max_images value, using default: 10")
file_size_mb = os.path.getsize(filepath) / (1024 * 1024) if os.path.exists(filepath) else 0
mime_type, _ = mimetypes.guess_type(filepath)
logger.info(
"[OCR] File: %s | size=%.2f MB | mime=%s | max_images=%d | engine=%r",
os.path.basename(filepath),
file_size_mb,
mime_type,
max_images,
engine,
)
# Immediate feedback so the UI shows something right away
yield f"🔄 Starte OCR mit **{engine}** — {os.path.basename(filepath)} ({file_size_mb:.1f} MB)...\n\n"
# NOTE: "Standard (lokal)" check must NOT use `"lokal" in engine` because
# "GLM-OCR (lokal)" also contains "lokal" and would be mis-routed here.
if "Standard" in engine:
logger.info(
"[OCR] Engine=Standard/local | user_id=%s | file=%s", _uid, os.path.basename(filepath)
)
progress(0.3, desc="Lokale Extraktion läuft...")
yield "🔄 Lokale Extraktion (Tesseract/ebook-convert) läuft...\n\n"
result = UniversalExtractor.extract(filepath, max_images=max_images)
logger.info("[OCR] Standard extraction done — result length=%d chars", len(result))
progress(1.0, desc="Fertig!")
yield result
return
if engine == "CrispEmbed (lokal)":
logger.info(
"[OCR] Engine=CrispEmbed | user_id=%s | file=%s", _uid, os.path.basename(filepath)
)
progress(0.2, desc="CrispEmbed OCR läuft...")
yield "🔄 CrispEmbed OCR (DBNet + TrOCR) läuft...\n\n"
try:
from crispembed_tool import crispembed_available, run_general_ocr
if not crispembed_available():
yield "❌ CrispEmbed binary nicht gefunden. Setze CRISPEMBED_PATH oder CRISPEMBED_EXECUTABLE."
return
# Use user-selected models if provided
_ce_det = (user_state or {}).get("_crispembed_det_model", "")
_ce_rec = (user_state or {}).get("_crispembed_rec_model", "")
# Override model discovery if user selected specific models
if _ce_det or _ce_rec:
os.environ["_CE_DET_OVERRIDE"] = _ce_det
os.environ["_CE_REC_OVERRIDE"] = _ce_rec
status, results = run_general_ocr(filepath)
if not results:
yield f"❌ {status}"
return
progress(0.9, desc="Ergebnisse formatieren...")
text_parts = [r["text"] for r in results]
full_text = "\n".join(text_parts)
yield f"✅ {status}\n\n---\n\n{full_text}"
except Exception as e:
logger.exception(f"[OCR] CrispEmbed error: {e}")
yield f"❌ CrispEmbed OCR Fehler: {e!s}"
return
if "CrispEmbed-HTTP" in engine:
logger.info(
"[OCR] Engine=CrispEmbed-HTTP | user_id=%s | file=%s", _uid, os.path.basename(filepath)
)
progress(0.2, desc="CrispEmbed-HTTP OCR läuft...")
yield "🔄 CrispEmbed-HTTP OCR läuft...\n\n"
try:
from crispembed_tool import run_general_ocr_http
status, results = run_general_ocr_http(filepath)
if not results:
yield f"❌ {status}"
return
progress(0.9, desc="Ergebnisse formatieren...")
text_parts = [r["text"] for r in results]
full_text = "\n".join(text_parts)
yield f"✅ {status}\n\n---\n\n{full_text}"
except Exception as e:
logger.exception(f"[OCR] CrispEmbed-HTTP error: {e}")
yield f"❌ CrispEmbed-HTTP OCR Fehler: {e!s}"
return
if "Layout" in engine:
logger.info("[OCR] Engine=Layout | user_id=%s | file=%s", _uid, os.path.basename(filepath))
progress(0.2, desc="Layout-Analyse läuft...")
yield "🔄 Dokument-Layout-Analyse (RT-DETRv2) läuft...\n\n"
try:
from crispembed_tool import run_layout_detection
_layout_model = (user_state or {}).get("_layout_model", "rt-detrv2-layout-q8_0")
_layout_thresh = float((user_state or {}).get("_layout_threshold", 0.3))
status, regions = run_layout_detection(
filepath, model=_layout_model, threshold=_layout_thresh
)
if not regions:
yield f"❌ {status}"
return
progress(0.9, desc="Ergebnisse formatieren...")
# Format results as a readable table
lines = [f"✅ {status}\n"]
lines.append("| # | Region | Konfidenz | Position |")
lines.append("|---|--------|-----------|----------|")
for i, r in enumerate(regions, 1):
label = r.get("label", "?")
score = r.get("score", 0)
x1, y1 = int(r.get("x1", 0)), int(r.get("y1", 0))
x2, y2 = int(r.get("x2", 0)), int(r.get("y2", 0))
lines.append(f"| {i} | **{label}** | {score:.1%} | ({x1},{y1})–({x2},{y2}) |")
# Summary by type
from collections import Counter
counts = Counter(r.get("label", "?") for r in regions)
summary = ", ".join(f"{v}× {k}" for k, v in counts.most_common())
lines.append(f"\n**Zusammenfassung:** {summary}")
yield "\n".join(lines)
except Exception as e:
logger.exception(f"[OCR] Layout error: {e}")
yield f"❌ Layout-Analyse Fehler: {e!s}"
return
if "Mistral" in engine:
key = API_KEYS.get("MISTRAL", "")
logger.info(
"[OCR] Engine=Mistral | user_id=%s | key_present=%s | file=%s",
_uid,
bool(key),
os.path.basename(filepath),
)
if not key:
logger.error("[OCR] Mistral API key missing for user_id=%s", _uid)
yield "❌ Mistral API Key fehlt."
return
for update in run_mistral_ocr(filepath, key, max_images, progress):
yield update
return
if "Groq" in engine:
key = API_KEYS.get("GROQ", "")
logger.info(
"[OCR] Engine=Groq | user_id=%s | model=%r | key_present=%s | file=%s",
_uid,
groq_model,
bool(key),
os.path.basename(filepath),
)
if not key:
logger.error("[OCR] Groq API key missing for user_id=%s", _uid)
yield "❌ Groq API Key fehlt."
return
for update in run_groq_ocr(filepath, groq_model, key, max_images, progress):
yield update
return
if "OpenRouter" in engine:
key = API_KEYS.get("OPENROUTER", "")
logger.info(
"[OCR] Engine=OpenRouter | user_id=%s | model=%r | pdf_engine=%r | key_present=%s | file=%s",
_uid,
or_model,
or_engine,
bool(key),
os.path.basename(filepath),
)
if not key:
logger.error("[OCR] OpenRouter API key missing for user_id=%s", _uid)
yield "❌ OpenRouter API Key fehlt."
return
for update in run_openrouter_ocr(filepath, or_model, or_engine, key, progress):
yield update
return
if "Vision" in engine:
try:
from config import PROVIDERS
prov_config = PROVIDERS.get(vision_provider, {})
key = API_KEYS.get(prov_config.get("key_name", ""), "")
logger.info(
"[OCR] Engine=Vision LLM | user_id=%s | provider=%r | model=%r | key_present=%s | file=%s",
_uid,
vision_provider,
vision_model,
bool(key),
os.path.basename(filepath),
)
if not key:
logger.error(
"[OCR] Vision LLM API key missing for provider=%r user_id=%s",
vision_provider,
_uid,
)
yield f"❌ API Key für {vision_provider} fehlt."
return
for update in run_ocr_vision_llm(
filepath, vision_provider, vision_model, key, max_images, progress
):
yield update
return
except Exception as e:
logger.error("[OCR] Vision LLM error for user_id=%s: %s", _uid, e, exc_info=True)
yield f"❌ Vision LLM Fehler: {e!s}"
return
if "Math OCR" in engine:
logger.info(
"[OCR] Engine=MathOCR | user_id=%s | file=%s", _uid, os.path.basename(filepath)
)
ext = os.path.splitext(filepath)[1].lower()
if ext not in (".png", ".jpg", ".jpeg", ".bmp", ".tiff", ".webp"):
yield "❌ Math OCR unterstützt nur Bilddateien (PNG, JPG, BMP, TIFF, WEBP)."
return
progress(0.3, desc="Math OCR läuft...")
yield "🔄 Formel-Erkennung läuft...\n\n"
from crispembed_tool import run_math_ocr
status_msg, latex = run_math_ocr(filepath)
logger.info("[OCR] MathOCR done — status=%s latex_len=%d", status_msg, len(latex))
progress(1.0, desc="Fertig!")
if not latex:
yield f"❌ {status_msg}"
return
# Render LaTeX result with preview
yield (
f"### Erkannte Formel\n\n"
f"**LaTeX:**\n```latex\n{latex}\n```\n\n"
f"**Vorschau:** $${latex}$$\n\n"
f"*{status_msg}*"
)
return
if "GLM" in engine:
ollama_host = "http://localhost:11434"
ollama_model = "glm-ocr:q8_0"
ext = os.path.splitext(filepath)[1].lower()
logger.info(
"[OCR] Engine=GLM/Ollama | user_id=%s | host=%s | model=%s | ext=%s | file=%s",
_uid,
ollama_host,
ollama_model,
ext,
os.path.basename(filepath),
)
# Test Ollama reachability before starting
try:
import requests as _req
_ping = _req.get(f"{ollama_host}/api/tags", timeout=3)
logger.info(
"[OCR] GLM: Ollama reachable (status=%d), checking model list...", _ping.status_code
)
_tags = _ping.json().get("models", [])
_model_names = [m.get("name", "") for m in _tags]
logger.info("[OCR] GLM: Available Ollama models: %s", _model_names)
if not any(ollama_model in n for n in _model_names):
logger.warning(
"[OCR] GLM: model %r not found in Ollama. Available: %s",
ollama_model,
_model_names,
)
yield (
f"⚠️ Modell `{ollama_model}` nicht in Ollama gefunden.\n"
f"Verfügbare Modelle: {', '.join(_model_names) or '(keine)'}\n\n"
f"Bitte mit `ollama pull {ollama_model}` laden."
)
return
except Exception as ping_err:
logger.error("[OCR] GLM: Ollama not reachable at %s — %s", ollama_host, ping_err)
yield f"❌ Ollama nicht erreichbar unter {ollama_host}: {ping_err}"
return
if ext == ".pdf":
logger.info("[OCR] GLM: converting PDF to images (max_images=%d)", max_images)
yield "🔄 PDF wird in Bilder konvertiert...\n\n"
images = UniversalExtractor.get_images_from_file(filepath, max_images=max_images)
if not images:
logger.error("[OCR] GLM: PDF-to-image conversion failed for user_id=%s", _uid)
yield "❌ PDF konnte nicht in Bilder umgewandelt werden."
return
logger.info("[OCR] GLM: PDF converted → %d page(s)", len(images))
full_res: list[str] = []
for i, (_, b64) in enumerate(images):
with tempfile.NamedTemporaryFile(suffix=".png", delete=False) as tmp:
tmp.write(base64.b64decode(b64))
tpath = tmp.name
logger.debug("[OCR] GLM: processing page %d/%d (tmp=%s)", i + 1, len(images), tpath)
progress(i / len(images), desc=f"GLM-OCR: Seite {i + 1}/{len(images)}")
yield f"🔄 GLM-OCR: Seite {i + 1}/{len(images)}...\n\n" + "\n\n---\n\n".join(
full_res
)
page_text = ""
for chunk in run_ollama_ocr(tpath, ollama_model, ollama_host, progress):
page_text = chunk
logger.debug("[OCR] GLM: page %d done — %d chars", i + 1, len(page_text))
full_res.append(f"## Seite {i + 1}\n{page_text}")
os.remove(tpath)
logger.info("[OCR] GLM: all %d pages done", len(images))
progress(1.0, desc="Fertig!")
yield "\n\n---\n\n".join(full_res)
return
else:
logger.info("[OCR] GLM: processing single image file")
for update in run_ollama_ocr(filepath, ollama_model, ollama_host, progress):
yield update
return
logger.error("[OCR] Unknown engine %r for user_id=%s", engine, _uid)
yield f"❌ Unbekannte Engine: {engine!r}"