File size: 9,652 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
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
#!/usr/bin/env python3
"""
embed_reports.py — embed EQC QA chunks with gemini-embedding-2-preview.

LOCKED: gemini-embedding-2-preview, RETRIEVAL_DOCUMENT, 768-dim, L2-normalized.
IPv4 egress forced (net_ipv4). Key = veretex_api_key in ../.env.

Modes:
  realtime (default) — resumable streaming; on sustained 429 print how to fall
                       back to batch and exit non-zero.
  batch    — submit Gemini Batch API job (schema mirrors marine_rag/embed.py),
             resumable via --mode poll. Sentinel EMBED_DONE written when >=99%.

Usage:
  embed_reports.py                 # realtime
  embed_reports.py --mode batch    # submit batch job
  embed_reports.py --mode poll     # download completed batch job
"""
import argparse
import json
import os
import sys
import time
from pathlib import Path

import numpy as np

# force IPv4 (reuse marine_rag net_ipv4)
sys.path.insert(0, "/Users/dmpantiu/copernicus_mcp/marine_rag")
import net_ipv4  # noqa: F401,E402

ROOT = Path(__file__).resolve().parent
IN = ROOT / "chunks.jsonl"
OUT = ROOT / "chunks_embedded.jsonl"
BATCH_INPUT = ROOT / "batch_embed_input.jsonl"
JOB_FILE = ROOT / "batch_job.txt"
SENTINEL = ROOT / "EMBED_DONE"

MODEL = "gemini-embedding-2-preview"
TASK = "RETRIEVAL_DOCUMENT"
DIM = 768
# Free-tier gemini-embedding-2 quota is tiny/fluctuating and counts per content.
# Keep requests small and well-spaced; the finisher loops passes until complete.
RT_BATCH = 5
RT_SLEEP = 20.0


def log(*a):
    print(*a, file=sys.stderr, flush=True)


def resolve_key() -> str:
    for var in ("GOOGLE_API_KEY", "GEMINI_API_KEY"):
        if os.environ.get(var):
            return os.environ[var]
    for env in (Path("/Users/dmpantiu/copernicus_mcp/.env"),
                Path("/Users/dmpantiu/cmip6/cmip6_gpt/.env")):
        if env.exists():
            for line in env.read_text().splitlines():
                line = line.strip()
                if "api_key" in line.lower() and "=" in line and not line.startswith("#"):
                    return line.split("=", 1)[1].strip().strip('"').strip("'")
    raise SystemExit("No Gemini API key found.")


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


def l2(vec):
    a = np.array(vec, dtype=np.float32)
    n = np.linalg.norm(a)
    return (a / n).tolist() if n > 0 else a.tolist()


def load_chunks():
    return [json.loads(l) for l in open(IN)]


def embedded_keys() -> set:
    keys = set()
    if OUT.exists():
        for line in open(OUT):
            try:
                keys.add(json.loads(line)["chunk_id"])
            except Exception:
                pass
    return keys


def embed_realtime(chunks):
    from google.genai import types
    client = get_client()
    done = embedded_keys()
    if done:
        log(f"resume: {len(done)} already embedded")
    todo = [c for c in chunks if c["chunk_id"] not in done]
    log(f"to embed: {len(todo)} / {len(chunks)}")
    n = 0
    consecutive_429 = 0
    with open(OUT, "a", encoding="utf-8") as fout:
        for b in range(0, len(todo), RT_BATCH):
            batch = todo[b:b + RT_BATCH]
            # genai 2.10: a list[str] is treated as ONE content -> 1 embedding.
            # Wrap each text in a Content object to get one embedding per input.
            contents = [types.Content(parts=[types.Part(text=c["text_with_prefix"])])
                        for c in batch]
            ok = False
            for attempt in range(6):
                try:
                    if attempt > 0:
                        client = get_client()
                    r = client.models.embed_content(
                        model=MODEL, contents=contents,
                        config=types.EmbedContentConfig(
                            task_type=TASK, output_dimensionality=DIM))
                    if len(r.embeddings) != len(batch):
                        raise RuntimeError(
                            f"embedding count mismatch {len(r.embeddings)}!={len(batch)}")
                    for c, e in zip(batch, r.embeddings):
                        c["embedding"] = l2(e.values)
                        fout.write(json.dumps(c, ensure_ascii=False) + "\n")
                        n += 1
                    fout.flush()
                    ok = True
                    consecutive_429 = 0
                    break
                except Exception as e:
                    es = str(e)
                    if "IP address restriction" in es:
                        raise SystemExit(
                            "BLOCKED: Gemini key IP restriction. Whitelist this host's IP.")
                    if any(k in es for k in ("429", "RESOURCE_EXHAUSTED", "Quota exceeded")):
                        wait = 35
                    elif "client has been closed" in es:
                        wait = 2
                    else:
                        wait = min(8 * (2 ** attempt), 60)
                    log(f"  retry {attempt+1}/6 in {wait}s: {repr(e)[:120]}")
                    time.sleep(wait)
            if not ok:
                consecutive_429 += 1
                log(f"  FATAL skip batch of {len(batch)}")
                if consecutive_429 >= 3:
                    log("SUSTAINED 429 — realtime quota exhausted.")
                    log("Fall back to batch: python embed_reports.py --mode batch ; "
                        "then: python embed_reports.py --mode poll")
                    sys.exit(2)
            if n and n % 400 == 0:
                log(f"  [{n}/{len(todo)}]")
            time.sleep(RT_SLEEP)
    finalize(chunks)
    log(f"DONE realtime: {n} newly embedded -> {OUT}")


