| |
| """ |
| 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 |
|
|
| |
| sys.path.insert(0, "/Users/dmpantiu/copernicus_mcp/marine_rag") |
| import net_ipv4 |
|
|
| 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 |
| |
| |
| 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] |
| |
| |
| 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}") |
|
|
|
|
| |
| 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() |
|
|