serializers.py 5.88 KB
"""ORM 与 dict 的相互转换:DB 行 -> API/前端结构,切块数据 -> DB 列。"""
from __future__ import annotations

import json
from typing import Any

from src.database.models import RagChunk, RagFile
from src.rag.core.config import RAG_CHUNK_PREVIEW_CHARS
from src.rag.core.contracts import RAG_CHUNKER_VERSION, RAG_PARSER_VERSION
from src.rag.core.utils import safe_json_dumps
from src.rag.infra.vector_store import vector_store
from src.rag.ingestion.chunking import RagChunkData
from src.rag.ingestion.taxonomy import load_taxonomy


def _file_to_dict(f: RagFile) -> dict:
    return {
        "id": f.id,
        "document_id": f.id,
        "name": f.name,
        "format": f.format,
        "size": f.size,
        "word_count": f.word_count,
        "status": f.status,
        "parser_version": getattr(f, "parser_version", None),
        "chunker_version": getattr(f, "chunker_version", None),
        "block_count": getattr(f, "block_count", 0),
        "chunk_count": f.chunk_count,
        "parent_chunk_count": f.parent_chunk_count,
        "child_chunk_count": f.child_chunk_count,
        "vlm_page_count": getattr(f, "vlm_page_count", 0),
        "vlm_total_tokens": getattr(f, "vlm_total_tokens", 0),
        "vlm_duration_ms": getattr(f, "vlm_duration_ms", 0),
        "error_code": getattr(f, "error_code", None),
        "error_detail_json": _json_or_empty(getattr(f, "error_detail_json", None)),
        "error_message": f.error_message,
        "created_at": f.created_at.strftime("%Y-%m-%d %H:%M:%S") if f.created_at else "",
        "indexed_at": f.indexed_at.strftime("%Y-%m-%d %H:%M:%S") if f.indexed_at else "",
    }

def _as_int(value: Any) -> int | None:
    if value is None or value == "":
        return None
    try:
        return int(value)
    except (TypeError, ValueError):
        return None


def _as_text(value: Any) -> str | None:
    if value is None:
        return None
    if isinstance(value, (list, dict)):
        return safe_json_dumps(value)
    text = str(value).strip()
    return text or None

def _chunk_model_kwargs(c: RagChunkData) -> dict:
    """构建精简 rag_chunks 的写库参数:只写真正用到的列,其余结构化字段全部收进 metadata_json。"""
    metadata = dict(c.metadata_json) if isinstance(c.metadata_json, dict) else {}
    # 业务标签已经全在 metadata_json 里(由 taxonomy 产出),这里只补数据类上的定位字段。
    for key in ("source_path", "file_type", "slide_number", "sheet_name",
                "parser_version", "chunker_version"):
        value = getattr(c, key, None)
        if value is None:
            value = metadata.get(key)
        if value is not None:
            metadata.setdefault(key, value)
    metadata.setdefault("parser_version", RAG_PARSER_VERSION)
    metadata.setdefault("chunker_version", RAG_CHUNKER_VERSION)
    return {
        "chunk_id": c.chunk_id,
        "file_id": c.file_id,
        "parent_chunk_id": c.parent_chunk_id,
        "chunk_level": c.chunk_level,
        "chunk_index": c.chunk_index,
        "content": c.content,
        "content_hash": c.content_hash,
        "token_estimate": c.token_estimate,
        "title_path": c.title_path,
        "source_name": c.source_name,
        "page_start": _as_int(metadata.get("page_start")) or c.page_number,
        "page_end": _as_int(metadata.get("page_end")),
        "row_start": c.row_start,
        "row_end": c.row_end,
        "prev_chunk_id": c.prev_chunk_id,
        "next_chunk_id": c.next_chunk_id,
        "status": c.status,
        # brand_series / business_category 两个业务专用列已从表结构删除——
        # 它们随 taxonomy 变化,写死成列意味着换个领域索引就是两个死列。
        "content_kind": _as_text(metadata.get("content_kind")),
        "section_title": _as_text(metadata.get("section_title")),
        "parse_status": _as_text(metadata.get("parse_status") or "ok"),
        "qdrant_point_id": vector_store.point_id(c.chunk_id),
        "metadata_json": safe_json_dumps(metadata),
    }


def _chunk_to_dict(c: RagChunk, preview: bool = False, source_index: int | None = None) -> dict:
    content = (c.content[:RAG_CHUNK_PREVIEW_CHARS] + "..."
               if preview and len(c.content) > RAG_CHUNK_PREVIEW_CHARS else c.content)
    metadata = _json_or_empty(c.metadata_json)
    data = {
        "chunk_id": c.chunk_id,
        "file_id": c.file_id,
        "document_id": c.file_id,
        "parent_chunk_id": c.parent_chunk_id,
        "chunk_level": c.chunk_level,
        "chunk_index": c.chunk_index,
        "content": content,
        "title_path": c.title_path,
        "source_name": c.source_name,
        "page_start": getattr(c, "page_start", None),
        "page_end": getattr(c, "page_end", None),
        "slide_number": metadata.get("slide_number"),
        "sheet_name": metadata.get("sheet_name"),
        "row_start": c.row_start,
        "row_end": c.row_end,
        "content_kind": getattr(c, "content_kind", None),
        "section_title": getattr(c, "section_title", None),
        "parse_status": getattr(c, "parse_status", None),
        "parse_quality": metadata.get("parse_quality"),
        "status": c.status,
        # 业务标签按 taxonomy 声明动态展开:加一个维度,前端自动拿得到,这里零改动。
        **{name: metadata.get(name) for name in load_taxonomy().filterable_names()},
        "metadata_json": metadata,
        "score": {
            "vector_score": round(float(getattr(c, "vector_score", 0.0) or 0.0), 4),
            "final_score": round(float(getattr(c, "final_score", 0.0) or 0.0), 4),
            "rerank_score": round(float(getattr(c, "rerank_score", 0.0) or 0.0), 4),
        },
    }
    if source_index is not None:
        data["source_index"] = source_index
    return data

def _json_or_empty(value: str | None) -> dict:
    if not value:
        return {}
    try:
        return json.loads(value)
    except Exception:
        return {}