documents.py 6.61 KB
"""文档接口:上传 / 列表 / 详情 / 分块预览 / 抽取(后台任务)/ 进度订阅 / 删除。"""
from __future__ import annotations
import hashlib
import logging

from fastapi import APIRouter, File, HTTPException, Request, UploadFile
from sse_starlette.sse import EventSourceResponse

from ..core import db
from ..core.config import get_settings
from ..extract import pipeline
from ..ingest.filename import resolve_upload_path, sanitize_display_name, stored_name
from ..ingest.parse import SUPPORTED, ParseError, parse_file
from ..ingest.chunk import chunk_text
from ..jobs.queue import runner
from . import deps

log = logging.getLogger(__name__)
router = APIRouter(prefix="/api/documents", tags=["documents"])
settings = get_settings()

MAX_UPLOAD_BYTES = 64 * 1024 * 1024


def _upload_path(doc: dict):
    return resolve_upload_path(doc, settings.data_path / "uploads")


@router.post("")
async def upload_document(file: UploadFile = File(...)):
    raw = await file.read()
    if not raw:
        raise HTTPException(400, "文件为空")
    if len(raw) > MAX_UPLOAD_BYTES:
        raise HTTPException(413, f"文件超过 {MAX_UPLOAD_BYTES // 1024 // 1024}MB 上限")

    # 乱码修复的入口:显示名走编码还原,磁盘名退化成 ascii 哈希名
    display = sanitize_display_name(file.filename or "untitled")
    suffix = ("." + display.rsplit(".", 1)[-1].lower()) if "." in display else ""
    if suffix not in SUPPORTED:
        raise HTTPException(
            415, f"暂不支持 {suffix or '无扩展名'} 格式。支持:{'、'.join(sorted(SUPPORTED))}")

    h = hashlib.sha256(raw).hexdigest()[:16]
    existing = db.find_document_by_hash(h)
    if existing:
        return {**existing, "duplicate": True,
                "message": f"该文件已存在(ID {existing['id']}:{existing['filename']})"}

    stored = stored_name(display, h)
    dest = settings.data_path / "uploads" / stored
    dest.write_bytes(raw)
    doc_id = db.create_document(display, str(dest), len(raw), h, stored)
    return {"id": doc_id, "filename": display, "stored_name": stored,
            "size_bytes": len(raw), "status": "uploaded", "duplicate": False}


@router.get("")
async def list_documents():
    docs = db.list_documents()
    for d in docs:
        job = db.active_job_for_doc(d["id"])
        d["active_job"] = {"id": job["id"], "progress": job["progress"], "stage": job["stage"],
                           "status": job["status"]} if job else None
    return docs


@router.get("/{doc_id}")
async def get_document(doc_id: int):
    doc = db.get_document(doc_id)
    if not doc:
        raise HTTPException(404, "文档不存在")
    doc["active_job"] = db.active_job_for_doc(doc_id)
    return doc


@router.get("/{doc_id}/chunks")
async def document_chunks(doc_id: int, preview: bool = False):
    """已入库的分块;preview=true 时现场重新切一遍(用于调参预览,不落库)。"""
    doc = db.get_document(doc_id)
    if not doc:
        raise HTTPException(404, "文档不存在")
    if preview:
        cfg = db.get_all_config()
        try:
            parsed = parse_file(_upload_path(doc))
        except ParseError as e:
            raise HTTPException(400, str(e)) from e
        chunks = chunk_text(parsed.text, doc_id,
                            chunk_tokens=int(cfg.get("CHUNK_TOKENS", "600")),
                            overlap_tokens=int(cfg.get("CHUNK_OVERLAP_TOKENS", "80")),
                            min_tokens=int(cfg.get("MIN_CHUNK_TOKENS", "120")))
        return {"preview": True, "encoding": parsed.encoding,
                "warnings": parsed.warnings, "chunks": chunks}
    recs = [c for c in deps.index().chunks.records if c.get("doc_id") == doc_id]
    recs.sort(key=lambda c: c.get("order", 0))
    return {"preview": False, "chunks": recs}


@router.get("/{doc_id}/entities")
async def document_entities(doc_id: int, limit: int = 200):
    g = deps.graph()
    out = [e for e in g.all_entities() if doc_id in (e.get("doc_ids") or [])]
    out.sort(key=lambda e: -e.get("degree", 0))
    return {"total": len(out), "items": out[:limit]}


@router.post("/{doc_id}/extract")
async def start_extract(doc_id: int):
    """提交后台抽取任务,立即返回 job_id。进度用 /jobs/{id}/events 订阅。"""
    doc = db.get_document(doc_id)
    if not doc:
        raise HTTPException(404, "文档不存在")
    active = db.active_job_for_doc(doc_id)
    if active:
        return {"job_id": active["id"], "already_running": True}

    job_id = db.create_job(doc_id, "extract")

    def factory():
        try:
            yield from pipeline.run_extract(doc_id, str(_upload_path(doc)), deps.graph(),
                                            deps.index(), deps.communities())
        except ParseError as e:
            db.update_document(doc_id, status="failed", error=str(e)[:2000])
            raise
        except Exception as e:  # noqa: BLE001
            db.update_document(doc_id, status="failed", error=str(e)[:2000])
            raise

    ok = runner.submit(job_id, factory)
    if not ok:
        raise HTTPException(503, "任务队列已满,请稍后再试")
    db.update_document(doc_id, status="queued", error="")
    return {"job_id": job_id, "already_running": False,
            "queue_depth": runner.queue_depth()}


@router.delete("/{doc_id}")
async def delete_document(doc_id: int):
    """删除文档:回收它独有的实体/关系与 chunk 索引。v1 没有这个能力。"""
    doc = db.get_document(doc_id)
    if not doc:
        raise HTTPException(404, "文档不存在")
    if db.active_job_for_doc(doc_id):
        raise HTTPException(409, "该文档正在抽取中,请等待任务结束后再删除")
    stats = pipeline.delete_document_data(doc_id, deps.graph(), deps.index(), deps.communities())
    try:
        _upload_path(doc).unlink(missing_ok=True)
    except OSError as e:
        log.warning("删除文件失败 %s:%s", doc.get("stored_name"), e)
    db.delete_document(doc_id)
    return {"ok": True, **stats}


jobs_router = APIRouter(prefix="/api/jobs", tags=["jobs"])


@jobs_router.get("")
async def list_jobs(limit: int = 20):
    return db.list_jobs(limit)


@jobs_router.get("/{job_id}")
async def get_job(job_id: int):
    job = db.get_job(job_id)
    if not job:
        raise HTTPException(404, "任务不存在")
    return job


@jobs_router.get("/{job_id}/events")
async def job_events(job_id: int, request: Request):
    """订阅任务进度。断线可重连,会先补发历史事件 —— 刷新页面不再丢进度。"""
    if not db.get_job(job_id):
        raise HTTPException(404, "任务不存在")
    return EventSourceResponse(deps.sse(runner.subscribe(job_id), request))