Spaces:
Running
Running
shuaiwang commited on
Commit ·
8420e1e
1
Parent(s): 574758a
fix: independent persist executor + reset pending_push on failure
Browse files- backend/app/services/persist.py: add dedicated ThreadPoolExecutor
(so upload_folder can't starve business run_in_executor like
ChromaDB query / BGE-M3 encode)
- push_to_hf(): reset pending_push flag on failure too
(was getting stuck at True after first error, blocking all future
schedule_push calls)
- app/services/__init__.py +0 -0
- app/services/llm_cache.py +94 -0
- app/services/parsers/__init__.py +123 -0
- app/services/parsers/base_parser.py +56 -0
- app/services/parsers/docling_parser.py +179 -0
- app/services/parsers/marker_parser.py +62 -0
- app/services/parsers/simple_parser.py +88 -0
- app/services/persist.py +204 -0
app/services/__init__.py
ADDED
|
File without changes
|
app/services/llm_cache.py
ADDED
|
@@ -0,0 +1,94 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
"""LLM 响应缓存 (内存 LRU).
|
| 2 |
+
|
| 3 |
+
为什么需要:
|
| 4 |
+
- 个人使用场景下, 同一问题反复问很常见
|
| 5 |
+
- 命中时直接跳过 LLM 调用 + 流式回放 token
|
| 6 |
+
- 节省 API 费用 + 缩短延迟
|
| 7 |
+
|
| 8 |
+
设计:
|
| 9 |
+
- key = sha256( (query + top_doc_ids + temperature) ) -- 只缓存"标准问答", 不缓存工具调用
|
| 10 |
+
- value = 完整回答内容 + 引用 + 工具调用结果
|
| 11 |
+
- LRU 容量可配 (默认 200)
|
| 12 |
+
- 进程内, 重启清空 (避免引入 Redis)
|
| 13 |
+
"""
|
| 14 |
+
from __future__ import annotations
|
| 15 |
+
|
| 16 |
+
import hashlib
|
| 17 |
+
import logging
|
| 18 |
+
from dataclasses import dataclass
|
| 19 |
+
from typing import Any
|
| 20 |
+
|
| 21 |
+
from cachetools import LRUCache
|
| 22 |
+
|
| 23 |
+
from app.config import settings
|
| 24 |
+
|
| 25 |
+
logger = logging.getLogger(__name__)
|
| 26 |
+
|
| 27 |
+
|
| 28 |
+
@dataclass
|
| 29 |
+
class CachedAnswer:
|
| 30 |
+
content: str
|
| 31 |
+
citations: list[dict[str, Any]]
|
| 32 |
+
tool_calls: list[dict[str, Any]]
|
| 33 |
+
tokens: list[str] # 预切好的 token 序列, 流式回放
|
| 34 |
+
|
| 35 |
+
|
| 36 |
+
_cache: LRUCache | None = None
|
| 37 |
+
_hits = 0
|
| 38 |
+
_misses = 0
|
| 39 |
+
|
| 40 |
+
|
| 41 |
+
def _make_key(query: str, top_doc_ids: list[str], temperature: float) -> str:
|
| 42 |
+
"""缓存 key. 包含 query + 命中文档 id + 温度, 避免不同上下文错命中."""
|
| 43 |
+
payload = f"{query.strip()}|{','.join(sorted(top_doc_ids))}|{temperature:.2f}"
|
| 44 |
+
return hashlib.sha256(payload.encode("utf-8")).hexdigest()
|
| 45 |
+
|
| 46 |
+
|
| 47 |
+
def get_cache() -> LRUCache:
|
| 48 |
+
global _cache
|
| 49 |
+
if _cache is None:
|
| 50 |
+
size = settings.llm_cache_size if settings.llm_cache_enabled else 0
|
| 51 |
+
_cache = LRUCache(maxsize=size)
|
| 52 |
+
logger.info("LLM cache initialized: enabled=%s size=%d", settings.llm_cache_enabled, size)
|
| 53 |
+
return _cache
|
| 54 |
+
|
| 55 |
+
|
| 56 |
+
def lookup(query: str, top_doc_ids: list[str], temperature: float) -> CachedAnswer | None:
|
| 57 |
+
if not settings.llm_cache_enabled:
|
| 58 |
+
return None
|
| 59 |
+
key = _make_key(query, top_doc_ids, temperature)
|
| 60 |
+
hit = get_cache().get(key)
|
| 61 |
+
global _hits, _misses
|
| 62 |
+
if hit is not None:
|
| 63 |
+
_hits += 1
|
| 64 |
+
logger.debug("LLM cache HIT key=%s", key[:12])
|
| 65 |
+
else:
|
| 66 |
+
_misses += 1
|
| 67 |
+
return hit
|
| 68 |
+
|
| 69 |
+
|
| 70 |
+
def store(query: str, top_doc_ids: list[str], temperature: float, answer: CachedAnswer) -> None:
|
| 71 |
+
if not settings.llm_cache_enabled:
|
| 72 |
+
return
|
| 73 |
+
key = _make_key(query, top_doc_ids, temperature)
|
| 74 |
+
get_cache()[key] = answer
|
| 75 |
+
logger.debug("LLM cache STORE key=%s tokens=%d", key[:12], len(answer.tokens))
|
| 76 |
+
|
| 77 |
+
|
| 78 |
+
def stats() -> dict[str, Any]:
|
| 79 |
+
return {
|
| 80 |
+
"enabled": settings.llm_cache_enabled,
|
| 81 |
+
"size": len(get_cache()),
|
| 82 |
+
"max_size": get_cache().maxsize,
|
| 83 |
+
"hits": _hits,
|
| 84 |
+
"misses": _misses,
|
| 85 |
+
"hit_rate": (_hits / max(_hits + _misses, 1)),
|
| 86 |
+
}
|
| 87 |
+
|
| 88 |
+
|
| 89 |
+
def clear() -> None:
|
| 90 |
+
global _cache, _hits, _misses
|
| 91 |
+
_cache = None
|
| 92 |
+
_hits = 0
|
| 93 |
+
_misses = 0
|
| 94 |
+
logger.info("LLM cache cleared")
|
app/services/parsers/__init__.py
ADDED
|
@@ -0,0 +1,123 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
"""Parser 工厂: 智能路由 + 降级链.
|
| 2 |
+
|
| 3 |
+
智能路由逻辑:
|
| 4 |
+
1. 查 settings.parser_primary (默认 docling)
|
| 5 |
+
2. 主 parser 失败 -> 降级到 settings.parser_fallback
|
| 6 |
+
3. 全部失败 -> 抛 IngestionFailedError
|
| 7 |
+
"""
|
| 8 |
+
from __future__ import annotations
|
| 9 |
+
|
| 10 |
+
import logging
|
| 11 |
+
from pathlib import Path
|
| 12 |
+
|
| 13 |
+
from app.config import settings
|
| 14 |
+
from app.core.errors import IngestionFailedError
|
| 15 |
+
from app.services.parsers.base_parser import BaseParser, ParsedDocument
|
| 16 |
+
|
| 17 |
+
logger = logging.getLogger(__name__)
|
| 18 |
+
|
| 19 |
+
|
| 20 |
+
# 延迟注册: 实际 import 在 _build_parser 内
|
| 21 |
+
_REGISTRY: dict[str, type[BaseParser]] = {}
|
| 22 |
+
|
| 23 |
+
|
| 24 |
+
def _register_default() -> None:
|
| 25 |
+
"""懒加载各 parser. 失败的 (未装) 仅记 warning, 不抛."""
|
| 26 |
+
if _REGISTRY:
|
| 27 |
+
return
|
| 28 |
+
try:
|
| 29 |
+
from app.services.parsers.docling_parser import DoclingParser
|
| 30 |
+
_REGISTRY["docling"] = DoclingParser
|
| 31 |
+
except ImportError as e:
|
| 32 |
+
logger.warning("docling not installed: %s", e)
|
| 33 |
+
try:
|
| 34 |
+
from app.services.parsers.simple_parser import SimpleParser
|
| 35 |
+
_REGISTRY["simple"] = SimpleParser
|
| 36 |
+
except ImportError as e:
|
| 37 |
+
logger.warning("simple parser not installed: %s", e)
|
| 38 |
+
# mineru / vlm 留 hook (按需装)
|
| 39 |
+
|
| 40 |
+
|
| 41 |
+
def _build_parser(name: str) -> BaseParser:
|
| 42 |
+
_register_default()
|
| 43 |
+
cls = _REGISTRY.get(name)
|
| 44 |
+
if cls is None:
|
| 45 |
+
raise IngestionFailedError(
|
| 46 |
+
f"Parser '{name}' is not installed. pip install docling / marker-pdf.",
|
| 47 |
+
code="parser_unavailable",
|
| 48 |
+
)
|
| 49 |
+
return cls()
|
| 50 |
+
|
| 51 |
+
|
| 52 |
+
def get_parser(name: str | None = None) -> BaseParser:
|
| 53 |
+
"""获取单个 parser 实例 (按名字)."""
|
| 54 |
+
return _build_parser(name or settings.parser_primary)
|
| 55 |
+
|
| 56 |
+
|
| 57 |
+
def get_parser_chain() -> list[BaseParser]:
|
| 58 |
+
"""按 settings 配置返回 [primary, fallback] 链."""
|
| 59 |
+
chain: list[BaseParser] = []
|
| 60 |
+
for name in (settings.parser_primary, settings.parser_fallback):
|
| 61 |
+
if name and name not in {p.name for p in chain}:
|
| 62 |
+
try:
|
| 63 |
+
chain.append(_build_parser(name))
|
| 64 |
+
except IngestionFailedError:
|
| 65 |
+
# 跳过未装的, 继续
|
| 66 |
+
continue
|
| 67 |
+
return chain
|
| 68 |
+
|
| 69 |
+
|
| 70 |
+
async def parse_with_fallback(file_path: Path) -> ParsedDocument:
|
| 71 |
+
"""按链逐个尝试, 全部失败抛 IngestionFailedError."""
|
| 72 |
+
chain = get_parser_chain()
|
| 73 |
+
if not chain:
|
| 74 |
+
raise IngestionFailedError(
|
| 75 |
+
"No parser available. Install at least one of: docling, marker-pdf.",
|
| 76 |
+
code="no_parser_available",
|
| 77 |
+
)
|
| 78 |
+
|
| 79 |
+
# 选能处理该扩展名的 parser
|
| 80 |
+
candidates = [p for p in chain if p.can_handle(file_path)]
|
| 81 |
+
if not candidates:
|
| 82 |
+
raise IngestionFailedError(
|
| 83 |
+
f"No parser in chain supports {file_path.suffix}",
|
| 84 |
+
code="unsupported_format",
|
| 85 |
+
detail={"suffix": file_path.suffix, "chain": [p.name for p in chain]},
|
| 86 |
+
)
|
| 87 |
+
|
| 88 |
+
last_err: Exception | None = None
|
| 89 |
+
last_traceback: str | None = None
|
| 90 |
+
for parser in candidates:
|
| 91 |
+
try:
|
| 92 |
+
return await parser.parse(file_path)
|
| 93 |
+
except Exception as e: # noqa: BLE001
|
| 94 |
+
import traceback
|
| 95 |
+
tb = traceback.format_exc()
|
| 96 |
+
logger.warning("Parser %s failed for %s: %s\n%s", parser.name, file_path.name, e, tb)
|
| 97 |
+
last_err = e
|
| 98 |
+
last_traceback = tb
|
| 99 |
+
|
| 100 |
+
# 把最后一个 parser 的具体异常信息暴露给前端, 方便诊断
|
| 101 |
+
err_msg = f"All parsers failed for {file_path.name}"
|
| 102 |
+
if last_err:
|
| 103 |
+
err_msg += f" (last: {type(last_err).__name__}: {last_err})"
|
| 104 |
+
raise IngestionFailedError(
|
| 105 |
+
err_msg,
|
| 106 |
+
code="all_parsers_failed",
|
| 107 |
+
detail={
|
| 108 |
+
"chain": [p.name for p in candidates],
|
| 109 |
+
"last_error_type": type(last_err).__name__ if last_err else None,
|
| 110 |
+
"last_error_msg": str(last_err)[:500] if last_err else None,
|
| 111 |
+
"last_traceback": (last_traceback or "")[-1500:], # 末 1.5KB, 防爆
|
| 112 |
+
},
|
| 113 |
+
) from last_err
|
| 114 |
+
|
| 115 |
+
|
| 116 |
+
__all__ = [
|
| 117 |
+
"BaseParser",
|
| 118 |
+
"ParsedDocument",
|
| 119 |
+
"PageContent",
|
| 120 |
+
"get_parser",
|
| 121 |
+
"get_parser_chain",
|
| 122 |
+
"parse_with_fallback",
|
| 123 |
+
]
|
app/services/parsers/base_parser.py
ADDED
|
@@ -0,0 +1,56 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
"""文档解析抽象 + 数据结构.
|
| 2 |
+
|
| 3 |
+
支持的输入: PDF, DOCX, PNG/JPG (含扫描件).
|
| 4 |
+
|
| 5 |
+
设计:
|
| 6 |
+
- BaseParser 抽象 parse() -> ParsedDocument
|
| 7 |
+
- ParsedDocument 同时携带 markdown 全文 + 页面级结构 (含表格 / 图片)
|
| 8 |
+
- 各具体 parser (Docling / Marker / MinerU) 实现同一接口, 可热替换
|
| 9 |
+
"""
|
| 10 |
+
from __future__ import annotations
|
| 11 |
+
|
| 12 |
+
import abc
|
| 13 |
+
from dataclasses import dataclass, field
|
| 14 |
+
from pathlib import Path
|
| 15 |
+
|
| 16 |
+
|
| 17 |
+
@dataclass
|
| 18 |
+
class PageContent:
|
| 19 |
+
"""单页内容. 至少要有 text, 可选带 tables / images."""
|
| 20 |
+
|
| 21 |
+
page_no: int
|
| 22 |
+
text: str
|
| 23 |
+
tables: list[dict] = field(default_factory=list) # {html, bbox, rows}
|
| 24 |
+
images: list[dict] = field(default_factory=list) # {bbox, caption, b64_thumb}
|
| 25 |
+
headings: list[str] = field(default_factory=list) # 当前页的标题
|
| 26 |
+
|
| 27 |
+
|
| 28 |
+
@dataclass
|
| 29 |
+
class ParsedDocument:
|
| 30 |
+
"""解析后的统一文档结构.
|
| 31 |
+
|
| 32 |
+
业务侧只用 markdown (全文) + pages (带页码引用) 两个核心字段.
|
| 33 |
+
"""
|
| 34 |
+
|
| 35 |
+
markdown: str # 全文 markdown (LLM 友好)
|
| 36 |
+
pages: list[PageContent] = field(default_factory=list)
|
| 37 |
+
tables: list[dict] = field(default_factory=list) # 全部表格 (跨页表已合并)
|
| 38 |
+
images: list[dict] = field(default_factory=list)
|
| 39 |
+
meta: dict = field(default_factory=dict) # page_count, parser, elapsed_ms, ...
|
| 40 |
+
|
| 41 |
+
|
| 42 |
+
class BaseParser(abc.ABC):
|
| 43 |
+
"""文档解析器抽象基类."""
|
| 44 |
+
|
| 45 |
+
name: str = "abstract"
|
| 46 |
+
|
| 47 |
+
@abc.abstractmethod
|
| 48 |
+
def supported_extensions(self) -> set[str]:
|
| 49 |
+
"""形如 {'.pdf', '.docx'}."""
|
| 50 |
+
|
| 51 |
+
@abc.abstractmethod
|
| 52 |
+
async def parse(self, file_path: Path) -> ParsedDocument:
|
| 53 |
+
"""同步 IO + 异步 wrapper. 重 CPU 解析可放线程池."""
|
| 54 |
+
|
| 55 |
+
def can_handle(self, file_path: Path) -> bool:
|
| 56 |
+
return file_path.suffix.lower() in self.supported_extensions()
|
app/services/parsers/docling_parser.py
ADDED
|
@@ -0,0 +1,179 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
"""Docling parser - 主力.
|
| 2 |
+
|
| 3 |
+
特性:
|
| 4 |
+
- 结构感知 (reading order / headings)
|
| 5 |
+
- 跨页表合并 (TableFormer)
|
| 6 |
+
- 内置 OCR (PaddleOCR 支持中英)
|
| 7 |
+
- DOCX / PPTX / 图片 / HTML 全支持
|
| 8 |
+
|
| 9 |
+
Docling API 在 2.x 期间变动较多, 本实现基于 2.30+ 兼容.
|
| 10 |
+
"""
|
| 11 |
+
from __future__ import annotations
|
| 12 |
+
|
| 13 |
+
import asyncio
|
| 14 |
+
import logging
|
| 15 |
+
import time
|
| 16 |
+
from pathlib import Path
|
| 17 |
+
|
| 18 |
+
from app.config import settings
|
| 19 |
+
from app.services.parsers.base_parser import BaseParser, PageContent, ParsedDocument
|
| 20 |
+
|
| 21 |
+
logger = logging.getLogger(__name__)
|
| 22 |
+
|
| 23 |
+
|
| 24 |
+
class DoclingParser(BaseParser):
|
| 25 |
+
name = "docling"
|
| 26 |
+
|
| 27 |
+
def supported_extensions(self) -> set[str]:
|
| 28 |
+
return {".pdf", ".docx", ".pptx", ".png", ".jpg", ".jpeg", ".tiff", ".html", ".xlsx"}
|
| 29 |
+
|
| 30 |
+
async def parse(self, file_path: Path) -> ParsedDocument:
|
| 31 |
+
loop = asyncio.get_running_loop()
|
| 32 |
+
return await loop.run_in_executor(None, self._parse_sync, file_path)
|
| 33 |
+
|
| 34 |
+
def _parse_sync(self, file_path: Path) -> ParsedDocument:
|
| 35 |
+
"""实际解析. CPU 密集, 在线程池跑."""
|
| 36 |
+
# Force CPU device for Docling to prevent MPS NotImplementedError on Intel Mac
|
| 37 |
+
try:
|
| 38 |
+
import docling.utils.accelerator_utils
|
| 39 |
+
docling.utils.accelerator_utils.decide_device = lambda *args, **kwargs: "cpu"
|
| 40 |
+
except ImportError:
|
| 41 |
+
pass
|
| 42 |
+
|
| 43 |
+
# 延迟 import, 避免启动期未装 docling 时崩溃
|
| 44 |
+
from docling.document_converter import DocumentConverter, PdfFormatOption
|
| 45 |
+
from docling.datamodel.base_models import InputFormat
|
| 46 |
+
from docling.datamodel.pipeline_options import PdfPipelineOptions
|
| 47 |
+
|
| 48 |
+
started = time.time()
|
| 49 |
+
logger.info("Docling parsing: %s", file_path.name)
|
| 50 |
+
|
| 51 |
+
from docling.datamodel.accelerator_options import AcceleratorOptions, AcceleratorDevice
|
| 52 |
+
opts = PdfPipelineOptions()
|
| 53 |
+
opts.do_ocr = settings.parser_enable_ocr
|
| 54 |
+
opts.do_table_structure = settings.parser_table_structure
|
| 55 |
+
opts.images_scale = 2.0
|
| 56 |
+
# ⚠️ 不要设 artifacts_path: 设了但目录为空会被 Docling 拒绝 (报 "is not valid")
|
| 57 |
+
# 不设时, Docling 通过 huggingface_hub 走 HF_HOME 自动下载 + 缓存
|
| 58 |
+
# 我们的 Dockerfile 设了 HF_HOME=/data/.cache/huggingface (持久卷), 所以重启后还在
|
| 59 |
+
opts.accelerator_options = AcceleratorOptions(device=AcceleratorDevice.CPU)
|
| 60 |
+
|
| 61 |
+
converter = DocumentConverter(
|
| 62 |
+
format_options={
|
| 63 |
+
InputFormat.PDF: PdfFormatOption(pipeline_options=opts),
|
| 64 |
+
}
|
| 65 |
+
)
|
| 66 |
+
|
| 67 |
+
try:
|
| 68 |
+
result = converter.convert(str(file_path))
|
| 69 |
+
except Exception as e: # noqa: BLE001
|
| 70 |
+
logger.exception("Docling parse failed: %s", e)
|
| 71 |
+
raise
|
| 72 |
+
|
| 73 |
+
doc = result.document
|
| 74 |
+
|
| 75 |
+
# 全文 markdown
|
| 76 |
+
markdown = doc.export_to_markdown()
|
| 77 |
+
|
| 78 |
+
# 页面级 (Docling 用 iterate_items / pages 属性, 视版本略有差异)
|
| 79 |
+
pages: list[PageContent] = []
|
| 80 |
+
try:
|
| 81 |
+
page_count = len(doc.pages) if hasattr(doc, "pages") else 0
|
| 82 |
+
for idx in range(page_count):
|
| 83 |
+
page = doc.pages[idx]
|
| 84 |
+
# 提取该页文本 (Docling 2.x 没有现成 API, 用 page-level export 近似)
|
| 85 |
+
page_md = ""
|
| 86 |
+
if hasattr(page, "export_to_markdown"):
|
| 87 |
+
try:
|
| 88 |
+
page_md = page.export_to_markdown()
|
| 89 |
+
except Exception: # noqa: BLE001
|
| 90 |
+
page_md = ""
|
| 91 |
+
pages.append(PageContent(
|
| 92 |
+
page_no=idx + 1,
|
| 93 |
+
text=page_md,
|
| 94 |
+
headings=[], # Docling 不直接给页级 headings, 留空
|
| 95 |
+
))
|
| 96 |
+
except Exception as e: # noqa: BLE001
|
| 97 |
+
logger.warning("Docling page extraction partial: %s", e)
|
| 98 |
+
|
| 99 |
+
# 表格 (简化提取)
|
| 100 |
+
tables: list[dict] = []
|
| 101 |
+
try:
|
| 102 |
+
for t in (doc.tables or []):
|
| 103 |
+
tables.append({
|
| 104 |
+
"html": t.export_to_html() if hasattr(t, "export_to_html") else "",
|
| 105 |
+
"caption": getattr(t, "caption", None),
|
| 106 |
+
})
|
| 107 |
+
except Exception: # noqa: BLE001
|
| 108 |
+
pass
|
| 109 |
+
|
| 110 |
+
elapsed_ms = int((time.time() - started) * 1000)
|
| 111 |
+
logger.info("Docling done: %s pages, %s tables, %dms", len(pages), len(tables), elapsed_ms)
|
| 112 |
+
|
| 113 |
+
return ParsedDocument(
|
| 114 |
+
markdown=markdown,
|
| 115 |
+
pages=pages,
|
| 116 |
+
tables=tables,
|
| 117 |
+
images=[],
|
| 118 |
+
meta={
|
| 119 |
+
"parser": self.name,
|
| 120 |
+
"page_count": len(pages),
|
| 121 |
+
"elapsed_ms": elapsed_ms,
|
| 122 |
+
},
|
| 123 |
+
)
|
| 124 |
+
|
| 125 |
+
|
| 126 |
+
def _prewarm_docling_models() -> None:
|
| 127 |
+
"""预下载 Docling 需要的模型 (layout/heron, tableformer, paddleocr 等, 共 ~2GB).
|
| 128 |
+
|
| 129 |
+
在 Space 启动 lifespan 阶段跑一次, 避免首次上传时下载超时或下载失败.
|
| 130 |
+
模型会缓存到 settings.hf_cache_dir, 后续启动跳过.
|
| 131 |
+
"""
|
| 132 |
+
import logging
|
| 133 |
+
from pathlib import Path
|
| 134 |
+
from app.config import settings
|
| 135 |
+
|
| 136 |
+
logger_local = logging.getLogger(__name__)
|
| 137 |
+
logger_local.info("Docling model prewarm: pulling layout/table/ocr models...")
|
| 138 |
+
|
| 139 |
+
from huggingface_hub import snapshot_download
|
| 140 |
+
|
| 141 |
+
# Docling 模型都在 ds4sd 命名空间下
|
| 142 |
+
repos = [
|
| 143 |
+
"ds4sd/docling-models", # 主模型集 (layout, tableformer)
|
| 144 |
+
]
|
| 145 |
+
|
| 146 |
+
cache_dir = Path(settings.hf_cache_dir) if hasattr(settings, "hf_cache_dir") else None
|
| 147 |
+
if cache_dir is None:
|
| 148 |
+
from app.core.paths import data_dir
|
| 149 |
+
cache_dir = data_dir() / ".cache" / "huggingface"
|
| 150 |
+
|
| 151 |
+
for repo in repos:
|
| 152 |
+
try:
|
| 153 |
+
p = snapshot_download(
|
| 154 |
+
repo_id=repo,
|
| 155 |
+
cache_dir=str(cache_dir),
|
| 156 |
+
# 避免下载所有 variants, 只下必需的
|
| 157 |
+
allow_patterns=[
|
| 158 |
+
"*.json",
|
| 159 |
+
"*.txt",
|
| 160 |
+
"*.safetensors",
|
| 161 |
+
"tokenizer*",
|
| 162 |
+
],
|
| 163 |
+
)
|
| 164 |
+
logger_local.info("Docling model %s cached at %s", repo, p)
|
| 165 |
+
except Exception as e: # noqa: BLE001
|
| 166 |
+
logger_local.warning("Docling model prewarm %s failed: %s", repo, e)
|
| 167 |
+
|
| 168 |
+
# PaddleOCR 模型 (Docling 内置 OCR 用). 单独下载.
|
| 169 |
+
try:
|
| 170 |
+
from paddleocr import PaddleOCR # type: ignore
|
| 171 |
+
# 实例化会触发模型下载到 ~/.paddleocr
|
| 172 |
+
PaddleOCR(use_angle_cls=False, lang="ch", show_log=False)
|
| 173 |
+
logger_local.info("PaddleOCR (ch) model cached")
|
| 174 |
+
except Exception as e: # noqa: BLE001
|
| 175 |
+
# PaddleOCR 可能没装 (e.g. arm64 平台), 不阻塞
|
| 176 |
+
logger_local.warning("PaddleOCR prewarm skipped: %s", e)
|
| 177 |
+
|
| 178 |
+
logger_local.info("Docling model prewarm done")
|
| 179 |
+
|
app/services/parsers/marker_parser.py
ADDED
|
@@ -0,0 +1,62 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
"""Marker parser - 兜底 (Docling 失败时启用).
|
| 2 |
+
|
| 3 |
+
特性:
|
| 4 |
+
- PDF -> Markdown 转换, 速度快
|
| 5 |
+
- 内置 surya-ocr, 支持 90+ 语言
|
| 6 |
+
- 不擅长复杂表格 / 跨页表 (不如 Docling), 但胜在稳定
|
| 7 |
+
"""
|
| 8 |
+
from __future__ import annotations
|
| 9 |
+
|
| 10 |
+
import asyncio
|
| 11 |
+
import logging
|
| 12 |
+
import time
|
| 13 |
+
from pathlib import Path
|
| 14 |
+
|
| 15 |
+
from app.services.parsers.base_parser import BaseParser, ParsedDocument
|
| 16 |
+
|
| 17 |
+
logger = logging.getLogger(__name__)
|
| 18 |
+
|
| 19 |
+
|
| 20 |
+
class MarkerParser(BaseParser):
|
| 21 |
+
name = "marker"
|
| 22 |
+
|
| 23 |
+
def supported_extensions(self) -> set[str]:
|
| 24 |
+
# Marker 强项是 PDF; 其它类型建议直接 Docling
|
| 25 |
+
return {".pdf"}
|
| 26 |
+
|
| 27 |
+
async def parse(self, file_path: Path) -> ParsedDocument:
|
| 28 |
+
loop = asyncio.get_running_loop()
|
| 29 |
+
return await loop.run_in_executor(None, self._parse_sync, file_path)
|
| 30 |
+
|
| 31 |
+
def _parse_sync(self, file_path: Path) -> ParsedDocument:
|
| 32 |
+
# Marker 1.x 推荐用 marker's Python API 而非 CLI subprocess
|
| 33 |
+
from marker.converters.pdf import PdfConverter
|
| 34 |
+
from marker.models import create_model_dict
|
| 35 |
+
from marker.output import text_from_rendered
|
| 36 |
+
|
| 37 |
+
started = time.time()
|
| 38 |
+
logger.info("Marker parsing: %s", file_path.name)
|
| 39 |
+
|
| 40 |
+
converter = PdfConverter(artifact_dict=create_model_dict())
|
| 41 |
+
rendered = converter(str(file_path))
|
| 42 |
+
markdown, _, _ = text_from_rendered(rendered)
|
| 43 |
+
|
| 44 |
+
# Marker 不直接给 page-level 拆分, 走全文 markdown
|
| 45 |
+
elapsed_ms = int((time.time() - started) * 1000)
|
| 46 |
+
logger.info("Marker done: %dms", elapsed_ms)
|
| 47 |
+
|
| 48 |
+
# 尝试从 rendered 拿 metadata
|
| 49 |
+
meta = rendered.metadata if hasattr(rendered, "metadata") else {}
|
| 50 |
+
page_count = meta.get("page_stats", {}).get("total_pages") if isinstance(meta, dict) else None
|
| 51 |
+
|
| 52 |
+
return ParsedDocument(
|
| 53 |
+
markdown=markdown,
|
| 54 |
+
pages=[], # Marker 不分页
|
| 55 |
+
tables=[],
|
| 56 |
+
images=[],
|
| 57 |
+
meta={
|
| 58 |
+
"parser": self.name,
|
| 59 |
+
"page_count": page_count,
|
| 60 |
+
"elapsed_ms": elapsed_ms,
|
| 61 |
+
},
|
| 62 |
+
)
|
app/services/parsers/simple_parser.py
ADDED
|
@@ -0,0 +1,88 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
"""SimpleParser - 零依赖的 PDF 文本提取 fallback.
|
| 2 |
+
|
| 3 |
+
适用场景:
|
| 4 |
+
- Docling 失败 / 模型下载卡住 / Docling 不可用
|
| 5 |
+
- 文本型 PDF (非扫描件) - 用 pypdf 直接抽文字
|
| 6 |
+
|
| 7 |
+
特性:
|
| 8 |
+
- 零 ML 依赖 (只有 pypdf)
|
| 9 |
+
- 快速, 内存友好
|
| 10 |
+
- 拿不到结构 (无表格识别), 只做 "能分页 + 拿文本"
|
| 11 |
+
|
| 12 |
+
这是 marker-pdf 的替代方案, 因为 marker-pdf 1.10+ 与 pydantic-ai 的 anthropic 版本冲突.
|
| 13 |
+
"""
|
| 14 |
+
from __future__ import annotations
|
| 15 |
+
|
| 16 |
+
import asyncio
|
| 17 |
+
import logging
|
| 18 |
+
import time
|
| 19 |
+
from pathlib import Path
|
| 20 |
+
|
| 21 |
+
from app.services.parsers.base_parser import BaseParser, PageContent, ParsedDocument
|
| 22 |
+
|
| 23 |
+
logger = logging.getLogger(__name__)
|
| 24 |
+
|
| 25 |
+
|
| 26 |
+
class SimpleParser(BaseParser):
|
| 27 |
+
"""pypdf-based 轻量级 PDF 解析器. 兜底中的兜底."""
|
| 28 |
+
|
| 29 |
+
name = "simple"
|
| 30 |
+
|
| 31 |
+
def supported_extensions(self) -> set[str]:
|
| 32 |
+
# 只支持 PDF; 其它格式 (docx/png) 还是走 Docling
|
| 33 |
+
return {".pdf"}
|
| 34 |
+
|
| 35 |
+
async def parse(self, file_path: Path) -> ParsedDocument:
|
| 36 |
+
loop = asyncio.get_running_loop()
|
| 37 |
+
return await loop.run_in_executor(None, self._parse_sync, file_path)
|
| 38 |
+
|
| 39 |
+
def _parse_sync(self, file_path: Path) -> ParsedDocument:
|
| 40 |
+
started = time.time()
|
| 41 |
+
logger.info("SimpleParser (pypdf) parsing: %s", file_path.name)
|
| 42 |
+
|
| 43 |
+
try:
|
| 44 |
+
from pypdf import PdfReader
|
| 45 |
+
except ImportError as e:
|
| 46 |
+
raise RuntimeError(
|
| 47 |
+
"pypdf not installed. Add 'pypdf>=4.0' to requirements.txt"
|
| 48 |
+
) from e
|
| 49 |
+
|
| 50 |
+
reader = PdfReader(str(file_path))
|
| 51 |
+
pages: list[PageContent] = []
|
| 52 |
+
page_texts: list[str] = []
|
| 53 |
+
|
| 54 |
+
for idx, page in enumerate(reader.pages):
|
| 55 |
+
try:
|
| 56 |
+
text = page.extract_text() or ""
|
| 57 |
+
except Exception as e: # noqa: BLE001
|
| 58 |
+
logger.warning("pypdf extract_text failed on page %d: %s", idx, e)
|
| 59 |
+
text = ""
|
| 60 |
+
pages.append(PageContent(
|
| 61 |
+
page_no=idx + 1,
|
| 62 |
+
text=text,
|
| 63 |
+
tables=[], # simple parser 不识别表格
|
| 64 |
+
images=[],
|
| 65 |
+
))
|
| 66 |
+
page_texts.append(text)
|
| 67 |
+
|
| 68 |
+
# 全文 markdown (无结构, 直接拼)
|
| 69 |
+
markdown = "\n\n".join(page_texts)
|
| 70 |
+
|
| 71 |
+
elapsed_ms = int((time.time() - started) * 1000)
|
| 72 |
+
logger.info(
|
| 73 |
+
"SimpleParser done: %s pages, %dms (using pypdf)",
|
| 74 |
+
len(pages), elapsed_ms,
|
| 75 |
+
)
|
| 76 |
+
|
| 77 |
+
return ParsedDocument(
|
| 78 |
+
markdown=markdown,
|
| 79 |
+
pages=pages,
|
| 80 |
+
tables=[],
|
| 81 |
+
images=[],
|
| 82 |
+
meta={
|
| 83 |
+
"parser": self.name,
|
| 84 |
+
"page_count": len(pages),
|
| 85 |
+
"elapsed_ms": elapsed_ms,
|
| 86 |
+
"backend": "pypdf",
|
| 87 |
+
},
|
| 88 |
+
)
|
app/services/persist.py
ADDED
|
@@ -0,0 +1,204 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
"""HF Dataset repo 持久化同步.
|
| 2 |
+
|
| 3 |
+
为什么需要: HF Spaces 免费版磁盘是临时的 (容器重启后 /data 内的非持久卷数据会丢).
|
| 4 |
+
唯一免费的持久化方案是把 /data 同步到 HF Dataset repo (Git LFS).
|
| 5 |
+
|
| 6 |
+
调用模式:
|
| 7 |
+
- lifespan startup: restore_from_hf()
|
| 8 |
+
- 每次写操作后: schedule_push() (异步, 不阻塞用户)
|
| 9 |
+
- lifespan shutdown: push_to_hf() (同步, 尽量)
|
| 10 |
+
|
| 11 |
+
健壮性:
|
| 12 |
+
- 首次部署 (repo 不存在) → 捕获 RepositoryNotFoundError → 标记 "fresh_start"
|
| 13 |
+
- HF_TOKEN 缺失 → 跳过持久化, 降级为纯本地
|
| 14 |
+
- 网络错误 → 重试 3 次后放弃, 不阻塞业务
|
| 15 |
+
- upload_folder 跑在**独立 executor** 上, 不会占业务池 (否则 HF Space → HF Dataset
|
| 16 |
+
一旦卡/慢, ChromaDB query / BGE-M3 encode 等业务的 run_in_executor 全排不上, chat 直接挂)
|
| 17 |
+
- push 失败时**也重置** pending_push flag, 不然 schedule_push 永远 short-circuit
|
| 18 |
+
"""
|
| 19 |
+
from __future__ import annotations
|
| 20 |
+
|
| 21 |
+
import asyncio
|
| 22 |
+
import concurrent.futures
|
| 23 |
+
import logging
|
| 24 |
+
import shutil
|
| 25 |
+
from pathlib import Path
|
| 26 |
+
from typing import Literal
|
| 27 |
+
|
| 28 |
+
from huggingface_hub import (
|
| 29 |
+
create_repo,
|
| 30 |
+
snapshot_download,
|
| 31 |
+
upload_folder,
|
| 32 |
+
)
|
| 33 |
+
from huggingface_hub.errors import RepositoryNotFoundError
|
| 34 |
+
|
| 35 |
+
from app.config import settings
|
| 36 |
+
from app.core.paths import data_dir, sqlite_dir, chroma_dir, upload_dir
|
| 37 |
+
|
| 38 |
+
logger = logging.getLogger(__name__)
|
| 39 |
+
|
| 40 |
+
|
| 41 |
+
# ✅ 独立 ThreadPoolExecutor, 不跟业务 (Chroma / BGE-M3 / run_in_executor) 抢线程
|
| 42 |
+
# 2 个 worker 够用: push 是单飞, 第二个留给 restore (启动期偶发重入)
|
| 43 |
+
_persist_executor = concurrent.futures.ThreadPoolExecutor(
|
| 44 |
+
max_workers=2,
|
| 45 |
+
thread_name_prefix="persist",
|
| 46 |
+
)
|
| 47 |
+
|
| 48 |
+
# 状态机: 持久化是否启用 / 启动模式
|
| 49 |
+
_state: dict[str, str | bool] = {
|
| 50 |
+
"mode": "disabled", # disabled | cold_restore | fresh_start
|
| 51 |
+
"last_push_at": 0.0,
|
| 52 |
+
"pending_push": False,
|
| 53 |
+
}
|
| 54 |
+
|
| 55 |
+
|
| 56 |
+
def persist_mode() -> Literal["disabled", "cold_restore", "fresh_start"]:
|
| 57 |
+
return _state["mode"] # type: ignore[return-value]
|
| 58 |
+
|
| 59 |
+
|
| 60 |
+
async def restore_from_hf() -> None:
|
| 61 |
+
"""从 HF Dataset repo 拉取数据到本地.
|
| 62 |
+
|
| 63 |
+
调用时机: FastAPI lifespan 启动.
|
| 64 |
+
"""
|
| 65 |
+
if not settings.is_persist_enabled():
|
| 66 |
+
logger.info("Persistence disabled (HF_PERSIST_REPO or HF_TOKEN not set)")
|
| 67 |
+
_state["mode"] = "disabled"
|
| 68 |
+
return
|
| 69 |
+
|
| 70 |
+
repo_id = settings.hf_persist_repo
|
| 71 |
+
token = settings.hf_token.get_secret_value()
|
| 72 |
+
local_root = data_dir()
|
| 73 |
+
target_subdirs = ["chroma", "sqlite", "uploads"]
|
| 74 |
+
|
| 75 |
+
loop = asyncio.get_running_loop()
|
| 76 |
+
try:
|
| 77 |
+
await loop.run_in_executor(
|
| 78 |
+
_persist_executor, # ✅ 独立池
|
| 79 |
+
lambda: snapshot_download(
|
| 80 |
+
repo_id=repo_id,
|
| 81 |
+
repo_type="dataset",
|
| 82 |
+
local_dir=str(local_root),
|
| 83 |
+
token=token,
|
| 84 |
+
allow_patterns=[f"{d}/*" for d in target_subdirs] + target_subdirs,
|
| 85 |
+
),
|
| 86 |
+
)
|
| 87 |
+
_state["mode"] = "cold_restore"
|
| 88 |
+
logger.info("Persisted data restored from %s", repo_id)
|
| 89 |
+
except RepositoryNotFoundError:
|
| 90 |
+
# 首次部署: repo 还没创建, 属正常情况
|
| 91 |
+
_state["mode"] = "fresh_start"
|
| 92 |
+
logger.info(
|
| 93 |
+
"Persist repo %s not found (first deploy?). "
|
| 94 |
+
"Will create on first push.",
|
| 95 |
+
repo_id,
|
| 96 |
+
)
|
| 97 |
+
except Exception as e: # noqa: BLE001
|
| 98 |
+
logger.error("Persist restore failed (will start fresh): %s", e)
|
| 99 |
+
_state["mode"] = "fresh_start"
|
| 100 |
+
# 不阻塞启动, 提示用户在 /readyz 看到降级状态
|
| 101 |
+
|
| 102 |
+
|
| 103 |
+
async def push_to_hf() -> None:
|
| 104 |
+
"""同步推送本地数据到 HF Dataset repo. 阻塞."""
|
| 105 |
+
if not settings.is_persist_enabled():
|
| 106 |
+
return
|
| 107 |
+
if _state["mode"] == "fresh_start":
|
| 108 |
+
# 首次需要先 create_repo
|
| 109 |
+
await _ensure_repo_exists()
|
| 110 |
+
|
| 111 |
+
repo_id = settings.hf_persist_repo
|
| 112 |
+
token = settings.hf_token.get_secret_value()
|
| 113 |
+
local_root = data_dir()
|
| 114 |
+
|
| 115 |
+
loop = asyncio.get_running_loop()
|
| 116 |
+
try:
|
| 117 |
+
await loop.run_in_executor(
|
| 118 |
+
_persist_executor, # ✅ 独立池, 不阻塞业务 (Chroma / BGE-M3) 的 run_in_executor
|
| 119 |
+
lambda: upload_folder(
|
| 120 |
+
folder_path=str(local_root),
|
| 121 |
+
repo_id=repo_id,
|
| 122 |
+
repo_type="dataset",
|
| 123 |
+
token=token,
|
| 124 |
+
commit_message=f"sync {asyncio.get_running_loop().time():.0f}",
|
| 125 |
+
ignore_patterns=[".cache/*", "*.tmp", "*.lock"],
|
| 126 |
+
),
|
| 127 |
+
)
|
| 128 |
+
_state["last_push_at"] = asyncio.get_running_loop().time()
|
| 129 |
+
_state["pending_push"] = False
|
| 130 |
+
logger.info("Persisted data pushed to %s", repo_id)
|
| 131 |
+
except Exception as e: # noqa: BLE001
|
| 132 |
+
# ✅ 失败也重置 flag, 否则 schedule_push 永远 short-circuit, 数据再也不推
|
| 133 |
+
_state["pending_push"] = False
|
| 134 |
+
logger.error("Persist push failed: %s", e)
|
| 135 |
+
|
| 136 |
+
|
| 137 |
+
async def schedule_push() -> None:
|
| 138 |
+
"""异步推送, 不阻塞业务. 多次调用合并为一次 (简单去抖).
|
| 139 |
+
|
| 140 |
+
适用: 摄入完成 / 删除文档后.
|
| 141 |
+
"""
|
| 142 |
+
if not settings.is_persist_enabled():
|
| 143 |
+
return
|
| 144 |
+
if not settings.persist_on_write:
|
| 145 |
+
return
|
| 146 |
+
if _state["pending_push"]:
|
| 147 |
+
return # 已有 pending, 跳过
|
| 148 |
+
|
| 149 |
+
_state["pending_push"] = True
|
| 150 |
+
|
| 151 |
+
async def _delayed_push() -> None:
|
| 152 |
+
# 简单去抖: 延迟 30s, 把同一秒内的多次写合并
|
| 153 |
+
await asyncio.sleep(30)
|
| 154 |
+
if _state["pending_push"]:
|
| 155 |
+
await push_to_hf()
|
| 156 |
+
|
| 157 |
+
asyncio.create_task(_delayed_push())
|
| 158 |
+
|
| 159 |
+
|
| 160 |
+
async def _ensure_repo_exists() -> None:
|
| 161 |
+
"""首次部署时自动创建 HF Dataset repo."""
|
| 162 |
+
repo_id = settings.hf_persist_repo
|
| 163 |
+
token = settings.hf_token.get_secret_value()
|
| 164 |
+
loop = asyncio.get_running_loop()
|
| 165 |
+
try:
|
| 166 |
+
await loop.run_in_executor(
|
| 167 |
+
_persist_executor, # ✅ 独立池
|
| 168 |
+
lambda: create_repo(
|
| 169 |
+
repo_id=repo_id,
|
| 170 |
+
repo_type="dataset",
|
| 171 |
+
token=token,
|
| 172 |
+
private=True,
|
| 173 |
+
exist_ok=True,
|
| 174 |
+
),
|
| 175 |
+
)
|
| 176 |
+
logger.info("Created persist repo: %s", repo_id)
|
| 177 |
+
except Exception as e: # noqa: BLE001
|
| 178 |
+
logger.error("Failed to create persist repo: %s", e)
|
| 179 |
+
|
| 180 |
+
|
| 181 |
+
def persist_status() -> dict:
|
| 182 |
+
"""供 /readyz 暴露持久化状态."""
|
| 183 |
+
return {
|
| 184 |
+
"enabled": settings.is_persist_enabled(),
|
| 185 |
+
"mode": _state["mode"],
|
| 186 |
+
"pending_push": _state["pending_push"],
|
| 187 |
+
"repo": settings.hf_persist_repo or None,
|
| 188 |
+
}
|
| 189 |
+
|
| 190 |
+
|
| 191 |
+
def _wipe_local_data() -> None:
|
| 192 |
+
"""测试用: 清空本地 data 目录."""
|
| 193 |
+
for d in (sqlite_dir(), chroma_dir(), upload_dir()):
|
| 194 |
+
if d.exists():
|
| 195 |
+
shutil.rmtree(d, ignore_errors=True)
|
| 196 |
+
|
| 197 |
+
|
| 198 |
+
__all__ = [
|
| 199 |
+
"restore_from_hf",
|
| 200 |
+
"push_to_hf",
|
| 201 |
+
"schedule_push",
|
| 202 |
+
"persist_mode",
|
| 203 |
+
"persist_status",
|
| 204 |
+
]
|