Spaces:
Sleeping
Sleeping
jefffffff9 Claude Sonnet 4.6 commited on
Commit ·
3d43385
1
Parent(s): a5737ac
Fix Kaggle trigger: use kaggle CLI push instead of fake /run endpoint
Browse filesThe Kaggle REST API has no /run endpoint. The correct way to trigger
a new kernel run is kaggle kernels push, which creates a new kernel
version (which immediately starts executing on Kaggle's servers).
New approach:
- Reads notebook + kernel-metadata.json from the Space filesystem
- Writes temporary kaggle.json from KAGGLE_USERNAME/KAGGLE_KEY secrets
- Runs: python -m kaggle kernels push -p notebooks/
- Returns the CLI output so errors are visible in the UI
Also logs auto-trigger result to Space logs instead of silently failing.
Co-Authored-By: Claude Sonnet 4.6 <noreply@anthropic.com>
608 unmodified lines6096106116126136146156166176186196206216226236246256266276286296306316326336342 unmodified lines637638639640641642643608 unmodified linesdef _trigger_kaggle_training(lang: str = "bam") -> str:"""Fire the Kaggle kernel via REST API if credentials are configured."""if not KAGGLE_USERNAME or not KAGGLE_KEY:return "⚠️ KAGGLE_USERNAME / KAGGLE_KEY not set in Space secrets — auto-trigger disabled."try:import urllib.request, urllib.parse, base64token = base64.b64encode(f"{KAGGLE_USERNAME}:{KAGGLE_KEY}".encode()).decode()url = f"https://www.kaggle.com/api/v1/kernels/{KAGGLE_KERNEL_SLUG}/run"body = json.dumps({"enableGpu": True}).encode()req = urllib.request.Request(url, data=body, method="POST",headers={"Authorization": f"Basic {token}","Content-Type": "application/json",},)with urllib.request.urlopen(req, timeout=15) as r:resp = json.loads(r.read())return f"✅ Kaggle training triggered! Run ID: {resp.get('currentRunningVersion', 'started')}"except Exception as e:return f"❌ Kaggle trigger failed: {e}"def _maybe_auto_trigger() -> None:2 unmodified linesreturncount = _count_corrections()if count > 0 and count % AUTO_TRAIN_THRESHOLD == 0:threading.Thread(target=_trigger_kaggle_training, daemon=True).start()# ── Bulk upload handler ────────────────────────────────────────────────────────608 unmodified lines6096106116126136146156166176186196206216226236246256266276286296306316326336346356366376386396406416426436446456466476486496506516526536546556566576586596606616626636642 unmodified lines667668669670671672673674675676677608 unmodified linesdef _trigger_kaggle_training(lang: str = "bam") -> str:"""Push the master trainer notebook to Kaggle via the kaggle CLI,which creates a new kernel version (i.e. triggers a run).Requires KAGGLE_USERNAME + KAGGLE_KEY Space secrets.The notebook is read from notebooks/ inside the Space filesystem."""if not KAGGLE_USERNAME or not KAGGLE_KEY:return "⚠️ KAGGLE_USERNAME / KAGGLE_KEY not set in Space secrets."import subprocess, tempfile, shutilnotebooks_dir = ROOT / "notebooks"meta_file = notebooks_dir / "kernel-metadata.json"nb_file = notebooks_dir / "kaggle_master_trainer.ipynb"if not nb_file.exists():return "❌ notebooks/kaggle_master_trainer.ipynb not found in Space."if not meta_file.exists():return "❌ notebooks/kernel-metadata.json not found in Space."# Write kaggle.json to a temp dir so the CLI authenticateswith tempfile.TemporaryDirectory() as tmpdir:kaggle_cfg = Path(tmpdir) / ".kaggle"kaggle_cfg.mkdir()creds_file = kaggle_cfg / "kaggle.json"creds_file.write_text(json.dumps({"username": KAGGLE_USERNAME, "key": KAGGLE_KEY}),encoding="utf-8",)creds_file.chmod(0o600)env = {**__import__("os").environ,"KAGGLE_CONFIG_DIR": str(kaggle_cfg),"PYTHONUTF8": "1","PYTHONIOENCODING": "utf-8",}result = subprocess.run(["python", "-m", "kaggle", "kernels", "push", "-p", str(notebooks_dir)],capture_output=True, text=True, timeout=60, env=env,)if result.returncode == 0:output = (result.stdout or "").strip()return f"✅ Kaggle training triggered!\n{output or 'Kernel version created — check Kaggle for progress.'}"else:err = (result.stderr or result.stdout or "unknown error").strip()return f"❌ Kaggle push failed:\n{err}"def _maybe_auto_trigger() -> None:2 unmodified linesreturncount = _count_corrections()if count > 0 and count % AUTO_TRAIN_THRESHOLD == 0:import loggingdef _run():msg = _trigger_kaggle_training()logging.getLogger(__name__).info("Auto-trigger: %s", msg)threading.Thread(target=_run, daemon=True).start()# ── Bulk upload handler ────────────────────────────────────────────────────────
app.py+53-19