Skip to content

Commit aa30909

Browse files
authored
Merge pull request CogStack/ocr-service#27 from CogStack/implementation_modern
Updating general implementation (XML file handling + other adaptations)
2 parents 0b97b54 + b3f2b75 commit aa30909

13 files changed

Lines changed: 698 additions & 41 deletions

File tree

‎apps/ocr-service/Dockerfile‎

Lines changed: 3 additions & 4 deletions
Original file line numberDiff line numberDiff line change
@@ -84,11 +84,11 @@ RUN apt-get -y --no-install-recommends -o Dpkg::Options::="--force-confold" -y -
8484
##### utils for python and TESSERACT
8585
RUN echo "ttf-mscorefonts-installer msttcorefonts/accepted-mscorefonts-eula select true" | debconf-set-selections
8686

87-
RUN apt-get install -y --no-install-recommends fontconfig ttf-mscorefonts-installer libimage-exiftool-perl libtcnative-1 \
87+
RUN apt-get update && apt-get install -y --no-install-recommends fontconfig ttf-mscorefonts-installer libimage-exiftool-perl libtcnative-1 \
8888
libsm6 libxext6 gstreamer1.0-libav fonts-deva fonts-dejavu fonts-gfs-didot fonts-gfs-didot-classic fonts-junicode fonts-ebgaramond fonts-noto-cjk fonts-takao-gothic fonts-vlgothic \
8989
ghostscript ghostscript-x gsfonts gsfonts-other gsfonts-x11 fonts-croscore fonts-crosextra-caladea fonts-crosextra-carlito fonts-liberation fonts-open-sans fonts-noto-core fonts-ibm-plex fonts-urw-base35 \
9090
fonts-noto fonts-noto-cjk fonts-noto-extra xfonts-terminus fonts-font-awesome fonts-hack fonts-inconsolata fonts-liberation2 fonts-mononoki \
91-
libpcre3 libpcre3-dev \
91+
libpcre3 libpcre3-dev libxml2 libxml2-dev libxslt1.1 libxslt-dev \
9292
mesa-opencl-icd pocl-opencl-icd libvips-tools libvips libvips-dev \
9393
imagemagick libcairo2-dev tesseract-ocr tesseract-ocr-all libtesseract5 libtesseract-dev libleptonica-dev liblept5
9494

@@ -168,5 +168,4 @@ RUN groupadd --system --gid "$OCR_SERVICE_GID" ocrsvc && \
168168
ENV HOME=/home/ocrsvc
169169
USER ocrsvc
170170

171-
# Now run the simple api
172-
CMD ["/bin/bash", "start_service_production.sh"]
171+
CMD ["./start_service_production.sh"]

‎apps/ocr-service/Makefile‎

Lines changed: 24 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,24 @@
1+
SHELL := /usr/bin/env bash
2+
.SHELLFLAGS := -o pipefail -c
3+
4+
HELM_RELEASE ?= ocr-service
5+
HELM_CHART ?= ./charts/ocr-service
6+
HELM_TEXT_ONLY_VALUES ?= ./charts/ocr-service/values-text-only.yaml
7+
HELM_ARGS ?=
8+
9+
.PHONY: helm-install helm-install-text-only helm-template helm-lint helm-uninstall
10+
11+
helm-install:
12+
helm upgrade --install $(HELM_RELEASE) $(HELM_CHART) $(HELM_ARGS)
13+
14+
helm-install-text-only:
15+
helm upgrade --install $(HELM_RELEASE) $(HELM_CHART) -f $(HELM_TEXT_ONLY_VALUES) $(HELM_ARGS)
16+
17+
helm-template:
18+
helm template $(HELM_RELEASE) $(HELM_CHART) $(HELM_ARGS)
19+
20+
helm-lint:
21+
helm lint $(HELM_CHART)
22+
23+
helm-uninstall:
24+
helm uninstall $(HELM_RELEASE) $(HELM_ARGS)

‎apps/ocr-service/export_env_vars.sh‎

