icoa-cli 2.19.447 → 2.19.449

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
@@ -17,3 +17,4 @@
17
17
  */
18
18
  import type { Command } from 'commander';
19
19
  export declare function registerIpynbCommand(program: Command): void;
20
+ export declare function runIpynb(file?: string): Promise<void>;
@@ -1 +1 @@
1
- import{existsSync as e,mkdirSync as o,readFileSync as n,writeFileSync as l}from"node:fs";import{homedir as t}from"node:os";import{Interface as r,createInterface as a}from"node:readline";import{basename as s,dirname as c,isAbsolute as i,join as g,resolve as y}from"node:path";import chalk from"chalk";import{aienvPaths as d}from"../lib/aienv.js";import{AI_MAX_INPUT_CHARS as u,askIoaiOneShot as h}from"./ai4ioai.js";import{getConfig as p}from"../lib/config.js";import{editTextInEditor as m}from"../lib/editor-spawn.js";import{buildSshArgs as f,leaseConnectProblems as w,parseLeaseResponse as b,queueLine as k}from"../lib/gpu.js";import{shouldExecuteCell as v}from"../lib/ipynb-input.js";import{looksLikeMarkdown as $,renderMarkdown as x}from"../lib/md-term.js";import{NotebookKernel as P,buildRemoteBridgeCommand as E}from"../lib/kernel.js";import{getMainRl as G}from"../lib/main-rl.js";import{logCommand as S}from"../lib/logger.js";import{startLogSync as A,stopLogSync as N}from"../lib/log-sync.js";import{cellPreview as j,parseIpynb as q,parsePercentPy as U,parseRunRange as I,serializeIpynb as O,statusChar as C}from"../lib/notebook-doc.js";import{openFile as _}from"../lib/open-file.js";const L=new RegExp(`${String.fromCharCode(27)}\\[[0-9;]*m`,"g");function T(){return(p().language||"en").toLowerCase().startsWith("zh")}export function registerIpynbCommand(p){p.command("ipynb").argument("[file]","notebook (.ipynb) or script (.py, split on # %%) to open").description("Open an in-terminal Python notebook (AI/ML — needs `aienv setup`)").action(async p=>{await async function(p){const b=d(t()),K=g(t(),".icoa","ipynb-out");if(R(),!e(b.python))return console.log(chalk.yellow(" The AI/ML environment is not set up yet.")),console.log(chalk.gray(" Run ")+chalk.bold.cyan("aienv setup")+chalk.gray(" first (one-time, ~300 MB).")),void console.log();const V=p?function(o){const l=i(o)?o:y(process.cwd(),o);if(!e(l))return{doc:{cells:[],path:l,dirty:!1},note:chalk.gray(" new notebook — will be created on ")+chalk.cyan("save")};try{const e=n(l,"utf8"),o=l.endsWith(".ipynb")?q(e):U(e);return{doc:{cells:o,path:l,dirty:!1},note:chalk.gray(" loaded ")+chalk.cyan(l)+chalk.gray(` — ${o.length} cell${1===o.length?"":"s"}. Type `)+chalk.cyan("cells")+chalk.gray(" to list them.")}}catch(e){return{doc:{cells:[],path:null,dirty:!1},note:chalk.yellow(` could not open ${l}: ${e instanceof Error?e.message:String(e)}`)+chalk.gray(" — starting an empty notebook.")}}}(p):null,Q=V?V.doc:{cells:[],path:null,dirty:!1};let X=new P({venvPython:b.python,venvRoot:b.root}),Z=null,ee=z(Q.path);process.stdout.write(chalk.gray(" Starting Python kernel…"));try{await X.start()}catch{return console.log(chalk.red(" failed.")),console.log(chalk.gray(" Check the environment: ")+chalk.cyan("aienv status")),void console.log()}console.log(chalk.green(" ready.")),V&&console.log(V.note),console.log(chalk.bold.white(" ▶ Start here: ")+chalk.bold.cyan("run all")+chalk.gray(" — runs every cell (trains the baseline, writes submission.csv).")),console.log(chalk.gray(" You are already inside the notebook — do ")+chalk.bold.red("not")+chalk.gray(" type ")+chalk.cyan("python file.ipynb")+chalk.gray(". Just ")+chalk.bold.cyan("run all")+chalk.gray(".")),console.log(chalk.gray(" Then: ")+chalk.cyan("cells")+chalk.gray(" list · ")+chalk.cyan("edit N")+chalk.gray(" edit · ")+chalk.cyan("add")+chalk.gray(" new cell · ")+chalk.cyan("save")+chalk.gray(" · ")+chalk.cyan("help")+chalk.gray(" full · ")+chalk.cyan("quit")),console.log(chalk.gray(" Or just type Python and press Enter (blocks continue until a blank line).")),console.log(chalk.bold.yellow(" 🧭 Lost at any point? Type ")+chalk.bold.cyan("guide")+chalk.bold.yellow(" — the full walkthrough + where you are.")),console.log();const oe=G(),ne=null!==oe,le=ne?oe.listeners("line").slice():[];ne&&oe.removeAllListeners("line");const te=ne?oe:a({input:process.stdin,output:process.stdout,terminal:!0}),re=ne?te.prompt:null;ne&&(te.prompt=r.prototype.prompt),ne||A();const ae=[];let se=!1,ce=!1,ie=!1;const ge=()=>{const e=Z?"icoa ipynb ⚡gpu":"icoa ipynb";te.setPrompt(chalk.bold.cyan(ae.length?`${e} ...> `:`${e}> `)),te.prompt()};let ye=()=>{};const de=new Promise(e=>{ye=e}),ue=async()=>{if(!Z)return void console.log(chalk.gray(" not on a GPU kernel."));const e=J();await X.shutdown().catch(()=>{}),e&&await Y("release",e),Z=null,console.log(chalk.green(" ⚡ GPU lease released")+chalk.gray(" — billing stopped.")),await(async()=>{X=new P({venvPython:b.python,venvRoot:b.root}),process.stdout.write(chalk.gray(" Starting local kernel…"));try{await X.start(),console.log(chalk.green(" ready.")+chalk.gray(" (local CPU — variables were reset)"))}catch{console.log(chalk.red(" failed.")+chalk.gray(" Check ")+chalk.cyan("aienv status"))}})()},he=async e=>{const[n,...r]=e.trim().split(/\s+/),a=(n??"").toLowerCase();"on"===a||"connect"===a?await(async()=>{if(Z)return void console.log(chalk.gray(" already on the GPU kernel — ")+chalk.cyan("gpu status")+chalk.gray(" for time left."));const e=J();if(!e)return console.log(chalk.yellow(" No GPU access key found.")),void console.log(chalk.gray(" Save yours once with ")+chalk.cyan("gpu key <your-key>")+chalk.gray(" (issued by your coach/ICOA)."));ee||(ee=z(Q.path)),process.stdout.write(chalk.gray(" Requesting a GPU box…"));let n=await Y("lease",e,ee??void 0),r=0;for(;"queued"===n.state&&r<24;)0===r&&console.log(),process.stdout.write(`\r ${chalk.yellow(k(n))} `),await new Promise(e=>setTimeout(e,5e3)),n=await Y("status",e),r++;if("queued"===n.state)return console.log(),console.log(chalk.yellow(" Still queued — your place is held server-side.")),void console.log(chalk.gray(" Keep working locally; ")+chalk.cyan("gpu on")+chalk.gray(" again in a few minutes."));if("ready"!==n.state)return void console.log(chalk.red(" failed.")+chalk.gray(` ${n.message??"no lease granted"}`));const a=w(n);if("local"!==n.transport||process.env.ICOA_GPU_SERVER||a.push("local transport from a non-dev broker"),a.length>0)return console.log(chalk.red(" rejected: ")+chalk.gray(a.join(", "))),void await Y("release",e);const s=ee?`${n.dataRoot}/${ee}`:n.dataRoot,c=E(n.python,{ICOA_KAGGLE_DATA:s,ICOA_KAGGLE_OUT:n.outDir},n.outDir);let i;if("local"===n.transport)i={command:"/bin/sh",args:["-c",c]};else{const r=g(t(),".icoa","gpu","lease-key");try{o(g(t(),".icoa","gpu"),{recursive:!0}),l(r,n.keyPem,{mode:384})}catch{return console.log(chalk.red(" could not write the ssh key locally.")),void await Y("release",e)}i={command:"ssh",args:f(n,r,c)}}const y=new P({spawnSpec:i,readyTimeoutMs:9e4});process.stdout.write(chalk.gray(" connecting…"));try{await y.start()}catch(o){return console.log(chalk.red(" connect failed.")),console.log(chalk.gray(` ${o instanceof Error?o.message:String(o)}`)),void await Y("release",e)}await X.shutdown().catch(()=>{}),X=y,Z=n;const d=Math.round((n.timeLeftSec??0)/60);console.log(chalk.bold.green(" ⚡ GPU connected.")),console.log(chalk.gray(` Cells now run on the GPU box · ${d}m left on this lease.`)),console.log(chalk.gray(" Variables were reset — ")+chalk.cyan("run all")+chalk.gray(" to retrain there.")),ee&&console.log(chalk.gray(` Dataset is already on the box (${ee}) — same cells, no edits.`)),console.log(chalk.gray(" When done: ")+chalk.cyan("download")+chalk.gray(" your submission, then ")+chalk.cyan("gpu off")+chalk.gray("."))})():"off"===a||"disconnect"===a?await ue():"status"===a||""===a?await(async()=>{const e=J();if(!e)return void console.log(chalk.gray(" no GPU key saved — ")+chalk.cyan("gpu key <your-key>"));const o=await Y("status",e);if("ready"===o.state){const e=Math.round((o.timeLeftSec??0)/60);console.log(chalk.green(` ⚡ GPU lease active · ${e}m left`)+chalk.gray(Z?" (this notebook is connected)":" (not connected here — gpu on)"))}else"queued"===o.state?console.log(chalk.yellow(` ${k(o)}`)):"none"===o.state?console.log(chalk.gray(" no GPU lease — ")+chalk.cyan("gpu on")+chalk.gray(" to request one.")):console.log(chalk.yellow(` ${o.message??"GPU broker not reachable"}`))})():"queue"===a||"q"===a?await(async()=>{const e=J();if(!e)return void console.log(chalk.gray(" no GPU key saved — ")+chalk.cyan("gpu key <your-key>"));let o=null;try{const n=await fetch(`${B()}/api/icoa/gpu/queue`,{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({key:e}),signal:AbortSignal.timeout(15e3)}),l=await n.json();o=l.data??l}catch{o=null}if(!o||"object"!=typeof o)return void console.log(chalk.yellow(" GPU queue not reachable right now — try again in a moment."));const n="number"==typeof o.boxes?o.boxes:0,l="number"==typeof o.free?o.free:0,t=Array.isArray(o.running)?o.running:[],r=Array.isArray(o.waiting)?o.waiting:[];console.log(),console.log(chalk.bold.cyan(" GPU queue")+chalk.gray(` · ${n} box${1===n?"":"es"} · ${l} free`)),console.log(chalk.bold.white(" ▶ running now:")),0===t.length&&console.log(chalk.gray(" (idle — gpu on takes a box immediately)"));for(const e of t){const o="string"==typeof e.label?e.label:"?",n="number"==typeof e.time_left_sec?e.time_left_sec:0,l=Math.floor(n/60),t=String(n%60).padStart(2,"0"),r=e.is_you?chalk.green(" ← you"):"";console.log(chalk.gray(" ")+chalk.white(o.padEnd(8))+chalk.gray(` ${l}:${t} left`)+r)}console.log(chalk.bold.white(` ⏳ waiting (${r.length}):`)),0===r.length&&console.log(chalk.gray(" (nobody queued)"));for(const e of r){const o="string"==typeof e.label?e.label:"?",n="number"==typeof e.position?e.position:"?",l=e.is_you?chalk.green(" ← you"):"";console.log(chalk.gray(` #${n} `)+chalk.white(o.padEnd(8))+l)}console.log()})():"key"===a?(e=>{const n=e.trim();if(n)try{o(g(t(),".icoa"),{recursive:!0}),l(W(),`${n}\n`,{mode:384}),console.log(chalk.green(" ✓ GPU key saved")+chalk.gray(" — ")+chalk.cyan("gpu on")+chalk.gray(" when you need the box."))}catch{console.log(chalk.red(" could not save the key")+chalk.gray(` (${W()})`))}else console.log(chalk.yellow(" usage: ")+chalk.cyan("gpu key <your-key>"))})(r.join(" ")):console.log(chalk.yellow(" usage: ")+chalk.cyan("gpu on")+chalk.yellow(" · ")+chalk.cyan("gpu off")+chalk.yellow(" · ")+chalk.cyan("gpu status")+chalk.yellow(" · ")+chalk.cyan("gpu queue")+chalk.yellow(" · ")+chalk.cyan("gpu key <k>"))},pe=e=>{const o=Number(e.trim());return!Number.isInteger(o)||o<1||o>Q.cells.length?(console.log(0===Q.cells.length?chalk.yellow(" no cells yet — type Python or use ")+chalk.cyan("add"):chalk.yellow(` no cell ${e.trim()||"?"} — pick 1-${Q.cells.length} (see `)+chalk.cyan("cells")+chalk.yellow(")")),null):{cell:Q.cells[o-1],idx:o}},me=(e,o)=>{if(e.length<=o)return e;const n=Math.floor(.6*o);return`${e.slice(0,n)}\n…(${e.length-o} chars elided)…\n${e.slice(-(o-n))}`};let fe=!1;const we=async e=>{const o=e.trim().split(/\s+/).filter(Boolean),l=o.length>0&&/^\d+$/.test(o[0]),t=(l?o.slice(1):o).join(" ").trim(),r=l?Number(o[0]):(()=>{for(let e=Q.cells.length-1;e>=0;e--)if((Q.cells[e].result?.outputs??[]).some(e=>"error"===e.kind))return e+1;return null})()??Q.cells.length;if(0===Q.cells.length)return void console.log(chalk.yellow(" 还没有 cell —— 先写点代码,或用 ")+chalk.cyan("add"));const a=pe(String(r));if(!a)return;if("markdown"===a.cell.kind)return void console.log(chalk.yellow(` cell ${a.idx} 是 markdown —— 挑一个代码格,比如 `)+chalk.cyan("ai 2"));const s=(e=>{const o=[];for(const n of e.result?.outputs??[])"stream"===n.kind||"result"===n.kind?o.push(n.text):"error"===n.kind&&(o.push(`${n.ename}: ${n.evalue}`),o.push(n.traceback.map(e=>e.replace(L,"")).join("\n")));return o.join("\n").replace(L,"").replace(/\n{3,}/g,"\n\n").trim()})(a.cell),i=(()=>{if(!Q.path||!z(Q.path))return"";try{const e=JSON.parse(n(g(c(Q.path),"meta.json"),"utf-8")),o=[e.title,e.metric?`metric: ${e.metric}`:"",e.description].filter(Boolean).join("\n");return me(o,350)}catch{return""}})(),y=T(),d=y?"你在帮一个 IOAI 选手调试 notebook。先说清楚这一格为什么会这样,再给出最小改动。用中文回答,简洁,给可直接粘回去的代码。":"You are helping an IOAI contestant debug a notebook cell. Say why it behaves this way, then give the smallest fix. Be concise and give code that can be pasted straight back.",p=d.length+t.length+120,m=Math.max(400,u-p-i.length),f=me(a.cell.source,Math.floor(.6*m)),w=s?($=s,P=m-f.length,$.length<=P?$:`…(${$.length-P} chars elided)…\n${$.slice(-P)}`):"",b=[d,i?`\n[task]\n${i}`:"",`\n[cell ${a.idx} code]\n${f}`,w?`\n[cell ${a.idx} output]\n${w}`:"\n(this cell has not been run yet)",t?`\n[question]\n${t}`:""].filter(Boolean).join("\n"),k=b.includes("chars elided"),v=y;var $,P;console.log(),fe||(fe=!0,console.log(chalk.gray(" ")+chalk.bold.white("IOAI 2026 ")+chalk.white("Gemma 3n E4B")+chalk.gray(" (32k) · ")+chalk.white(T()?"单轮无记忆":"single-turn, no memory")+chalk.gray(" · ")+chalk.white(`${u} ${T()?"字符/条":"chars/message"}`)+chalk.gray(" · ")+chalk.white(T()?"1000 token/回复":"1000 tokens/reply")),console.log(chalk.gray(T()?" —— 现场就是这个模型和这几条上限,在这里练的手感能原样带过去。":" — the onsite model and the onsite limits, so the habit transfers as-is."))),console.log(chalk.gray(` → cell ${a.idx} · ${b.length}/${u} chars`)+chalk.gray(v?" · 单轮(竞赛档模型)":" · single-turn (contest model)")+(s?chalk.gray(v?" · 含输出":" · output included"):"")+(k?chalk.yellow(v?" ⚠ 上下文被裁过,加一句具体问题会更准":" ⚠ context trimmed — a specific question helps"):"")),S(`ipynb: ai ${a.idx}${t?` — ${t}`:""}`);const E=await h(b);if(console.log(),!E.ok)return console.log(chalk.yellow(" AI 现在连不上 —— ")+chalk.gray(E.text)),console.log(chalk.gray(" 过一会儿再试,或用 ")+chalk.cyan("ai4ioai")+chalk.gray(" 单开一个会话。")),void console.log();for(const e of x(E.text))console.log(e);console.log(),console.log(chalk.gray(" ")+chalk.cyan(`ai ${a.idx} ${v?"<你的问题>":"<your question>"}`)+chalk.gray(v?" 追问 · ":" follow up · ")+chalk.cyan(`edit ${a.idx}`)+chalk.gray(v?" 改这一格 · ":" edit it · ")+chalk.cyan(`run ${a.idx}`)+chalk.gray(v?" 再跑一次":" run it again")),console.log(chalk.gray(v?" 这是调试助手(超限自动裁剪);想练现场那堵墙用 ":" This is the debugging aid (it trims to fit). To train against the real wall: ")+chalk.cyan("ai4ioai")),console.log()},be=(e,o)=>!(!e.result||e.result.ok)&&!(!e.result.outputs.some(e=>"error"===e.kind&&"SyntaxError"===e.ename)||!$(e.source)||(console.log(chalk.gray(" ✎ looks like text/markdown, not Python — ")+chalk.cyan(`md ${o}`)+chalk.gray(" converts this cell to markdown (new note: ")+chalk.cyan("add md")+chalk.gray(").")),0)),ke=async t=>{if(t.trim()&&S(`ipynb: ${t.trim()}`),ce)return void(t.trim()&&console.log(chalk.gray(" (busy — wait for the current cell to finish, then retype)")));let r=t.trim();if(0===ae.length&&/^icoa\s+[a-z/]/i.test(r)&&(r=r.replace(/^icoa\s+/i,"")),0===ae.length){const t=r.split(/\s+/),a=(t[0]??"").toLowerCase(),d=r.slice(t[0]?.length??0).trim();if("quit"!==a&&"exit"!==a&&"q"!==a&&(ie=!1),"quit"===a||"exit"===a||"back"===a||"q"===a||"menu"===a)return Q.dirty&&!ie?(ie=!0,console.log(chalk.yellow(" unsaved changes — ")+chalk.cyan("save")+chalk.yellow(" first, or type ")+chalk.cyan("quit")+chalk.yellow(" again to discard.")),void ge()):void await(async()=>{if(te.removeAllListeners("line"),ne||N(),console.log(),Z){const e=J();e&&await Y("release",e),Z=null,console.log(chalk.green(" ⚡ GPU lease released")+chalk.gray(" — billing stopped."))}if(console.log(chalk.gray(" Notebook closed. Kernel stopped.")),console.log(),await X.shutdown().catch(()=>{}),ne){re&&(te.prompt=re);for(const e of le)te.on("line",e);te.prompt(),ye()}else ye(),te.close()})();if("clear"===a||"cls"===a)return console.clear(),R(),void ge();if("restart"===a)return await(async()=>{process.stdout.write(chalk.gray(" Restarting kernel…")),await X.shutdown().catch(()=>{});try{await X.start(),console.log(chalk.green(" fresh kernel ready.")+chalk.gray(" (all variables cleared)"))}catch{console.log(chalk.red(" restart failed.")+chalk.gray(" Leave and re-enter the notebook."))}})(),void ge();if("help"===a||"?"===a)return console.log(),console.log(chalk.bold.white(" Notebook commands")),console.log(chalk.cyan(" cells")+chalk.gray(" list cells (○ not run · ✓ ok · ✗ error)")),console.log(chalk.cyan(" show N")+chalk.gray(" print cell N source + outputs")),console.log(chalk.cyan(" edit N")+chalk.gray(" edit cell N in your editor ($EDITOR, default vi)")),console.log(chalk.cyan(" add")+chalk.gray(" write a new Python cell in your editor")),console.log(chalk.cyan(" add md")+chalk.gray(" write a markdown/text cell (notes, headings)")),console.log(chalk.cyan(" md N / py N")+chalk.gray(" convert cell N to markdown / Python")),console.log(chalk.cyan(" del N")+chalk.gray(" delete cell N")),console.log(chalk.cyan(" run N")+chalk.gray(" run cell N — markdown cells render (also: run 2-5, run all)")),console.log(chalk.cyan(" ai [N] [问题]")+chalk.gray(T()?" 问 AI 这一格(默认最近报错的那格;带上代码和 traceback)":" ask the AI about a cell (defaults to the last one that errored)")),console.log(chalk.cyan(" save [file]")+chalk.gray(" save as a real .ipynb")),console.log(chalk.cyan(" restart")+chalk.gray(" restart the kernel (wipes all variables)")),console.log(chalk.cyan(" gpu on/off")+chalk.gray(" run cells on a leased GPU box (dataset pre-mounted)")),console.log(chalk.cyan(" gpu status")+chalk.gray(" your lease/queue · ")+chalk.cyan("gpu queue")+chalk.gray(" who is on the GPU now")),console.log(chalk.cyan(" gpu key <k>")+chalk.gray(" save your access key")),console.log(chalk.cyan(" download")+chalk.gray(" pull submission.csv from the GPU box to this machine")),console.log(chalk.cyan(" open")+chalk.gray(" reopen the last figure in your image viewer")),console.log(chalk.cyan(" clear")+chalk.gray(" clear the screen · ")+chalk.cyan("quit")+chalk.gray(" leave")),console.log(chalk.gray(" Everything else runs as Python in the persistent kernel (and is appended as a cell).")),console.log(),void ge();if("guide"===a||"/guide"===a)return(()=>{const o=Q.path?c(Q.path):process.cwd(),l=z(Q.path);let t="",r=!1;try{const e=JSON.parse(n(g(o,"meta.json"),"utf-8"));t=e.judge??"",r=!0===e.needs_gpu}catch{}const a=Q.cells.filter(e=>null!==e.result).length,i=e(g(o,"submission.csv"));console.log(),console.log(chalk.bold.white(" ═══ 📖 Notebook guide ═══")),console.log(),console.log(chalk.gray(" Where you are: ")+chalk.white(Q.path?s(Q.path):"new empty notebook")+chalk.gray(` · ${Q.cells.length} cells (${a} run) · submission.csv: `)+(i?chalk.green("written ✓"):chalk.yellow("not yet — run all"))),Z?console.log(chalk.gray(" ⚡ GPU: ")+chalk.green("connected")+chalk.gray(" — ")+chalk.cyan("gpu status")+chalk.gray(" your time left · ")+chalk.cyan("gpu queue")+chalk.gray(" who is on · ")+chalk.cyan("download <file>")+chalk.gray(" pull results")):r&&console.log(chalk.gray(" ⚡ GPU task, not connected — ")+chalk.cyan("gpu key <your-key>")+chalk.gray(" then ")+chalk.cyan("gpu on")+chalk.gray(" · ")+chalk.cyan("gpu queue")+chalk.gray(" shows who is on")),console.log(),console.log(chalk.bold.white(" The loop:")),console.log(chalk.gray(" 1. ")+chalk.bold.cyan("run all")+chalk.gray(" — trains the baseline, writes submission.csv")),l&&"icoa-holdout"===t?(console.log(chalk.gray(" 2. ")+chalk.cyan("quit")+chalk.gray(", then ")+chalk.cyan(`kaggle submit ${l}`)+chalk.gray(" — scored + ranked on the live board")),console.log(chalk.gray(" 3. come back, improve the MODEL cell (")+chalk.cyan("cells")+chalk.gray(" lists them, ")+chalk.cyan("edit N")+chalk.gray(" edits) — beat your score."))):l&&r?(console.log(chalk.gray(" 2. ")+chalk.cyan("download <file>")+chalk.gray(" — pull your results (submission.csv / predictions.zip) off the GPU box")),console.log(chalk.gray(" 3. submit on kaggle.com — the notebook's final cell has the exact steps")),console.log(chalk.gray(" 4. come back, improve the MODEL cell (")+chalk.cyan("cells")+chalk.gray(" lists them, ")+chalk.cyan("edit N")+chalk.gray(" edits) — beat it."))):l?(console.log(chalk.gray(" 2. ")+chalk.cyan("quit")+chalk.gray(", then ")+chalk.cyan(`kaggle check ${l}`)+chalk.gray(" — verifies the file format")),console.log(chalk.gray(" 3. upload submission.csv on kaggle.com — read your public score")),console.log(chalk.gray(" 4. come back, improve the MODEL cell (")+chalk.cyan("cells")+chalk.gray(" lists them, ")+chalk.cyan("edit N")+chalk.gray(" edits) — beat it."))):console.log(chalk.gray(" 2. edit cells (")+chalk.cyan("edit N")+chalk.gray("), re-run, ")+chalk.cyan("save")+chalk.gray(" — this is a free notebook.")),console.log(),console.log(chalk.bold.white(" If it looks stuck:")),console.log(chalk.gray(" · prompt shows ")+chalk.cyan("...>")+chalk.gray(" → you are inside a code block. Press Enter on an ")+chalk.bold.white("empty line")+chalk.gray(".")),console.log(chalk.gray(" · never type ")+chalk.cyan("python file.ipynb")+chalk.gray(" here — you are already inside. Just ")+chalk.bold.cyan("run all")+chalk.gray(".")),console.log(),console.log(chalk.bold.white(" 🤝 AI help: ")+chalk.gray("split the screen ")+chalk.bold.cyan("Ctrl-b %")+chalk.gray(" · right pane: ")+chalk.bold.cyan("icoa")+chalk.gray(" then ")+chalk.bold.cyan("ai4ioai")+chalk.gray(" — live Gemma 3")),console.log(chalk.gray(" All commands: ")+chalk.cyan("help")+chalk.gray(" · leave: ")+chalk.cyan("quit")),console.log()})(),void ge();if("python"===a||"python3"===a)return console.log(chalk.gray(" You're already inside the notebook kernel — no need to run python.")),console.log(chalk.gray(" Type ")+chalk.bold.cyan("run all")+chalk.gray(" to run every cell, or ")+chalk.cyan("guide")+chalk.gray(" for the basics.")),void ge();if("open"===a)return F&&_(F)?console.log(chalk.gray(" reopening ")+chalk.cyan(F)):console.log(chalk.gray(" no figure yet — plot something (e.g. matplotlib) first.")),void ge();if("cells"===a||"ls"===a)return(()=>{if(0===Q.cells.length)return void console.log(chalk.gray(" no cells yet — type Python, or ")+chalk.cyan("add")+chalk.gray(" to write one in your editor."));console.log();const e=Math.max(20,(process.stdout.columns??80)-12);Q.cells.forEach((o,n)=>{const l=C(o),t="✓"===l?chalk.green(l.padEnd(2)):"✗"===l?chalk.red(l.padEnd(2)):"md"===l?chalk.magenta(l.padEnd(2)):chalk.gray(l.padEnd(2));console.log(`${chalk.cyan(String(n+1).padStart(4))} ${t} ${chalk.white(j(o,e))}`)}),console.log(),console.log(chalk.gray(" ")+chalk.cyan("show N")+chalk.gray(" · ")+chalk.cyan("edit N")+chalk.gray(" · ")+chalk.cyan("run N")+chalk.gray(" · ")+chalk.cyan("run all"))})(),void ge();if("show"===a)return(e=>{const o=pe(e);if(o){if(console.log(),console.log(chalk.gray(` ── cell ${o.idx} ${"markdown"===o.cell.kind?"(markdown) ":""}──`)),"markdown"===o.cell.kind){for(const e of x(o.cell.source))console.log(e);console.log(chalk.gray(" (rendered — ")+chalk.cyan(`edit ${o.idx}`)+chalk.gray(" for the raw source)"))}else for(const e of o.cell.source.split("\n"))console.log(chalk.white(` ${e}`));o.cell.result&&(console.log(chalk.gray(" ── output ──")),H(o.cell.result,K)),console.log()}})(d),void ge();if("edit"===a)return(e=>{const o=pe(e);if(!o)return;te.pause();const n=m(o.cell.source,"markdown"===o.cell.kind?".md":".py");if(te.resume(),null===n)return void console.log(chalk.yellow(" editor cancelled or failed — cell unchanged.")+chalk.gray(" (set $EDITOR to choose your editor)"));const l=n.replace(/\s+$/,"");l!==o.cell.source?(o.cell.source=l,o.cell.result=null,o.cell.rawOutputs=void 0,o.cell.rawExecCount=void 0,Q.dirty=!0,console.log(chalk.green(` ✓ cell ${o.idx} updated`)+chalk.gray(" — ")+chalk.cyan(`run ${o.idx}`)+chalk.gray(" to execute."))):console.log(chalk.gray(" no changes."))})(d),void ge();if("add"===a)return(e=>{const o=e.trim().toLowerCase(),n="md"===o||"markdown"===o||"text"===o||"txt"===o;if(o&&!n&&"py"!==o&&"code"!==o&&"python"!==o)return void console.log(chalk.yellow(" usage: ")+chalk.cyan("add")+chalk.yellow(" (Python cell) · ")+chalk.cyan("add md")+chalk.yellow(" (markdown/text cell)"));te.pause();const l=m(n?"\x3c!-- markdown cell — write notes/headings, save & exit --\x3e\n":"",n?".md":".py");te.resume();const t=null===l?"":l.replace(/^<!-- markdown cell[^\n]*-->\n?/,"").replace(/\s+$/,"");t?(Q.cells.push({kind:n?"markdown":"code",source:t,result:null}),Q.dirty=!0,console.log(chalk.green(` ✓ added ${n?"markdown ":""}cell ${Q.cells.length}`)+chalk.gray(" — ")+chalk.cyan(`run ${Q.cells.length}`)+chalk.gray(n?" to render it.":" to execute."))):console.log(chalk.gray(" nothing added."))})(d),void ge();if("del"===a||"delete"===a)return(e=>{const o=pe(e);o&&(Q.cells.splice(o.idx-1,1),Q.dirty=!0,console.log(chalk.gray(` deleted cell ${o.idx} — ${Q.cells.length} left.`)+(o.idx<=Q.cells.length?chalk.yellow(" ⚠ 后面的 cell 号已顺移")+chalk.gray(" — ")+chalk.cyan("cells")+chalk.gray(" 重看一眼"):"")))})(d),void ge();if(("md"===a||"py"===a)&&/^\d+$/.test(d))return((e,o)=>{const n=pe(e);if(!n)return;const l="markdown"===o?"markdown":"Python";n.cell.kind!==o?(n.cell.kind=o,n.cell.result=null,n.cell.rawOutputs=void 0,n.cell.rawExecCount=void 0,Q.dirty=!0,console.log(chalk.green(` ✓ cell ${n.idx} → ${l}`)+chalk.gray(" — ")+chalk.cyan(`run ${n.idx}`)+chalk.gray("markdown"===o?" to render it.":" to execute."))):console.log(chalk.gray(` cell ${n.idx} is already ${l}.`))})(d,"md"===a?"markdown":"code"),void ge();if("gpu"===a)return ce=!0,await he(d),ce=!1,void ge();if("download"===a||"dl"===a)return ce=!0,await(async e=>{if(!Z)return void console.log(chalk.gray(" local kernel — your files are already on this machine (no download needed)."));const n=e.trim()||"submission.csv",t=n.startsWith("/")?n:`${Z.outDir}/${n}`;let r;try{r=await X.fetchFile(t)}catch(e){return console.log(chalk.yellow(` could not fetch ${t}: `)+chalk.gray(e instanceof Error?e.message:String(e))),void console.log(chalk.gray(" (run the submission cell first — it writes into the GPU workspace)"))}const a=ee?g(process.cwd(),"icoa-kaggle",ee):process.cwd(),c=g(a,s(n));try{o(a,{recursive:!0}),l(c,r)}catch{return void console.log(chalk.yellow(" could not write the file here — check directory permissions."))}console.log(chalk.green(" ✓ downloaded ")+chalk.white(c)+chalk.gray(` (${r.length} bytes)`)),ee&&"submission.csv"===s(n)&&console.log(chalk.gray(" verify it: ")+chalk.cyan(`kaggle check ${ee}`)+chalk.gray(" — then upload on Kaggle yourself."))})(d),ce=!1,void ge();if("ai"===a||"/ai"===a)return ce=!0,await we(d),ce=!1,void ge();if("run"===a)return ce=!0,await(async e=>{const o=I(e,Q.cells.length);if(o)for(const e of o){const n=Q.cells[e-1];if("markdown"!==n.kind){console.log(chalk.gray(` ── run cell ${e}: `)+chalk.white(j(n,50))+chalk.gray(" ──"));try{n.result=await X.execute(n.source)}catch(e){return console.log(chalk.red(" Kernel error: ")+chalk.gray(e instanceof Error?e.message:String(e))),void D()}if(Q.dirty=!0,H(n.result,K),be(n,e),!n.result.ok){const n=e!==o[o.length-1];return console.log(chalk.yellow(` ✗ cell ${e} raised${n?" — stopping here.":"."}`)+chalk.gray(" Fix it (")+chalk.cyan(`edit ${e}`)+chalk.gray(") and re-run.")),console.log(chalk.gray(T()?" 卡住了? ":" Stuck? ")+chalk.bold.cyan(`ai ${e}`)+chalk.gray(T()?" 把这一格的代码和报错一起问 AI(不用离开 notebook)":" sends this cell and its traceback to the AI — without leaving the notebook")),void D()}}else{console.log(chalk.gray(` ── cell ${e} (markdown) ──`));for(const e of x(n.source))console.log(e);console.log()}}else console.log(0===Q.cells.length?chalk.yellow(" no cells yet — type Python or use ")+chalk.cyan("add"):chalk.yellow(" usage: ")+chalk.cyan("run 3")+chalk.yellow(" · ")+chalk.cyan("run 1-5")+chalk.yellow(" · ")+chalk.cyan("run all"))})(d),ce=!1,void ge();if("save"===a)return(e=>{if(0===Q.cells.length)return void console.log(chalk.yellow(" nothing to save — the notebook is empty."));let o;o=e.trim()?i(e.trim())?e.trim():y(process.cwd(),e.trim()):Q.path?Q.path.endsWith(".ipynb")?Q.path:`${Q.path.replace(/\.[^./]+$/,"")}.ipynb`:y(process.cwd(),"notebook.ipynb"),o.endsWith(".ipynb")||(o+=".ipynb");try{l(o,O(Q.cells)),Q.path=o,Q.dirty=!1,console.log(chalk.green(" ✓ saved ")+chalk.cyan(o)+chalk.gray(` (${Q.cells.length} cells)`))}catch(e){console.log(chalk.red(" save failed: ")+chalk.gray(e instanceof Error?e.message:String(e)))}})(d),void ge();if(""===r)return void ge()}if(ae.length>0&&M.has(r.toLowerCase()))return console.log(chalk.gray(" (⏸ you are inside a multi-line block — press Enter on an ")+chalk.bold.white("empty line")+chalk.gray(" to run it; then ")+chalk.cyan(r.toLowerCase().replace(/^\//,""))+chalk.gray(" will work. This line was not added to the block.)")),void ge();if(ae.push(t),!v(ae))return 1!==ae.length||se||(se=!0,console.log(chalk.gray(" (multi-line block started — keep typing; an empty line runs it)"))),void ge();const a=ae.join("\n").replace(/\s+$/,"");if(ae.length=0,""!==a.trim()){ce=!0;try{const e=await X.execute(a);Q.cells.push({kind:"code",source:a,result:e}),Q.dirty=!0,H(e,K);const o=be(Q.cells[Q.cells.length-1],Q.cells.length);e.ok||o||D()}catch(e){console.log(chalk.red(" Kernel error: ")+chalk.gray(e instanceof Error?e.message:String(e))),D()}ce=!1,ge()}else ge()};te.on("line",e=>{ke(e)}),ne||te.on("close",async()=>{await X.shutdown().catch(()=>{}),process.exit(0)}),ge(),await de}(p)})}function R(){console.log(),console.log(chalk.bold.white(" ICOA Notebook ")+chalk.gray("· in-terminal Python · AI/ML notebook arena")),console.log(chalk.gray(" ─────────────────────────────────────────────"))}const M=new Set(["guide","/guide","help","?","quit","exit","back","menu","cells","run all"]);function D(){console.log(chalk.gray(" 🧭 stuck? type ")+chalk.cyan("guide")+chalk.gray(" for the basics · ")+chalk.cyan("help")+chalk.gray(" for every command."))}const K="https://practice.icoa2026.au";function B(){return process.env.ICOA_GPU_SERVER?process.env.ICOA_GPU_SERVER.replace(/\/$/,""):K}function W(){return g(t(),".icoa","gpu-key")}function J(){if(process.env.ICOA_GPU_KEY)return process.env.ICOA_GPU_KEY.trim();try{return n(W(),"utf-8").trim()||null}catch{return null}}async function Y(e,o,n){try{const l=await fetch(`${B()}/api/icoa/gpu/${e}`,{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify(n?{key:o,task:n}:{key:o}),signal:AbortSignal.timeout(2e4)});return b(await l.json())}catch{return{state:"error",message:"GPU broker not reachable"}}}function z(e){const o=e?.match(/icoa-kaggle[/\\]([a-z0-9-]+)[/\\]/);return o?o[1]:null}let V=0,F=null;function H(e,o){for(const n of e.outputs)if("stream"===n.kind){const e=n.text.replace(/\n$/,"");if(0===e.length)continue;console.log("stderr"===n.name?chalk.yellow(e):chalk.white(e))}else if("result"===n.kind)console.log(chalk.cyan(` Out[${e.execCount??"*"}]: `)+chalk.white(n.text));else if("error"===n.kind){console.log(chalk.bold.red(` ${n.ename}: ${n.evalue}`));for(const e of n.traceback)console.log(chalk.gray(` ${e.replace(L,"")}`))}else"display"===n.kind&&Q(n.data,o)}function Q(e,n){if(e["image/png"])try{o(n,{recursive:!0}),V+=1;const t=g(n,`figure-${V}.png`);return l(t,Buffer.from(e["image/png"],"base64")),F=t,console.log(chalk.magenta(" 🖼 figure saved → ")+chalk.cyan(t)),void(_(t)?console.log(chalk.gray(" opening in your image viewer… (type ")+chalk.cyan("open")+chalk.gray(" to reopen)")):console.log(chalk.gray(" open it with your file browser (inline images need a graphical viewer).")))}catch{}e["text/plain"]&&console.log(chalk.white(` ${e["text/plain"]}`))}
1
+ import{existsSync as e,mkdirSync as o,readFileSync as n,writeFileSync as l}from"node:fs";import{homedir as t}from"node:os";import{Interface as r,createInterface as a}from"node:readline";import{basename as s,dirname as c,isAbsolute as i,join as g,resolve as y}from"node:path";import chalk from"chalk";import{aienvPaths as d}from"../lib/aienv.js";import{AI_MAX_INPUT_CHARS as u,askIoaiOneShot as h}from"./ai4ioai.js";import{getConfig as p}from"../lib/config.js";import{editTextInEditor as m}from"../lib/editor-spawn.js";import{buildSshArgs as f,leaseConnectProblems as w,parseLeaseResponse as b,queueLine as k}from"../lib/gpu.js";import{shouldExecuteCell as v}from"../lib/ipynb-input.js";import{looksLikeMarkdown as $,renderMarkdown as x}from"../lib/md-term.js";import{NotebookKernel as P,buildRemoteBridgeCommand as E}from"../lib/kernel.js";import{getMainRl as G}from"../lib/main-rl.js";import{logCommand as S}from"../lib/logger.js";import{startLogSync as A,stopLogSync as I}from"../lib/log-sync.js";import{cellPreview as N,parseIpynb as j,parsePercentPy as q,parseRunRange as U,serializeIpynb as O,statusChar as C}from"../lib/notebook-doc.js";import{openFile as _}from"../lib/open-file.js";const L=new RegExp(`${String.fromCharCode(27)}\\[[0-9;]*m`,"g");function T(){return(p().language||"en").toLowerCase().startsWith("zh")}export function registerIpynbCommand(e){e.command("ipynb").argument("[file]","notebook (.ipynb) or script (.py, split on # %%) to open").description("Open an in-terminal Python notebook (AI/ML — needs `aienv setup`)").action(async e=>{await runIpynb(e)})}function R(){console.log(),console.log(chalk.bold.white(" ICOA Notebook ")+chalk.gray("· in-terminal Python · AI/ML notebook arena")),console.log(chalk.gray(" ─────────────────────────────────────────────"))}const M=new Set(["guide","/guide","help","?","quit","exit","back","menu","cells","run all"]);function D(){console.log(chalk.gray(" 🧭 stuck? type ")+chalk.cyan("guide")+chalk.gray(" for the basics · ")+chalk.cyan("help")+chalk.gray(" for every command."))}const K="https://practice.icoa2026.au";function B(){return process.env.ICOA_GPU_SERVER?process.env.ICOA_GPU_SERVER.replace(/\/$/,""):K}function W(){return g(t(),".icoa","gpu-key")}function J(){if(process.env.ICOA_GPU_KEY)return process.env.ICOA_GPU_KEY.trim();try{return n(W(),"utf-8").trim()||null}catch{return null}}async function Y(e,o,n){try{const l=await fetch(`${B()}/api/icoa/gpu/${e}`,{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify(n?{key:o,task:n}:{key:o}),signal:AbortSignal.timeout(2e4)});return b(await l.json())}catch{return{state:"error",message:"GPU broker not reachable"}}}function z(e){const o=e?.match(/icoa-kaggle[/\\]([a-z0-9-]+)[/\\]/);return o?o[1]:null}let V=0,F=null;function H(e,o){for(const n of e.outputs)if("stream"===n.kind){const e=n.text.replace(/\n$/,"");if(0===e.length)continue;console.log("stderr"===n.name?chalk.yellow(e):chalk.white(e))}else if("result"===n.kind)console.log(chalk.cyan(` Out[${e.execCount??"*"}]: `)+chalk.white(n.text));else if("error"===n.kind){console.log(chalk.bold.red(` ${n.ename}: ${n.evalue}`));for(const e of n.traceback)console.log(chalk.gray(` ${e.replace(L,"")}`))}else"display"===n.kind&&Q(n.data,o)}function Q(e,n){if(e["image/png"])try{o(n,{recursive:!0}),V+=1;const t=g(n,`figure-${V}.png`);return l(t,Buffer.from(e["image/png"],"base64")),F=t,console.log(chalk.magenta(" 🖼 figure saved → ")+chalk.cyan(t)),void(_(t)?console.log(chalk.gray(" opening in your image viewer… (type ")+chalk.cyan("open")+chalk.gray(" to reopen)")):console.log(chalk.gray(" open it with your file browser (inline images need a graphical viewer).")))}catch{}e["text/plain"]&&console.log(chalk.white(` ${e["text/plain"]}`))}export async function runIpynb(p){const b=d(t()),K=g(t(),".icoa","ipynb-out");if(R(),!e(b.python))return console.log(chalk.yellow(" The AI/ML environment is not set up yet.")),console.log(chalk.gray(" Run ")+chalk.bold.cyan("aienv setup")+chalk.gray(" first (one-time, ~300 MB).")),void console.log();const V=p?function(o){const l=i(o)?o:y(process.cwd(),o);if(!e(l))return{doc:{cells:[],path:l,dirty:!1},note:chalk.gray(" new notebook — will be created on ")+chalk.cyan("save")};try{const e=n(l,"utf8"),o=l.endsWith(".ipynb")?j(e):q(e);return{doc:{cells:o,path:l,dirty:!1},note:chalk.gray(" loaded ")+chalk.cyan(l)+chalk.gray(` — ${o.length} cell${1===o.length?"":"s"}. Type `)+chalk.cyan("cells")+chalk.gray(" to list them.")}}catch(e){return{doc:{cells:[],path:null,dirty:!1},note:chalk.yellow(` could not open ${l}: ${e instanceof Error?e.message:String(e)}`)+chalk.gray(" — starting an empty notebook.")}}}(p):null,Q=V?V.doc:{cells:[],path:null,dirty:!1};let X=new P({venvPython:b.python,venvRoot:b.root}),Z=null,ee=z(Q.path);process.stdout.write(chalk.gray(" Starting Python kernel…"));try{await X.start()}catch{return console.log(chalk.red(" failed.")),console.log(chalk.gray(" Check the environment: ")+chalk.cyan("aienv status")),void console.log()}console.log(chalk.green(" ready.")),V&&console.log(V.note),console.log(chalk.bold.white(" ▶ Start here: ")+chalk.bold.cyan("run all")+chalk.gray(" — runs every cell (trains the baseline, writes submission.csv).")),console.log(chalk.gray(" You are already inside the notebook — do ")+chalk.bold.red("not")+chalk.gray(" type ")+chalk.cyan("python file.ipynb")+chalk.gray(". Just ")+chalk.bold.cyan("run all")+chalk.gray(".")),console.log(chalk.gray(" Then: ")+chalk.cyan("cells")+chalk.gray(" list · ")+chalk.cyan("edit N")+chalk.gray(" edit · ")+chalk.cyan("add")+chalk.gray(" new cell · ")+chalk.cyan("save")+chalk.gray(" · ")+chalk.cyan("help")+chalk.gray(" full · ")+chalk.cyan("quit")),console.log(chalk.gray(" Or just type Python and press Enter (blocks continue until a blank line).")),console.log(chalk.bold.yellow(" 🧭 Lost at any point? Type ")+chalk.bold.cyan("guide")+chalk.bold.yellow(" — the full walkthrough + where you are.")),console.log();const oe=G(),ne=null!==oe,le=ne?oe.listeners("line").slice():[];ne&&oe.removeAllListeners("line");const te=ne?oe:a({input:process.stdin,output:process.stdout,terminal:!0}),re=ne?te.prompt:null;ne&&(te.prompt=r.prototype.prompt),ne||A();const ae=[];let se=!1,ce=!1,ie=!1;const ge=()=>{const e=Z?"icoa ipynb ⚡gpu":"icoa ipynb";te.setPrompt(chalk.bold.cyan(ae.length?`${e} ...> `:`${e}> `)),te.prompt()};let ye=()=>{};const de=new Promise(e=>{ye=e}),ue=async e=>{const[n,...r]=e.trim().split(/\s+/),a=(n??"").toLowerCase();"on"===a||"connect"===a?await(async()=>{if(Z)return void console.log(chalk.gray(" already on the GPU kernel — ")+chalk.cyan("gpu status")+chalk.gray(" for time left."));const e=J();if(!e)return console.log(chalk.yellow(" No GPU access key found.")),void console.log(chalk.gray(" Save yours once with ")+chalk.cyan("gpu key <your-key>")+chalk.gray(" (issued by your coach/ICOA)."));ee||(ee=z(Q.path)),process.stdout.write(chalk.gray(" Requesting a GPU box…"));let n=await Y("lease",e,ee??void 0),r=0;for(;"queued"===n.state&&r<24;)0===r&&console.log(),process.stdout.write(`\r ${chalk.yellow(k(n))} `),await new Promise(e=>setTimeout(e,5e3)),n=await Y("status",e),r++;if("queued"===n.state)return console.log(),console.log(chalk.yellow(" Still queued — your place is held server-side.")),void console.log(chalk.gray(" Keep working locally; ")+chalk.cyan("gpu on")+chalk.gray(" again in a few minutes."));if("ready"!==n.state)return void console.log(chalk.red(" failed.")+chalk.gray(` ${n.message??"no lease granted"}`));const a=w(n);if("local"!==n.transport||process.env.ICOA_GPU_SERVER||a.push("local transport from a non-dev broker"),a.length>0)return console.log(chalk.red(" rejected: ")+chalk.gray(a.join(", "))),void await Y("release",e);const s=ee?`${n.dataRoot}/${ee}`:n.dataRoot,c=E(n.python,{ICOA_KAGGLE_DATA:s,ICOA_KAGGLE_OUT:n.outDir},n.outDir);let i;if("local"===n.transport)i={command:"/bin/sh",args:["-c",c]};else{const r=g(t(),".icoa","gpu","lease-key");try{o(g(t(),".icoa","gpu"),{recursive:!0}),l(r,n.keyPem,{mode:384})}catch{return console.log(chalk.red(" could not write the ssh key locally.")),void await Y("release",e)}i={command:"ssh",args:f(n,r,c)}}const y=new P({spawnSpec:i,readyTimeoutMs:9e4});process.stdout.write(chalk.gray(" connecting…"));try{await y.start()}catch(o){return console.log(chalk.red(" connect failed.")),console.log(chalk.gray(` ${o instanceof Error?o.message:String(o)}`)),void await Y("release",e)}await X.shutdown().catch(()=>{}),X=y,Z=n;const d=Math.round((n.timeLeftSec??0)/60);console.log(chalk.bold.green(" ⚡ GPU connected.")),console.log(chalk.gray(` Cells now run on the GPU box · ${d}m left on this lease.`)),console.log(chalk.gray(" Variables were reset — ")+chalk.cyan("run all")+chalk.gray(" to retrain there.")),ee&&console.log(chalk.gray(` Dataset is already on the box (${ee}) — same cells, no edits.`)),console.log(chalk.gray(" When done: ")+chalk.cyan("download")+chalk.gray(" your submission, then ")+chalk.cyan("gpu off")+chalk.gray("."))})():"off"===a||"disconnect"===a?await(async()=>{if(!Z)return void console.log(chalk.gray(" not on a GPU kernel."));const e=J();await X.shutdown().catch(()=>{}),e&&await Y("release",e),Z=null,console.log(chalk.green(" ⚡ GPU lease released")+chalk.gray(" — billing stopped.")),await(async()=>{X=new P({venvPython:b.python,venvRoot:b.root}),process.stdout.write(chalk.gray(" Starting local kernel…"));try{await X.start(),console.log(chalk.green(" ready.")+chalk.gray(" (local CPU — variables were reset)"))}catch{console.log(chalk.red(" failed.")+chalk.gray(" Check ")+chalk.cyan("aienv status"))}})()})():"status"===a||""===a?await(async()=>{const e=J();if(!e)return void console.log(chalk.gray(" no GPU key saved — ")+chalk.cyan("gpu key <your-key>"));const o=await Y("status",e);if("ready"===o.state){const e=Math.round((o.timeLeftSec??0)/60);console.log(chalk.green(` ⚡ GPU lease active · ${e}m left`)+chalk.gray(Z?" (this notebook is connected)":" (not connected here — gpu on)"))}else"queued"===o.state?console.log(chalk.yellow(` ${k(o)}`)):"none"===o.state?console.log(chalk.gray(" no GPU lease — ")+chalk.cyan("gpu on")+chalk.gray(" to request one.")):console.log(chalk.yellow(` ${o.message??"GPU broker not reachable"}`))})():"queue"===a||"q"===a?await(async()=>{const e=J();if(!e)return void console.log(chalk.gray(" no GPU key saved — ")+chalk.cyan("gpu key <your-key>"));let o=null;try{const n=await fetch(`${B()}/api/icoa/gpu/queue`,{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({key:e}),signal:AbortSignal.timeout(15e3)}),l=await n.json();o=l.data??l}catch{o=null}if(!o||"object"!=typeof o)return void console.log(chalk.yellow(" GPU queue not reachable right now — try again in a moment."));const n="number"==typeof o.boxes?o.boxes:0,l="number"==typeof o.free?o.free:0,t=Array.isArray(o.running)?o.running:[],r=Array.isArray(o.waiting)?o.waiting:[];console.log(),console.log(chalk.bold.cyan(" GPU queue")+chalk.gray(` · ${n} box${1===n?"":"es"} · ${l} free`)),console.log(chalk.bold.white(" ▶ running now:")),0===t.length&&console.log(chalk.gray(" (idle — gpu on takes a box immediately)"));for(const e of t){const o="string"==typeof e.label?e.label:"?",n="number"==typeof e.time_left_sec?e.time_left_sec:0,l=Math.floor(n/60),t=String(n%60).padStart(2,"0"),r=e.is_you?chalk.green(" ← you"):"";console.log(chalk.gray(" ")+chalk.white(o.padEnd(8))+chalk.gray(` ${l}:${t} left`)+r)}console.log(chalk.bold.white(` ⏳ waiting (${r.length}):`)),0===r.length&&console.log(chalk.gray(" (nobody queued)"));for(const e of r){const o="string"==typeof e.label?e.label:"?",n="number"==typeof e.position?e.position:"?",l=e.is_you?chalk.green(" ← you"):"";console.log(chalk.gray(` #${n} `)+chalk.white(o.padEnd(8))+l)}console.log()})():"key"===a?(e=>{const n=e.trim();if(n)try{o(g(t(),".icoa"),{recursive:!0}),l(W(),`${n}\n`,{mode:384}),console.log(chalk.green(" ✓ GPU key saved")+chalk.gray(" — ")+chalk.cyan("gpu on")+chalk.gray(" when you need the box."))}catch{console.log(chalk.red(" could not save the key")+chalk.gray(` (${W()})`))}else console.log(chalk.yellow(" usage: ")+chalk.cyan("gpu key <your-key>"))})(r.join(" ")):console.log(chalk.yellow(" usage: ")+chalk.cyan("gpu on")+chalk.yellow(" · ")+chalk.cyan("gpu off")+chalk.yellow(" · ")+chalk.cyan("gpu status")+chalk.yellow(" · ")+chalk.cyan("gpu queue")+chalk.yellow(" · ")+chalk.cyan("gpu key <k>"))},he=e=>{const o=Number(e.trim());return!Number.isInteger(o)||o<1||o>Q.cells.length?(console.log(0===Q.cells.length?chalk.yellow(" no cells yet — type Python or use ")+chalk.cyan("add"):chalk.yellow(` no cell ${e.trim()||"?"} — pick 1-${Q.cells.length} (see `)+chalk.cyan("cells")+chalk.yellow(")")),null):{cell:Q.cells[o-1],idx:o}},pe=(e,o)=>{if(e.length<=o)return e;const n=Math.floor(.6*o);return`${e.slice(0,n)}\n…(${e.length-o} chars elided)…\n${e.slice(-(o-n))}`};let me=!1;const fe=(e,o)=>!(!e.result||e.result.ok)&&!(!e.result.outputs.some(e=>"error"===e.kind&&"SyntaxError"===e.ename)||!$(e.source)||(console.log(chalk.gray(" ✎ looks like text/markdown, not Python — ")+chalk.cyan(`md ${o}`)+chalk.gray(" converts this cell to markdown (new note: ")+chalk.cyan("add md")+chalk.gray(").")),0)),we=async t=>{if(t.trim()&&S(`ipynb: ${t.trim()}`),ce)return void(t.trim()&&console.log(chalk.gray(" (busy — wait for the current cell to finish, then retype)")));let r=t.trim();if(0===ae.length&&/^icoa\s+[a-z/]/i.test(r)&&(r=r.replace(/^icoa\s+/i,"")),0===ae.length){const t=r.split(/\s+/),a=(t[0]??"").toLowerCase(),d=r.slice(t[0]?.length??0).trim();if("quit"!==a&&"exit"!==a&&"q"!==a&&(ie=!1),"quit"===a||"exit"===a||"back"===a||"q"===a||"menu"===a)return Q.dirty&&!ie?(ie=!0,console.log(chalk.yellow(" unsaved changes — ")+chalk.cyan("save")+chalk.yellow(" first, or type ")+chalk.cyan("quit")+chalk.yellow(" again to discard.")),void ge()):void await(async()=>{if(te.removeAllListeners("line"),ne||I(),console.log(),Z){const e=J();e&&await Y("release",e),Z=null,console.log(chalk.green(" ⚡ GPU lease released")+chalk.gray(" — billing stopped."))}if(console.log(chalk.gray(" Notebook closed. Kernel stopped.")),console.log(),await X.shutdown().catch(()=>{}),ne){re&&(te.prompt=re);for(const e of le)te.on("line",e);te.prompt(),ye()}else ye(),te.close()})();if("clear"===a||"cls"===a)return console.clear(),R(),void ge();if("restart"===a)return await(async()=>{process.stdout.write(chalk.gray(" Restarting kernel…")),await X.shutdown().catch(()=>{});try{await X.start(),console.log(chalk.green(" fresh kernel ready.")+chalk.gray(" (all variables cleared)"))}catch{console.log(chalk.red(" restart failed.")+chalk.gray(" Leave and re-enter the notebook."))}})(),void ge();if("help"===a||"?"===a)return console.log(),console.log(chalk.bold.white(" Notebook commands")),console.log(chalk.cyan(" cells")+chalk.gray(" list cells (○ not run · ✓ ok · ✗ error)")),console.log(chalk.cyan(" show N")+chalk.gray(" print cell N source + outputs")),console.log(chalk.cyan(" edit N")+chalk.gray(" edit cell N in your editor ($EDITOR, default vi)")),console.log(chalk.cyan(" add")+chalk.gray(" write a new Python cell in your editor")),console.log(chalk.cyan(" add md")+chalk.gray(" write a markdown/text cell (notes, headings)")),console.log(chalk.cyan(" md N / py N")+chalk.gray(" convert cell N to markdown / Python")),console.log(chalk.cyan(" del N")+chalk.gray(" delete cell N")),console.log(chalk.cyan(" run N")+chalk.gray(" run cell N — markdown cells render (also: run 2-5, run all)")),console.log(chalk.cyan(" ai [N] [问题]")+chalk.gray(T()?" 问 AI 这一格(默认最近报错的那格;带上代码和 traceback)":" ask the AI about a cell (defaults to the last one that errored)")),console.log(chalk.cyan(" save [file]")+chalk.gray(" save as a real .ipynb")),console.log(chalk.cyan(" restart")+chalk.gray(" restart the kernel (wipes all variables)")),console.log(chalk.cyan(" gpu on/off")+chalk.gray(" run cells on a leased GPU box (dataset pre-mounted)")),console.log(chalk.cyan(" gpu status")+chalk.gray(" your lease/queue · ")+chalk.cyan("gpu queue")+chalk.gray(" who is on the GPU now")),console.log(chalk.cyan(" gpu key <k>")+chalk.gray(" save your access key")),console.log(chalk.cyan(" download")+chalk.gray(" pull submission.csv from the GPU box to this machine")),console.log(chalk.cyan(" open")+chalk.gray(" reopen the last figure in your image viewer")),console.log(chalk.cyan(" clear")+chalk.gray(" clear the screen · ")+chalk.cyan("quit")+chalk.gray(" leave")),console.log(chalk.gray(" Everything else runs as Python in the persistent kernel (and is appended as a cell).")),console.log(),void ge();if("guide"===a||"/guide"===a)return(()=>{const o=Q.path?c(Q.path):process.cwd(),l=z(Q.path);let t="",r=!1;try{const e=JSON.parse(n(g(o,"meta.json"),"utf-8"));t=e.judge??"",r=!0===e.needs_gpu}catch{}const a=Q.cells.filter(e=>null!==e.result).length,i=e(g(o,"submission.csv"));console.log(),console.log(chalk.bold.white(" ═══ 📖 Notebook guide ═══")),console.log(),console.log(chalk.gray(" Where you are: ")+chalk.white(Q.path?s(Q.path):"new empty notebook")+chalk.gray(` · ${Q.cells.length} cells (${a} run) · submission.csv: `)+(i?chalk.green("written ✓"):chalk.yellow("not yet — run all"))),Z?console.log(chalk.gray(" ⚡ GPU: ")+chalk.green("connected")+chalk.gray(" — ")+chalk.cyan("gpu status")+chalk.gray(" your time left · ")+chalk.cyan("gpu queue")+chalk.gray(" who is on · ")+chalk.cyan("download <file>")+chalk.gray(" pull results")):r&&console.log(chalk.gray(" ⚡ GPU task, not connected — ")+chalk.cyan("gpu key <your-key>")+chalk.gray(" then ")+chalk.cyan("gpu on")+chalk.gray(" · ")+chalk.cyan("gpu queue")+chalk.gray(" shows who is on")),console.log(),console.log(chalk.bold.white(" The loop:")),console.log(chalk.gray(" 1. ")+chalk.bold.cyan("run all")+chalk.gray(" — trains the baseline, writes submission.csv")),l&&"icoa-holdout"===t?(console.log(chalk.gray(" 2. ")+chalk.cyan("quit")+chalk.gray(", then ")+chalk.cyan(`kaggle submit ${l}`)+chalk.gray(" — scored + ranked on the live board")),console.log(chalk.gray(" 3. come back, improve the MODEL cell (")+chalk.cyan("cells")+chalk.gray(" lists them, ")+chalk.cyan("edit N")+chalk.gray(" edits) — beat your score."))):l&&r?(console.log(chalk.gray(" 2. ")+chalk.cyan("download <file>")+chalk.gray(" — pull your results (submission.csv / predictions.zip) off the GPU box")),console.log(chalk.gray(" 3. submit on kaggle.com — the notebook's final cell has the exact steps")),console.log(chalk.gray(" 4. come back, improve the MODEL cell (")+chalk.cyan("cells")+chalk.gray(" lists them, ")+chalk.cyan("edit N")+chalk.gray(" edits) — beat it."))):l?(console.log(chalk.gray(" 2. ")+chalk.cyan("quit")+chalk.gray(", then ")+chalk.cyan(`kaggle check ${l}`)+chalk.gray(" — verifies the file format")),console.log(chalk.gray(" 3. upload submission.csv on kaggle.com — read your public score")),console.log(chalk.gray(" 4. come back, improve the MODEL cell (")+chalk.cyan("cells")+chalk.gray(" lists them, ")+chalk.cyan("edit N")+chalk.gray(" edits) — beat it."))):console.log(chalk.gray(" 2. edit cells (")+chalk.cyan("edit N")+chalk.gray("), re-run, ")+chalk.cyan("save")+chalk.gray(" — this is a free notebook.")),console.log(),console.log(chalk.bold.white(" If it looks stuck:")),console.log(chalk.gray(" · prompt shows ")+chalk.cyan("...>")+chalk.gray(" → you are inside a code block. Press Enter on an ")+chalk.bold.white("empty line")+chalk.gray(".")),console.log(chalk.gray(" · never type ")+chalk.cyan("python file.ipynb")+chalk.gray(" here — you are already inside. Just ")+chalk.bold.cyan("run all")+chalk.gray(".")),console.log(),console.log(chalk.bold.white(" 🤝 AI help: ")+chalk.gray("split the screen ")+chalk.bold.cyan("Ctrl-b %")+chalk.gray(" · right pane: ")+chalk.bold.cyan("icoa")+chalk.gray(" then ")+chalk.bold.cyan("ai4ioai")+chalk.gray(" — live Gemma 3")),console.log(chalk.gray(" All commands: ")+chalk.cyan("help")+chalk.gray(" · leave: ")+chalk.cyan("quit")),console.log()})(),void ge();if("python"===a||"python3"===a)return console.log(chalk.gray(" You're already inside the notebook kernel — no need to run python.")),console.log(chalk.gray(" Type ")+chalk.bold.cyan("run all")+chalk.gray(" to run every cell, or ")+chalk.cyan("guide")+chalk.gray(" for the basics.")),void ge();if("open"===a)return F&&_(F)?console.log(chalk.gray(" reopening ")+chalk.cyan(F)):console.log(chalk.gray(" no figure yet — plot something (e.g. matplotlib) first.")),void ge();if("cells"===a||"ls"===a)return(()=>{if(0===Q.cells.length)return void console.log(chalk.gray(" no cells yet — type Python, or ")+chalk.cyan("add")+chalk.gray(" to write one in your editor."));console.log();const e=Math.max(20,(process.stdout.columns??80)-12);Q.cells.forEach((o,n)=>{const l=C(o),t="✓"===l?chalk.green(l.padEnd(2)):"✗"===l?chalk.red(l.padEnd(2)):"md"===l?chalk.magenta(l.padEnd(2)):chalk.gray(l.padEnd(2));console.log(`${chalk.cyan(String(n+1).padStart(4))} ${t} ${chalk.white(N(o,e))}`)}),console.log(),console.log(chalk.gray(" ")+chalk.cyan("show N")+chalk.gray(" · ")+chalk.cyan("edit N")+chalk.gray(" · ")+chalk.cyan("run N")+chalk.gray(" · ")+chalk.cyan("run all"))})(),void ge();if("show"===a)return(e=>{const o=he(e);if(o){if(console.log(),console.log(chalk.gray(` ── cell ${o.idx} ${"markdown"===o.cell.kind?"(markdown) ":""}──`)),"markdown"===o.cell.kind){for(const e of x(o.cell.source))console.log(e);console.log(chalk.gray(" (rendered — ")+chalk.cyan(`edit ${o.idx}`)+chalk.gray(" for the raw source)"))}else for(const e of o.cell.source.split("\n"))console.log(chalk.white(` ${e}`));o.cell.result&&(console.log(chalk.gray(" ── output ──")),H(o.cell.result,K)),console.log()}})(d),void ge();if("edit"===a)return(e=>{const o=he(e);if(!o)return;te.pause();const n=m(o.cell.source,"markdown"===o.cell.kind?".md":".py");if(te.resume(),null===n)return void console.log(chalk.yellow(" editor cancelled or failed — cell unchanged.")+chalk.gray(" (set $EDITOR to choose your editor)"));const l=n.replace(/\s+$/,"");l!==o.cell.source?(o.cell.source=l,o.cell.result=null,o.cell.rawOutputs=void 0,o.cell.rawExecCount=void 0,Q.dirty=!0,console.log(chalk.green(` ✓ cell ${o.idx} updated`)+chalk.gray(" — ")+chalk.cyan(`run ${o.idx}`)+chalk.gray(" to execute."))):console.log(chalk.gray(" no changes."))})(d),void ge();if("add"===a)return(e=>{const o=e.trim().toLowerCase(),n="md"===o||"markdown"===o||"text"===o||"txt"===o;if(o&&!n&&"py"!==o&&"code"!==o&&"python"!==o)return void console.log(chalk.yellow(" usage: ")+chalk.cyan("add")+chalk.yellow(" (Python cell) · ")+chalk.cyan("add md")+chalk.yellow(" (markdown/text cell)"));te.pause();const l=m(n?"\x3c!-- markdown cell — write notes/headings, save & exit --\x3e\n":"",n?".md":".py");te.resume();const t=null===l?"":l.replace(/^<!-- markdown cell[^\n]*-->\n?/,"").replace(/\s+$/,"");t?(Q.cells.push({kind:n?"markdown":"code",source:t,result:null}),Q.dirty=!0,console.log(chalk.green(` ✓ added ${n?"markdown ":""}cell ${Q.cells.length}`)+chalk.gray(" — ")+chalk.cyan(`run ${Q.cells.length}`)+chalk.gray(n?" to render it.":" to execute."))):console.log(chalk.gray(" nothing added."))})(d),void ge();if("del"===a||"delete"===a)return(e=>{const o=he(e);o&&(Q.cells.splice(o.idx-1,1),Q.dirty=!0,console.log(chalk.gray(` deleted cell ${o.idx} — ${Q.cells.length} left.`)+(o.idx<=Q.cells.length?chalk.yellow(" ⚠ 后面的 cell 号已顺移")+chalk.gray(" — ")+chalk.cyan("cells")+chalk.gray(" 重看一眼"):"")))})(d),void ge();if(("md"===a||"py"===a)&&/^\d+$/.test(d))return((e,o)=>{const n=he(e);if(!n)return;const l="markdown"===o?"markdown":"Python";n.cell.kind!==o?(n.cell.kind=o,n.cell.result=null,n.cell.rawOutputs=void 0,n.cell.rawExecCount=void 0,Q.dirty=!0,console.log(chalk.green(` ✓ cell ${n.idx} → ${l}`)+chalk.gray(" — ")+chalk.cyan(`run ${n.idx}`)+chalk.gray("markdown"===o?" to render it.":" to execute."))):console.log(chalk.gray(` cell ${n.idx} is already ${l}.`))})(d,"md"===a?"markdown":"code"),void ge();if("gpu"===a)return ce=!0,await ue(d),ce=!1,void ge();if("download"===a||"dl"===a)return ce=!0,await(async e=>{if(!Z)return void console.log(chalk.gray(" local kernel — your files are already on this machine (no download needed)."));const n=e.trim()||"submission.csv",t=n.startsWith("/")?n:`${Z.outDir}/${n}`;let r;try{r=await X.fetchFile(t)}catch(e){return console.log(chalk.yellow(` could not fetch ${t}: `)+chalk.gray(e instanceof Error?e.message:String(e))),void console.log(chalk.gray(" (run the submission cell first — it writes into the GPU workspace)"))}const a=ee?g(process.cwd(),"icoa-kaggle",ee):process.cwd(),c=g(a,s(n));try{o(a,{recursive:!0}),l(c,r)}catch{return void console.log(chalk.yellow(" could not write the file here — check directory permissions."))}console.log(chalk.green(" ✓ downloaded ")+chalk.white(c)+chalk.gray(` (${r.length} bytes)`)),ee&&"submission.csv"===s(n)&&console.log(chalk.gray(" verify it: ")+chalk.cyan(`kaggle check ${ee}`)+chalk.gray(" — then upload on Kaggle yourself."))})(d),ce=!1,void ge();if("ai"===a||"/ai"===a)return ce=!0,await(async e=>{const o=e.trim().split(/\s+/).filter(Boolean),l=o.length>0&&/^\d+$/.test(o[0]),t=(l?o.slice(1):o).join(" ").trim(),r=l?Number(o[0]):(()=>{for(let e=Q.cells.length-1;e>=0;e--)if((Q.cells[e].result?.outputs??[]).some(e=>"error"===e.kind))return e+1;return null})()??Q.cells.length;if(0===Q.cells.length)return void console.log(chalk.yellow(" 还没有 cell —— 先写点代码,或用 ")+chalk.cyan("add"));const a=he(String(r));if(!a)return;if("markdown"===a.cell.kind)return void console.log(chalk.yellow(` cell ${a.idx} 是 markdown —— 挑一个代码格,比如 `)+chalk.cyan("ai 2"));const s=(e=>{const o=[];for(const n of e.result?.outputs??[])"stream"===n.kind||"result"===n.kind?o.push(n.text):"error"===n.kind&&(o.push(`${n.ename}: ${n.evalue}`),o.push(n.traceback.map(e=>e.replace(L,"")).join("\n")));return o.join("\n").replace(L,"").replace(/\n{3,}/g,"\n\n").trim()})(a.cell),i=(()=>{if(!Q.path||!z(Q.path))return"";try{const e=JSON.parse(n(g(c(Q.path),"meta.json"),"utf-8")),o=[e.title,e.metric?`metric: ${e.metric}`:"",e.description].filter(Boolean).join("\n");return pe(o,350)}catch{return""}})(),y=T(),d=y?"你在帮一个 IOAI 选手调试 notebook。先说清楚这一格为什么会这样,再给出最小改动。用中文回答,简洁,给可直接粘回去的代码。":"You are helping an IOAI contestant debug a notebook cell. Say why it behaves this way, then give the smallest fix. Be concise and give code that can be pasted straight back.",p=d.length+t.length+120,m=Math.max(400,u-p-i.length),f=pe(a.cell.source,Math.floor(.6*m)),w=s?(b=s,k=m-f.length,b.length<=k?b:`…(${b.length-k} chars elided)…\n${b.slice(-k)}`):"";var b,k;const v=[d,i?`\n[task]\n${i}`:"",`\n[cell ${a.idx} code]\n${f}`,w?`\n[cell ${a.idx} output]\n${w}`:"\n(this cell has not been run yet)",t?`\n[question]\n${t}`:""].filter(Boolean).join("\n"),$=v.includes("chars elided"),P=y;console.log(),me||(me=!0,console.log(chalk.gray(" ")+chalk.bold.white("IOAI 2026 ")+chalk.white("Gemma 3n E4B")+chalk.gray(" (32k) · ")+chalk.white(T()?"单轮无记忆":"single-turn, no memory")+chalk.gray(" · ")+chalk.white(`${u} ${T()?"字符/条":"chars/message"}`)+chalk.gray(" · ")+chalk.white(T()?"1000 token/回复":"1000 tokens/reply")),console.log(chalk.gray(T()?" —— 现场就是这个模型和这几条上限,在这里练的手感能原样带过去。":" — the onsite model and the onsite limits, so the habit transfers as-is."))),console.log(chalk.gray(` → cell ${a.idx} · ${v.length}/${u} chars`)+chalk.gray(P?" · 单轮(竞赛档模型)":" · single-turn (contest model)")+(s?chalk.gray(P?" · 含输出":" · output included"):"")+($?chalk.yellow(P?" ⚠ 上下文被裁过,加一句具体问题会更准":" ⚠ context trimmed — a specific question helps"):"")),S(`ipynb: ai ${a.idx}${t?` — ${t}`:""}`);const E=await h(v);if(console.log(),!E.ok)return console.log(chalk.yellow(" AI 现在连不上 —— ")+chalk.gray(E.text)),console.log(chalk.gray(" 过一会儿再试,或用 ")+chalk.cyan("ai4ioai")+chalk.gray(" 单开一个会话。")),void console.log();for(const e of x(E.text))console.log(e);console.log(),console.log(chalk.gray(" ")+chalk.cyan(`ai ${a.idx} ${P?"<你的问题>":"<your question>"}`)+chalk.gray(P?" 追问 · ":" follow up · ")+chalk.cyan(`edit ${a.idx}`)+chalk.gray(P?" 改这一格 · ":" edit it · ")+chalk.cyan(`run ${a.idx}`)+chalk.gray(P?" 再跑一次":" run it again")),console.log(chalk.gray(P?" 这是调试助手(超限自动裁剪);想练现场那堵墙用 ":" This is the debugging aid (it trims to fit). To train against the real wall: ")+chalk.cyan("ai4ioai")),console.log()})(d),ce=!1,void ge();if("run"===a)return ce=!0,await(async e=>{const o=U(e,Q.cells.length);if(o)for(const e of o){const n=Q.cells[e-1];if("markdown"!==n.kind){console.log(chalk.gray(` ── run cell ${e}: `)+chalk.white(N(n,50))+chalk.gray(" ──"));try{n.result=await X.execute(n.source)}catch(e){return console.log(chalk.red(" Kernel error: ")+chalk.gray(e instanceof Error?e.message:String(e))),void D()}if(Q.dirty=!0,H(n.result,K),fe(n,e),!n.result.ok){const n=e!==o[o.length-1];return console.log(chalk.yellow(` ✗ cell ${e} raised${n?" — stopping here.":"."}`)+chalk.gray(" Fix it (")+chalk.cyan(`edit ${e}`)+chalk.gray(") and re-run.")),console.log(chalk.gray(T()?" 卡住了? ":" Stuck? ")+chalk.bold.cyan(`ai ${e}`)+chalk.gray(T()?" 把这一格的代码和报错一起问 AI(不用离开 notebook)":" sends this cell and its traceback to the AI — without leaving the notebook")),void D()}}else{console.log(chalk.gray(` ── cell ${e} (markdown) ──`));for(const e of x(n.source))console.log(e);console.log()}}else console.log(0===Q.cells.length?chalk.yellow(" no cells yet — type Python or use ")+chalk.cyan("add"):chalk.yellow(" usage: ")+chalk.cyan("run 3")+chalk.yellow(" · ")+chalk.cyan("run 1-5")+chalk.yellow(" · ")+chalk.cyan("run all"))})(d),ce=!1,void ge();if("save"===a)return(e=>{if(0===Q.cells.length)return void console.log(chalk.yellow(" nothing to save — the notebook is empty."));let o;o=e.trim()?i(e.trim())?e.trim():y(process.cwd(),e.trim()):Q.path?Q.path.endsWith(".ipynb")?Q.path:`${Q.path.replace(/\.[^./]+$/,"")}.ipynb`:y(process.cwd(),"notebook.ipynb"),o.endsWith(".ipynb")||(o+=".ipynb");try{l(o,O(Q.cells)),Q.path=o,Q.dirty=!1,console.log(chalk.green(" ✓ saved ")+chalk.cyan(o)+chalk.gray(` (${Q.cells.length} cells)`))}catch(e){console.log(chalk.red(" save failed: ")+chalk.gray(e instanceof Error?e.message:String(e)))}})(d),void ge();if(""===r)return void ge()}if(ae.length>0&&M.has(r.toLowerCase()))return console.log(chalk.gray(" (⏸ you are inside a multi-line block — press Enter on an ")+chalk.bold.white("empty line")+chalk.gray(" to run it; then ")+chalk.cyan(r.toLowerCase().replace(/^\//,""))+chalk.gray(" will work. This line was not added to the block.)")),void ge();if(ae.push(t),!v(ae))return 1!==ae.length||se||(se=!0,console.log(chalk.gray(" (multi-line block started — keep typing; an empty line runs it)"))),void ge();const a=ae.join("\n").replace(/\s+$/,"");if(ae.length=0,""!==a.trim()){ce=!0;try{const e=await X.execute(a);Q.cells.push({kind:"code",source:a,result:e}),Q.dirty=!0,H(e,K);const o=fe(Q.cells[Q.cells.length-1],Q.cells.length);e.ok||o||D()}catch(e){console.log(chalk.red(" Kernel error: ")+chalk.gray(e instanceof Error?e.message:String(e))),D()}ce=!1,ge()}else ge()};te.on("line",e=>{we(e)}),ne||te.on("close",async()=>{await X.shutdown().catch(()=>{}),process.exit(0)}),ge(),await de}
@@ -1 +1 @@
1
- import{existsSync as o,mkdirSync as e,readFileSync as n,readdirSync as t,writeFileSync as l}from"node:fs";import{join as s}from"node:path";import chalk from"chalk";import{makeReplAsker as a}from"../lib/repl-asker.js";import{getConfig as i}from"../lib/config.js";import{logCommand as r}from"../lib/logger.js";import{openFile as c}from"../lib/open-file.js";import{serializeIpynb as g}from"../lib/notebook-doc.js";import{loadLearnState as u}from"../lib/learn-state.js";import{buildStarterCells as y,dataFileUrls as d,parseKaggleTaskList as h,parseSubmitResponse as b,validateSubmissionText as m}from"../lib/kaggle.js";function p(){return process.env.ICOA_KAGGLE_SERVER?process.env.ICOA_KAGGLE_SERVER.replace(/\/$/,""):"https://practice.icoa2026.au"}async function f(o){try{const e=await fetch(p()+o,{signal:AbortSignal.timeout(3e4)});return await e.json()}catch{return null}}async function k(o){try{const e=await fetch(o,{signal:AbortSignal.timeout(6e4)});return e.ok?await e.text():null}catch{return null}}function w(o,e){return(i().language||"en").toLowerCase().startsWith("zh")?o:e}function v(){console.log(),console.log(chalk.yellow(w(" 练习服务器现在连不上。"," The practice server is not reachable right now."))),console.log(chalk.gray(w(" 检查一下网络,或者过一会儿再试。"," Check your connection, or try again later."))),console.log()}function $(o){return s(process.cwd(),"icoa-kaggle",o)}function _(o,e){const n=[];let t="",l=0;const s=o=>/[ᄀ-ᅟ⺀-꓏가-힣豈-﫿︰-﹏＀-⦆¢-₩]/.test(o);for(const a of o){const o=s(a)?2:1;if(l+o>e){const o=t.lastIndexOf(" ");if(!s(a)&&" "!==a&&o>e/3){const e=t.slice(o+1);n.push(t.slice(0,o)),t=e,l=[...e].reduce((o,e)=>o+(s(e)?2:1),0)}else n.push(t),t="",l=0;if(" "===a&&""===t)continue}t+=a,l+=o}return""!==t.trim()&&n.push(t),n}function j(o){return"local-eval"===o?.judge?(console.log(chalk.bold.white(w(" 出分(就在 notebook 里):"," Scoring (inside the notebook):"))),void console.log(chalk.gray(w(" 跑最后一格 —— "," run the final cell — the "))+chalk.white("FINAL")+chalk.gray(w(" 那一行就是你的分数,没有东西要上传。"," line is your score. Nothing to upload.")))):"icoa-holdout"===o?.judge?(console.log(chalk.bold.white(w(" 交给 ICOA 判分(服务端评分):"," Submit to ICOA (scored on the server):"))),console.log(chalk.gray(" ")+chalk.bold.cyan(`kaggle submit ${o.comp_id}`)),void console.log(chalk.gray(w(" 与秘密测试标签比对 → 实时排名看 "," scores vs the secret test labels → live rank on "))+chalk.cyan("board"))):"nitro"===o?.judge?(console.log(chalk.bold.white(w(" 怎么知道做得对不对:"," How to tell whether you got it right:"))),console.log(chalk.gray(w(" · 这道题来自 judge.nitro-ai.org,判分在他们服务器上"," · this task comes from judge.nitro-ai.org — the judging lives on their server"))),console.log(chalk.gray(w(" · 想要真分数:去 "," · for a real score: register at "))+chalk.cyan("judge.nitro-ai.org")+chalk.gray(w(" 注册后提交"," and submit there"))),void console.log(chalk.gray(w(" · 冲刺期更快的办法:做完对照官方解答,或问 "," · faster right now: compare against the official solution, or ask "))+chalk.cyan("ai4ioai"))):(console.log(chalk.bold.white(w(" 去 Kaggle 提交(手动,用你自己的账号):"," Submit on Kaggle (manual, your own account):"))),void(o?.kaggle_url?(console.log(chalk.gray(w(" 1. 打开 "," 1. open "))+chalk.cyan(o.kaggle_url)),o?.needs_gpu?console.log(chalk.gray(w(" 2. 交 notebook 产出的那个文件 —— 最后一格写了确切步骤"," 2. submit the file your notebook produced — its final cell has the exact steps"))):console.log(chalk.gray(w(" 2. Submit Predictions → 上传 "," 2. Submit Predictions → upload "))+chalk.white("submission.csv")),console.log(chalk.gray(w(" 3. 看分数,改 MODEL 那一格,重跑,再来一轮。"," 3. read your score, improve the MODEL cell, re-run, repeat.")))):(console.log(chalk.gray(w(" 在 kaggle.com 搜这个比赛名提交,或做完对照官方解答自查。"," Search kaggle.com for this competition, or check yourself against the official solution."))),console.log(chalk.gray(w(" 卡住了问 "," Stuck? ask "))+chalk.cyan("ai4ioai")+chalk.gray(w(" —— 它是弱模型,把问题问准是这次要练的本事。"," — a deliberately weak model; asking precisely is the skill you are training."))))))}export async function runKaggle(n){const t=a(),i=async o=>await t.ask(o)??"";try{console.log(),console.log(chalk.bold.cyan(" 📊 KAGGLE PRACTICE")+chalk.gray(w(" · 真实的 ML 比赛,配一本能直接跑的 starter notebook"," · real ML competitions, a runnable starter notebook"))),console.log(chalk.gray(w(" 小题在你自己的 CPU 上跑;"," Small tasks run on your CPU; "))+chalk.magenta(w("⚡ GPU 题","⚡ GPU tasks"))+chalk.gray(w("在 ICOA 的 GPU 箱上跑。"," run on the ICOA GPU box."))),console.log();const t=await f("/api/icoa/kaggle/tasks");if(!t)return v();const a=h(t);if(0===a.length)return console.log(chalk.yellow(w(" 现在还没有上线的练习赛 —— 过一会儿再来。"," No practice competitions are live yet — check back soon."))),void console.log();let c=n?a.find(o=>o.comp_id===n):void 0;if(n&&!c&&console.log(chalk.yellow(w(` 没有叫 "${n}" 的比赛。`,` No competition called "${n}".`))),!c){console.log(chalk.white(w(" 正在开放的练习赛:"," Live practice competitions:"))),a.forEach((o,e)=>{const n=o.needs_gpu?chalk.magenta(" ⚡GPU"):"";console.log(chalk.gray(` ${e+1}. `)+chalk.cyan(o.comp_id)+chalk.gray(` — ${o.title} · ${o.metric}`)+n)});for(let o=0;o<3&&!c;o++){const o=(await i(chalk.cyan(w(" 选一个(序号或 id): "," Pick one (number or id): ")))).trim();if(!o)return;const e=Number(o);c=!Number.isNaN(e)&&a[e-1]||a.find(e=>e.comp_id===o.toLowerCase())||void 0,c||console.log(chalk.gray(w(` 输 1-${a.length} 之间的序号,或者一个 id,比如 "${a[0].comp_id}"。`,` Try a number 1-${a.length} or an id like "${a[0].comp_id}".`)))}if(!c)return}const u=c.comp_id;if(r(`kaggle: download ${u}`),c.needs_gpu)return void await async function(n,t){const a=$(n);if(console.log(),console.log(chalk.white(` ${t.title}`)+chalk.gray(` · ${t.metric}`)+chalk.bold.magenta(" ⚡ GPU task")),t.description){console.log();for(const o of _(t.description,74))console.log(chalk.white(` ${o}`))}console.log(),console.log(chalk.gray(w(" 正在取 notebook…"," Fetching the notebook…"))+chalk.gray(w(" (数据留在 GPU 箱上,不下载)"," (the dataset stays on the GPU box — no download)")));const i=await f(`/api/icoa/kaggle/${n}/starter`),r=i?.data?.starter??i?.starter;if("string"!=typeof r||0===r.length)return v();const c=s(a,"starter.ipynb");let g=!1;try{e(a,{recursive:!0}),o(c)?g=!0:l(c,r),l(s(a,"meta.json"),`${JSON.stringify(t,null,2)}\n`)}catch{return void console.log(chalk.yellow(w(" 写不进 notebook —— 检查一下这个目录的写权限。"," Could not write the notebook here — check directory permissions.")))}console.log(chalk.green(" ✓ notebook: ")+chalk.white(c)+chalk.gray(g?w(" (保留了你原来那本)"," (kept your existing one)"):w(" (里面是真正的 IOAI 题)"," (the real IOAI task inside)"))),console.log(chalk.green(" ✓ dataset: ")+chalk.white(w("已经在 GPU 箱上","already on the GPU box"))+chalk.gray(w(" —— 不用下载"," — no download needed"))),console.log(),console.log(chalk.bold.white(w(" 这是 GPU 题 —— 三步:"," This is a GPU task — 3 steps:"))),console.log(chalk.gray(" 1. ")+chalk.bold.cyan(`icoa ipynb ${c}`)),console.log(chalk.gray(" 2. ")+chalk.bold.cyan("gpu key <your-key>")+chalk.gray(w(" 然后 "," then "))+chalk.bold.cyan("gpu on")+chalk.gray(w(" (连到数据所在的那台箱子)"," (connects you to the box where the data lives)"))),console.log(chalk.gray(" 3. ")+chalk.bold.cyan("run all")+chalk.gray(w(" → notebook 在 GPU 上训练。"," → the notebook trains on the GPU."))),console.log(),console.log(chalk.gray(w(" 做题时随时看: "," While you work: "))+chalk.cyan("gpu status")+chalk.gray(w(" 你还剩多少时间 · "," your time left · "))+chalk.cyan("gpu queue")+chalk.gray(w(" 谁在用,谁在等"," who is on, who is waiting"))),console.log(),t.kaggle_url&&(console.log(chalk.gray(w(" 去 Kaggle 提交: "," Submit on Kaggle: "))+chalk.cyan(t.kaggle_url)),console.log())}(u,c);if(console.log(),console.log(chalk.white(` ${c.title}`)+chalk.gray(` · ${c.metric}`)),c.description){console.log();for(const o of _(c.description,74))console.log(chalk.white(` ${o}`))}console.log(),console.log(chalk.gray(w(" 正在下载数据…"," Downloading data…")));let b=null;const m=d(c);if(m){const[o,e,n]=await Promise.all([k(m.train),k(m.test),k(m.sample_submission)]);o&&e&&n&&(b={train:o,test:e,sample_submission:n})}if(!b){const o=await f(`/api/icoa/kaggle/${u}/data`);b=o?.data??o}if(!b?.train||!b?.test||!b?.sample_submission)return v();const p=$(u),j={...c,...b.meta??{}};try{e(p,{recursive:!0}),l(s(p,"train.csv"),b.train),l(s(p,"test.csv"),b.test),l(s(p,"sample_submission.csv"),b.sample_submission),l(s(p,"meta.json"),`${JSON.stringify(j,null,2)}\n`)}catch{return void console.log(chalk.yellow(" Could not write the data files here — check directory permissions."))}const G=s(p,"starter.ipynb");let P=!1;if(o(G))P=!0;else{const o=await f(`/api/icoa/kaggle/${u}/starter`),e=o?.data?.starter??o?.starter;"string"==typeof e&&e.length>0?l(G,e):l(G,g(y(p,j)))}const x="number"==typeof j.n_train?`${j.n_train} rows`:"labelled",C="number"==typeof j.n_test?`${j.n_test} rows`:"predict these";console.log(chalk.green(" ✓ train: ")+chalk.white(s(p,"train.csv"))+chalk.gray(` (${x})`)),console.log(chalk.green(" ✓ test: ")+chalk.white(s(p,"test.csv"))+chalk.gray(` (${C})`)),console.log(chalk.green(" ✓ format: ")+chalk.white(s(p,"sample_submission.csv"))),console.log(chalk.green(" ✓ notebook: ")+chalk.white(G)+chalk.gray(P?" (kept your existing one)":" (runnable baseline inside)")),(j.licence||j.attribution)&&console.log(chalk.gray(` licence: ${j.licence??"—"} · ${j.attribution??""}`)),console.log(),S(u,j,G),console.log()}finally{t.close()}}function S(o,e,n){e?.needs_gpu?(console.log(chalk.bold.white(" Your move — 4 steps (⚡ GPU task):")),console.log(chalk.gray(" 1. ")+chalk.bold.cyan(`icoa ipynb ${n}`)),console.log(chalk.gray(" 2. ")+chalk.bold.cyan("gpu key <your-key>")+chalk.gray(" then ")+chalk.bold.cyan("gpu on")+chalk.gray(" → ")+chalk.bold.cyan("run all")+chalk.gray(" (trains on the GPU box)")),console.log(chalk.gray(" 3. ")+chalk.bold.cyan("download <file>")+chalk.gray(" → pulls your results (submission.csv / predictions.zip) here")),console.log(chalk.gray(" 4. submit on kaggle.com — the notebook's final cell has the exact steps.")),console.log(),console.log(chalk.gray(" While you work: ")+chalk.cyan("gpu status")+chalk.gray(" your time left · ")+chalk.cyan("gpu queue")+chalk.gray(" who is on, who is waiting"))):(console.log(chalk.bold.white(" Your move — 3 steps:")),console.log(chalk.gray(" 1. ")+chalk.bold.cyan(`icoa ipynb ${n}`)+chalk.gray(" → run all (baseline trains)")),console.log(chalk.gray(" 2. it writes ")+chalk.white("submission.csv")+chalk.gray(" → verify with ")+chalk.cyan(`kaggle check ${o}`)),"icoa-holdout"===e?.judge?console.log(chalk.gray(" 3. ")+chalk.bold.cyan(`kaggle submit ${o}`)+chalk.gray(" → scored + ranked live.")):"nitro"===e?.judge?console.log(chalk.gray(" 3. scored at ")+chalk.cyan("judge.nitro-ai.org")+chalk.gray(" (not Kaggle) — or just work the val score. See below.")):console.log(chalk.gray(" 3. upload it on Kaggle yourself — then beat the baseline."))),console.log(),console.log(chalk.bold.white(" 🤝 Want AI help? Set up your cockpit:")),console.log(chalk.gray(" 1. split the screen: ")+chalk.bold.cyan("Ctrl-b %")+chalk.gray(" (lesson/work left · AI right)")),console.log(chalk.gray(" 2. in the right pane: ")+chalk.bold.cyan("icoa")+chalk.gray(" then type ")+chalk.bold.cyan("ai4ioai")+chalk.gray(" → live Gemma 3")),console.log(chalk.gray(" 3. ask it for feature ideas or bug fixes — then ")+chalk.bold.white("VERIFY")+chalk.gray(" with your val score (a tip that lowers it, drop it).")),console.log(),j(e)}export async function runKaggleGuide(e){console.log();const t=G(e,"guide");if(!t)return;const l=$(t);let a=null;try{a=JSON.parse(n(s(l,"meta.json"),"utf-8"))}catch{a=null}r(`kaggle: guide ${t}`);const i=s(l,"starter.ipynb"),c=o(s(l,"submission.csv"));console.log(chalk.bold.white(` ═══ 📖 ${a?.title??t} — walkthrough ═══`)),console.log(),console.log(chalk.gray(" Where you are: data ")+chalk.green("downloaded ✓")+chalk.gray(" · submission.csv: ")+(c?chalk.green("written ✓"):chalk.yellow("not yet — run the notebook"))),console.log(),S(t,a,i),console.log(),console.log(chalk.gray(" Inside the notebook, ")+chalk.cyan("guide")+chalk.gray(" shows the notebook-level guide.")),console.log()}function G(e,n){if(e)return e;const l=s(process.cwd(),"icoa-kaggle"),a=o(l)?t(l,{withFileTypes:!0}).filter(e=>e.isDirectory()&&(o(s(l,e.name,"sample_submission.csv"))||o(s(l,e.name,"meta.json")))).map(o=>o.name):[];if(1===a.length)return a[0];if(0===a.length)return console.log(chalk.yellow(" No downloaded competition found here — run ")+chalk.cyan("kaggle")+chalk.yellow(" first.")),console.log(),null;console.log(chalk.white(" Several competitions downloaded — pick one:"));for(const o of a)console.log(chalk.gray(` kaggle ${n} `)+chalk.cyan(o));return console.log(),null}export async function runKaggleCheck(e){console.log();const t=G(e,"check");if(!t)return;const l=$(t),a=s(l,"submission.csv"),i=s(l,"sample_submission.csv");try{if(JSON.parse(n(s(l,"meta.json"),"utf-8")).needs_gpu&&!o(i))return console.log(chalk.gray(" ⚡ GPU task — results are produced and validated by the notebook itself.")),console.log(chalk.gray(" Pull them with ")+chalk.cyan("download <file>")+chalk.gray(" inside ")+chalk.cyan("icoa ipynb")+chalk.gray(", then submit on kaggle.com (final cell has the steps).")),void console.log()}catch{}if(!o(i))return console.log(chalk.yellow(` No data for "${t}" here — run `)+chalk.cyan(`kaggle ${t}`)+chalk.yellow(" first.")),void console.log();if(!o(a))return console.log(chalk.yellow(" No submission.csv yet — open the notebook and run all cells:")),console.log(chalk.gray(" ")+chalk.cyan(`icoa ipynb ${s(l,"starter.ipynb")}`)),void console.log();const g=m(n(a,"utf-8"),n(i,"utf-8"));r(`kaggle: check ${t} → ${g.ok?"ok":`rejected: ${g.problems[0]??"format"}`}`);let u=null;try{u=JSON.parse(n(s(l,"meta.json"),"utf-8"))}catch{u=null}if(g.ok)console.log(chalk.bold.green(" ✓ submission.csv has the right format")+chalk.gray(" (matches sample_submission.csv)")),console.log(chalk.gray(" ")+chalk.white(a)),console.log(),j(u),c(l);else{console.log(chalk.bold.red(" ✗ submission.csv would be rejected:"));for(const o of g.problems)console.log(chalk.yellow(` · ${o}`));console.log(),console.log(chalk.gray(" Fix the submission cell in the notebook and re-run it."))}console.log()}export async function runKaggleSubmit(e){console.log();const t=G(e,"submit");if(!t)return;const l=$(t),i=s(l,"submission.csv"),c=s(l,"sample_submission.csv");let g=null;try{g=JSON.parse(n(s(l,"meta.json"),"utf-8"))}catch{g=null}if("local-eval"===g?.judge)return console.log(chalk.yellow(" This task is scored inside the notebook — nothing to upload.")),j(g),void console.log();if(!g||!o(c))return console.log(chalk.yellow(` No data for "${t}" here — run `)+chalk.cyan(`kaggle ${t}`)+chalk.yellow(" first.")),void console.log();if("icoa-holdout"!==g.judge)return console.log(chalk.yellow(" This competition is judged on kaggle.com — nothing to submit here.")),console.log(),j(g),void console.log();if(!o(i))return console.log(chalk.yellow(" No submission.csv yet — open the notebook and run all cells:")),console.log(chalk.gray(" ")+chalk.cyan(`icoa ipynb ${s(l,"starter.ipynb")}`)),void console.log();const y=n(i,"utf-8"),d=m(y,n(c,"utf-8"));if(!d.ok){r(`kaggle: submit ${t} → local-reject: ${d.problems[0]??"format"}`),console.log(chalk.bold.red(" ✗ submission.csv would be rejected:"));for(const o of d.problems)console.log(chalk.yellow(` · ${o}`));return console.log(),console.log(chalk.gray(" Fix the submission cell in the notebook and re-run it.")),void console.log()}let h=u()?.token??"";if(!h){const o=a();try{h=(await o.ask(chalk.cyan(" Your learn token: "))??"").trim()}finally{o.close()}if(!h)return console.log(chalk.gray(" A learn token identifies you on the board — ask your coach for one.")),void console.log()}console.log(chalk.gray(" Scoring on the server…"));const f=await async function(o,e){try{const n=await fetch(p()+o,{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify(e),signal:AbortSignal.timeout(6e4)});return await n.json()}catch{return null}}(`/api/icoa/kaggle/${t}/submit`,{token:h,submission_csv:y}),k=b(f);if(r(`kaggle: submit ${t} → ${k.ok?`${k.metric}=${k.score}${k.deduped?" (deduped)":""} rank=${k.rank??"-"}`:k.reason??"error"}`),console.log(),k.ok){const o=`${k.metric}: ${Number(k.score).toFixed(4).replace(/\.?0+$/,"")}`;k.deduped?(console.log(chalk.bold.white(` ✓ already scored — ${o}`)),console.log(chalk.gray(" These exact predictions were scored before. Improve the MODEL cell and re-run."))):(console.log(chalk.bold.green(` ✓ scored — ${o}`)),"number"==typeof k.rank&&"number"==typeof k.fieldSize&&console.log(chalk.bold.white(` 🏁 board rank #${k.rank}`)+chalk.gray(` of ${k.fieldSize}`))),k.boardEvent&&console.log(chalk.gray(" standings: ")+chalk.cyan(`board ${k.boardEvent} ${t}`))}else switch(k.reason){case"bad_token":console.log(chalk.bold.red(" ✗ that learn token was not accepted")+chalk.gray(" (invalid or expired)")),console.log(chalk.gray(" Check the token with your coach, then try again."));break;case"format":console.log(chalk.bold.red(" ✗ the server rejected submission.csv:"));for(const o of k.problems??[])console.log(chalk.yellow(` · ${o}`));break;case"event_closed":case"outside_window":console.log(chalk.bold.yellow(" ⏱ the submission window for this competition is closed."));break;case"cap_reached":console.log(chalk.bold.yellow(" ⏱ you have used all your submissions for this competition."));break;case"kaggle_judged":console.log(chalk.yellow(" This competition is judged on kaggle.com — nothing to submit here."));break;default:console.log(chalk.yellow(" The scoring server is not reachable right now — try again in a minute."))}console.log()}export function registerKaggleCommand(o){o.command("kaggle").argument("[action]",'competition id, or "check" / "submit"').argument("[comp]",'competition id (with "check" / "submit")').description("Kaggle-style ML practice — dataset + starter notebook, check & submit").action(async(o,e)=>{"check"===o?await runKaggleCheck(e):"submit"===o?await runKaggleSubmit(e):"guide"===o?await runKaggleGuide(e):await runKaggle(o)}),o.command("guide").argument("[comp]","competition id").description("Show the competition walkthrough (3 steps + AI cockpit)").action(async o=>{await runKaggleGuide(o)})}
1
+ import{existsSync as o,mkdirSync as e,readFileSync as n,readdirSync as t,writeFileSync as l}from"node:fs";import{join as s}from"node:path";import chalk from"chalk";import{makeReplAsker as a}from"../lib/repl-asker.js";import{getConfig as i}from"../lib/config.js";import{logCommand as r}from"../lib/logger.js";import{openFile as c}from"../lib/open-file.js";import{serializeIpynb as g}from"../lib/notebook-doc.js";import{loadLearnState as u}from"../lib/learn-state.js";import{buildStarterCells as d,dataFileUrls as y,parseKaggleTaskList as h,parseSubmitResponse as m,validateSubmissionText as b}from"../lib/kaggle.js";import{mediaHelpLines as p,sprintTaskForComp as f}from"../lib/sprint-meta.js";function k(){return process.env.ICOA_KAGGLE_SERVER?process.env.ICOA_KAGGLE_SERVER.replace(/\/$/,""):"https://practice.icoa2026.au"}async function w(o){try{const e=await fetch(k()+o,{signal:AbortSignal.timeout(3e4)});return await e.json()}catch{return null}}async function v(o){try{const e=await fetch(o,{signal:AbortSignal.timeout(6e4)});return e.ok?await e.text():null}catch{return null}}function $(){return(i().language||"en").toLowerCase().startsWith("zh")}function j(o,e){return $()?o:e}function _(){console.log(),console.log(chalk.yellow(j(" 练习服务器现在连不上。"," The practice server is not reachable right now."))),console.log(chalk.gray(j(" 检查一下网络,或者过一会儿再试。"," Check your connection, or try again later."))),console.log()}function S(o){return s(process.cwd(),"icoa-kaggle",o)}function G(o,e){const n=[];let t="",l=0;const s=o=>/[ᄀ-ᅟ⺀-꓏가-힣豈-﫿︰-﹏＀-⦆¢-₩]/.test(o);for(const a of o){const o=s(a)?2:1;if(l+o>e){const o=t.lastIndexOf(" ");if(!s(a)&&" "!==a&&o>e/3){const e=t.slice(o+1);n.push(t.slice(0,o)),t=e,l=[...e].reduce((o,e)=>o+(s(e)?2:1),0)}else n.push(t),t="",l=0;if(" "===a&&""===t)continue}t+=a,l+=o}return""!==t.trim()&&n.push(t),n}function P(o){return"local-eval"===o?.judge?(console.log(chalk.bold.white(j(" 出分(就在 notebook 里):"," Scoring (inside the notebook):"))),void console.log(chalk.gray(j(" 跑最后一格 —— "," run the final cell — the "))+chalk.white("FINAL")+chalk.gray(j(" 那一行就是你的分数,没有东西要上传。"," line is your score. Nothing to upload.")))):"icoa-holdout"===o?.judge?(console.log(chalk.bold.white(j(" 交给 ICOA 判分(服务端评分):"," Submit to ICOA (scored on the server):"))),console.log(chalk.gray(" ")+chalk.bold.cyan(`kaggle submit ${o.comp_id}`)),void console.log(chalk.gray(j(" 与秘密测试标签比对 → 实时排名看 "," scores vs the secret test labels → live rank on "))+chalk.cyan("board"))):"nitro"===o?.judge?(console.log(chalk.bold.white(j(" 怎么知道做得对不对:"," How to tell whether you got it right:"))),console.log(chalk.gray(j(" · 这道题来自 judge.nitro-ai.org,判分在他们服务器上"," · this task comes from judge.nitro-ai.org — the judging lives on their server"))),console.log(chalk.gray(j(" · 想要真分数:去 "," · for a real score: register at "))+chalk.cyan("judge.nitro-ai.org")+chalk.gray(j(" 注册后提交"," and submit there"))),void console.log(chalk.gray(j(" · 冲刺期更快的办法:做完对照官方解答,或问 "," · faster right now: compare against the official solution, or ask "))+chalk.cyan("ai4ioai"))):(console.log(chalk.bold.white(j(" 去 Kaggle 提交(手动,用你自己的账号):"," Submit on Kaggle (manual, your own account):"))),void(o?.kaggle_url?(console.log(chalk.gray(j(" 1. 打开 "," 1. open "))+chalk.cyan(o.kaggle_url)),o?.needs_gpu?console.log(chalk.gray(j(" 2. 交 notebook 产出的那个文件 —— 最后一格写了确切步骤"," 2. submit the file your notebook produced — its final cell has the exact steps"))):console.log(chalk.gray(j(" 2. Submit Predictions → 上传 "," 2. Submit Predictions → upload "))+chalk.white("submission.csv")),console.log(chalk.gray(j(" 3. 看分数,改 MODEL 那一格,重跑,再来一轮。"," 3. read your score, improve the MODEL cell, re-run, repeat.")))):(console.log(chalk.gray(j(" 在 kaggle.com 搜这个比赛名提交,或做完对照官方解答自查。"," Search kaggle.com for this competition, or check yourself against the official solution."))),console.log(chalk.gray(j(" 卡住了问 "," Stuck? ask "))+chalk.cyan("ai4ioai")+chalk.gray(j(" —— 它是弱模型,把问题问准是这次要练的本事。"," — a deliberately weak model; asking precisely is the skill you are training."))))))}export async function runKaggle(n){const t=a(),i=async o=>await t.ask(o)??"";try{console.log(),console.log(chalk.bold.cyan(" 📊 KAGGLE PRACTICE")+chalk.gray(j(" · 真实的 ML 比赛,配一本能直接跑的 starter notebook"," · real ML competitions, a runnable starter notebook"))),console.log(chalk.gray(j(" 小题在你自己的 CPU 上跑;"," Small tasks run on your CPU; "))+chalk.magenta(j("⚡ GPU 题","⚡ GPU tasks"))+chalk.gray(j("在 ICOA 的 GPU 箱上跑。"," run on the ICOA GPU box."))),console.log();const t=await w("/api/icoa/kaggle/tasks");if(!t)return _();const a=h(t);if(0===a.length)return console.log(chalk.yellow(j(" 现在还没有上线的练习赛 —— 过一会儿再来。"," No practice competitions are live yet — check back soon."))),void console.log();let c=n?a.find(o=>o.comp_id===n):void 0;if(n&&!c&&console.log(chalk.yellow(j(` 没有叫 "${n}" 的比赛。`,` No competition called "${n}".`))),!c){console.log(chalk.white(j(" 正在开放的练习赛:"," Live practice competitions:"))),a.forEach((o,e)=>{const n=o.needs_gpu?chalk.magenta(" ⚡GPU"):"";console.log(chalk.gray(` ${e+1}. `)+chalk.cyan(o.comp_id)+chalk.gray(` — ${o.title} · ${o.metric}`)+n)});for(let o=0;o<3&&!c;o++){const o=(await i(chalk.cyan(j(" 选一个(序号或 id): "," Pick one (number or id): ")))).trim();if(!o)return;const e=Number(o);c=!Number.isNaN(e)&&a[e-1]||a.find(e=>e.comp_id===o.toLowerCase())||void 0,c||console.log(chalk.gray(j(` 输 1-${a.length} 之间的序号,或者一个 id,比如 "${a[0].comp_id}"。`,` Try a number 1-${a.length} or an id like "${a[0].comp_id}".`)))}if(!c)return}const u=c.comp_id;if(r(`kaggle: download ${u}`),c.needs_gpu)return void await async function(n,t){const a=S(n);if(console.log(),console.log(chalk.white(` ${t.title}`)+chalk.gray(` · ${t.metric}`)+chalk.bold.magenta(" ⚡ GPU task")),t.description){console.log();for(const o of G(t.description,74))console.log(chalk.white(` ${o}`))}console.log(),console.log(chalk.gray(j(" 正在取 notebook…"," Fetching the notebook…"))+chalk.gray(j(" (数据留在 GPU 箱上,不下载)"," (the dataset stays on the GPU box — no download)")));const i=await w(`/api/icoa/kaggle/${n}/starter`),r=i?.data?.starter??i?.starter;if("string"!=typeof r||0===r.length)return _();const c=s(a,"starter.ipynb");let g=!1;try{e(a,{recursive:!0}),o(c)?g=!0:l(c,r),l(s(a,"meta.json"),`${JSON.stringify(t,null,2)}\n`)}catch{return void console.log(chalk.yellow(j(" 写不进 notebook —— 检查一下这个目录的写权限。"," Could not write the notebook here — check directory permissions.")))}console.log(chalk.green(" ✓ notebook: ")+chalk.white(c)+chalk.gray(g?j(" (保留了你原来那本)"," (kept your existing one)"):j(" (里面是真正的 IOAI 题)"," (the real IOAI task inside)"))),console.log(chalk.green(" ✓ dataset: ")+chalk.white(j("已经在 GPU 箱上","already on the GPU box"))+chalk.gray(j(" —— 不用下载"," — no download needed"))),console.log(),console.log(chalk.bold.white(j(" 这是 GPU 题 —— 三步:"," This is a GPU task — 3 steps:"))),console.log(chalk.gray(" 1. ")+chalk.bold.cyan(`icoa ipynb ${c}`)),console.log(chalk.gray(" 2. ")+chalk.bold.cyan("gpu key <your-key>")+chalk.gray(j(" 然后 "," then "))+chalk.bold.cyan("gpu on")+chalk.gray(j(" (连到数据所在的那台箱子)"," (connects you to the box where the data lives)"))),console.log(chalk.gray(" 3. ")+chalk.bold.cyan("run all")+chalk.gray(j(" → notebook 在 GPU 上训练。"," → the notebook trains on the GPU."))),console.log(),console.log(chalk.gray(j(" 做题时随时看: "," While you work: "))+chalk.cyan("gpu status")+chalk.gray(j(" 你还剩多少时间 · "," your time left · "))+chalk.cyan("gpu queue")+chalk.gray(j(" 谁在用,谁在等"," who is on, who is waiting"))),console.log(),t.kaggle_url&&(console.log(chalk.gray(j(" 去 Kaggle 提交: "," Submit on Kaggle: "))+chalk.cyan(t.kaggle_url)),console.log())}(u,c);if(console.log(),console.log(chalk.white(` ${c.title}`)+chalk.gray(` · ${c.metric}`)),c.description){console.log();for(const o of G(c.description,74))console.log(chalk.white(` ${o}`))}console.log(),console.log(chalk.gray(j(" 正在下载数据…"," Downloading data…")));let m=null;const b=y(c);if(b){const[o,e,n]=await Promise.all([v(b.train),v(b.test),v(b.sample_submission)]);o&&e&&n&&(m={train:o,test:e,sample_submission:n})}if(!m){const o=await w(`/api/icoa/kaggle/${u}/data`);m=o?.data??o}if(!m?.train||!m?.test||!m?.sample_submission)return _();const p=S(u),k={...c,...m.meta??{}};try{e(p,{recursive:!0}),l(s(p,"train.csv"),m.train),l(s(p,"test.csv"),m.test),l(s(p,"sample_submission.csv"),m.sample_submission),l(s(p,"meta.json"),`${JSON.stringify(k,null,2)}\n`)}catch{return void console.log(chalk.yellow(" Could not write the data files here — check directory permissions."))}const $=s(p,"starter.ipynb");let P=!1;if(o($))P=!0;else{const o=await w(`/api/icoa/kaggle/${u}/starter`),e=o?.data?.starter??o?.starter;"string"==typeof e&&e.length>0?l($,e):l($,g(d(p,k)))}const A="number"==typeof k.n_train?`${k.n_train} rows`:"labelled",C="number"==typeof k.n_test?`${k.n_test} rows`:"predict these";console.log(chalk.green(" ✓ train: ")+chalk.white(s(p,"train.csv"))+chalk.gray(` (${A})`)),console.log(chalk.green(" ✓ test: ")+chalk.white(s(p,"test.csv"))+chalk.gray(` (${C})`)),console.log(chalk.green(" ✓ format: ")+chalk.white(s(p,"sample_submission.csv")));const E=f(u),U="none"===(E?.baseline||"").trim();console.log(chalk.green(" ✓ notebook: ")+chalk.white($)+chalk.gray(P?" (kept your existing one)":U?j(" (starter 在里面,FEATURES 那一格要你自己写)"," (starter inside — the FEATURES cell is yours to write)"):" (runnable baseline inside)")),(k.licence||k.attribution)&&console.log(chalk.gray(` licence: ${k.licence??"—"} · ${k.attribution??""}`)),console.log(),x(u,k,$),console.log()}finally{t.close()}}function A(o){const e=$();switch(o){case"audio":return e?"音频":"audio";case"image":return e?"图片":"images";case"weights":return e?"模型权重":"model weights";default:return e?"附件":"the extra files"}}function x(o,e,n){const t=f(o),l=t?p(t,$()):[];if(l.length>0){for(const o of l)for(const e of G(o,74))console.log(chalk.yellow(` ${e}`));console.log()}if(e?.needs_gpu)console.log(chalk.bold.white(" Your move — 4 steps (⚡ GPU task):")),console.log(chalk.gray(" 1. ")+chalk.bold.cyan(`icoa ipynb ${n}`)),console.log(chalk.gray(" 2. ")+chalk.bold.cyan("gpu key <your-key>")+chalk.gray(" then ")+chalk.bold.cyan("gpu on")+chalk.gray(" → ")+chalk.bold.cyan("run all")+chalk.gray(" (trains on the GPU box)")),console.log(chalk.gray(" 3. ")+chalk.bold.cyan("download <file>")+chalk.gray(" → pulls your results (submission.csv / predictions.zip) here")),console.log(chalk.gray(" 4. submit on kaggle.com — the notebook's final cell has the exact steps.")),console.log(),console.log(chalk.gray(" While you work: ")+chalk.cyan("gpu status")+chalk.gray(" your time left · ")+chalk.cyan("gpu queue")+chalk.gray(" who is on, who is waiting"));else{const l=t?.media?.pack,s="none"===(t?.baseline||"").trim();console.log(chalk.bold.white(l?j(" 接下来 4 步:"," Your move — 4 steps:"):j(" 接下来 3 步:"," Your move — 3 steps:")));let a=1;l&&console.log(chalk.gray(` ${a++}. `)+chalk.bold.cyan(`teleload ${l}`)+chalk.gray(j(` → 把${A(t?.media?.kind)}拉下来(CSV 里没有)`,` → fetch the ${A(t?.media?.kind)} (the CSVs do not carry it)`))),console.log(chalk.gray(` ${a++}. `)+chalk.bold.cyan(`icoa ipynb ${n}`)+chalk.gray(s?j(" → run all 到 FEATURES 那格会停,那格是你的活"," → run all stops at FEATURES — that cell is your job"):" → run all (baseline trains)")),console.log(chalk.gray(` ${a++}. it writes `)+chalk.white("submission.csv")+chalk.gray(" → verify with ")+chalk.cyan(`kaggle check ${o}`)),"icoa-holdout"===e?.judge?console.log(chalk.gray(` ${a}. `)+chalk.bold.cyan(`kaggle submit ${o}`)+chalk.gray(" → scored + ranked live.")):"nitro"===e?.judge?console.log(chalk.gray(` ${a}. scored at `)+chalk.cyan("judge.nitro-ai.org")+chalk.gray(" (not Kaggle) — or just work the val score. See below.")):console.log(chalk.gray(` ${a}. upload it on Kaggle yourself — then beat the baseline.`))}console.log(),console.log(chalk.bold.white(" 🤝 Want AI help? Set up your cockpit:")),console.log(chalk.gray(" 1. split the screen: ")+chalk.bold.cyan("Ctrl-b %")+chalk.gray(" (lesson/work left · AI right)")),console.log(chalk.gray(" 2. in the right pane: ")+chalk.bold.cyan("icoa")+chalk.gray(" then type ")+chalk.bold.cyan("ai4ioai")+chalk.gray(" → live Gemma 3")),console.log(chalk.gray(" 3. ask it for feature ideas or bug fixes — then ")+chalk.bold.white("VERIFY")+chalk.gray(" with your val score (a tip that lowers it, drop it).")),console.log(),P(e)}export async function runKaggleGuide(e){console.log();const t=C(e,"guide");if(!t)return;const l=S(t);let a=null;try{a=JSON.parse(n(s(l,"meta.json"),"utf-8"))}catch{a=null}r(`kaggle: guide ${t}`);const i=s(l,"starter.ipynb"),c=o(s(l,"submission.csv"));console.log(chalk.bold.white(` ═══ 📖 ${a?.title??t} — walkthrough ═══`)),console.log(),console.log(chalk.gray(" Where you are: data ")+chalk.green("downloaded ✓")+chalk.gray(" · submission.csv: ")+(c?chalk.green("written ✓"):chalk.yellow("not yet — run the notebook"))),console.log(),x(t,a,i),console.log(),console.log(chalk.gray(" Inside the notebook, ")+chalk.cyan("guide")+chalk.gray(" shows the notebook-level guide.")),console.log()}function C(e,n){if(e)return e;const l=s(process.cwd(),"icoa-kaggle"),a=o(l)?t(l,{withFileTypes:!0}).filter(e=>e.isDirectory()&&(o(s(l,e.name,"sample_submission.csv"))||o(s(l,e.name,"meta.json")))).map(o=>o.name):[];if(1===a.length)return a[0];if(0===a.length)return console.log(chalk.yellow(" No downloaded competition found here — run ")+chalk.cyan("kaggle")+chalk.yellow(" first.")),console.log(),null;console.log(chalk.white(" Several competitions downloaded — pick one:"));for(const o of a)console.log(chalk.gray(` kaggle ${n} `)+chalk.cyan(o));return console.log(),null}export async function runKaggleCheck(e){console.log();const t=C(e,"check");if(!t)return;const l=S(t),a=s(l,"submission.csv"),i=s(l,"sample_submission.csv");try{if(JSON.parse(n(s(l,"meta.json"),"utf-8")).needs_gpu&&!o(i))return console.log(chalk.gray(" ⚡ GPU task — results are produced and validated by the notebook itself.")),console.log(chalk.gray(" Pull them with ")+chalk.cyan("download <file>")+chalk.gray(" inside ")+chalk.cyan("icoa ipynb")+chalk.gray(", then submit on kaggle.com (final cell has the steps).")),void console.log()}catch{}if(!o(i))return console.log(chalk.yellow(` No data for "${t}" here — run `)+chalk.cyan(`kaggle ${t}`)+chalk.yellow(" first.")),void console.log();if(!o(a))return console.log(chalk.yellow(" No submission.csv yet — open the notebook and run all cells:")),console.log(chalk.gray(" ")+chalk.cyan(`icoa ipynb ${s(l,"starter.ipynb")}`)),void console.log();const g=b(n(a,"utf-8"),n(i,"utf-8"));r(`kaggle: check ${t} → ${g.ok?"ok":`rejected: ${g.problems[0]??"format"}`}`);let u=null;try{u=JSON.parse(n(s(l,"meta.json"),"utf-8"))}catch{u=null}if(g.ok)console.log(chalk.bold.green(" ✓ submission.csv has the right format")+chalk.gray(" (matches sample_submission.csv)")),console.log(chalk.gray(" ")+chalk.white(a)),console.log(),P(u),c(l);else{console.log(chalk.bold.red(" ✗ submission.csv would be rejected:"));for(const o of g.problems)console.log(chalk.yellow(` · ${o}`));console.log(),console.log(chalk.gray(" Fix the submission cell in the notebook and re-run it."))}console.log()}export async function runKaggleSubmit(e){console.log();const t=C(e,"submit");if(!t)return;const l=S(t),i=s(l,"submission.csv"),c=s(l,"sample_submission.csv");let g=null;try{g=JSON.parse(n(s(l,"meta.json"),"utf-8"))}catch{g=null}if("local-eval"===g?.judge)return console.log(chalk.yellow(" This task is scored inside the notebook — nothing to upload.")),P(g),void console.log();if(!g||!o(c))return console.log(chalk.yellow(` No data for "${t}" here — run `)+chalk.cyan(`kaggle ${t}`)+chalk.yellow(" first.")),void console.log();if("icoa-holdout"!==g.judge)return console.log(chalk.yellow(" This competition is judged on kaggle.com — nothing to submit here.")),console.log(),P(g),void console.log();if(!o(i))return console.log(chalk.yellow(" No submission.csv yet — open the notebook and run all cells:")),console.log(chalk.gray(" ")+chalk.cyan(`icoa ipynb ${s(l,"starter.ipynb")}`)),void console.log();const d=n(i,"utf-8"),y=b(d,n(c,"utf-8"));if(!y.ok){r(`kaggle: submit ${t} → local-reject: ${y.problems[0]??"format"}`),console.log(chalk.bold.red(" ✗ submission.csv would be rejected:"));for(const o of y.problems)console.log(chalk.yellow(` · ${o}`));return console.log(),console.log(chalk.gray(" Fix the submission cell in the notebook and re-run it.")),void console.log()}let h=u()?.token??"";if(!h){const o=a();try{h=(await o.ask(chalk.cyan(" Your learn token: "))??"").trim()}finally{o.close()}if(!h)return console.log(chalk.gray(" A learn token identifies you on the board — ask your coach for one.")),void console.log()}console.log(chalk.gray(" Scoring on the server…"));const p=await async function(o,e){try{const n=await fetch(k()+o,{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify(e),signal:AbortSignal.timeout(6e4)});return await n.json()}catch{return null}}(`/api/icoa/kaggle/${t}/submit`,{token:h,submission_csv:d}),f=m(p);if(r(`kaggle: submit ${t} → ${f.ok?`${f.metric}=${f.score}${f.deduped?" (deduped)":""} rank=${f.rank??"-"}`:f.reason??"error"}`),console.log(),f.ok){const o=`${f.metric}: ${Number(f.score).toFixed(4).replace(/\.?0+$/,"")}`;f.deduped?(console.log(chalk.bold.white(` ✓ already scored — ${o}`)),console.log(chalk.gray(" These exact predictions were scored before. Improve the MODEL cell and re-run."))):(console.log(chalk.bold.green(` ✓ scored — ${o}`)),"number"==typeof f.rank&&"number"==typeof f.fieldSize&&console.log(chalk.bold.white(` 🏁 board rank #${f.rank}`)+chalk.gray(` of ${f.fieldSize}`))),f.boardEvent&&console.log(chalk.gray(" standings: ")+chalk.cyan(`board ${f.boardEvent} ${t}`))}else switch(f.reason){case"bad_token":console.log(chalk.bold.red(" ✗ that learn token was not accepted")+chalk.gray(" (invalid or expired)")),console.log(chalk.gray(" Check the token with your coach, then try again."));break;case"format":console.log(chalk.bold.red(" ✗ the server rejected submission.csv:"));for(const o of f.problems??[])console.log(chalk.yellow(` · ${o}`));break;case"event_closed":case"outside_window":console.log(chalk.bold.yellow(" ⏱ the submission window for this competition is closed."));break;case"cap_reached":console.log(chalk.bold.yellow(" ⏱ you have used all your submissions for this competition."));break;case"kaggle_judged":console.log(chalk.yellow(" This competition is judged on kaggle.com — nothing to submit here."));break;default:console.log(chalk.yellow(" The scoring server is not reachable right now — try again in a minute."))}console.log()}export function registerKaggleCommand(o){o.command("kaggle").argument("[action]",'competition id, or "check" / "submit"').argument("[comp]",'competition id (with "check" / "submit")').description("Kaggle-style ML practice — dataset + starter notebook, check & submit").action(async(o,e)=>{"check"===o?await runKaggleCheck(e):"submit"===o?await runKaggleSubmit(e):"guide"===o?await runKaggleGuide(e):await runKaggle(o)}),o.command("guide").argument("[comp]","competition id").description("Show the competition walkthrough (3 steps + AI cockpit)").action(async o=>{await runKaggleGuide(o)})}
@@ -1 +1 @@
1
- import{existsSync as e,mkdirSync as o,readFileSync as n,writeFileSync as t}from"node:fs";import{createInterface as l}from"node:readline";import{dirname as s,join as a}from"node:path";import{fileURLToPath as r}from"node:url";import chalk from"chalk";import{getConfig as c}from"../lib/config.js";import{getMainRl as i}from"../lib/main-rl.js";import{logCommand as g}from"../lib/logger.js";let y=!1;export function isSprintActive(){return y}const d=s(r(import.meta.url)),p=a(process.env.HOME||".",".icoa"),u=a(p,"sprint-state.json"),h={"T-torch":"裸 torch:手写 attention / causal mask / perplexity","T-umap":"降维当特征提取器,不是画图工具","T-lora":"peft LoRA 参数高效微调","T-librosa":"音频特征流水线:mel / MFCC → 定长向量"},m=["",chalk.bold.cyan(" ASTANA 2027"),chalk.gray(" — 给还没出发的你"),"",chalk.white(" 草原的风从额尔齐斯河吹到阿斯塔纳的时候,会带着一点雪的味道。"),chalk.white(" 你还没去过那里。但那里已经有一个座位,写着你的名字。"),"",chalk.white(" 你现在坐在屏幕前,离比赛还有几天。"),chalk.white(" 你可能会想:几天能改变什么?"),"",chalk.white(" 足够让一个人从「看着题发呆」变成「看到题就知道该拆哪一层」。"),chalk.white(" 足够让手指记住 import torch 之后该敲什么。"),chalk.white(" 足够让你在比赛那天早上醒来时,不再害怕。"),"",chalk.bold.yellow(" M")+chalk.white(" —— 你总是第一个说「我先试试」的那个。别停。"),chalk.bold.yellow(" V")+chalk.white(" —— 你总是问「为什么是这样」的那个。继续问。"),chalk.bold.yellow(" A")+chalk.white(" —— 你总是在别人放弃时还在改最后一版的那个。改下去。"),"",chalk.white(" 你们三个人,一个人是一条腿走路,三个人是奔跑。"),"",chalk.white(" 你们要面对的不是一场考试,是一次证明:"),chalk.bold.white(" 中国的高中生,可以在 AI 的赛场上,和世界站在同一排。"),"",chalk.white(" 而 2027 年的阿斯塔纳,是我们下一个约定。"),"",chalk.gray(" 现在,把这行字关掉,去做第 1 题。"),chalk.gray(" — 熊猫教练"),""];function f(o){const n=[a(d,"..","data",o),a(d,"..","..","src","data",o)];for(const o of n)if(e(o))return o;return n[0]}function w(e){try{o(p,{recursive:!0}),t(u,`${JSON.stringify(e,null,1)}\n`)}catch{}}function b(e,o){return(c().language||"en").toLowerCase().startsWith("zh")?e:o}function $(e){return"★".repeat(Math.max(1,Math.min(5,e||3)))}const k=a(p,"sprint-memos.json");function A(e){try{o(p,{recursive:!0}),t(k,`${JSON.stringify(e,null,1)}\n`)}catch{}}function S(e,o){const n=new Set(o.done),t=new Set(o.opened);console.log(),console.log(chalk.bold.cyan(b(" ⚔ IOAI 2026 · 四工具冲刺"," ⚔ IOAI 2026 · four-tool sprint"))+chalk.gray(` ${b("已攻克","cleared")} ${n.size} / ${e.length}`));const l=new Map;for(const o of e)l.has(o.bullseye)||l.set(o.bullseye,[]),l.get(o.bullseye)?.push(o);for(const[e,o]of l){console.log(),console.log(chalk.bold.white(` ${e}`)+chalk.gray(` — ${h[e]||""}`));for(const e of o){const o=n.has(e.seq)?chalk.green("✓"):t.has(e.seq)?chalk.yellow("◐"):chalk.gray("⬜");console.log(` ${o} ${chalk.bold.white(String(e.seq).padStart(2))} `+chalk.white(e.title.slice(0,34).padEnd(34))+chalk.gray($(e.difficulty).padEnd(5))+chalk.gray(e.needs_gpu?" ⚡":" ")+chalk.gray(` ${e.data_mb}M`)+("teleload"===e.status?chalk.gray(b(" · teleload"," · teleload")):"")+(e.judged?chalk.green(b(" · 可出分"," · scored")):""))}}console.log(),console.log(chalk.gray(" ")+chalk.cyan("open <n>")+chalk.gray(b(" 看题 · "," view · "))+chalk.cyan("done <n>")+chalk.gray(b(" 标记攻克 · "," mark cleared · "))+chalk.cyan("ai4ioai")+chalk.gray(b(" 开 AI 分屏 · "," AI in a split · "))+chalk.cyan("memo")+chalk.gray(b(" 记问题 · "," report a problem · "))+chalk.cyan("back")+chalk.gray(b(" 退出"," leave"))),console.log(chalk.gray(b(" ⬜ 没看过 ◐ 看过没做完 ✓ 攻克"," ⬜ unseen ◐ opened ✓ cleared"))),console.log(chalk.gray(b(" ⚡ 要 GPU(notebook 里 gpu key → gpu on) · teleload 数据是大包,用 teleload 拉 · 可出分 交上去有真分数"," ⚡ needs GPU (inside the notebook: gpu key → gpu on) · teleload big pack, pull with teleload · scored real score on submit"))),console.log()}function q(e,o){const n=[];let t="",l=0;for(const s of e){const e=/[ -鿿＀-￯]/.test(s)?2:1;l+e>o&&(n.push(t),t="",l=0),t+=s,l+=e}return t&&n.push(t),n}export async function runSprint(){g("sprint");const e=function(){try{const e=JSON.parse(n(f("sprint-tasks.json"),"utf8")),o=Array.isArray(e?.tasks)?e.tasks:[];try{const e=JSON.parse(n(f("sprint-cards.json"),"utf8")),t=new Map((e.cards||[]).map(e=>[e.seq,e]));for(const e of o){const o=t.get(e.seq);o&&Object.assign(e,{star:o.star,trap:o.trap,action:o.action,hint:o.hint,meta:o.meta})}}catch{}return o.sort((e,o)=>e.seq-o.seq)}catch{return[]}}();if(0===e.length)return console.log(),console.log(chalk.yellow(" 冲刺题单还没装进这个版本。")),console.log(chalk.gray(" 升级后再试:")+chalk.cyan("npm install -g icoa-cli@latest")),void console.log();const o=function(){try{const e=JSON.parse(n(u,"utf8"));return{who:e.who||"",opened:e.opened||[],done:e.done||[]}}catch{return{who:"",opened:[],done:[]}}}();if(0===o.opened.length&&0===o.done.length)for(const e of m)console.log(e);o.who||(o.who=""),S(e,o);const t=i(),s=null!==t,a=s?t:l({input:process.stdin,output:process.stdout,terminal:!0}),r=s?a.listeners("line").slice():[];a.removeAllListeners("line");const c=a.prompt.bind(a);y=!0,a.setPrompt(chalk.bold.cyan("icoa ioai2026> ")),await new Promise(t=>{a.on("line",async l=>{const i=l.trim(),[d,p]=[i.split(/\s+/)[0]?.toLowerCase()||"",i.split(/\s+/)[1]||""];if(["back","quit","exit","menu"].includes(d))return w(o),console.log(chalk.gray(" 进度已保存。")),(()=>{if(y=!1,a.removeAllListeners("line"),s){for(const e of r)a.on("line",e);a.setPrompt(chalk.green("icoa> ")),a.prompt()}else a.close()})(),void t();if(""===d||["challenges","list","ls"].includes(d))S(e,o);else if(["open","o"].includes(d)||/^\d+$/.test(d)){const n=Number.parseInt(/^\d+$/.test(d)?d:p,10),t=e.find(e=>e.seq===n);t?(o.opened.includes(n)||o.opened.push(n),w(o),function(e){console.log(),console.log(chalk.cyan(" ╭─ ")+chalk.bold.white(`${e.seq} · ${e.title}`)+chalk.gray(` · ${e.bullseye}`)+chalk.cyan(" ─────")),console.log(chalk.cyan(" │"));const o=[e.star,e.trap,e.action,e.hint?` ${e.hint}`:""].filter(Boolean);0===o.length&&e.topic_cn&&o.push(`▸ ${e.topic_cn}`);for(const e of o){for(const o of q(e,58))console.log(chalk.cyan(" │ ")+chalk.white(o));console.log(chalk.cyan(" │"))}console.log(chalk.cyan(" │ ")+chalk.gray(e.meta||`⏱ 难度 ${$(e.difficulty)}`)+chalk.gray(e.needs_gpu?" ⚡ 需要 GPU":"")),console.log(chalk.cyan(" ╰──────────────────────────────────────────────────────")),console.log(chalk.gray(" ")+chalk.cyan("ai4ioai")+chalk.gray(b(" 开 AI 分屏 · "," AI in a split · "))+chalk.cyan(`done ${e.seq}`)+chalk.gray(b(" 标记攻克 · "," mark cleared · "))+chalk.cyan(`memo ${e.seq}`)+chalk.gray(b(" 记问题 · "," report · "))+chalk.cyan("back")+chalk.gray(b(" 回列表"," back to list"))),console.log()}(t)):console.log(chalk.yellow(` 没有第 ${p||d} 题。`)+chalk.gray(` 题号 1-${e.length}。`))}else if("done"===d){const n=Number.parseInt(p,10);e.some(e=>e.seq===n)?(o.done.includes(n)||o.done.push(n),w(o),console.log(chalk.green(` ✓ 第 ${n} 题标记为攻克`)+chalk.gray(` (${o.done.length}/${e.length})`))):console.log(chalk.yellow(` 题号 1-${e.length}。`))}else"memo"===d||"note"===d?await async function(e,o){const t=function(){try{const e=JSON.parse(n(k,"utf8"));return Array.isArray(e)?e:[]}catch{return[]}}(),l=e.trim();if(""===l||"list"===l||"ls"===l){if(console.log(),0===t.length)console.log(chalk.gray(b(" 还没有记录。"," Nothing noted yet."))),console.log(chalk.gray(b(" 用法:"," Usage: "))+chalk.cyan(b("memo 17 卡片说的命令在这里敲不了","memo 17 the command on the card does not work here"))),console.log(chalk.gray(b(" "," "))+chalk.cyan(b("memo teleload 是什么意思","memo what does teleload mean"))+chalk.gray(b(" (不带题号 = 通用反馈)"," (no number = general feedback)")));else{console.log(chalk.bold.white(b(` 📝 已记 ${t.length} 条`,` 📝 ${t.length} noted`)));for(const e of t.slice(-12)){const o=e.seq?chalk.cyan(`#${e.seq}`):chalk.gray("—");console.log(` ${o} ${chalk.white(e.text.slice(0,60))}`+chalk.gray(e.synced?b(" ·已上报"," ·sent"):b(" ·仅本地"," ·local only")))}console.log(chalk.gray(` ${k}`))}return void console.log()}const s=l.split(/\s+/),a=/^\d+$/.test(s[0])&&o.some(e=>e.seq===Number(s[0])),r=a?Number(s[0]):null,c=(a?s.slice(1):s).join(" ").trim();if(""===c)return void console.log(chalk.yellow(b(" 写点什么吧:"," Say what happened: "))+chalk.cyan(`memo ${s[0]} …`));const i={ts:(new Date).toISOString(),seq:r,text:c,synced:!1};t.push(i),A(t),g(`sprint: memo${r?` ${r}`:""} — ${c}`);let y=!1;try{const{loadLearnState:e}=await import("../lib/learn-state.js"),o=e()?.token??"";if(o){const{syncCardFeedback:e}=await import("../lib/learn-curricula.js");y=await e(o,{curriculum_id:"pandahelpme31",card_number:r??0,feedback_text:c})}}catch{}y&&(i.synced=!0,A(t)),console.log(),console.log(chalk.green(b(" ✓ 记下了"," ✓ noted"))+(r?chalk.gray(b(` (第 ${r} 题)`,` (task ${r})`)):"")+chalk.gray(y?b(" ·已上报"," ·sent"):b(" ·存在本机,教练可以来取"," ·saved on this machine"))),console.log(chalk.gray(b(" 继续做题就好。"," Carry on."))),console.log()}(i.split(/\s+/).slice(1).join(" "),e):["ai4ioai","/ai4ioai","ai"].includes(d)?(console.log(),console.log(chalk.bold.white(b(" 左右分屏,左边看题右边问 AI:"," Split the screen — tasks left, AI right:"))),console.log(chalk.gray(" 1. ")+chalk.bold.cyan("Ctrl-b %")+chalk.gray(b(" 左右分屏(上下分屏是 "," split left/right (up/down is "))+chalk.cyan('Ctrl-b "')+chalk.gray(b(")",")"))),console.log(chalk.gray(" 2. ")+chalk.gray(b("右边那格输 ","in the right pane type "))+chalk.bold.cyan("icoa")+chalk.gray(b(" ,再输 "," , then "))+chalk.bold.cyan("ai4ioai")),console.log(chalk.gray(b(" 3. 两格之间切换:"," 3. move between panes: "))+chalk.cyan("Ctrl-b ←")+chalk.gray(" / ")+chalk.cyan("Ctrl-b →")),console.log(),console.log(chalk.gray(b(" 它是弱模型 —— 单轮、2000 字符以内。把问题问准,就是这次要练的本事。"," A deliberately weak model — single-turn, 2000 chars. Asking precisely is the skill."))),console.log(chalk.gray(b(" 在 notebook 里卡住时,那边可以直接敲 "," Stuck inside a notebook? there you can type "))+chalk.cyan("ai")+chalk.gray(b(" —— 它会把那一格的代码和报错一起带上。"," — it carries that cell and its traceback."))),console.log()):["help","?","guide"].includes(d)?S(e,o):console.log(chalk.gray(" ")+chalk.cyan("challenges")+chalk.gray(" 列表 · ")+chalk.cyan("open <n>")+chalk.gray(" 看题 · ")+chalk.cyan("done <n>")+chalk.gray(" 标记 · ")+chalk.cyan("memo")+chalk.gray(" 记问题 · ")+chalk.cyan("back")+chalk.gray(b(" 退出"," leave")));a.prompt=c,a.prompt()}),s||a.once("close",()=>t()),a.prompt=c,a.prompt()})}export function registerSprintCommand(e){e.command("pandahelpme31",{hidden:!0}).action(async()=>{await runSprint()})}
1
+ import{existsSync as o,mkdirSync as e,readFileSync as n,writeFileSync as t}from"node:fs";import{createInterface as l}from"node:readline";import{dirname as a,join as s}from"node:path";import{fileURLToPath as r}from"node:url";import chalk from"chalk";import{getConfig as c}from"../lib/config.js";import{getMainRl as i,setMainRl as g}from"../lib/main-rl.js";import{logCommand as y}from"../lib/logger.js";import{baselineChip as d,computeChip as p,loadSprintTasks as u,mediaHelpLines as h,taskSteps as m}from"../lib/sprint-meta.js";let f=!1;export function isSprintActive(){return f}const b=a(r(import.meta.url)),w=s(process.env.HOME||".",".icoa"),k=s(w,"sprint-state.json"),$={"T-torch":"裸 torch:手写 attention / causal mask / perplexity","T-umap":"降维当特征提取器,不是画图工具","T-lora":"peft LoRA 参数高效微调","T-librosa":"音频特征流水线:mel / MFCC → 定长向量"},S=["",chalk.bold.cyan(" ASTANA 2027"),chalk.gray(" — 给还没出发的你"),"",chalk.white(" 草原的风从额尔齐斯河吹到阿斯塔纳的时候,会带着一点雪的味道。"),chalk.white(" 你还没去过那里。但那里已经有一个座位,写着你的名字。"),"",chalk.white(" 你现在坐在屏幕前,离比赛还有几天。"),chalk.white(" 你可能会想:几天能改变什么?"),"",chalk.white(" 足够让一个人从「看着题发呆」变成「看到题就知道该拆哪一层」。"),chalk.white(" 足够让手指记住 import torch 之后该敲什么。"),chalk.white(" 足够让你在比赛那天早上醒来时,不再害怕。"),"",chalk.bold.yellow(" M")+chalk.white(" —— 你总是第一个说「我先试试」的那个。别停。"),chalk.bold.yellow(" V")+chalk.white(" —— 你总是问「为什么是这样」的那个。继续问。"),chalk.bold.yellow(" A")+chalk.white(" —— 你总是在别人放弃时还在改最后一版的那个。改下去。"),"",chalk.white(" 你们三个人,一个人是一条腿走路,三个人是奔跑。"),"",chalk.white(" 你们要面对的不是一场考试,是一次证明:"),chalk.bold.white(" 中国的高中生,可以在 AI 的赛场上,和世界站在同一排。"),"",chalk.white(" 而 2027 年的阿斯塔纳,是我们下一个约定。"),"",chalk.gray(" 现在,把这行字关掉,去做第 1 题。"),chalk.gray(" — 熊猫教练"),""];function A(o){try{e(w,{recursive:!0}),t(k,`${JSON.stringify(o,null,1)}\n`)}catch{}}function q(){return(c().language||"en").toLowerCase().startsWith("zh")}function v(o,e){return q()?o:e}function j(o){return"★".repeat(Math.max(1,Math.min(5,o||3)))}const I=s(w,"sprint-memos.json");function C(o){try{e(w,{recursive:!0}),t(I,`${JSON.stringify(o,null,1)}\n`)}catch{}}function N(o,e){const n=new Set(e.done),t=new Set(e.opened);console.log(),console.log(chalk.bold.cyan(v(" ⚔ IOAI 2026 · 四工具冲刺"," ⚔ IOAI 2026 · four-tool sprint"))+chalk.gray(` ${v("已攻克","cleared")} ${n.size} / ${o.length}`));const l=new Map;for(const e of o)l.has(e.bullseye)||l.set(e.bullseye,[]),l.get(e.bullseye)?.push(e);for(const[o,e]of l){console.log(),console.log(chalk.bold.white(` ${o}`)+chalk.gray(` — ${$[o]||""}`));for(const o of e){const e=n.has(o.seq)?chalk.green("✓"):t.has(o.seq)?chalk.yellow("◐"):chalk.gray("⬜");console.log(` ${e} ${chalk.bold.white(String(o.seq).padStart(2))} `+chalk.white(o.title.slice(0,34).padEnd(34))+chalk.gray(j(o.difficulty).padEnd(5))+chalk.gray(o.needs_gpu?" ⚡":" ")+chalk.gray(` ${o.data_mb}M`)+("teleload"===o.status?chalk.gray(v(" · teleload"," · teleload")):"")+(o.judged?chalk.green(v(" · 可出分"," · scored")):""))}}console.log(),console.log(chalk.gray(" ")+chalk.cyan("open <n>")+chalk.gray(v(" 看题 · "," view · "))+chalk.cyan("done <n>")+chalk.gray(v(" 标记攻克 · "," mark cleared · "))+chalk.cyan("ai4ioai")+chalk.gray(v(" 开 AI 分屏 · "," AI in a split · "))+chalk.cyan("memo")+chalk.gray(v(" 记问题 · "," report a problem · "))+chalk.cyan("back")+chalk.gray(v(" 退出"," leave"))),console.log(chalk.gray(v(" ⬜ 没看过 ◐ 看过没做完 ✓ 攻克"," ⬜ unseen ◐ opened ✓ cleared"))),console.log(chalk.gray(v(" ⚡ 要 GPU(notebook 里 gpu key → gpu on) · teleload 数据是大包,用 teleload 拉 · 可出分 交上去有真分数"," ⚡ needs GPU (inside the notebook: gpu key → gpu on) · teleload big pack, pull with teleload · scored real score on submit"))),console.log()}function O(o,e){const n=[];let t="",l=0;for(const a of o){const o=/[ -鿿＀-￯]/.test(a)?2:1;l+o>e&&(n.push(t),t="",l=0),t+=a,l+=o}return t&&n.push(t),n}export async function runSprint(){y("sprint");const e=function(){try{const e=u();try{const t=JSON.parse(n(function(e){const n=[s(b,"..","data",e),s(b,"..","..","src","data",e)];for(const e of n)if(o(e))return e;return n[0]}("sprint-cards.json"),"utf8")),l=new Map((t.cards||[]).map(o=>[o.seq,o]));for(const o of e){const e=l.get(o.seq);e&&Object.assign(o,{star:e.star,trap:e.trap,action:e.action,hint:e.hint,meta:e.meta})}}catch{}return e.sort((o,e)=>o.seq-e.seq)}catch{return[]}}();if(0===e.length)return console.log(),console.log(chalk.yellow(" 冲刺题单还没装进这个版本。")),console.log(chalk.gray(" 升级后再试:")+chalk.cyan("npm install -g icoa-cli@latest")),void console.log();const t=function(){try{const o=JSON.parse(n(k,"utf8"));return{who:o.who||"",opened:o.opened||[],done:o.done||[]}}catch{return{who:"",opened:[],done:[]}}}();if(0===t.opened.length&&0===t.done.length)for(const o of S)console.log(o);t.who||(t.who=""),N(e,t);const a=i(),r=null!==a,c=r?a:l({input:process.stdin,output:process.stdout,terminal:!0});r||g(c);const w=r?c.listeners("line").slice():[];c.removeAllListeners("line");const $=c.prompt.bind(c);f=!0;const T=chalk.bold.cyan("icoa ioai2026> ");c.setPrompt(T);let x=null;await new Promise(o=>{c.on("line",async l=>{const a=l.trim().replace(/^icoa\s+/i,""),[s,i]=[a.split(/\s+/)[0]?.toLowerCase()||"",a.split(/\s+/)[1]||""];if(["back","quit","exit","menu"].includes(s))return A(t),console.log(chalk.gray(" 进度已保存。")),(()=>{if(f=!1,c.removeAllListeners("line"),r){for(const o of w)c.on("line",o);c.setPrompt(chalk.green("icoa> ")),c.prompt()}else g(null),c.close()})(),void o();if(""===s||["challenges","list","ls"].includes(s))N(e,t);else if(["open","o"].includes(s)||/^\d+$/.test(s)){const o=Number.parseInt(/^\d+$/.test(s)?s:i,10),n=e.find(e=>e.seq===o);n?(t.opened.includes(o)||t.opened.push(o),A(t),x=o,function(o){console.log(),console.log(chalk.cyan(" ╭─ ")+chalk.bold.white(`${o.seq} · ${o.title}`)+chalk.gray(` · ${o.bullseye}`)+chalk.cyan(" ─────")),console.log(chalk.cyan(" │"));const e=m(o).length>1,n=[o.star,o.trap,e?"":o.action,o.hint?` ${o.hint}`:""].filter(Boolean);0===n.length&&o.topic_cn&&n.push(`▸ ${o.topic_cn}`);for(const o of n){for(const e of O(o,58))console.log(chalk.cyan(" │ ")+chalk.white(e));console.log(chalk.cyan(" │"))}const t=q();console.log(chalk.cyan(" │ ")+chalk.gray(p(o,t)));const l=d(o,t);if(l)for(const o of O(l,58))console.log(chalk.cyan(" │ ")+chalk.gray(o));console.log(chalk.cyan(" │ ")+chalk.gray(o.meta||`⏱ 难度 ${j(o.difficulty)}`)+chalk.gray(o.needs_gpu?" ⚡ 需要 GPU":"")),console.log(chalk.cyan(" ╰──────────────────────────────────────────────────────"));for(const e of h(o,t))for(const o of O(e,60))console.log(chalk.yellow(" ")+chalk.yellow(o));const a=m(o),s=function(o){const e=m(o);if(e.length>0)return e[0];const n=/(?:kaggle|teleload)\s+[a-z0-9][a-z0-9-]*/i.exec(o.action||"");return n?n[0]:null}(o);a.length>1?(console.log(chalk.bold.white(v(" ▸ 就在这里敲,两步:"," ▸ Type these here, in order:"))),a.forEach((o,e)=>{console.log(chalk.gray(` ${e+1}. `)+chalk.bold.cyan(o)+chalk.gray(0===e?v(" ← 先把数据拉下来"," ← fetch the data first"):v(" ← 题面 + notebook"," ← statement + notebook")))})):s&&console.log(chalk.bold.white(v(" ▸ 就在这里敲: "," ▸ Type it right here: "))+chalk.bold.cyan(s)+chalk.gray(v(" ← 数据 + notebook 落到本机"," ← pulls the data + notebook"))),console.log(chalk.gray(" ")+chalk.cyan("ai4ioai")+chalk.gray(v(" 开 AI 分屏 · "," AI in a split · "))+chalk.cyan(`done ${o.seq}`)+chalk.gray(v(" 标记攻克 · "," mark cleared · "))+chalk.cyan("memo")+chalk.gray(v(` 记问题(自动记在第 ${o.seq} 题) · `,` report (auto-filed under ${o.seq}) · `))+chalk.cyan("back")+chalk.gray(v(" 回列表"," back to list"))),console.log()}(n)):console.log(chalk.yellow(` 没有第 ${i||s} 题。`)+chalk.gray(` 题号 1-${e.length}。`))}else if("done"===s){const o=Number.parseInt(i,10);e.some(e=>e.seq===o)?(t.done.includes(o)||t.done.push(o),A(t),console.log(chalk.green(` ✓ 第 ${o} 题标记为攻克`)+chalk.gray(` (${t.done.length}/${e.length})`))):console.log(chalk.yellow(` 题号 1-${e.length}。`))}else["kaggle","teleload","ipynb"].includes(s)?await async function(o,e){const n=e.split(/\s+/).filter(Boolean);try{if("teleload"===o){const{runTeleload:o}=await import("./teleload.js");return void await o(n[0])}if("ipynb"===o){const{runIpynb:o}=await import("./ipynb.js");return void await o(n[0])}const e=await import("./kaggle.js"),t=(n[0]||"").toLowerCase();"submit"===t?await e.runKaggleSubmit(n[1]):"check"===t?await e.runKaggleCheck(n[1]):"guide"===t?await e.runKaggleGuide(n[1]):await e.runKaggle(n[0])}catch(o){console.log(),console.log(chalk.yellow(v(" 这条命令没跑成:"," That command failed: "))+chalk.gray(String(o))),console.log(chalk.gray(v(" 记一条给教练:"," Tell the coach: "))+chalk.cyan(v("memo …","memo …"))),console.log()}}(s,a.split(/\s+/).slice(1).join(" ")):"memo"===s||"note"===s?await async function(o,e,t,l){const a=function(){try{const o=JSON.parse(n(I,"utf8"));return Array.isArray(o)?o:[]}catch{return[]}}(),s=o.trim();if(["list","ls","all"].includes(s.toLowerCase())){if(console.log(),0===a.length)console.log(chalk.gray(v(" 还没有记录。"," Nothing noted yet.")));else{console.log(chalk.bold.white(v(` 📝 已记 ${a.length} 条`,` 📝 ${a.length} noted`)));for(const o of a.slice(-12)){const e=o.seq?chalk.cyan(`#${o.seq}`):chalk.gray("—");console.log(` ${e} ${chalk.white(o.text.slice(0,60))}`+chalk.gray(o.synced?v(" ·已上报"," ·sent"):v(" ·仅本地"," ·local only")))}console.log(chalk.gray(` ${I}`))}return console.log(chalk.gray(v(" 再记一条:"," Note another: "))+chalk.cyan("memo")+chalk.gray(v(" (光敲这一个词就给你写字的地方)"," (just the word — it gives you a place to type)"))),void console.log()}const r=s?s.split(/\s+/):[],c=r.length>0&&/^\d+$/.test(r[0])&&e.some(o=>o.seq===Number(r[0])),i=c?Number(r[0]):t;let g=(c?r.slice(1):r).join(" ").trim();if(""===g){const o=i?chalk.gray(v(` —— 记在第 ${i} 题下`,` — filed under task ${i}`)):chalk.gray(v(" —— 通用反馈"," — general feedback"));if(console.log(),console.log(chalk.bold.white(v(" 📝 撞到什么就写什么"," 📝 Say what you hit"))+o),console.log(chalk.gray(v(" 一行写完,回车就存下(不用等回复);直接回车 = 不记。"," One line, Enter files it (no reply comes back). Empty Enter cancels."))),g=await function(o,e){return new Promise(n=>{o.question(e,o=>n(o.trim()))})}(l,chalk.cyan(" memo > ")),""===g)return console.log(chalk.gray(v(" 没记。"," Nothing noted."))),void console.log()}const d={ts:(new Date).toISOString(),seq:i,text:g,synced:!1};a.push(d),C(a),y(`sprint: memo${i?` ${i}`:""} — ${g}`);let p=!1;try{const{loadLearnState:o}=await import("../lib/learn-state.js"),e=o()?.token??"";if(e){const{syncCardFeedback:o}=await import("../lib/learn-curricula.js");p=await o(e,{curriculum_id:"pandahelpme31",card_number:i??0,feedback_text:g})}}catch{}p&&(d.synced=!0,C(a)),console.log(),console.log(chalk.green(v(" ✓ 记下了"," ✓ noted"))+(i?chalk.gray(v(` (第 ${i} 题)`,` (task ${i})`)):"")+chalk.gray(p?v(" ·已上报"," ·sent"):v(" ·存在本机,教练可以来取"," ·saved on this machine"))),console.log(chalk.gray(v(" 继续做题就好。看全部:"," Carry on. See them all: "))+chalk.cyan("memo list")),console.log()}(a.split(/\s+/).slice(1).join(" "),e,x,c):["ai4ioai","/ai4ioai","ai"].includes(s)?(console.log(),console.log(chalk.bold.white(v(" 左右分屏,左边看题右边问 AI:"," Split the screen — tasks left, AI right:"))),console.log(chalk.gray(" 1. ")+chalk.bold.cyan("Ctrl-b %")+chalk.gray(v(" 左右分屏(上下分屏是 "," split left/right (up/down is "))+chalk.cyan('Ctrl-b "')+chalk.gray(v(")",")"))),console.log(chalk.gray(" 2. ")+chalk.gray(v("右边那格输 ","in the right pane type "))+chalk.bold.cyan("icoa")+chalk.gray(v(" ,再输 "," , then "))+chalk.bold.cyan("ai4ioai")),console.log(chalk.gray(v(" 3. 两格之间切换:"," 3. move between panes: "))+chalk.cyan("Ctrl-b ←")+chalk.gray(" / ")+chalk.cyan("Ctrl-b →")),console.log(),console.log(chalk.gray(v(" 它是弱模型 —— 单轮、2000 字符以内。把问题问准,就是这次要练的本事。"," A deliberately weak model — single-turn, 2000 chars. Asking precisely is the skill."))),console.log(chalk.gray(v(" 在 notebook 里卡住时,那边可以直接敲 "," Stuck inside a notebook? there you can type "))+chalk.cyan("ai")+chalk.gray(v(" —— 它会把那一格的代码和报错一起带上。"," — it carries that cell and its traceback."))),console.log()):["help","?","guide"].includes(s)?N(e,t):(console.log(chalk.gray(" ")+chalk.cyan("open <n>")+chalk.gray(v(" 看题 · "," view · "))+chalk.cyan("kaggle <题目id>")+chalk.gray(v(" 领数据 · "," get the data · "))+chalk.cyan("ipynb <路径>")+chalk.gray(v(" 开 notebook · "," open the notebook · "))+chalk.cyan("done <n>")+chalk.gray(v(" 标记 · "," mark · "))+chalk.cyan("memo")+chalk.gray(v(" 记问题 · "," report · "))+chalk.cyan("back")+chalk.gray(v(" 退出"," leave"))),console.log(chalk.gray(v(" 题目 id 在卡片的 ▸ 那一行,例如 "," The task id is on the card’s ▸ line, e.g. "))+chalk.cyan("open 17")+chalk.gray(" → ")+chalk.cyan("kaggle s17-bazarul-lui-riki")));c.prompt=$,c.setPrompt(T),c.prompt()}),r||c.once("close",()=>o()),c.prompt=$,c.prompt()})}export function registerSprintCommand(o){o.command("pandahelpme31",{hidden:!0}).action(async()=>{await runSprint()})}
@@ -1 +1 @@
1
- import{spawn as o}from"node:child_process";import{createHash as e}from"node:crypto";import{createReadStream as t,createWriteStream as n,existsSync as r,mkdirSync as a,renameSync as s,rmSync as l,statSync as i}from"node:fs";import{Readable as c}from"node:stream";import{pipeline as d}from"node:stream/promises";import{join as g}from"node:path";import chalk from"chalk";function u(){if(process.env.ICOA_AIDATA_DIR)return process.env.ICOA_AIDATA_DIR;const o="/data/aiproblems";try{if(r(o)&&i(o).isDirectory())return o}catch{}return g(process.cwd(),"icoa-aidata")}function f(o){return g(u(),o.platform,o.id)}function h(o){return o>=1024?`${(o/1024).toFixed(1)}G`:`${o}M`}function y(e,t){return new Promise(n=>{const r=o(e,t,{stdio:"ignore",shell:!1});r.on("error",()=>n(!1)),r.on("close",o=>n(0===o))})}async function p(o){const i=f(o);if(r(i))return console.log(),console.log(chalk.green(` ✓ ${o.id} is already here`)+chalk.gray(` (${i})`)),console.log(chalk.gray(" Nothing to do. ")+chalk.cyan("teleload")+chalk.gray(" lists the rest.")),void console.log();const p=g(u(),o.platform);a(p,{recursive:!0});const m=g(p,`.${o.id}.tar.zst.part`);if(console.log(),console.log(chalk.bold.white(` ⬇ ${o.id}`)+chalk.gray(` · ${h(o.tar_mb)} packed → ${h(o.unpacked_mb)} on disk · ${o.n_files} files`)),console.log(chalk.gray(" Straight from the Singapore data node — nothing goes through your laptop.")),console.log(),!await async function(o,e){const t=Date.now();let r=0,a=1048576*o.tar_mb,s=0;const l=Boolean(process.stdout.isTTY);let i=-1;const g=(o=!1)=>{const e=a>0?Math.min(100,Math.round(r/a*100)):0,n=(Date.now()-t)/1e3,s=n>0?r/1048576/n:0,c=r/1048576,d=a/1048576,g=n>=3&&r>=4194304&&s>0&&a>r?(a-r)/1048576/s:0;if(!l){const t=Math.floor(e/25);return void((t>i||o)&&(i=t,console.log(chalk.cyan(` ${String(e).padStart(3)}% · ${c.toFixed(0)}/${d.toFixed(0)} MB · ${s.toFixed(1)} MB/s`))))}const u=Math.round(e/5),f="█".repeat(u)+"░".repeat(20-u),h=o?"":` · ${function(o){if(!Number.isFinite(o)||o<=0)return"--";const e=Math.floor(o/60),t=Math.round(o%60);return e>0?`${e}m${String(t).padStart(2,"0")}s`:`${t}s`}(g)} left`,y=` ${f} ${String(e).padStart(3)}% · ${c.toFixed(0)}/${d.toFixed(0)} MB · ${s.toFixed(1)} MB/s${h}`;process.stdout.write(`\r${chalk.cyan(y)}${" ".repeat(12)}${o?"\n":""}`)};try{const t=await fetch(o.url,{signal:AbortSignal.timeout(36e5)});if(!t.ok||!t.body)return!1;const l=Number(t.headers.get("content-length"));Number.isFinite(l)&&l>0&&(a=l);const i=n(e),u=c.fromWeb(t.body);return u.on("data",o=>{r+=o.length;const e=Date.now();e-s>250&&(s=e,g())}),await d(u,i),g(!0),!0}catch{return process.stdout.write("\n"),!1}}(o,m))return l(m,{force:!0}),console.log(chalk.yellow(" ✗ Download failed.")+chalk.gray(" Nothing was changed — just run it again.")),void console.log();process.stdout.write(chalk.gray(" checking the file is intact… "));const w=await($=m,new Promise((o,n)=>{const r=e("sha256"),a=t($);a.on("data",o=>{r.update(o)}),a.on("end",()=>o(r.digest("hex"))),a.on("error",n)})).catch(()=>"");var $;if(o.sha256&&w!==o.sha256)return l(m,{force:!0}),console.log(chalk.yellow("✗")),console.log(chalk.yellow(" The file arrived damaged and was discarded.")+chalk.gray(" Run it again.")),void console.log();console.log(chalk.green("✓")),process.stdout.write(chalk.gray(" unpacking… "));const b=g(p,`.${o.id}.staging`);l(b,{recursive:!0,force:!0});const v=await async function(o,e){if(a(e,{recursive:!0}),await y("tar",["-xf",o,"-C",e]))return!0;if(await y("tar",["--zstd","-xf",o,"-C",e]))return!0;if(await y("tar",["-I","unzstd","-xf",o,"-C",e]))return!0;const t=`${o}.plain`;if(await y("zstd",["-d","-f","-o",t,o])){const o=await y("tar",["-xf",t,"-C",e]);return l(t,{force:!0}),o}return!1}(m,b);if(l(m,{force:!0}),!v)return l(b,{recursive:!0,force:!0}),console.log(chalk.yellow("✗")),console.log(chalk.yellow(" Could not unpack the archive.")+chalk.gray(" Run it again.")),void console.log();const k=g(b,o.id);try{s(r(k)?k:b,i)}catch{return console.log(chalk.yellow("✗")),console.log(chalk.yellow(" Could not move the data into place.")+chalk.gray(" Check disk space.")),void console.log()}l(b,{recursive:!0,force:!0}),console.log(chalk.green("✓")),console.log(),console.log(chalk.green(" 🎁 ready: ")+chalk.white(i)),console.log(chalk.gray(" Open it in a notebook — the path above is the dataset root.")),console.log(chalk.gray(" ")+chalk.cyan("teleload")+chalk.gray(" lists what else is available.")),console.log()}export async function runTeleload(o){const e=await async function(){try{const o=await fetch(process.env.ICOA_TELELOAD_MANIFEST||"https://icoa-datasets.sg-sin-1.linodeobjects.com/aidata/manifest.json",{signal:AbortSignal.timeout(3e4)});if(!o.ok)return null;const e=await o.json(),t=Array.isArray(e?.packs)?e.packs:null;return t?t.slice().sort((o,e)=>o.n-e.n):null}catch{return null}}();if(!e)return console.log(),console.log(chalk.yellow(" Could not reach the dataset node right now.")),console.log(chalk.gray(" Check your connection and try again — nothing was changed.")),void console.log();if(0===e.length)return console.log(),console.log(chalk.gray(" No on-demand datasets are published yet — everything ships inside this machine.")),void console.log();const t=(o??"").trim().replace(/^#/,"");if(""===t)return function(o){console.log(),console.log(chalk.bold.cyan(" ⬇ TELELOAD")+chalk.gray(" · big datasets, pulled straight from the data node")),console.log();for(const e of o){const o=r(f(e))?chalk.green("✓ here"):chalk.gray("⬇ not yet");console.log(` ${chalk.bold.white(String(e.n))}. ${chalk.white(e.id.padEnd(34))}`+chalk.gray(`${h(e.unpacked_mb).padStart(6)} `)+o)}console.log(),console.log(chalk.gray(" Pull one with ")+chalk.cyan("teleload <number>")+chalk.gray(" (e.g. ")+chalk.cyan("teleload 2")+chalk.gray(")")),console.log(chalk.gray(" Everything smaller than 0.6 G already ships inside this machine — no pull needed.")),console.log()}(e);const n=Number.parseInt(t,10);let a=Number.isFinite(n)?e.find(o=>o.n===n):void 0;if(!a){const o=t.toLowerCase();a=e.find(e=>e.id.toLowerCase()===o)??e.find(e=>e.id.toLowerCase().includes(o))}if(!a){console.log(),console.log(chalk.yellow(` No dataset called "${t}".`)),console.log(chalk.gray(" These are the ones you can pull:"));for(const o of e)console.log(chalk.gray(` ${o.n}. ${o.id}`));return console.log(chalk.gray(" Try ")+chalk.cyan(`teleload ${e[0].n}`)+chalk.gray(" — or just ")+chalk.cyan("teleload")+chalk.gray(" to see sizes.")),void console.log()}await p(a)}export function registerTeleloadCommand(o){o.command("teleload").argument("[pack]","pack number (or id) from `teleload`").description("Pull a big dataset from the data node onto this machine").action(async o=>{await runTeleload(o)})}
1
+ import{spawn as o}from"node:child_process";import{createHash as e}from"node:crypto";import{createReadStream as t,createWriteStream as n,existsSync as a,mkdirSync as r,renameSync as s,rmSync as l,statSync as i}from"node:fs";import{Readable as c}from"node:stream";import{pipeline as d}from"node:stream/promises";import{join as g}from"node:path";import chalk from"chalk";function u(){if(process.env.ICOA_AIDATA_DIR)return process.env.ICOA_AIDATA_DIR;const o="/data/aiproblems";try{if(a(o)&&i(o).isDirectory())return o}catch{}return g(process.cwd(),"icoa-aidata")}function f(o){return g(u(),o.platform,o.id)}function h(o){return o>=1024?`${(o/1024).toFixed(1)}G`:`${o}M`}function y(e,t){return new Promise(n=>{const a=o(e,t,{stdio:"ignore",shell:!1});a.on("error",()=>n(!1)),a.on("close",o=>n(0===o))})}async function p(o){const i=f(o);if(a(i))return console.log(),console.log(chalk.green(` ✓ ${o.id} is already here`)+chalk.gray(` (${i})`)),console.log(chalk.gray(" Nothing to do. ")+chalk.cyan("teleload")+chalk.gray(" lists the rest.")),void console.log();const p=g(u(),o.platform);r(p,{recursive:!0});const m=g(p,`.${o.id}.tar.zst.part`);if(console.log(),console.log(chalk.bold.white(` ⬇ ${o.id}`)+chalk.gray(` · ${h(o.tar_mb)} packed → ${h(o.unpacked_mb)} on disk · ${o.n_files} files`)),console.log(chalk.gray(" Straight from the Singapore data node — nothing goes through your laptop.")),console.log(),!await async function(o,e){const t=Date.now();let a=0,r=1048576*o.tar_mb,s=0;const l=Boolean(process.stdout.isTTY);let i=-1;const g=(o=!1)=>{const e=r>0?Math.min(100,Math.round(a/r*100)):0,n=(Date.now()-t)/1e3,s=n>0?a/1048576/n:0,c=a/1048576,d=r/1048576,g=n>=3&&a>=4194304&&s>0&&r>a?(r-a)/1048576/s:0;if(!l){const t=Math.floor(e/25);return void((t>i||o)&&(i=t,console.log(chalk.cyan(` ${String(e).padStart(3)}% · ${c.toFixed(0)}/${d.toFixed(0)} MB · ${s.toFixed(1)} MB/s`))))}const u=Math.round(e/5),f="█".repeat(u)+"░".repeat(20-u),h=o?"":` · ${function(o){if(!Number.isFinite(o)||o<=0)return"--";const e=Math.floor(o/60),t=Math.round(o%60);return e>0?`${e}m${String(t).padStart(2,"0")}s`:`${t}s`}(g)} left`,y=` ${f} ${String(e).padStart(3)}% · ${c.toFixed(0)}/${d.toFixed(0)} MB · ${s.toFixed(1)} MB/s${h}`;process.stdout.write(`\r${chalk.cyan(y)}${" ".repeat(12)}${o?"\n":""}`)};try{const t=await fetch(o.url,{signal:AbortSignal.timeout(36e5)});if(!t.ok||!t.body)return!1;const l=Number(t.headers.get("content-length"));Number.isFinite(l)&&l>0&&(r=l);const i=n(e),u=c.fromWeb(t.body);return u.on("data",o=>{a+=o.length;const e=Date.now();e-s>250&&(s=e,g())}),await d(u,i),g(!0),!0}catch{return process.stdout.write("\n"),!1}}(o,m))return l(m,{force:!0}),console.log(chalk.yellow(" ✗ Download failed.")+chalk.gray(" Nothing was changed — just run it again.")),void console.log();process.stdout.write(chalk.gray(" checking the file is intact… "));const w=await($=m,new Promise((o,n)=>{const a=e("sha256"),r=t($);r.on("data",o=>{a.update(o)}),r.on("end",()=>o(a.digest("hex"))),r.on("error",n)})).catch(()=>"");var $;if(o.sha256&&w!==o.sha256)return l(m,{force:!0}),console.log(chalk.yellow("✗")),console.log(chalk.yellow(" The file arrived damaged and was discarded.")+chalk.gray(" Run it again.")),void console.log();console.log(chalk.green("✓")),process.stdout.write(chalk.gray(" unpacking… "));const b=g(p,`.${o.id}.staging`);l(b,{recursive:!0,force:!0});const v=await async function(o,e){if(r(e,{recursive:!0}),await y("tar",["-xf",o,"-C",e]))return!0;if(await y("tar",["--zstd","-xf",o,"-C",e]))return!0;if(await y("tar",["-I","unzstd","-xf",o,"-C",e]))return!0;const t=`${o}.plain`;if(await y("zstd",["-d","-f","-o",t,o])){const o=await y("tar",["-xf",t,"-C",e]);return l(t,{force:!0}),o}return!1}(m,b);if(l(m,{force:!0}),!v)return l(b,{recursive:!0,force:!0}),console.log(chalk.yellow("✗")),console.log(chalk.yellow(" Could not unpack the archive.")+chalk.gray(" Run it again.")),void console.log();const k=g(b,o.id);try{s(a(k)?k:b,i)}catch{return console.log(chalk.yellow("✗")),console.log(chalk.yellow(" Could not move the data into place.")+chalk.gray(" Check disk space.")),void console.log()}l(b,{recursive:!0,force:!0}),console.log(chalk.green("✓")),console.log(),console.log(chalk.green(" 🎁 ready: ")+chalk.white(i)),console.log(chalk.gray(" Open it in a notebook — the path above is the dataset root.")),console.log(chalk.gray(" ")+chalk.cyan("teleload")+chalk.gray(" lists what else is available.")),console.log()}export async function runTeleload(o){const e=await async function(){try{const o=await fetch(process.env.ICOA_TELELOAD_MANIFEST||"https://icoa-datasets.sg-sin-1.linodeobjects.com/aidata/manifest.json",{signal:AbortSignal.timeout(3e4)});if(!o.ok)return null;const e=await o.json(),t=Array.isArray(e?.packs)?e.packs:null;return t?t.slice().sort((o,e)=>o.n-e.n):null}catch{return null}}();if(!e)return console.log(),console.log(chalk.yellow(" Could not reach the dataset node right now.")),console.log(chalk.gray(" Check your connection and try again — nothing was changed.")),void console.log();if(0===e.length)return console.log(),console.log(chalk.gray(" No on-demand datasets are published yet — everything ships inside this machine.")),void console.log();const t=(o??"").trim().replace(/^#/,"");if(""===t)return function(o){console.log(),console.log(chalk.bold.cyan(" ⬇ TELELOAD")+chalk.gray(" · big datasets, pulled straight from the data node")),console.log();for(const e of o){const o=a(f(e))?chalk.green("✓ here"):chalk.gray("⬇ not yet");console.log(` ${chalk.bold.white(String(e.n))}. ${chalk.white(e.id.padEnd(34))}`+chalk.gray(`${h(e.unpacked_mb).padStart(6)} `)+o)}console.log(),console.log(chalk.gray(" Pull one with ")+chalk.cyan("teleload <number>")+chalk.gray(" (e.g. ")+chalk.cyan("teleload 2")+chalk.gray(")"));const e="/data/aiproblems"===u();console.log(chalk.gray(e?" Smaller datasets are already baked into this boxthose need no pull.":" On a laptop nothing is pre-installed: whatever a task needs, pull it here first.")),console.log()}(e);const n=Number.parseInt(t,10);let r=Number.isFinite(n)?e.find(o=>o.n===n):void 0;if(!r){const o=t.toLowerCase();r=e.find(e=>e.id.toLowerCase()===o)??e.find(e=>e.id.toLowerCase().includes(o))}if(!r){console.log(),console.log(chalk.yellow(` No dataset called "${t}".`)),console.log(chalk.gray(" These are the ones you can pull:"));for(const o of e)console.log(chalk.gray(` ${o.n}. ${o.id}`));return console.log(chalk.gray(" Try ")+chalk.cyan(`teleload ${e[0].n}`)+chalk.gray(" — or just ")+chalk.cyan("teleload")+chalk.gray(" to see sizes.")),void console.log()}await p(r)}export function registerTeleloadCommand(o){o.command("teleload").argument("[pack]","pack number (or id) from `teleload`").description("Pull a big dataset from the data node onto this machine").action(async o=>{await runTeleload(o)})}
@@ -8,7 +8,7 @@
8
8
  "action": "▸ 领数据:kaggle s01-sound-of-nature",
9
9
  "meta": "⏱ 参考 25 分钟 · 难度 ★★☆☆☆",
10
10
  "note": "288 条训练 9 类,wav 全是 5 秒 44.1kHz,先重采到 16k",
11
- "hint": "先用 torchaudio 读一条 wav 走 MelSpectrogramlog 打出 shape,再照着写 Dataset。"
11
+ "hint": "本机没有 torchaudio/librosa:用 scipy.io.wavfile.read 读一条 wav → numpy,先打出 shape 再写 Dataset(GPU 箱上两个库都有)。"
12
12
  },
13
13
  {
14
14
  "seq": 2,
@@ -35,7 +35,7 @@
35
35
  "action": "▸ 领数据:kaggle s04-is-that-audio",
36
36
  "meta": "⏱ 参考 25 分钟 · 难度 ★★☆☆☆",
37
37
  "note": "官方承认本轮有泄漏:样本 id 的 A_/B_ 前缀本身就带类组信息",
38
- "hint": "先统计 train.csv 每类样本数,再定分层切分和 mel 的固定帧数。"
38
+ "hint": "先统计 train.csv 每类样本数,再定分层切分和固定帧数(本机求谱用 scipy.signal,librosa 只在 GPU 箱上有)。"
39
39
  },
40
40
  {
41
41
  "seq": 5,