fix(doc_parser): enhance DOC to DOCX conversion reliability

- Implemented a retry mechanism for DOC to DOCX conversion to handle concurrent `soffice` invocations, ensuring each attempt uses a dedicated user profile directory.
- Added logging for each conversion attempt, including success and failure messages, to improve visibility into the conversion process.
- Adjusted the handling of temporary directories for both conversion output and user profiles, enhancing robustness against conversion failures.
This commit is contained in:
wizardchen
2026-06-01 19:54:11 +08:00
committed by lyingbug
parent 65f9018f73
commit 959eba2136
+65 -34
View File
@@ -1,6 +1,9 @@
import logging import logging
import os import os
import subprocess import subprocess
import time
import uuid
from pathlib import Path
from typing import List, Optional from typing import List, Optional
import textract import textract
@@ -188,44 +191,72 @@ class DocParser(Docx2Parser):
# Execute conversion command # Execute conversion command
logger.info(f"Using {soffice_path} to convert DOC to DOCX") logger.info(f"Using {soffice_path} to convert DOC to DOCX")
# Create a temporary directory to store the converted file # LibreOffice shares a single user profile by default, so concurrent
with TempDirContext() as temp_dir: # `soffice` invocations contend for the same profile lock and the loser
cmd = [ # silently fails to convert. Give each attempt a dedicated profile dir
soffice_path, # and retry a few times so concurrent requests don't fall back to the
"--headless", # lower-fidelity antiword path.
"--convert-to", max_attempts = 3
"docx", for attempt in range(1, max_attempts + 1):
"--outdir", # Create a temporary directory to store the converted file
temp_dir, with TempDirContext() as temp_dir, TempDirContext() as profile_dir:
doc_path, user_installation = Path(profile_dir).as_uri()
] cmd = [
logger.info(f"Running command in sandbox: {' '.join(cmd)}") soffice_path,
"--headless",
# Execute in sandbox with proxy configuration f"-env:UserInstallation={user_installation}",
stdout, stderr, returncode = self.sandbox_executor.execute_in_sandbox(cmd) "--convert-to",
"docx",
if returncode != 0: "--outdir",
logger.warning( temp_dir,
f"Error converting DOC to DOCX: {stderr.decode('utf-8')}" doc_path,
]
logger.info(
f"Running command in sandbox (attempt {attempt}/{max_attempts}): "
f"{' '.join(cmd)}"
) )
return None
# Find the converted file # Execute in sandbox with proxy configuration
docx_file = [ stdout, stderr, returncode = self.sandbox_executor.execute_in_sandbox(
file for file in os.listdir(temp_dir) if file.endswith(".docx") cmd
] )
logger.info(f"Found {len(docx_file)} DOCX file(s) in temporary directory")
for file in docx_file:
converted_file = os.path.join(temp_dir, file)
logger.info(f"Found converted file: {converted_file}")
# Read the converted file content if returncode != 0:
with open(converted_file, "rb") as f: logger.warning(
docx_content = f.read() f"Error converting DOC to DOCX (attempt {attempt}/"
logger.info( f"{max_attempts}): {stderr.decode('utf-8', errors='ignore')}"
f"Successfully read DOCX file, size: {len(docx_content)}"
) )
return docx_content if attempt < max_attempts:
time.sleep(0.5 * attempt)
continue
return None
# Find the converted file
docx_file = [
file for file in os.listdir(temp_dir) if file.endswith(".docx")
]
logger.info(
f"Found {len(docx_file)} DOCX file(s) in temporary directory"
)
for file in docx_file:
converted_file = os.path.join(temp_dir, file)
logger.info(f"Found converted file: {converted_file}")
# Read the converted file content
with open(converted_file, "rb") as f:
docx_content = f.read()
logger.info(
f"Successfully read DOCX file, size: {len(docx_content)}"
)
return docx_content
# Conversion reported success but produced no docx; retry.
logger.warning(
f"No DOCX produced despite success (attempt {attempt}/"
f"{max_attempts})"
)
if attempt < max_attempts:
time.sleep(0.5 * attempt)
return None return None
def _try_find_executable_path( def _try_find_executable_path(