48 lines
1.3 KiB
Python
48 lines
1.3 KiB
Python
"""PDF 解析器(PyMuPDF fallback)。"""
|
|
|
|
from app.core.logging import get_logger
|
|
|
|
logger = get_logger(__name__)
|
|
|
|
|
|
def parse_pdf_with_pymupdf(file_content: bytes) -> str | None:
|
|
"""用 PyMuPDF 解析 PDF,返回 Markdown 或 None(失败时)。"""
|
|
try:
|
|
import pymupdf # PyMuPDF >= 1.24
|
|
|
|
doc = pymupdf.open(stream=file_content, filetype="pdf")
|
|
pages = []
|
|
for page_num in range(len(doc)):
|
|
page = doc.load_page(page_num)
|
|
text = page.get_text()
|
|
if text.strip():
|
|
pages.append(text)
|
|
doc.close()
|
|
|
|
if not pages:
|
|
return None
|
|
|
|
# 组合成 Markdown(每页一个段落)
|
|
markdown = "\n\n".join(pages)
|
|
return markdown
|
|
except Exception as e:
|
|
logger.warning("PyMuPDF 解析失败: %s", e)
|
|
return None
|
|
|
|
|
|
def has_text_layer(file_content: bytes) -> bool:
|
|
"""检查 PDF 是否有文本层。"""
|
|
try:
|
|
import pymupdf
|
|
|
|
doc = pymupdf.open(stream=file_content, filetype="pdf")
|
|
for page_num in range(min(3, len(doc))): # 检查前 3 页
|
|
page = doc.load_page(page_num)
|
|
if page.get_text().strip():
|
|
doc.close()
|
|
return True
|
|
doc.close()
|
|
return False
|
|
except Exception:
|
|
return False
|