100644100755
File mode changed.

‎apps/ocr-service/ocr_service/app/app.py‎

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -141,7 +141,7 @@ def create_app() -> FastAPI:
141141
global _started
142142

143143
try:
144-
app = FastAPI(title="OCR Service",
144+
app = FastAPI(title="OCR_Service",
145145
description="OCR Service API",
146146
version=settings.OCR_SERVICE_VERSION,
147147
default_response_class=ORJSONResponse,

‎apps/ocr-service/ocr_service/processor/converter.py‎

Lines changed: 117 additions & 16 deletions
Original file line numberDiff line numberDiff line change
@@ -3,9 +3,12 @@
33
import atexit
44
import multiprocessing
55
import os
6+
import re
67
import time
78
import traceback
89
import uuid
10+
import zipfile
11+
from html import unescape
912
from io import BytesIO
1013
from subprocess import PIPE, Popen
1114
from threading import Timer
@@ -19,12 +22,21 @@
1922

2023
from ocr_service.dto.process_context import ProcessContext
2124
from ocr_service.settings import settings
22-
from ocr_service.utils.utils import INPUT_FILTERS, delete_tmp_files, terminate_hanging_process
25+
from ocr_service.utils.utils import (
26+
INPUT_FILTERS,
27+
delete_tmp_files,
28+
is_encrypted_office_document,
29+
terminate_hanging_process,
30+
)
2331

2432
CURRENT_PDF_FILE: pdfium.PdfDocument | None = None
2533

2634

2735
class DocumentConverter:
36+
37+
MULTI_WHITESPACE = re.compile(r"[ \t]+")
38+
MULTI_NEWLINES = re.compile(r"\n{3,}")
39+
2840
def __init__(self, log, loffice_process_list: dict[str, Any]) -> None:
2941
self.log = log
3042
self.loffice_process_list = loffice_process_list
@@ -45,8 +57,15 @@ def resolve_content_type(file_type: object | None) -> str:
4557

4658
@staticmethod
4759
def finalize_output_text(output_text: str) -> str:
48-
output_text = output_text.translate({'\\n': '', '\\t': '', '\n\n': '\n'}) # type: ignore
49-
return str(output_text).encode("utf-8", errors="replace").decode("utf-8")
60+
61+
# normalize line endings
62+
output_text = output_text.replace("\r\n", "\n").replace("\r", "\n")
63+
# remove multiple whitespaces
64+
output_text = DocumentConverter.MULTI_WHITESPACE.sub(" ", output_text)
65+
# remove multiple new-lines
66+
output_text = DocumentConverter.MULTI_NEWLINES.sub("\n\n", output_text)
67+
68+
return output_text.encode("utf-8", errors="replace").decode("utf-8").strip()
5069

5170
def _extract_text_fallback(self,
5271
stream: bytes, *,
@@ -57,7 +76,7 @@ def _extract_text_fallback(self,
5776
text = ""
5877

5978
if is_html or is_xml:
60-
parser = "html.parser" if is_html else "xml"
79+
parser = "html.parser" if is_html else "lxml-xml"
6180
try:
6281
soup = BeautifulSoup(stream, parser)
6382
except Exception:
@@ -70,16 +89,34 @@ def _extract_text_fallback(self,
7089
else:
7190
text = soup.get_text(separator="\n")
7291

92+
# remove XML-ish self-closing tags
93+
text = re.sub(r"<[^>]+/>", "", text)
94+
# remove empty XML tags
95+
text = re.sub(r"</?[\w:.-]+>", "", text)
96+
7397
if not text and is_rtf:
7498
try:
7599
text = rtf_to_text(stream.decode("utf-8", "ignore"))
76100
except Exception:
77101
self.log.warning("Failed to parse RTF during fallback; using raw decode")
78102

79103
if not text:
80-
text = stream.decode("utf-8", "ignore")
104+
text = stream.decode("utf-8", "ignore")
105+
106+
return unescape(text)
81107

82-
return text.strip()
108+
def _extract_office_zip_text_fallback(self, stream: bytes, file_name: str) -> str:
109+
ext = os.path.splitext(file_name)[1].lower()
110+
xml_path = {".docx": "word/document.xml", ".odt": "content.xml"}.get(ext)
111+
if not xml_path:
112+
return ""
113+
114+
try:
115+
with zipfile.ZipFile(BytesIO(stream)) as archive:
116+
return self._extract_text_fallback(archive.read(xml_path), is_xml=True)
117+
except Exception:
118+
self.log.warning("Failed to extract %s from %s during fallback", xml_path, file_name)
119+
return ""
83120

84121
@staticmethod
85122
def initialize_pdf_worker(stream: bytes) -> None:
@@ -111,11 +148,14 @@ def render_page(page_num: int) -> Image.Image:
111148
crop=(0, 0, 0, 0),
112149
grayscale=settings.OCR_CONVERT_GRAYSCALE_IMAGES,
113150
).to_pil()
151+
152+
114153
page.close()
115154

116155
return img
117156

118157
def _pdf_to_img(self, stream: bytes) -> tuple[list[Image.Image], dict]:
158+
119159
pdf_image_pages = []
120160
doc_metadata: dict[str, Any] = {}
121161

@@ -351,6 +391,35 @@ def _xml_to_text(self, ctx: ProcessContext) -> str:
351391
return " ".join(parts)
352392

353393

394+
def _apply_text_fallback(
395+
self,
396+
ctx: ProcessContext,
397+
*,
398+
is_html: bool = False,
399+
is_xml: bool = False,
400+
is_rtf: bool = False,
401+
reason: str,
402+
) -> None:
403+
self.log.warning(
404+
"Falling back to text extraction for %s after %s",
405+
ctx.file_name,
406+
reason,
407+
)
408+
ctx.pdf_stream = b""
409+
ctx.images = []
410+
ctx.output_text = self._extract_office_zip_text_fallback(ctx.stream, ctx.file_name)
411+
if not ctx.output_text:
412+
ctx.output_text = self._extract_text_fallback(
413+
ctx.stream,
414+
is_html=is_html,
415+
is_xml=is_xml,
416+
is_rtf=is_rtf,
417+
)
418+
ctx.metadata["pages"] = 1
419+
ctx.metadata["content-type"] = "text/plain"
420+
ctx.metadata["fallback_reason"] = reason
421+
422+
354423
def _handle_pdf_stream(self, ctx: ProcessContext) -> None:
355424
if settings.OPERATION_MODE == "OCR":
356425
ctx.images, pdf_metadata = self._preprocess_pdf_to_img(ctx.pdf_stream)
@@ -364,11 +433,24 @@ def prepare(self, ctx: ProcessContext) -> None:
364433

365434
self.log.info("Checking file type for doc id: %s", ctx.file_name)
366435

436+
if is_encrypted_office_document(ctx.stream):
437+
self.log.warning(
438+
"Encrypted Office document detected for %s; skipping LibreOffice conversion",
439+
ctx.file_name,
440+
)
441+
ctx.metadata["content-type"] = "application/vnd.openxmlformats-officedocument"
442+
ctx.metadata["encrypted"] = True
443+
ctx.metadata["unsupported_reason"] = "encrypted_office_document"
444+
ctx.metadata["pages"] = 0
445+
return
446+
367447
_is_pdf = type(ctx.file_type) is archive.Pdf
368448
_is_rtf = type(ctx.file_type) is archive.Rtf or ctx.checks.is_rtf()
369449
_is_html = ctx.checks.is_html()
370450
_is_xml = ctx.checks.is_xml() and not _is_html
371451
_is_plain = ctx.checks.is_plain_text()
452+
_has_office_zip_fallback = os.path.splitext(ctx.file_name)[1].lower() in {".docx", ".odt"}
453+
text_fallback_allowed = _is_xml or _is_rtf or _has_office_zip_fallback
372454

373455
if _is_pdf:
374456
ctx.pdf_stream = ctx.stream
@@ -427,19 +509,38 @@ def prepare(self, ctx: ProcessContext) -> None:
427509
self.log.info("Unknown file type; attempting to convert to PDF via unoserver/LO")
428510
ctx.pdf_stream = self._preprocess_doc(ctx.stream, file_name=ctx.file_name)
429511

430-
if not ctx.pdf_stream and not ctx.output_text and ctx.checks.is_text_like():
431-
self.log.warning(
432-
"No PDF produced for %s; falling back to plain-text extraction",
433-
ctx.file_name,
434-
)
435-
ctx.output_text = self._extract_text_fallback(
436-
ctx.stream,
512+
if not ctx.pdf_stream and not ctx.output_text and (ctx.checks.is_text_like() or _has_office_zip_fallback):
513+
self._apply_text_fallback(
514+
ctx,
437515
is_html=_is_html,
438516
is_xml=_is_xml,
439517
is_rtf=_is_rtf,
518+
reason="no_pdf_produced",
440519
)
441-
ctx.metadata["pages"] = 1
442-
ctx.metadata["content-type"] = "text/plain"
443520

444521
if ctx.pdf_stream:
445-
self._handle_pdf_stream(ctx)
522+
try:
523+
self._handle_pdf_stream(ctx)
524+
except Exception:
525+
if not text_fallback_allowed:
526+
raise
527+
self.log.exception(
528+
"Converted PDF handling failed for %s; trying text fallback",
529+
ctx.file_name,
530+
)
531+
self._apply_text_fallback(
532+
ctx,
533+
is_html=_is_html,
534+
is_xml=_is_xml,
535+
is_rtf=_is_rtf,
536+
reason="converted_pdf_handling_failed",
537+
)
538+
else:
539+
if text_fallback_allowed and not ctx.output_text and not ctx.images:
540+
self._apply_text_fallback(
541+
ctx,
542+
is_html=_is_html,
543+
is_xml=_is_xml,
544+
is_rtf=_is_rtf,
545+
reason="converted_pdf_handling_failed",
546+
)

‎apps/ocr-service/ocr_service/processor/ocr_engine.py‎

Lines changed: 7 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -1,5 +1,6 @@
11
from __future__ import annotations
22

3+
from enum import Enum
34
import logging
45
import time
56
import traceback
@@ -11,11 +12,16 @@
1112
from ocr_service.settings import settings
1213

1314

15+
class OcrPipeline(str, Enum):
16+
TESSERACT = "tesseract"
17+
VLM = "vlm"
18+
MIXED = "mixed"
19+
20+
1421
class OcrEngine:
1522
def __init__(self, log: logging.Logger) -> None:
1623
self.log = log
1724

18-
1925
def _init_tesseract_api_worker(self) -> PyTessBaseAPI:
2026
tesseract_api = PyTessBaseAPI(path=settings.TESSDATA_PREFIX, lang=settings.TESSERACT_LANGUAGE) # type: ignore
2127
self.log.debug("Initialised pytesseract api worker for language:" + str(settings.TESSERACT_LANGUAGE))

‎apps/ocr-service/ocr_service/settings.py‎

Lines changed: 5 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -1,6 +1,7 @@
11
# mypy: disable-error-code=prop-decorator
22

33
import ast
4+
from enum import Enum
45
import logging
56
import multiprocessing
67
import os
@@ -89,6 +90,10 @@ def validate_lo_port_range(cls, value: str | None) -> str | None:
8990
return value
9091

9192
def model_post_init(self, __context: Any) -> None:
93+
"""
94+
Performs additional actions after the model is instantiated and all field validators are applied.
95+
"""
96+
9297
default_lo_python = "/Applications/LibreOffice.app/Contents/Resources/python"
9398
default_lo_exec = "/Applications/LibreOffice.app/Contents/MacOS/soffice"
9499
tessdata_prefix = self.OCR_TESSDATA_PREFIX

0 commit comments

Comments
 (0)