-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathkeepsync_ocr.py
More file actions
48 lines (39 loc) · 1.2 KB
/
Copy pathkeepsync_ocr.py
File metadata and controls
48 lines (39 loc) · 1.2 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
"""Optional OCR for image attachments via Tesseract."""
from pathlib import Path
from typing import List, Optional
from keepsync_models import Attachment, Note
try:
import pytesseract
from PIL import Image
OCR_AVAILABLE = True
except ImportError:
pytesseract = None
OCR_AVAILABLE = False
def ocr_image(path: str, lang: str = "eng") -> str:
if not OCR_AVAILABLE:
return ""
source = Path(path)
if not source.exists():
return ""
try:
img = Image.open(source)
text = pytesseract.image_to_string(img, lang=lang)
return (text or "").strip()
except Exception:
return ""
def ocr_note_attachments(note: Note, lang: str = "eng") -> List[str]:
results = []
for attachment in note.attachments:
if not attachment.is_image:
continue
text = ocr_image(attachment.stored_path, lang=lang)
if text:
results.append(text)
return results
def append_ocr_text(note: Note, ocr_texts: List[str]) -> Note:
if not ocr_texts:
return note
block = "\n\n---\n[OCR]\n" + "\n---\n".join(ocr_texts)
note.content = (note.content or "") + block
note.update_hash()
return note