files.py 7.04 KB
"""文件生命周期:上传、列表、解析预览、切片查询、统计。不含索引流程(见 pipeline)。"""
from __future__ import annotations

import asyncio
import os
import shutil
import time

from fastapi import HTTPException, UploadFile
from sqlalchemy import func, select

from config import BASE_DIR
from src.database.models import RagChunk, RagFile
from src.database.session import AsyncSessionLocal
from src.rag.core.config import RAG_PREVIEW_BLOCK_LIMIT, RAG_PREVIEW_TEXT_CHARS, RAG_RAW_DIR
from src.rag.core.utils import file_ext, sha256_file
from src.rag.infra.serializers import _chunk_to_dict, _file_to_dict
from src.rag.infra.vector_store import vector_store
from src.rag.ingestion import build_chunks, parse_document


async def init_upload(files: list[str]) -> dict:
    """
    文件上传第一步:初始化记录。
    
    在数据库中创建处于 'Uploading' 状态的文件记录,并校验是否已有同名文件存在。
    """
    mapping, errors = {}, {}
    async with AsyncSessionLocal() as session:
        for name in files:
            ext = file_ext(name).lstrip(".") or "txt"
            existing = await session.execute(select(RagFile).where(RagFile.name == name, RagFile.status != "Deleted"))
            if existing.scalars().first():
                errors[name] = "文件已存在,请勿重复上传。"
                continue
            raw_dir = os.path.join(RAG_RAW_DIR, ext)
            os.makedirs(raw_dir, exist_ok=True)
            db_file = RagFile(name=name, format=ext.upper(), size=0, source_path=os.path.join(raw_dir, name), status="Uploading")
            session.add(db_file)
            await session.flush()
            mapping[name] = db_file.id
        await session.commit()
    return {"mapping": mapping, "errors": errors}


async def save_upload(file_id: str, upload: UploadFile) -> dict:
    """
    文件上传第二步:保存物理文件流。
    
    将用户上传的二进制流固化到本地指定路径,更新文件大小与 Hash,状态变更为 'Pending'(等待建立索引)。
    """
    async with AsyncSessionLocal() as session:
        db_file = await session.get(RagFile, file_id)
        if not db_file:
            raise HTTPException(status_code=404, detail="RAG file not found")
        if db_file.status != "Uploading":
            raise HTTPException(status_code=400, detail="文件不在 Uploading 状态")
        os.makedirs(os.path.dirname(db_file.source_path), exist_ok=True)
        await asyncio.to_thread(_save_upload_file, db_file.source_path, upload)
        db_file.size = os.path.getsize(db_file.source_path)
        db_file.content_hash = sha256_file(db_file.source_path)
        db_file.status = "Pending"
        await session.commit()
    return {"status": "success"}


async def preview_parse(path: str) -> dict:
    """
    后台调试方法:直接读取本地文件执行解析与切块,并不进行向量化及入库操作。
    主要用于在真实入库前评估解析器的提取质量。
    """
    source_path = _safe_project_path(path)
    if not os.path.exists(source_path):
        raise HTTPException(status_code=404, detail=f"文件不存在: {path}")
    start = time.time()
    blocks = await asyncio.to_thread(parse_document, source_path)
    parents, children = build_chunks("preview", os.path.basename(source_path), source_path, file_ext(source_path).lstrip(".").upper(), blocks)
    table_blocks = [b for b in blocks if b.block_type in {"table", "table_row"}]
    return {
        "path": source_path,
        "blocks": len(blocks),
        "table_blocks": len(table_blocks),
        "parent_chunks": len(parents),
        "child_chunks": len(children),
        "duration_ms": int((time.time() - start) * 1000),
        "sample_blocks": [
            {
                "block_type": b.block_type,
                "page_number": b.page_number,
                "title_path": b.title_path,
                "metadata": b.metadata,
                "text": b.text[:RAG_PREVIEW_TEXT_CHARS],
            }
            for b in blocks[:RAG_PREVIEW_BLOCK_LIMIT]
        ],
    }


async def list_files(page: int, page_size: int, search: str) -> dict:
    """
    分页查询文件列表及当前索引状态。
    支持按文件名模糊搜索。
    """
    async with AsyncSessionLocal() as session:
        query = select(RagFile).where(RagFile.status != "Deleted")
        if search:
            query = query.where(RagFile.name.ilike(f"%{search}%"))
        total = (await session.execute(select(func.count()).select_from(query.subquery()))).scalar() or 0
        rows = (await session.execute(query.order_by(RagFile.created_at.desc()).offset((page - 1) * page_size).limit(page_size))).scalars().all()
        return {"files": [_file_to_dict(f) for f in rows], "total": total, "page": page, "page_size": page_size}

async def get_chunks(file_id: str) -> dict:
    """读取并返回某个文件所有切分的子段列表(含 Chunk 元数据)。"""
    async with AsyncSessionLocal() as session:
        rows = (await session.execute(select(RagChunk).where(RagChunk.file_id == file_id).order_by(RagChunk.chunk_level.desc(), RagChunk.chunk_index))).scalars().all()
        return {"chunks": [_chunk_to_dict(c, preview=False) for c in rows]}


async def get_chunk(chunk_id: str) -> dict:
    async with AsyncSessionLocal() as session:
        row = (await session.execute(select(RagChunk).where(RagChunk.chunk_id == chunk_id))).scalar_one_or_none()
        if not row:
            raise HTTPException(status_code=404, detail="Chunk not found")
        return {"chunk": _chunk_to_dict(row)}

async def stats() -> dict:
    """汇总各个阶段的文件数量及 Qdrant 集群健康概况统计。"""
    async with AsyncSessionLocal() as session:
        total_files = (await session.execute(select(func.count()).select_from(RagFile).where(RagFile.status != "Deleted"))).scalar() or 0
        indexed = (await session.execute(select(func.count()).select_from(RagFile).where(RagFile.status == "Indexed"))).scalar() or 0
        disabled = (await session.execute(select(func.count()).select_from(RagFile).where(RagFile.status == "Disabled"))).scalar() or 0
        indexing = (await session.execute(select(func.count()).select_from(RagFile).where(RagFile.status == "Indexing"))).scalar() or 0
        failed = (await session.execute(select(func.count()).select_from(RagFile).where(RagFile.status == "Failed"))).scalar() or 0
        chunks = (await session.execute(select(func.count()).select_from(RagChunk).where(RagChunk.status == "active"))).scalar() or 0
    return {"files": total_files, "indexed": indexed, "disabled": disabled, "indexing": indexing, "failed": failed, "chunks": chunks, **vector_store.health()}


def _save_upload_file(path: str, upload: UploadFile) -> None:
    with open(path, "wb") as f:
        shutil.copyfileobj(upload.file, f)


def _safe_project_path(path: str) -> str:
    abs_path = os.path.abspath(path)
    base = os.path.abspath(BASE_DIR)
    if not abs_path.startswith(base + os.sep):
        raise HTTPException(status_code=400, detail="只允许导入项目目录内的文件")
    return abs_path