File size: 3,535 Bytes
b4f2238 | 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 | """Business logic services."""
import contextlib
import io
import logging
from typing import Any
from apps.core.utils.path import Path
logger = logging.getLogger("apps.documents")
def get_pdf_page_count_with_error(source: Any, default: int = 1) -> tuple[int, str | None]:
data = _read_source_bytes(source)
last_error: Exception | None = None
try:
import pikepdf
with pikepdf.open(io.BytesIO(data)) as pdf:
return len(pdf.pages), None
except Exception as e:
logger.exception("操作失败")
last_error = e
try:
import fitz
doc = fitz.open(stream=data, filetype="pdf")
try:
return int(doc.page_count), None
finally:
doc.close()
except Exception as e:
logger.exception("操作失败")
last_error = e
try:
import pdfplumber
with pdfplumber.open(io.BytesIO(data)) as pdf:
return len(pdf.pages), None
except Exception as e:
logger.exception("操作失败")
last_error = e
error_text = str(last_error) if last_error else "unknown error"
logger.warning("PDF 页数识别失败: %s", error_text)
return default, error_text
def get_pdf_page_count(source: Any, default: int = 1) -> int:
count, _ = get_pdf_page_count_with_error(source, default=default)
return count
def _read_source_bytes(source: Any) -> Any:
if source is None:
raise ValueError("source is None")
if isinstance(source, (bytes, bytearray)):
return bytes(source)
if isinstance(source, Path):
return source.read_bytes()
if isinstance(source, str):
return Path(source).read_bytes()
# 尝试各种读取策略
readers: list[tuple[str, Any]] = [
("django_field_file", _read_django_field_file),
("file_like", _read_file_like),
("path_attr", _read_from_path_attr),
]
for _name, reader in readers:
result = reader(source)
if result is not None:
return result
raise TypeError(f"Unsupported source type: {type(source)}")
def _read_django_field_file(source: Any) -> Any:
"""读取 Django FieldFile 或 InMemoryUploadedFile"""
if not (hasattr(source, "open") and hasattr(source, "read")):
return None
try:
source.seek(0)
except Exception:
logger.exception("操作失败")
with contextlib.suppress(Exception):
source.open("rb")
try:
data = source.read()
with contextlib.suppress(Exception):
source.seek(0)
return data
except Exception:
logger.exception("操作失败")
return None
def _read_file_like(source: Any) -> Any:
"""读取类文件对象"""
if not hasattr(source, "read"):
return None
pos = None
if hasattr(source, "tell"):
with contextlib.suppress(Exception):
pos = source.tell()
if hasattr(source, "seek"):
with contextlib.suppress(Exception):
source.seek(0)
try:
data = source.read()
except Exception:
logger.exception("操作失败")
return None
if hasattr(source, "seek"):
with contextlib.suppress(Exception):
source.seek(pos if pos is not None else 0)
return data
def _read_from_path_attr(source: Any) -> Any:
"""通过 path 属性读取(已保存到磁盘的文件)"""
if hasattr(source, "path"):
return Path(source.path).read_bytes()
return None
|