File size: 9,722 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 | #!/usr/bin/env python3
"""
embed.py — Embed marine doc chunks with Gemini Embedding 2 (locked model).
Model: gemini-embedding-2-preview (768-dim, L2-normalized, RETRIEVAL_DOCUMENT).
No substitutes. Reranker is handled separately in search.py (Google Vertex Rank API).
Key resolution order:
1. env GOOGLE_API_KEY
2. env GEMINI_API_KEY
3. vertex_api_key=... in /Users/dmpantiu/cmip6/cmip6_gpt/.env
Modes:
realtime — streaming API, resumable (default)
batch — submit Batch API job (50% cost), then `status` / `download`
status --resume <job>
download --resume <job>
Usage:
python embed.py --mode realtime
python embed.py --mode realtime --limit 20 # smoke test
"""
import argparse
import json
import math
import os
import sys
import time
from pathlib import Path
import numpy as np
import net_ipv4 # noqa: F401 — force IPv4 egress (VPN), must precede genai client
ROOT = Path(__file__).resolve().parent
OUT = ROOT / "out"
IN_JSONL = OUT / "chunks.jsonl"
OUT_JSONL = OUT / "chunks_embedded.jsonl"
BATCH_INPUT = OUT / "batch_embed_input.jsonl"
MODEL = "gemini-embedding-2-preview"
TASK_TYPE = "RETRIEVAL_DOCUMENT"
OUTPUT_DIM = 768
# AQ express key on gemini-embedding-2-preview is quota-capped at ~5 req/min.
# Big batches (100 contents/req) + ~13s spacing keep us under the cap.
RT_BATCH = 100
RT_SLEEP = 13.0
def resolve_key() -> str:
for var in ("GOOGLE_API_KEY", "GEMINI_API_KEY"):
if os.environ.get(var):
return os.environ[var]
# new key lives in copernicus_mcp/.env (field may be misspelled 'veretex_api_key')
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 (GOOGLE_API_KEY / vertex_api_key).")
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(limit=None):
rows = []
with open(IN_JSONL) as f:
for i, line in enumerate(f):
if limit and i >= limit:
break
rows.append(json.loads(line))
return rows
def embed_realtime(chunks):
from google.genai import types
client = get_client()
done = set()
if OUT_JSONL.exists():
for line in open(OUT_JSONL):
try:
done.add(json.loads(line)["chunk_id"])
except Exception:
pass
print(f"resume: {len(done)} already embedded")
todo = [c for c in chunks if c["chunk_id"] not in done]
print(f"to embed: {len(todo)} / {len(chunks)}")
n = 0
with open(OUT_JSONL, "a", encoding="utf-8") as fout:
for b in range(0, len(todo), RT_BATCH):
batch = todo[b:b + RT_BATCH]
texts = [c["text_with_prefix"] for c in batch]
for attempt in range(6):
try:
# genai 1.64 can raise "client has been closed" — recreate on retry
if attempt > 0:
client = get_client()
r = client.models.embed_content(
model=MODEL, contents=texts,
config=types.EmbedContentConfig(
task_type=TASK_TYPE, output_dimensionality=OUTPUT_DIM),
)
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()
break
except Exception as e:
es = str(e)
if "IP address restriction" in es:
raise SystemExit(
"BLOCKED: Gemini key has IP restriction. Whitelist this host's "
"IP in Google Cloud Console (API key settings) and re-run.")
if any(k in es for k in ("429", "RESOURCE_EXHAUSTED", "Quota exceeded")):
wait = 35 # ~5 RPM quota — wait out the minute window
elif "client has been closed" in es:
wait = 2 # flaky genai transport; client recreated on retry
else:
wait = min(8 * (2 ** attempt), 60)
print(f" retry {attempt+1}/8 in {wait}s: {repr(e)[:120]}", file=sys.stderr)
time.sleep(wait)
else:
print(f" FATAL skip {len(batch)}", file=sys.stderr)
if n % 400 == 0:
print(f" [{n}/{len(todo)}]")
time.sleep(RT_SLEEP)
print(f"DONE: {n} embedded → {OUT_JSONL}")
JOB_FILE = OUT / "batch_job.txt"
def prepare_batch(chunks):
# Correct batch schema: request.content (singular) + flat task_type/output_dimensionality.
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} ({BATCH_INPUT.stat().st_size/1e6:.1f} MB, {len(chunks)} reqs)")
def submit_batch():
client = get_client()
up = client.files.upload(file=str(BATCH_INPUT),
config={"display_name": "marine_embed_input", "mime_type": "jsonl"})
job = client.batches.create_embeddings(
model=MODEL, src={"file_name": up.name},
config={"display_name": "marine_docs_embeddings"})
JOB_FILE.write_text(job.name)
print(f"job: {job.name} state: {job.state} (saved to {JOB_FILE})")
return job.name
def _extract_values(resp: dict):
"""Pull the embedding vector out of a batch result line, shape-tolerant."""
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_and_download(chunks, wait=True):
client = get_client()
name = JOB_FILE.read_text().strip()
while True:
job = client.batches.get(name=name)
state = str(job.state)
print(f" job {name}: {state}")
if "SUCCEEDED" in state or "FAILED" in state or "CANCELLED" in state or "EXPIRED" in state:
break
if not wait:
return False
time.sleep(30)
if "SUCCEEDED" not in state:
print(f"job not successful: {state}")
return False
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_metadata") 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)} embeddings → {OUT_JSONL}")
return n >= len(chunks) * 0.99
def main():
ap = argparse.ArgumentParser()
ap.add_argument("--mode", choices=["realtime", "batch", "submit", "poll", "status", "download"],
default="realtime")
ap.add_argument("--limit", type=int, default=None)
ap.add_argument("--resume", type=str, default=None)
a = ap.parse_args()
chunks = load_chunks(a.limit)
toks = sum(c["token_count"] for c in chunks)
print(f"chunks={len(chunks):,} tokens={toks:,} "
f"est realtime=${toks/1e6*0.25:.2f} batch=${toks/1e6*0.125:.2f}")
if a.mode == "realtime":
embed_realtime(chunks)
elif a.mode in ("batch", "submit"):
prepare_batch(chunks)
submit_batch()
if a.mode == "batch":
poll_and_download(chunks, wait=True)
elif a.mode == "poll":
poll_and_download(chunks, wait=True)
elif a.mode in ("status", "download"):
client = get_client()
name = a.resume or JOB_FILE.read_text().strip()
job = client.batches.get(name=name)
print(f"state: {job.state}")
if a.mode == "download":
poll_and_download(chunks, wait=False)
if __name__ == "__main__":
main()
|