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
+36 -5
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,33 +191,53 @@ 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")
# LibreOffice shares a single user profile by default, so concurrent
# `soffice` invocations contend for the same profile lock and the loser
# silently fails to convert. Give each attempt a dedicated profile dir
# and retry a few times so concurrent requests don't fall back to the
# lower-fidelity antiword path.
max_attempts = 3
for attempt in range(1, max_attempts + 1):
# Create a temporary directory to store the converted file # Create a temporary directory to store the converted file
with TempDirContext() as temp_dir: with TempDirContext() as temp_dir, TempDirContext() as profile_dir:
user_installation = Path(profile_dir).as_uri()
cmd = [ cmd = [
soffice_path, soffice_path,
"--headless", "--headless",
f"-env:UserInstallation={user_installation}",
"--convert-to", "--convert-to",
"docx", "docx",
"--outdir", "--outdir",
temp_dir, temp_dir,
doc_path, doc_path,
] ]
logger.info(f"Running command in sandbox: {' '.join(cmd)}") logger.info(
f"Running command in sandbox (attempt {attempt}/{max_attempts}): "
f"{' '.join(cmd)}"
)
# Execute in sandbox with proxy configuration # Execute in sandbox with proxy configuration
stdout, stderr, returncode = self.sandbox_executor.execute_in_sandbox(cmd) stdout, stderr, returncode = self.sandbox_executor.execute_in_sandbox(
cmd
)
if returncode != 0: if returncode != 0:
logger.warning( logger.warning(
f"Error converting DOC to DOCX: {stderr.decode('utf-8')}" f"Error converting DOC to DOCX (attempt {attempt}/"
f"{max_attempts}): {stderr.decode('utf-8', errors='ignore')}"
) )
if attempt < max_attempts:
time.sleep(0.5 * attempt)
continue
return None return None
# Find the converted file # Find the converted file
docx_file = [ docx_file = [
file for file in os.listdir(temp_dir) if file.endswith(".docx") 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") logger.info(
f"Found {len(docx_file)} DOCX file(s) in temporary directory"
)
for file in docx_file: for file in docx_file:
converted_file = os.path.join(temp_dir, file) converted_file = os.path.join(temp_dir, file)
logger.info(f"Found converted file: {converted_file}") logger.info(f"Found converted file: {converted_file}")
@@ -226,6 +249,14 @@ class DocParser(Docx2Parser):
f"Successfully read DOCX file, size: {len(docx_content)}" f"Successfully read DOCX file, size: {len(docx_content)}"
) )
return 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(