# ── batch fallback (mirrors marine_rag/embed.py) ─────────────────────────────
def prepare_batch(chunks):
    done = embedded_keys()
    todo = [c for c in chunks if c["chunk_id"] not in done]
    with open(BATCH_INPUT, "w", encoding="utf-8") as f:
        for c in todo:
            f.write(json.dumps({
                "key": c["chunk_id"],
                "request": {
                    "content": {"parts": [{"text": c["text_with_prefix"]}]},
                    "task_type": TASK,
                    "output_dimensionality": DIM,
                }}, ensure_ascii=False) + "\n")
    log(f"batch input: {BATCH_INPUT} ({len(todo)} reqs)")
    return todo


def submit_batch(chunks):
    prepare_batch(chunks)
    client = get_client()
    up = client.files.upload(file=str(BATCH_INPUT),
                             config={"display_name": "eqc_qa_embed", "mime_type": "jsonl"})
    job = client.batches.create_embeddings(
        model=MODEL, src={"file_name": up.name},
        config={"display_name": "eqc_qa_embeddings"})
    JOB_FILE.write_text(job.name)
    log(f"job: {job.name} state: {job.state} (saved {JOB_FILE})")


def _extract_values(resp: dict):
    for path in (("response", "embeddings"), ("response", "embedding"),
                 ("embeddings",), ("embedding",)):
        node = resp; ok = True
        for k in path:
            if isinstance(node, dict) and k in node:
                node = node[k]
            else:
                ok = False; break
        if not ok:
            continue
        if isinstance(node, list) and node and isinstance(node[0], dict) and "values" in node[0]:
            return node[0]["values"]
        if isinstance(node, dict) and "values" in node:
            return node["values"]
    return None


def poll_batch(chunks, wait=True):
    client = get_client()
    name = JOB_FILE.read_text().strip()
    while True:
        job = client.batches.get(name=name)
        state = str(job.state)
        log(f"  job {name}: {state}")
        if any(s in state for s in ("SUCCEEDED", "FAILED", "CANCELLED", "EXPIRED")):
            break
        if not wait:
            return
        time.sleep(30)
    if "SUCCEEDED" not in state:
        log(f"job not successful: {state}"); return
    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, "a", 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
    log(f"downloaded {n} embeddings -> {OUT}")
    finalize(chunks)


def finalize(chunks):
    got = embedded_keys()
    frac = len(got) / max(1, len(chunks))
    log(f"coverage: {len(got)}/{len(chunks)} = {frac:.1%}")
    if frac >= 0.99:
        SENTINEL.write_text(f"{len(got)}/{len(chunks)}\n")
        log(f"SENTINEL {SENTINEL} written")


def main():
    ap = argparse.ArgumentParser()
    ap.add_argument("--mode", choices=["realtime", "batch", "poll"], default="realtime")
    a = ap.parse_args()
    chunks = load_chunks()
    toks = sum(c["token_count"] for c in chunks)
    log(f"chunks={len(chunks):,} tokens={toks:,} est ${toks/1e6*0.25:.2f}")
    if a.mode == "realtime":
        embed_realtime(chunks)
    elif a.mode == "batch":
        submit_batch(chunks)
    elif a.mode == "poll":
        poll_batch(chunks, wait=True)


if __name__ == "__main__":
    main()