File size: 3,616 Bytes
0ec8fd6
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
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
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
#!/usr/bin/env python3
"""
embed_cds_batch.py — embed the 164 CDS/ADS/EWDS cards via the Gemini Batch API
(free-tier realtime RPM is ~0 on gemini-embedding-2-preview; batch works).

Autonomous: submit → poll every 60s → download → then the caller runs
load_copernicus_docs.py + verify. Writes out/cds_cards_embedded.jsonl and a
marker out/CDS_EMBED_DONE on success.
"""
import json
import time
import sys
from pathlib import Path

import net_ipv4  # noqa: F401
from embed import resolve_key, l2, MODEL, TASK_TYPE, OUTPUT_DIM, _extract_values

ROOT = Path(__file__).resolve().parent
OUT = ROOT / "out"
IN_JSONL = OUT / "cds_cards_chunks.jsonl"
OUT_JSONL = OUT / "cds_cards_embedded.jsonl"
BATCH_INPUT = OUT / "cds_batch_input.jsonl"
JOB_FILE = OUT / "cds_batch_job.txt"
DONE = OUT / "CDS_EMBED_DONE"


def get_client():
    from google import genai
    return genai.Client(api_key=resolve_key())


def prepare(chunks):
    with open(BATCH_INPUT, "w", encoding="utf-8") as f:
        for c in chunks:
            f.write(json.dumps({
                "key": c["chunk_id"],
                "request": {
                    "content": {"parts": [{"text": c["text_with_prefix"]}]},
                    "task_type": TASK_TYPE,
                    "output_dimensionality": OUTPUT_DIM,
                },
            }, ensure_ascii=False) + "\n")
    print(f"batch input: {BATCH_INPUT} ({len(chunks)} reqs)", flush=True)


def submit():
    client = get_client()
    up = client.files.upload(file=str(BATCH_INPUT),
                             config={"display_name": "cds_cards_input", "mime_type": "jsonl"})
    job = client.batches.create_embeddings(
        model=MODEL, src={"file_name": up.name},
        config={"display_name": "copernicus_cds_cards"})
    JOB_FILE.write_text(job.name)
    print(f"job: {job.name}  state: {job.state}", flush=True)
    return job.name


def poll_download(chunks):
    client = get_client()
    name = JOB_FILE.read_text().strip()
    while True:
        job = client.batches.get(name=name)
        state = str(job.state)
        print(f"  {name}: {state}", flush=True)
        if any(s in state for s in ("SUCCEEDED", "FAILED", "CANCELLED", "EXPIRED")):
            break
        time.sleep(60)
    if "SUCCEEDED" not in state:
        print(f"job not successful: {state}", flush=True)
        return 0
    by_key = {c["chunk_id"]: c for c in chunks}
    dest = getattr(job, "dest", None)
    fn = getattr(dest, "file_name", None) if dest else None
    lines = []
    if fn:
        lines = client.files.download(file=fn).decode("utf-8").strip().split("\n")
    elif dest and getattr(dest, "inlined_responses", None):
        lines = [json.dumps(r) for r in dest.inlined_responses]
    n = 0
    with open(OUT_JSONL, "w", encoding="utf-8") as fout:
        for line in lines:
            if not line.strip():
                continue
            r = json.loads(line)
            k = r.get("key") or r.get("custom_id")
            vals = _extract_values(r)
            if k in by_key and vals:
                c = dict(by_key[k])
                c["embedding"] = l2(vals)
                fout.write(json.dumps(c, ensure_ascii=False) + "\n")
                n += 1
    print(f"DOWNLOADED: {n}/{len(chunks)}{OUT_JSONL}", flush=True)
    if n >= len(chunks) * 0.99:
        DONE.write_text(f"{n}/{len(chunks)}")
    return n


def main():
    chunks = [json.loads(l) for l in open(IN_JSONL)]
    resume = "--poll" in sys.argv and JOB_FILE.exists()
    if not resume:
        prepare(chunks)
        submit()
    poll_download(chunks)


if __name__ == "__main__":
    main()