migrate_v1_to_v2.py 6.97 KB
"""v1 → v2 迁移。

做四件事:
1. 修复 MySQL 里已经存成乱码的文件名(`ÐèÇóÎĵµ...` → `需求文档...`)。
2. 把磁盘上的文件改名成 `{hash}{ext}` 的纯 ascii 名,并回写 stored_path / stored_name。
3. 把 v1 的图谱与索引备份到 data/v1_backup/,供 quality_report.py 做新旧质量对比。
4. 可选(--reset)清空 v2 的图谱与索引,为重新抽取做准备。

用法:
    python scripts/migrate_v1_to_v2.py            # 只修乱码 + 备份,不动数据
    python scripts/migrate_v1_to_v2.py --reset    # 顺带清空图谱与索引
"""
from __future__ import annotations
import argparse
import hashlib
import shutil
import sys
from pathlib import Path

sys.path.insert(0, str(Path(__file__).resolve().parent.parent))

# Windows 控制台默认是 GBK,直接 print 乱码字符串会抛 UnicodeEncodeError,
# 反而让"修乱码"的脚本自己先挂掉。这里强制 UTF-8 输出。
if hasattr(sys.stdout, "reconfigure"):
    sys.stdout.reconfigure(encoding="utf-8", errors="replace")
    sys.stderr.reconfigure(encoding="utf-8", errors="replace")


from app.core import db                                       # noqa: E402
from app.core.config import get_settings                      # noqa: E402
from app.core.ontology import default_ontology                    # noqa: E402
from app.ingest.filename import sanitize_display_name, stored_name  # noqa: E402


def backup_v1(data: Path) -> Path | None:
    backup = data / "v1_backup"
    graph = data / "graph.json"
    if not graph.exists():
        print("· 没有找到 data/graph.json,跳过备份")
        return None
    if (backup / "graph.json").exists():
        print(f"· 备份已存在,跳过:{backup / 'graph.json'}")
        return backup
    backup.mkdir(parents=True, exist_ok=True)
    shutil.copy2(graph, backup / "graph.json")
    idx = data / "index"
    if idx.exists():
        shutil.copytree(idx, backup / "index", dirs_exist_ok=True)
    print(f"· 已备份 v1 图谱与索引到 {backup}")
    return backup


def fix_documents(data: Path) -> None:
    uploads = data / "uploads"
    docs = db.list_documents()
    if not docs:
        print("· 库里没有文档记录")
        return
    for d in docs:
        raw_name = d["filename"]
        fixed = sanitize_display_name(raw_name)
        old_path = Path(d["stored_path"])
        changes: dict[str, object] = {}

        if fixed != raw_name:
            changes["filename"] = fixed
            print(f"· #{d['id']} 文件名修复:{raw_name!r} → {fixed!r}")

        # 库里存的可能是容器内路径(/app/data/...),在宿主机上不存在;
        # 文件名本身也可能是乱码。按 ① 同名落到本地 uploads ② 哈希前缀 逐级找回。
        if not old_path.exists() and uploads.exists():
            same_name = uploads / old_path.name
            if same_name.exists():
                old_path = same_name
            elif d.get("file_hash"):
                cand = [p for p in uploads.iterdir()
                        if p.is_file() and p.name.startswith(d["file_hash"])]
                if len(cand) == 1:
                    old_path = cand[0]
            if not old_path.exists():
                # 最后兜底:按内容哈希逐个比对(文件不多,代价可接受)
                for p in uploads.iterdir():
                    if not p.is_file():
                        continue
                    if hashlib.sha256(p.read_bytes()).hexdigest()[:16] == d.get("file_hash"):
                        old_path = p
                        break

        if old_path.exists():
            file_hash = d.get("file_hash") or hashlib.sha256(old_path.read_bytes()).hexdigest()[:16]
            new_name = stored_name(fixed, file_hash)
            new_path = uploads / new_name
            if old_path.resolve() != new_path.resolve():
                uploads.mkdir(parents=True, exist_ok=True)
                shutil.move(str(old_path), str(new_path))
                print(f"·   落盘改名:{old_path.name} → {new_name}")
            changes["stored_name"] = new_name
            changes["stored_path"] = str(new_path)
            if not d.get("file_hash"):
                changes["file_hash"] = file_hash
        else:
            print(f"·   警告:#{d['id']} 的原始文件已不存在({d['stored_path']}),只修数据库显示名")

        if changes:
            db.update_document(d["id"], **changes)


# v1 内置的实体类型清单。库里存的如果**正好**是这一份,说明用户没改过,
# 可以安全升级到 v2 闭集(v2 补了 流程/协议/组织角色,并去掉了 盯防/批次 这类噪声类目)。
_V1_DEFAULT_ENTITY_TYPES = [
    "品牌", "集团", "门店", "兜底协议", "口径", "周期", "产品",
    "指标", "数据源", "数仓层", "分析模型", "策略", "盯防",
    "批次", "角色", "功能项", "业务规则", "任务",
]


def upgrade_ontology() -> None:
    import json as _json
    raw = db.get_config("ONTOLOGY")
    try:
        cur = _json.loads(raw)
    except Exception:
        cur = {}
    cur_types = cur.get("entity_types") or []
    if sorted(cur_types) != sorted(_V1_DEFAULT_ENTITY_TYPES):
        print("· 本体已被自定义过,保持不动(如需升级请到设置页手动勾选)")
        return
    db.set_config({"ONTOLOGY": _json.dumps(default_ontology(), ensure_ascii=False)})
    print("· 本体已升级到 v2 闭集:" + "、".join(default_ontology()["entity_types"]))


def reset_v2(data: Path) -> None:
    for target in (data / "graph.json", data / "communities.json"):
        if target.exists():
            target.unlink()
            print(f"· 已删除 {target.name}")
    idx = data / "index"
    if idx.exists():
        shutil.rmtree(idx)
        print("· 已清空 index/")
    for d in db.list_documents():
        db.update_document(d["id"], status="uploaded", entity_count=0,
                           relation_count=0, chunk_count=0, error="")
    print("· 所有文档已重置为「待抽取」")


def main() -> None:
    ap = argparse.ArgumentParser(description="v1 → v2 迁移")
    ap.add_argument("--reset", action="store_true", help="清空 v2 图谱与索引,准备重新抽取")
    args = ap.parse_args()

    settings = get_settings()
    data = settings.data_path
    print(f"数据目录:{data.resolve()}")

    print("\n[1/4] 初始化 / 升级数据库表结构…")
    db.init_db()

    print("\n[2/4] 备份 v1 数据…")
    backup_v1(data)

    print("\n[3/4] 修复文档文件名与落盘路径…")
    fix_documents(data)

    print("\n[3.5/4] 升级本体类型…")
    upgrade_ontology()

    if args.reset:
        print("\n[4/4] 重置 v2 图谱与索引…")
        reset_v2(data)
    else:
        print("\n[4/4] 跳过重置(加 --reset 可清空图谱与索引)")

    print("\n完成。接下来:启动服务 → 文档页点「抽取」→ 跑完后执行 "
          "scripts/quality_report.py 出新旧对比报告。")


if __name__ == "__main__":
    main()