copernicus-rag-core / scripts /marine_rag /embed_cds_batch.py
dmpantiu's picture
Upload folder using huggingface_hub
0ec8fd6 verified
Raw
History Blame Contribute Delete
3.62 kB
#!/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()