Spaces:
Sleeping

File size: 3,314 Bytes
dee378b
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
"""Build the persisted corpus, manifest and dense indexes.

Usage:
    python scripts/build_index.py                      # all methods (experiments)
    python scripts/build_index.py --methods selected   # only the frozen production backend
"""

from __future__ import annotations

import argparse
import json
import logging
import sys
import time
from datetime import datetime, timezone
from pathlib import Path

import numpy as np

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

from app.data import PREPROCESSING_VERSION, fingerprint, group_duplicates, load_occurrences  # noqa: E402
from app.models import (  # noqa: E402
    ARTIFACTS_DIR, DENSE_MODELS, download_model, embeddings_path, load_encoder, selected_method,
)

DEFAULT_DATA = Path(__file__).resolve().parent.parent / "data" / "ToS"


def main() -> None:
    parser = argparse.ArgumentParser()
    parser.add_argument("--data", type=Path, default=DEFAULT_DATA)
    parser.add_argument("--artifacts", type=Path, default=ARTIFACTS_DIR)
    parser.add_argument("--methods", default="all", help="'all', 'selected' or comma-separated method names")
    args = parser.parse_args()
    logging.basicConfig(level=logging.INFO, format="%(levelname)s %(message)s")
    args.artifacts.mkdir(parents=True, exist_ok=True)

    occurrences = load_occurrences(args.data)
    groups, conflicts = group_duplicates(occurrences)
    (args.artifacts / "corpus.json").write_text(json.dumps([g.to_dict() for g in groups]), encoding="utf-8")
    (args.artifacts / "conflicts.json").write_text(json.dumps(conflicts, indent=2), encoding="utf-8")
    logging.info("%d sentences -> %d unique groups, %d conflicts", len(occurrences), len(groups), len(conflicts))

    if args.methods == "all":
        methods = ["bm25", *DENSE_MODELS]
    elif args.methods == "selected":
        methods = [selected_method(args.artifacts)]
    else:
        methods = args.methods.split(",")

    texts = [g.text for g in groups]
    for method in methods:
        if method not in DENSE_MODELS:
            continue  # BM25 statistics are derived from corpus.json at load time
        download_model(method, args.artifacts)
        t0 = time.perf_counter()
        emb = load_encoder(method, args.artifacts).encode(texts)
        np.save(embeddings_path(method, args.artifacts), emb)
        logging.info("%s: embedded %d groups in %.1fs -> %s", method, len(texts), time.perf_counter() - t0, emb.shape)

    selection_path = args.artifacts / "selection.json"
    selection = json.loads(selection_path.read_text(encoding="utf-8")) if selection_path.exists() else {}
    manifest = {
        "built_at": datetime.now(timezone.utc).isoformat(timespec="seconds"),
        "input_fingerprint": fingerprint(args.data),
        "preprocessing_version": PREPROCESSING_VERSION,
        "n_sentences": len(occurrences),
        "n_groups": len(groups),
        "n_conflicts": len(conflicts),
        "indexed_methods": sorted({"bm25", *methods}),
        "models": {m: DENSE_MODELS[m] for m in methods if m in DENSE_MODELS},
        "selected_backend": selected_method(args.artifacts),
        "split_seed": selection.get("split_seed"),
    }
    (args.artifacts / "manifest.json").write_text(json.dumps(manifest, indent=2), encoding="utf-8")


if __name__ == "__main__":
    main()