33import atexit
44import multiprocessing
55import os
6+ import re
67import time
78import traceback
89import uuid
10+ import zipfile
11+ from html import unescape
912from io import BytesIO
1013from subprocess import PIPE , Popen
1114from threading import Timer
1922
2023from ocr_service .dto .process_context import ProcessContext
2124from 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
2432CURRENT_PDF_FILE : pdfium .PdfDocument | None = None
2533
2634
2735class 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+ )
0 commit comments