icoa-cli 2.19.480 → 2.19.482

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.
@@ -1 +1 @@
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 r}from"node:path";import{fileURLToPath as s}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,computeLegend as u,loadSprintTasks as h,mediaHelpLines as m,taskSteps as f}from"../lib/sprint-meta.js";let w=!1;export function isSprintActive(){return w}const b=a(s(import.meta.url)),$=r(process.env.HOME||".",".icoa"),k=r($,"sprint-state.json"),S={"T-torch":"裸 torch:手写 attention / causal mask / perplexity","T-umap":"降维当特征提取器,不是画图工具","T-lora":"peft LoRA 参数高效微调","T-librosa":"音频特征流水线:mel / MFCC → 定长向量"},A=["",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 q(o){try{e($,{recursive:!0}),t(k,`${JSON.stringify(o,null,1)}\n`)}catch{}}function v(){return(c().language||"en").toLowerCase().startsWith("zh")}function j(o,e){return v()?o:e}function I(o){return"★".repeat(Math.max(1,Math.min(5,o||3)))}const C=r($,"sprint-memos.json");function N(o){try{e($,{recursive:!0}),t(C,`${JSON.stringify(o,null,1)}\n`)}catch{}}function O(o,e){const n=new Set(e.done),t=new Set(e.opened);console.log(),console.log(chalk.bold.cyan(j(" ⚔ IOAI 2026 · 四工具冲刺"," ⚔ IOAI 2026 · four-tool sprint"))+chalk.gray(` ${j("已攻克","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(` — ${S[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(I(o.difficulty).padEnd(5))+chalk.gray(o.needs_gpu?" ⚡":" ")+chalk.gray(` ${o.data_mb}M`)+("teleload"===o.status?chalk.gray(j(" · teleload"," · teleload")):"")+(o.judged?chalk.green(j(" · 可出分"," · scored")):""))}}console.log(),console.log(chalk.gray(" ")+chalk.cyan("open <n>")+chalk.gray(j(" 看题 · "," view · "))+chalk.cyan("done <n>")+chalk.gray(j(" 标记攻克 · "," mark cleared · "))+chalk.cyan("ai4ioai")+chalk.gray(j(" 开 AI 分屏 · "," AI in a split · "))+chalk.cyan("memo")+chalk.gray(j(" 记问题 · "," report a problem · "))+chalk.cyan("back")+chalk.gray(j(" 退出"," leave"))),console.log(chalk.gray(j(" ⬜ 没看过 ◐ 看过没做完 ✓ 攻克"," ⬜ unseen ◐ opened ✓ cleared"))),console.log(chalk.gray(u(v()))),console.log()}function T(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=h();try{const t=JSON.parse(n(function(e){const n=[r(b,"..","data",e),r(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 A)console.log(o);t.who||(t.who=""),O(e,t);const a=i(),s=null!==a,c=s?a:l({input:process.stdin,output:process.stdout,terminal:!0});s||g(c);const u=s?c.listeners("line").slice():[];c.removeAllListeners("line");const $=c.prompt.bind(c);w=!0;const S=chalk.bold.cyan("icoa ioai2026> ");c.setPrompt(S);let x=null;await new Promise(o=>{c.on("line",async l=>{const a=l.trim().replace(/^icoa\s+/i,""),[r,i]=[a.split(/\s+/)[0]?.toLowerCase()||"",a.split(/\s+/)[1]||""];if(["back","quit","exit","menu"].includes(r))return q(t),console.log(chalk.gray(" 进度已保存。")),(()=>{if(w=!1,c.removeAllListeners("line"),s){for(const o of u)c.on("line",o);c.setPrompt(chalk.green("icoa> ")),c.prompt()}else g(null),c.close()})(),void o();if(""===r||["challenges","list","ls"].includes(r))O(e,t);else if(["open","o"].includes(r)||/^\d+$/.test(r)){const o=Number.parseInt(/^\d+$/.test(r)?r:i,10),n=e.find(e=>e.seq===o);n?(t.opened.includes(o)||t.opened.push(o),q(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=f(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 T(o,58))console.log(chalk.cyan(" │ ")+chalk.white(e));console.log(chalk.cyan(" │"))}const t=v();console.log(chalk.cyan(" │ ")+chalk.gray(p(o,t)));const l=d(o,t);if(l)for(const o of T(l,58))console.log(chalk.cyan(" │ ")+chalk.gray(o));console.log(chalk.cyan(" │ ")+chalk.gray(o.meta||`⏱ 难度 ${I(o.difficulty)}`)+chalk.gray(o.needs_gpu?" ⚡ 需要 GPU":"")),console.log(chalk.cyan(" ╰──────────────────────────────────────────────────────"));for(const e of m(o,t))for(const o of T(e,60))console.log(chalk.yellow(" ")+chalk.yellow(o));const a=f(o),r=function(o){const e=f(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(j(" ▸ 就在这里敲,两步:"," ▸ Type these here, in order:"))),a.forEach((o,e)=>{console.log(chalk.gray(` ${e+1}. `)+chalk.bold.cyan(o)+chalk.gray(0===e?j(" ← 先把数据拉下来"," ← fetch the data first"):j(" ← 题面 + notebook"," ← statement + notebook")))})):r&&console.log(chalk.bold.white(j(" ▸ 就在这里敲: "," ▸ Type it right here: "))+chalk.bold.cyan(r)+chalk.gray(j(" ← 数据 + notebook 落到本机"," ← pulls the data + notebook"))),console.log(chalk.gray(" ")+chalk.cyan("ai4ioai")+chalk.gray(j(" 开 AI 分屏 · "," AI in a split · "))+chalk.cyan(`done ${o.seq}`)+chalk.gray(j(" 标记攻克 · "," mark cleared · "))+chalk.cyan("memo")+chalk.gray(j(` 记问题(自动记在第 ${o.seq} 题) · `,` report (auto-filed under ${o.seq}) · `))+chalk.cyan("back")+chalk.gray(j(" 回列表"," back to list"))),console.log()}(n)):console.log(chalk.yellow(` 没有第 ${i||r} 题。`)+chalk.gray(` 题号 1-${e.length}。`))}else if("done"===r){const o=Number.parseInt(i,10);e.some(e=>e.seq===o)?(t.done.includes(o)||t.done.push(o),q(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(r)?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(j(" 这条命令没跑成:"," That command failed: "))+chalk.gray(String(o))),console.log(chalk.gray(j(" 记一条给教练:"," Tell the coach: "))+chalk.cyan(j("memo …","memo …"))),console.log()}}(r,a.split(/\s+/).slice(1).join(" ")):"memo"===r||"note"===r?await async function(o,e,t,l){const a=function(){try{const o=JSON.parse(n(C,"utf8"));return Array.isArray(o)?o:[]}catch{return[]}}(),r=o.trim();if(["list","ls","all"].includes(r.toLowerCase())){if(console.log(),0===a.length)console.log(chalk.gray(j(" 还没有记录。"," Nothing noted yet.")));else{console.log(chalk.bold.white(j(` 📝 已记 ${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?j(" ·已上报"," ·sent"):j(" ·仅本地"," ·local only")))}console.log(chalk.gray(` ${C}`))}return console.log(chalk.gray(j(" 再记一条:"," Note another: "))+chalk.cyan("memo")+chalk.gray(j(" (光敲这一个词就给你写字的地方)"," (just the word — it gives you a place to type)"))),void console.log()}const s=r?r.split(/\s+/):[],c=s.length>0&&/^\d+$/.test(s[0])&&e.some(o=>o.seq===Number(s[0])),i=c?Number(s[0]):t;let g=(c?s.slice(1):s).join(" ").trim();if(""===g){const o=i?chalk.gray(j(` —— 记在第 ${i} 题下`,` — filed under task ${i}`)):chalk.gray(j(" —— 通用反馈"," — general feedback"));if(console.log(),console.log(chalk.bold.white(j(" 📝 撞到什么就写什么"," 📝 Say what you hit"))+o),console.log(chalk.gray(j(" 一行写完,回车就存下(不用等回复);直接回车 = 不记。"," 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(j(" 没记。"," Nothing noted."))),void console.log()}const d={ts:(new Date).toISOString(),seq:i,text:g,synced:!1};a.push(d),N(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,N(a)),console.log(),console.log(chalk.green(j(" ✓ 记下了"," ✓ noted"))+(i?chalk.gray(j(` (第 ${i} 题)`,` (task ${i})`)):"")+chalk.gray(p?j(" ·已上报"," ·sent"):j(" ·存在本机,教练可以来取"," ·saved on this machine"))),console.log(chalk.gray(j(" 继续做题就好。看全部:"," Carry on. See them all: "))+chalk.cyan("memo list")),console.log()}(a.split(/\s+/).slice(1).join(" "),e,x,c):["ai4ioai","/ai4ioai","ai"].includes(r)?(console.log(),console.log(chalk.bold.white(j(" 左右分屏,左边看题右边问 AI:"," Split the screen — tasks left, AI right:"))),console.log(chalk.gray(" 1. ")+chalk.bold.cyan("Ctrl-b %")+chalk.gray(j(" 左右分屏(上下分屏是 "," split left/right (up/down is "))+chalk.cyan('Ctrl-b "')+chalk.gray(j(")",")"))),console.log(chalk.gray(" 2. ")+chalk.gray(j("右边那格输 ","in the right pane type "))+chalk.bold.cyan("icoa")+chalk.gray(j(" ,再输 "," , then "))+chalk.bold.cyan("ai4ioai")),console.log(chalk.gray(j(" 3. 两格之间切换:"," 3. move between panes: "))+chalk.cyan("Ctrl-b ←")+chalk.gray(" / ")+chalk.cyan("Ctrl-b →")),console.log(),console.log(chalk.gray(j(" 它是弱模型 —— 单轮、2000 字符以内。把问题问准,就是这次要练的本事。"," A deliberately weak model — single-turn, 2000 chars. Asking precisely is the skill."))),console.log(chalk.gray(j(" 在 notebook 里卡住时,那边可以直接敲 "," Stuck inside a notebook? there you can type "))+chalk.cyan("ai")+chalk.gray(j(" —— 它会把那一格的代码和报错一起带上。"," — it carries that cell and its traceback."))),console.log()):["help","?","guide"].includes(r)?O(e,t):(console.log(chalk.gray(" ")+chalk.cyan("open <n>")+chalk.gray(j(" 看题 · "," view · "))+chalk.cyan("kaggle <题目id>")+chalk.gray(j(" 领数据 · "," get the data · "))+chalk.cyan("ipynb <路径>")+chalk.gray(j(" 开 notebook · "," open the notebook · "))+chalk.cyan("done <n>")+chalk.gray(j(" 标记 · "," mark · "))+chalk.cyan("memo")+chalk.gray(j(" 记问题 · "," report · "))+chalk.cyan("back")+chalk.gray(j(" 退出"," leave"))),console.log(chalk.gray(j(" 题目 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(S),c.prompt()}),s||c.once("close",()=>o()),c.prompt=$,c.prompt()})}export function registerSprintCommand(o){o.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 a}from"node:readline";import{dirname as l,join as r}from"node:path";import{fileURLToPath as s}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,computeLegend as h,loadSprintTasks as u,mediaHelpLines as m,taskSteps as f}from"../lib/sprint-meta.js";let b=!1;export function isSprintActive(){return b}const w=l(s(import.meta.url)),k=r(process.env.HOME||".",".icoa"),$=r(k,"sprint-state.json"),A={"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 v(o){try{e(k,{recursive:!0}),t($,`${JSON.stringify(o,null,1)}\n`)}catch{}}function I(){return(c().language||"en").toLowerCase().startsWith("zh")}function j(o,e){return I()?o:e}function q(o){return"★".repeat(Math.max(1,Math.min(5,o||3)))}const C=r(k,"sprint-memos.json");function x(o){try{e(k,{recursive:!0}),t(C,`${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(j(" ⚔ IOAI 2026 · 四工具冲刺"," ⚔ IOAI 2026 · four-tool sprint"))+chalk.gray(` ${j("已攻克","cleared")} ${n.size} / ${o.length}`));const a=new Map;for(const e of o)a.has(e.bullseye)||a.set(e.bullseye,[]),a.get(e.bullseye)?.push(e);for(const[o,e]of a){console.log(),console.log(chalk.bold.white(` ${o}`)+chalk.gray(` — ${A[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(T(o.title,34))+chalk.gray(q(o.difficulty).padEnd(5))+chalk.gray(o.needs_gpu?" ⚡":" ")+chalk.gray(` ${o.data_mb}M`)+("teleload"===o.status?chalk.gray(j(" · teleload"," · teleload")):"")+(o.judged?chalk.green(j(" · 可出分"," · scored")):""))}}console.log(),console.log(chalk.gray(" ")+chalk.cyan("open <n>")+chalk.gray(j(" 看题 · "," view · "))+chalk.cyan("done <n>")+chalk.gray(j(" 标记攻克 · "," mark cleared · "))+chalk.cyan("ai4ioai")+chalk.gray(j(" 开 AI 分屏 · "," AI in a split · "))+chalk.cyan("memo")+chalk.gray(j(" 记问题 · "," report a problem · "))+chalk.cyan("back")+chalk.gray(j(" 退出"," leave"))),console.log(chalk.gray(j(" ⬜ 没看过 ◐ 看过没做完 ✓ 攻克"," ⬜ unseen ◐ opened ✓ cleared"))),console.log(chalk.gray(h(I()))),console.log()}function O(o){if(/[ -鿿＀-￯]/.test(o))return 2;const e=o.codePointAt(0)??0;return e>=126976&&e<=129791||e>=9728&&e<=10175?2:1}function T(o,e){const n=[...o].reduce((o,e)=>o+O(e),0);if(n<=e)return o+" ".repeat(e-n);let t="",a=0;for(const n of o){const o=O(n);if(a+o>e-1)break;t+=n,a+=o}return`${t}…${" ".repeat(Math.max(0,e-a-1))}`}function L(o,e){const n=[];let t="",a=0;for(const l of o){const o=/[ -鿿＀-￯]/.test(l)?2:1;a+o>e&&(n.push(t),t="",a=0),t+=l,a+=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=[r(w,"..","data",e),r(w,"..","..","src","data",e)];for(const e of n)if(o(e))return e;return n[0]}("sprint-cards.json"),"utf8")),a=new Map((t.cards||[]).map(o=>[o.seq,o]));for(const o of e){const e=a.get(o.seq);e&&Object.assign(o,{star:e.star,trap:e.trap,action:e.action,note:e.note,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($,"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 l=i(),s=null!==l,c=s?l:a({input:process.stdin,output:process.stdout,terminal:!0});s||g(c);const h=s?c.listeners("line").slice():[];c.removeAllListeners("line");const k=c.prompt.bind(c);b=!0;const A=chalk.bold.cyan("icoa ioai2026> ");c.setPrompt(A);let O=null;await new Promise(o=>{c.on("line",async a=>{const l=a.trim().replace(/^icoa\s+/i,""),[r,i]=[l.split(/\s+/)[0]?.toLowerCase()||"",l.split(/\s+/)[1]||""];if(["back","quit","exit","menu"].includes(r))return v(t),console.log(chalk.gray(" 进度已保存。")),(()=>{if(b=!1,c.removeAllListeners("line"),s){for(const o of h)c.on("line",o);c.setPrompt(chalk.green("icoa> ")),c.prompt()}else g(null),c.close()})(),void o();if(""===r||["challenges","list","ls"].includes(r))N(e,t);else if(["open","o"].includes(r)||/^\d+$/.test(r)){const o=Number.parseInt(/^\d+$/.test(r)?r:i,10),n=e.find(e=>e.seq===o);n?(t.opened.includes(o)||t.opened.push(o),v(t),O=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=f(o).length>1,n=[o.star,o.trap,e?"":o.action,o.note,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 L(o,58))console.log(chalk.cyan(" │ ")+chalk.white(e));console.log(chalk.cyan(" │"))}const t=I();console.log(chalk.cyan(" │ ")+chalk.gray(p(o,t)));const a=d(o,t);if(a)for(const o of L(a,58))console.log(chalk.cyan(" │ ")+chalk.gray(o));console.log(chalk.cyan(" │ ")+chalk.gray(o.meta||`⏱ 难度 ${q(o.difficulty)}`)+chalk.gray(o.needs_gpu?" ⚡ 需要 GPU":"")),console.log(chalk.cyan(" ╰──────────────────────────────────────────────────────"));for(const e of m(o,t))for(const o of L(e,60))console.log(chalk.yellow(" ")+chalk.yellow(o));const l=f(o),r=function(o){const e=f(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);l.length>1?(console.log(chalk.bold.white(j(" ▸ 就在这里敲,两步:"," ▸ Type these here, in order:"))),l.forEach((o,e)=>{console.log(chalk.gray(` ${e+1}. `)+chalk.bold.cyan(o)+chalk.gray(0===e?j(" ← 先把数据拉下来"," ← fetch the data first"):j(" ← 题面 + notebook"," ← statement + notebook")))})):r&&console.log(chalk.bold.white(j(" ▸ 就在这里敲: "," ▸ Type it right here: "))+chalk.bold.cyan(r)+chalk.gray(j(" ← 数据 + notebook 落到本机"," ← pulls the data + notebook"))),console.log(chalk.gray(" ")+chalk.cyan("ai4ioai")+chalk.gray(j(" 开 AI 分屏 · "," AI in a split · "))+chalk.cyan(`done ${o.seq}`)+chalk.gray(j(" 标记攻克 · "," mark cleared · "))+chalk.cyan("memo")+chalk.gray(j(` 记问题(自动记在第 ${o.seq} 题) · `,` report (auto-filed under ${o.seq}) · `))+chalk.cyan("back")+chalk.gray(j(" 回列表"," back to list"))),console.log()}(n)):console.log(chalk.yellow(` 没有第 ${i||r} 题。`)+chalk.gray(` 题号 1-${e.length}。`))}else if("done"===r){const o=Number.parseInt(i,10);e.some(e=>e.seq===o)?(t.done.includes(o)||t.done.push(o),v(t),console.log(chalk.green(` ✓ 第 ${o} 题标记为攻克`)+chalk.gray(` (${t.done.length}/${e.length})`))):console.log(chalk.yellow(` 题号 1-${e.length}。`))}else["kaggle","teleload","ipynb","board"].includes(r)?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])}if("board"===o){const{runBoard:o}=await import("./board.js");return void await o(n[0],n[1])}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(j(" 这条命令没跑成:"," That command failed: "))+chalk.gray(String(o))),console.log(chalk.gray(j(" 记一条给教练:"," Tell the coach: "))+chalk.cyan(j("memo …","memo …"))),console.log()}}(r,l.split(/\s+/).slice(1).join(" ")):"memo"===r||"note"===r?await async function(o,e,t,a){const l=function(){try{const o=JSON.parse(n(C,"utf8"));return Array.isArray(o)?o:[]}catch{return[]}}(),r=o.trim();if(["list","ls","all"].includes(r.toLowerCase())){if(console.log(),0===l.length)console.log(chalk.gray(j(" 还没有记录。"," Nothing noted yet.")));else{console.log(chalk.bold.white(j(` 📝 已记 ${l.length} 条`,` 📝 ${l.length} noted`)));for(const o of l.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?j(" ·已上报"," ·sent"):j(" ·仅本地"," ·local only")))}console.log(chalk.gray(` ${C}`))}return console.log(chalk.gray(j(" 再记一条:"," Note another: "))+chalk.cyan("memo")+chalk.gray(j(" (光敲这一个词就给你写字的地方)"," (just the word — it gives you a place to type)"))),void console.log()}const s=r?r.split(/\s+/):[],c=s.length>0&&/^\d+$/.test(s[0])&&e.some(o=>o.seq===Number(s[0])),i=c?Number(s[0]):t;let g=(c?s.slice(1):s).join(" ").trim();if(""===g){const o=i?chalk.gray(j(` —— 记在第 ${i} 题下`,` — filed under task ${i}`)):chalk.gray(j(" —— 通用反馈"," — general feedback"));if(console.log(),console.log(chalk.bold.white(j(" 📝 撞到什么就写什么"," 📝 Say what you hit"))+o),console.log(chalk.gray(j(" 一行写完,回车就存下(不用等回复);直接回车 = 不记。"," 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()))})}(a,chalk.cyan(" memo > ")),""===g)return console.log(chalk.gray(j(" 没记。"," Nothing noted."))),void console.log()}const d={ts:(new Date).toISOString(),seq:i,text:g,synced:!1};l.push(d),x(l),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,x(l)),console.log(),console.log(chalk.green(j(" ✓ 记下了"," ✓ noted"))+(i?chalk.gray(j(` (第 ${i} 题)`,` (task ${i})`)):"")+chalk.gray(p?j(" ·已上报"," ·sent"):j(" ·存在本机,教练可以来取"," ·saved on this machine"))),console.log(chalk.gray(j(" 继续做题就好。看全部:"," Carry on. See them all: "))+chalk.cyan("memo list")),console.log()}(l.split(/\s+/).slice(1).join(" "),e,O,c):["ai4ioai","/ai4ioai","ai"].includes(r)?(console.log(),console.log(chalk.bold.white(j(" 左右分屏,左边看题右边问 AI:"," Split the screen — tasks left, AI right:"))),console.log(chalk.gray(" 1. ")+chalk.bold.cyan("Ctrl-b %")+chalk.gray(j(" 左右分屏(上下分屏是 "," split left/right (up/down is "))+chalk.cyan('Ctrl-b "')+chalk.gray(j(")",")"))),console.log(chalk.gray(" 2. ")+chalk.gray(j("右边那格输 ","in the right pane type "))+chalk.bold.cyan("icoa")+chalk.gray(j(" → ↑↓ 选 "," → ↑↓ pick "))+chalk.bold.white("🧠 Learn")+chalk.gray(j(" → 在 "," → at "))+chalk.cyan("icoa learn>")+chalk.gray(j(" 输 "," type "))+chalk.bold.cyan("ai4ioai")),console.log(chalk.gray(j(" 3. 两格之间切换:"," 3. move between panes: "))+chalk.cyan("Ctrl-b ←")+chalk.gray(" / ")+chalk.cyan("Ctrl-b →")),console.log(),console.log(chalk.gray(j(" 它是弱模型 —— 单轮、2000 字符以内。把问题问准,就是这次要练的本事。"," A deliberately weak model — single-turn, 2000 chars. Asking precisely is the skill."))),console.log(chalk.gray(j(" 在 notebook 里卡住时,那边可以直接敲 "," Stuck inside a notebook? there you can type "))+chalk.cyan("ai")+chalk.gray(j(" —— 它会把那一格的代码和报错一起带上。"," — it carries that cell and its traceback."))),console.log()):["help","?","guide"].includes(r)?function(o,e){const n=I();console.log(),console.log(chalk.bold.white(n?" ═══ 📖 冲刺指南 ═══":" ═══ 📖 Sprint guide ═══")),console.log(chalk.gray(n?` 这里是 IOAI 2026 四工具冲刺:${o.length} 张卡,每张 = 一个要点 + 一道真题。已攻克 ${e.done.length}/${o.length}。`:` The IOAI 2026 four-tool sprint: ${o.length} cards, each = one idea + one real task. Cleared ${e.done.length}/${o.length}.`)),console.log(),console.log(chalk.bold.white(n?" 一张卡的循环:":" The loop for one card:")),[["open <n>",n?"看题卡(要点/陷阱/下一步)":"read the card (idea / trap / next step)",""],["teleload / kaggle …",n?"照卡片 ▸ 行领数据":"fetch the data — copy the card’s ▸ line",""],["ipynb <路径>",n?"开 notebook,先 run all":"open the notebook, run all first",""],["kaggle check / submit",n?"验格式 → 判分出分(可出分的题)":"check the format → score it (judged tasks)",""],["board <event> <comp>",n?"看排行":"see the standings",""],["done <n>",n?"标记攻克,回列表挑下一张":"mark it cleared, pick the next card",""]].forEach(([o,e],n)=>{console.log(chalk.gray(` ${n+1}. `)+chalk.cyan(o.padEnd(22))+chalk.gray(e))}),console.log(),console.log(chalk.gray(n?" 卡住了: ":" Stuck: ")+chalk.cyan("ai4ioai")+chalk.gray(n?" 开 AI 分屏 · ":" AI in a split · ")+chalk.cyan("memo")+chalk.gray(n?" 把问题记给教练 · ":" report to the coach · ")+chalk.cyan("challenges")+chalk.gray(n?" 回列表 · ":" the list · ")+chalk.cyan("back")+chalk.gray(n?" 退出(进度自动存)":" leave (progress saved)")),console.log()}(e,t):(console.log(chalk.gray(" ")+chalk.cyan("open <n>")+chalk.gray(j(" 看题 · "," view · "))+chalk.cyan("kaggle <题目id>")+chalk.gray(j(" 领数据 · "," get the data · "))+chalk.cyan("ipynb <路径>")+chalk.gray(j(" 开 notebook · "," open the notebook · "))+chalk.cyan("done <n>")+chalk.gray(j(" 标记 · "," mark · "))+chalk.cyan("memo")+chalk.gray(j(" 记问题 · "," report · "))+chalk.cyan("back")+chalk.gray(j(" 退出"," leave"))),console.log(chalk.gray(j(" 题目 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=k,c.setPrompt(A),c.prompt()}),s||c.once("close",()=>o()),c.prompt=k,c.prompt()})}export function registerSprintCommand(o){o.command("pandahelpme31",{hidden:!0}).action(async()=>{await runSprint()})}
@@ -1 +1 @@
1
- import{sprintTaskForComp as e}from"./sprint-meta.js";export function parseKaggleTaskList(e){const t=e??{},s=(t.data??t).tasks;if(!Array.isArray(s))return[];const a=[];for(const e of s){if(!e||"object"!=typeof e)continue;const t=e;"string"==typeof t.comp_id&&""!==t.comp_id&&a.push({comp_id:t.comp_id,title:"string"==typeof t.title?t.title:t.comp_id,metric:"string"==typeof t.metric?t.metric:"accuracy",description:"string"==typeof t.description&&""!==t.description?t.description:void 0,kaggle_url:"string"==typeof t.kaggle_url?t.kaggle_url:null,licence:"string"==typeof t.licence?t.licence:void 0,attribution:"string"==typeof t.attribution?t.attribution:void 0,data_base:"string"==typeof t.data_base&&""!==t.data_base?t.data_base:null,id_col:"string"==typeof t.id_col?t.id_col:void 0,target_col:"string"==typeof t.target_col?t.target_col:void 0,n_train:"number"==typeof t.n_train?t.n_train:void 0,n_test:"number"==typeof t.n_test?t.n_test:void 0,judge:"string"==typeof t.judge&&""!==t.judge?t.judge:void 0,board_event:"string"==typeof t.board_event&&""!==t.board_event?t.board_event:null,needs_gpu:!0===t.needs_gpu})}return a}export function dataFileUrls(e){const t=e.data_base;if("string"!=typeof t||""===t)return null;const s=t.replace(/\/$/,"");return{train:`${s}/train.csv`,test:`${s}/test.csv`,sample_submission:`${s}/sample_submission.csv`}}export function buildStarterCells(t,s){const a=s.id_col??"id",i=s.target_col??"target";var n;n=s.metric,/rmse|mse|mae|error/i.test(n);const r="icoa-holdout"===s.judge,o=e=>({kind:"markdown",source:e,result:null}),l=e=>({kind:"code",source:e.join("\n"),result:null}),c=[`# ${s.title}`,"",...s.description?[s.description,""]:[],`Kaggle-style practice — metric: **${s.metric}**.`,"","- `train.csv` — labelled training data",`- \`test.csv\` — rows to predict (no \`${i}\` column)`,"- `sample_submission.csv` — the exact format Kaggle expects","","Run all cells top to bottom: a baseline model trains on your CPU and","`submission.csv` appears next to the data. Then improve the model cell",...r?["and re-run — `icoa kaggle submit` scores it and ranks you on the board."]:["and re-run — your score is whatever Kaggle says it is."],"","**AI help:** split your terminal (`Ctrl-b %`), run `icoa` in the right pane","and type `ai4ioai` for a live Gemma 3n E4B. Ask it for feature ideas or bug fixes —","then verify every suggestion with the val score. A tip that lowers it, drop it.",...s.licence?["",`**Data licence:** ${s.licence}`]:[],...s.attribution?[`**Attribution:** ${s.attribution}`]:[]].join("\n"),p=l(["# setup — load the data (leave as is)","import os","import numpy as np","import pandas as pd","from pandas.api.types import is_numeric_dtype","from sklearn.feature_extraction.text import TfidfVectorizer","from sklearn.model_selection import train_test_split","from sklearn.metrics import accuracy_score, mean_squared_error","","# same code everywhere: in a GPU session these env vars point at the","# box's own dataset copy + workspace — locally they are unset.",`DIR = os.environ.get("ICOA_KAGGLE_DATA") or r"${t}"`,'OUT = os.environ.get("ICOA_KAGGLE_OUT") or DIR',...s.data_base?[`DATA_BASE = "${s.data_base.replace(/\/$/,"")}"`,'if not os.path.exists(DIR + "/train.csv"):'," import urllib.request"," os.makedirs(DIR, exist_ok=True)",' for f in ("train.csv", "test.csv", "sample_submission.csv"):',' urllib.request.urlretrieve(DATA_BASE + "/" + f, DIR + "/" + f)']:[],'train = pd.read_csv(DIR + "/train.csv")','test = pd.read_csv(DIR + "/test.csv")','sub_fmt = pd.read_csv(DIR + "/sample_submission.csv")',"","# 🔴 The submission column names are NOT always the training column names.","# On tasks imported from other platforms the two genuinely differ: train.csv",'# labels the answer "class" or "result" while sample_submission.csv calls it','# "answer". Hard-coding the submission name here used to raise KeyError on the',"# very first cell. So trust the DATA: whatever column train has and test lacks","# is the thing to predict.",`SUB_ID, SUB_TARGET = "${a}", "${i}" # names the submission file wants`,"only_train = [c for c in train.columns if c not in test.columns]","TARGET = only_train[-1] if only_train else SUB_TARGET","shared = [c for c in train.columns if c in test.columns]","# Only treat a column as the row id when the submission actually names it AND",'# both files carry it. Falling back to "first shared column" silently spent a',"# real feature as an id on tasks whose id lives only in test.csv.","ID = SUB_ID if SUB_ID in shared else None",'assert TARGET in train.columns, f"cannot find the label column in {list(train.columns)}"',"","# Regression or classification? Decided from the labels, not from metadata —","# several tasks ship continuous labels, and handing those to a classifier",'# raises "Unknown label type: continuous".',"REG = is_numeric_dtype(train[TARGET]) and train[TARGET].nunique() > 20",'print(f"train {train.shape} · test {test.shape} · predicting {TARGET!r} "'," f\"({'regression' if REG else 'classification'})\")","# 前几行 —— 看一眼真实数据长什么样,比看列名有用得多","print(train.head(3).to_string(max_colwidth=24)[:700])"]),d=e(s.comp_id),u=d?.media,m="audio"===u?.kind?"scipy.io.wavfile.read(path) -> numpy, then scipy.signal for a spectrogram":"image"===u?.kind?"PIL.Image.open(path) -> numpy":"weights"===u?.kind?"torch.load(path, weights_only=True) — the model itself is the input here":"unpack the archive inside the pack, then read what is in it",h=l(["# FEATURES — turn raw columns into numbers a model can use (improve THIS cell).","# Numbers: fill gaps with the median. Category (<= 20 distinct): one-hot.","# Free text: TF-IDF — on a text task the sentences ARE the signal, and dropping",'# them as "high-cardinality" leaves nothing to train on (that used to crash the','# whole notebook with "No objects to concatenate").',"# only columns present in BOTH files — a train-only column cannot be a feature","# at prediction time, and indexing test with it raises KeyError.","feat = [c for c in shared if c not in (ID, TARGET)]","Xtr_raw, Xte_raw = train[feat].copy(), test[feat].copy()","num = [c for c in feat if is_numeric_dtype(Xtr_raw[c])]","cat = [c for c in feat if c not in num and Xtr_raw[c].nunique() <= 20]","# Everything else is vectorised as text. Requiring a long average length here","# used to throw away high-cardinality SHORT strings — ingredient names, single","# words, category codes — which on several tasks are the entire signal, leaving","# the notebook with zero features.","txt = [c for c in feat if c not in num and c not in cat]","for c in num:"," med = Xtr_raw[c].median()"," Xtr_raw[c] = Xtr_raw[c].fillna(med)"," Xte_raw[c] = Xte_raw[c].fillna(med)","blocks_tr, blocks_te = [], []","if num or cat:"," d_tr = pd.get_dummies(Xtr_raw[num + cat], columns=cat, dummy_na=True)"," d_te = pd.get_dummies(Xte_raw[num + cat], columns=cat, dummy_na=True)",' d_tr, d_te = d_tr.align(d_te, join="left", axis=1, fill_value=0)'," blocks_tr.append(d_tr.to_numpy(dtype=float))"," blocks_te.append(d_te.to_numpy(dtype=float))","for c in txt:"," # fillna BEFORE astype(str): a real NaN reaching the vectoriser raises",' # "np.nan is an invalid document", and astype alone does not catch it.',' tr_txt = Xtr_raw[c].fillna("").astype(str)',' te_txt = Xte_raw[c].fillna("").astype(str)'," # min_df=1: on a short-token column (one ingredient per row) min_df=2 can"," # filter the vocabulary down to nothing."," long_col = tr_txt.str.len().mean() >= 12"," # Try the good settings, then a permissive fallback, then give up on THIS"," # column only. A column whose vocabulary prunes to nothing used to abort the",' # whole run with "After pruning, no terms remain".',' for kw in ({"min_df": 2 if long_col else 1,',' "analyzer": "word" if long_col else "char_wb"},',' {"min_df": 1, "analyzer": "char_wb"}):'," try:"," vec = TfidfVectorizer(max_features=3000, ngram_range=(1, 2), **kw)"," b_tr = vec.fit_transform(tr_txt).toarray()"," blocks_tr.append(b_tr)"," blocks_te.append(vec.transform(te_txt).toarray())"," break"," except ValueError as e:"," last = e"," else:",' print(f" skipped text column {c!r}: {last}")',"if not blocks_tr:"," raise SystemExit(",' f"No usable feature columns. The shared columns are {feat} — none of them "',' f"is numeric, categorical or text.\\n"',...u?[` "The signal for this task is in ${u.kind} files, not in the CSVs.\\n"`,` " 1. fetch them (${u.mb}MB): teleload ${u.pack}\\n"`,...u.glob?[` " files land at <pack dir>/${u.glob}\\n"`]:[],` " 2. replace this cell: ${m}\\n"`,' " build one feature row per file, then keep the rest of the notebook.\\n"']:[' f"Two kinds of task land here, and both are real work rather than a bug:\\n"',' f" 1. audio/image — train.csv only lists sample ids and labels and the "',' f"signal is in media files. Read them with scipy.io.wavfile (audio) or "',' f"PIL (images) and turn each file into a feature row.\\n"',' f" 2. train.csv and test.csv describe different things (a retrieval or "',' f"matching task). Read both files, work out what links a test row to a "',' f"train row, and build that mapping yourself.\\n"'],...u?[' f"columns — train={list(train.columns)} test={list(test.columns)}"']:[' f"Either way: replace this cell. train={list(train.columns)} "',' f"test={list(test.columns)}"']," )","X = np.hstack(blocks_tr)","X_test = np.hstack(blocks_te)","y = train[TARGET]","X_tr, X_val, y_tr, y_val = train_test_split(X, y, test_size=0.2, random_state=0)",'print(f"{X.shape[1]} model-ready features "',' f"({len(num)} numeric, {len(cat)} one-hot, {len(txt)} TF-IDF text)")']),f=l(["# EDA — look at the labels before you model. Produces ONE figure:","# left = what you are predicting (class balance / value spread)","# right = what the FEATURES cell will have to work with","# icoa ipynb saves it as a .png and opens your image viewer (type `open` to reopen).","import matplotlib.pyplot as plt","try:"," fig, ax = plt.subplots(1, 2, figsize=(11, 4))"," if REG:",' vals = pd.to_numeric(train[TARGET], errors="coerce").dropna()'," ax[0].hist(vals, bins=30)",' ax[0].set_title(f"{TARGET} — {len(vals)} values, mean {vals.mean():.3g}")'," else:"," vc = train[TARGET].astype(str).value_counts().head(12)"," ax[0].bar(range(len(vc)), vc.values)"," ax[0].set_xticks(range(len(vc)))",' ax[0].set_xticklabels([s[:14] for s in vc.index], rotation=45, ha="right")',' # An imbalanced target is the single most common reason a "good"'," # accuracy means nothing — show the majority share right in the title."," top = vc.iloc[0] / len(train)",' ax[0].set_title(f"{TARGET} — {train[TARGET].nunique()} classes · biggest {top:.0%}")',' kinds = {"numeric": 0, "category": 0, "text": 0}'," for c in [c for c in shared if c not in (ID, TARGET)]:"," if is_numeric_dtype(train[c]):",' kinds["numeric"] += 1'," elif train[c].nunique() <= 20:",' kinds["category"] += 1'," else:",' kinds["text"] += 1'," miss = train.isna().mean()"," miss = miss[miss > 0].sort_values(ascending=False).head(10)"," if len(miss) > 0:"," ax[1].barh(range(len(miss)), miss.values)"," ax[1].set_yticks(range(len(miss)))"," ax[1].set_yticklabels([s[:16] for s in miss.index])",' ax[1].set_title("missing rate (top columns)")'," else:"," ax[1].bar(list(kinds), list(kinds.values()))",' ax[1].set_title(f"{sum(kinds.values())} usable columns · no missing values")'," plt.tight_layout()"," plt.show()",' print("columns by kind:", kinds)',"except Exception as e:"," # EDA is never allowed to stop the run — `run all` halts on the first"," # error, and a plotting hiccup must not cost the student their baseline.",' print("EDA skipped:", type(e).__name__, e)']),g=l(["# MODEL — a working baseline. Improve THIS cell to climb the board.","from sklearn.linear_model import LogisticRegression, Ridge","# REG was decided from the labels back in setup.","model = Ridge() if REG else LogisticRegression(max_iter=2000)"]),_=l(["# validate — quick local score on a held-out fifth of train","model.fit(X_tr, y_tr)","p_val = model.predict(X_val)","if REG:",' print("val RMSE:", round(mean_squared_error(y_val, p_val) ** 0.5, 4))',"else:"," acc = accuracy_score(y_val, p_val)",' print("val accuracy:", round(acc, 4))'," if acc < 0.3:"," # A near-zero baseline is the expected result on several of these tasks,"," # not a broken notebook — say so, or the student reads it as a bug.",' print(" A score this low usually means the linear baseline cannot "',' "represent the pattern at all (combination rules, sequences, "',' "spelling). That IS the task: build features that expose it, "',' "or switch to a model that can. The chain itself works — "',' "submission.csv is written either way.")']),b=l(["# submission — retrain on ALL data, write submission.csv (Kaggle format)","model.fit(X, y)","pred = model.predict(X_test)",'out = OUT + "/submission.csv"',"# Copy the layout of sample_submission.csv and swap in the predictions, rather","# than rebuilding the file from column names. Some tasks want more than two","# columns (e.g. subtaskID,datapointID,answer) and a hand-built 2-column frame","# is rejected by the grader even when every prediction is right.","if len(sub_fmt) == len(pred):"," sub = sub_fmt.copy()"," sub[sub.columns[-1]] = pred","else:"," keys = {}"," if ID is not None and ID in test.columns:"," keys[SUB_ID] = test[ID]"," keys[SUB_TARGET] = pred"," sub = pd.DataFrame(keys)",' print(f"NOTE: sample_submission has {len(sub_fmt)} rows but test has "',' f"{len(pred)} — built the file from column names instead; "',' f"check it against the task page before submitting.")',"sub.to_csv(out, index=False)",'print("wrote", out, "·", list(sub.columns))',r?`print("score it: icoa kaggle submit ${s.comp_id}")`:'print("format check: icoa kaggle check")']),y=r?["## Submit to ICOA (scored on the server)","",`1. In the ICOA CLI run \`icoa kaggle submit ${s.comp_id}\``,"2. The server scores `submission.csv` against the secret test labels"," and your rank lands on the live board (`icoa board`).","3. Improve the MODEL cell, re-run, submit again — best score counts."]:"nitro"===s.judge?["## Where this one gets scored","","This task comes from **judge.nitro-ai.org** and the answer key stays on","their server, so ICOA cannot score it for you. That does not make it a","practice stub — it is a real task, just judged elsewhere.","",`1. \`icoa kaggle check ${s.comp_id}\` — checks the FORMAT of`," `submission.csv` (headers, row count, ids). Format errors are the most"," common way a correct answer still scores zero.","2. Watch the **val score** printed above — that is your real feedback loop"," during the sprint, and it needs no account anywhere.","3. Want the official number? Register at judge.nitro-ai.org and submit"," there. Otherwise compare against the official solution, or ask"," `ai4ioai` to review your approach."]:s.kaggle_url?["## Submit on Kaggle (manual, your own account)","",`1. Open ${s.kaggle_url}`,"2. **Submit Predictions** → upload `submission.csv`","3. Read your leaderboard score, come back, improve the MODEL cell, repeat."]:["## Submit on Kaggle (manual, your own account)","","_This dataset has no live Kaggle page linked yet._","The loop is identical: upload `submission.csv`, read the score, improve","the MODEL cell, repeat. Meanwhile the **val score** printed above is a","real signal you can work against with no account at all."];return[o(c),p,f,h,g,_,b,o(y.join("\n"))]}export function parseSubmitResponse(e){const t=e&&"object"==typeof e?e:{},s=t.data??t,a=s&&"object"==typeof s?s:{};return"number"==typeof a.score&&"string"==typeof a.metric?{ok:!0,score:a.score,metric:a.metric,rank:"number"==typeof a.rank_at_time?a.rank_at_time:null,fieldSize:"number"==typeof a.field_size?a.field_size:null,deduped:!0===a.deduped,boardEvent:"string"==typeof a.board_event?a.board_event:null}:"string"==typeof a.reason&&""!==a.reason?{ok:!1,reason:a.reason,error:"string"==typeof a.error?a.error:void 0,problems:Array.isArray(a.problems)?a.problems.filter(e=>"string"==typeof e):void 0}:{ok:!1,reason:"network"}}export function validateSubmissionText(e,t){const s=[],a=e.trim().split(/\r?\n/),i=t.trim().split(/\r?\n/),n=a[0]??"",r=i[0]??"";n.trim()!==r.trim()&&s.push(`header mismatch: expected "${r}", got "${n}"`);const o=a.slice(1).filter(e=>""!==e.trim()),l=i.slice(1).filter(e=>""!==e.trim());o.length!==l.length&&s.push(`row count mismatch: expected ${l.length}, got ${o.length}`);const c=e=>new Set(e.map(e=>(e.split(",")[0]??"").trim())),p=c(o),d=c(l),u=[...d].filter(e=>!p.has(e)),m=[...p].filter(e=>!d.has(e));if(u.length>0||m.length>0){const e=[];u.length>0&&e.push(`${u.length} missing (e.g. ${u[0]})`),m.length>0&&e.push(`${m.length} unknown (e.g. ${m[0]})`),s.push(`id mismatch vs sample_submission: ${e.join(", ")}`)}for(let e=0;e<o.length;e++)if(o[e].split(",").some(e=>""===e.trim())){s.push(`empty cell in data row ${e+1}`);break}return{ok:0===s.length,problems:s}}export function buildMediaStarterCells(e,t){const s=e=>({kind:"markdown",source:e,result:null}),a=e=>({kind:"code",source:e.join("\n"),result:null}),i=t.media?.kind??"archive",n=t.title??"ICOA sprint task",r=[`# ${t.seq?`${t.seq} · `:""}${n}`,"",...t.topic_cn?[t.topic_cn,""]:[],"This task ships **data, not a baseline** — the CSV starter cannot help here",`because the signal lives in the ${i} files you just pulled.`,"","Run all cells: they inventory the pack and draw one picture of what is inside,","so you start from evidence instead of from the folder name. The last cell says","what you have to build — that part is the task.","","**Reading the files:** on your laptop the notebook env has numpy / scipy /","pandas / scikit-learn / torch / transformers / Pillow — but NOT librosa,","torchaudio or soundfile. The GPU contest box has librosa and torchaudio too."].join("\n"),o=a(["# inventory — what is actually in this pack (counts, sizes, a few real names)","import os","import numpy as np",`DIR = os.environ.get("ICOA_PACK_DIR") or r"${e}"`,"by_ext, total, sample = {}, 0, {}","for root, _dirs, files in os.walk(DIR):"," for f in files:",' ext = os.path.splitext(f)[1].lower() or "(no ext)"'," p = os.path.join(root, f)"," by_ext[ext] = by_ext.get(ext, 0) + 1"," total += os.path.getsize(p)"," sample.setdefault(ext, p)",'print(f"{DIR}\\n{sum(by_ext.values())} files · {total/1048576:.0f} MB")',"for ext, n in sorted(by_ext.items(), key=lambda kv: -kv[1])[:8]:",' print(f" {ext:>10} {n:>6} e.g. {os.path.relpath(sample[ext], DIR)}")',"# 🔴 a leftover .zip means the pack still needs unpacking before you can read it",'zips = [p for e, p in sample.items() if e == ".zip"]',"if zips:",' print("\\nNOTE: there is still a .zip in here — unpack it first:")',' print(f" import zipfile; zipfile.ZipFile(r\\"{zips[0]}\\").extractall(DIR)")']),l=["# EDA — one picture of what is inside. icoa ipynb saves it as a .png and","# opens your image viewer (`open` reopens it).","import matplotlib.pyplot as plt","try:"];"image"===i?l.push(" from PIL import Image"," imgs = []"," for root, _d, files in os.walk(DIR):"," for f in sorted(files):",' if os.path.splitext(f)[1].lower() in (".jpg", ".jpeg", ".png"):'," imgs.append(os.path.join(root, f))"," if len(imgs) >= 9:"," break"," fig, axes = plt.subplots(3, 3, figsize=(7, 7))"," for ax, p in zip(axes.ravel(), imgs[:9]):"," ax.imshow(Image.open(p))"," ax.set_title(os.path.basename(p)[:18], fontsize=8)"," for ax in axes.ravel():",' ax.axis("off")',' plt.suptitle(f"{len(imgs)}+ images · first 9")'):"weights"===i?l.push(" import torch"," wfiles = []"," for root, _d, files in os.walk(DIR):"," for f in sorted(files):",' if os.path.splitext(f)[1].lower() in (".pt", ".pth"):'," wfiles.append(os.path.join(root, f))"," fig, ax = plt.subplots(1, max(1, min(2, len(wfiles))), figsize=(10, 4), squeeze=False)"," for i, p in enumerate(wfiles[:2]):"," # weights_only=True: never unpickle arbitrary objects from a data file",' obj = torch.load(p, map_location="cpu", weights_only=True)',' t = obj if hasattr(obj, "flatten") else list(obj.values())[0]'," v = np.asarray(t, dtype=float).ravel()"," ax[0][i].hist(v, bins=60)",' ax[0][i].set_title(f"{os.path.basename(p)} · shape {tuple(np.shape(t))}", fontsize=9)',' print(os.path.basename(p), "shape", tuple(np.shape(t)))'):l.push(" import pandas as pd"," csvs = []"," for root, _d, files in os.walk(DIR):"," for f in files:",' if f.lower().endswith(".csv"):'," csvs.append(os.path.join(root, f))"," csvs.sort(key=os.path.getsize, reverse=True)"," df = pd.read_csv(csvs[0])"," print(os.path.basename(csvs[0]), df.shape)"," print(df.head(3).to_string(max_colwidth=24)[:600])"," # the last low-cardinality column is the usual label; if there is none,"," # plot the row-length spread so the picture still says something true"," cand = [c for c in df.columns if df[c].nunique() <= 30]"," fig, ax = plt.subplots(figsize=(8, 4))"," if cand:"," vc = df[cand[-1]].astype(str).value_counts().head(12)"," ax.bar(range(len(vc)), vc.values)"," ax.set_xticks(range(len(vc)))",' ax.set_xticklabels([s[:14] for s in vc.index], rotation=45, ha="right")',' ax.set_title(f"{cand[-1]} — {df[cand[-1]].nunique()} values")'," else:"," ax.hist([len(str(x)) for x in df[df.columns[-1]]], bins=30)",' ax.set_title(f"length of {df.columns[-1]}")'),l.push(" plt.tight_layout()"," plt.show()","except Exception as e:"," # never stop the run on a plotting problem — `run all` halts on first error",' print("EDA skipped:", type(e).__name__, e)');const c=["## Your job","","There is no baseline to beat here — you build the first one. The shape of it:","","1. **turn each file into a row of numbers** — that is the whole trick","image"===i?" (`PIL.Image.open` → resize → `np.asarray` → flatten, or a pretrained encoder)":"weights"===i?" (`torch.load(..., weights_only=True)` → the tensors themselves ARE the features)":" (read the CSVs / unpack the archive, then vectorise the text columns)","2. keep a held-out fifth of the data and print a val score every time","3. write your predictions in exactly the format the task page asks for","","`add` makes a new code cell · `add md` a note cell · `run all` runs everything ·","a cell that raises offers `ai N`, which sends that cell and its traceback to the AI."].join("\n");return[s(r),o,a(l),s(c)]}
1
+ import{sprintTaskForComp as e}from"./sprint-meta.js";export function parseKaggleTaskList(e){const t=e??{},s=(t.data??t).tasks;if(!Array.isArray(s))return[];const a=[];for(const e of s){if(!e||"object"!=typeof e)continue;const t=e;"string"==typeof t.comp_id&&""!==t.comp_id&&a.push({comp_id:t.comp_id,title:"string"==typeof t.title?t.title:t.comp_id,metric:"string"==typeof t.metric?t.metric:"accuracy",description:"string"==typeof t.description&&""!==t.description?t.description:void 0,kaggle_url:"string"==typeof t.kaggle_url?t.kaggle_url:null,licence:"string"==typeof t.licence?t.licence:void 0,attribution:"string"==typeof t.attribution?t.attribution:void 0,data_base:"string"==typeof t.data_base&&""!==t.data_base?t.data_base:null,id_col:"string"==typeof t.id_col?t.id_col:void 0,target_col:"string"==typeof t.target_col?t.target_col:void 0,n_train:"number"==typeof t.n_train?t.n_train:void 0,n_test:"number"==typeof t.n_test?t.n_test:void 0,judge:"string"==typeof t.judge&&""!==t.judge?t.judge:void 0,board_event:"string"==typeof t.board_event&&""!==t.board_event?t.board_event:null,needs_gpu:!0===t.needs_gpu})}return a}export function dataFileUrls(e){const t=e.data_base;if("string"!=typeof t||""===t)return null;const s=t.replace(/\/$/,"");return{train:`${s}/train.csv`,test:`${s}/test.csv`,sample_submission:`${s}/sample_submission.csv`}}export function buildStarterCells(t,s){const a=s.id_col??"id",i=s.target_col??"target";var n;n=s.metric,/rmse|mse|mae|error/i.test(n);const o="icoa-holdout"===s.judge,r=e=>({kind:"markdown",source:e,result:null}),l=e=>({kind:"code",source:e.join("\n"),result:null}),c=[`# ${s.title}`,"",...s.description?[s.description,""]:[],`Kaggle-style practice — metric: **${s.metric}**.`,"","- `train.csv` — labelled training data",`- \`test.csv\` — rows to predict (no \`${i}\` column)`,"- `sample_submission.csv` — the exact format Kaggle expects","","Run all cells top to bottom: a baseline model trains on your CPU and","`submission.csv` appears next to the data. Then improve the model cell",...o?["and re-run — `icoa kaggle submit` scores it and ranks you on the board."]:["and re-run — your score is whatever Kaggle says it is."],"","**AI help:** split your terminal (`Ctrl-b %`), run `icoa` in the right pane","and type `ai4ioai` for a live Gemma 3n E4B. Ask it for feature ideas or bug fixes —","then verify every suggestion with the val score. A tip that lowers it, drop it.",...s.licence?["",`**Data licence:** ${s.licence}`]:[],...s.attribution?[`**Attribution:** ${s.attribution}`]:[]].join("\n"),p=l(["# setup — load the data (leave as is)","import os","import numpy as np","import pandas as pd","from pandas.api.types import is_numeric_dtype","from sklearn.feature_extraction.text import TfidfVectorizer","from sklearn.model_selection import train_test_split","from sklearn.metrics import accuracy_score, mean_squared_error","","# same code everywhere: in a GPU session these env vars point at the","# box's own dataset copy + workspace — locally they are unset.",`DIR = os.environ.get("ICOA_KAGGLE_DATA") or r"${t}"`,'OUT = os.environ.get("ICOA_KAGGLE_OUT") or DIR',...s.data_base?[`DATA_BASE = "${s.data_base.replace(/\/$/,"")}"`,'if not os.path.exists(DIR + "/train.csv"):'," import urllib.request"," os.makedirs(DIR, exist_ok=True)",' for f in ("train.csv", "test.csv", "sample_submission.csv"):',' urllib.request.urlretrieve(DATA_BASE + "/" + f, DIR + "/" + f)']:[],'train = pd.read_csv(DIR + "/train.csv")','test = pd.read_csv(DIR + "/test.csv")','sub_fmt = pd.read_csv(DIR + "/sample_submission.csv")',"","# 🔴 The submission column names are NOT always the training column names.","# On tasks imported from other platforms the two genuinely differ: train.csv",'# labels the answer "class" or "result" while sample_submission.csv calls it','# "answer". Hard-coding the submission name here used to raise KeyError on the',"# very first cell. So trust the DATA: whatever column train has and test lacks","# is the thing to predict.",`SUB_ID, SUB_TARGET = "${a}", "${i}" # names the submission file wants`,"only_train = [c for c in train.columns if c not in test.columns]","TARGET = only_train[-1] if only_train else SUB_TARGET","shared = [c for c in train.columns if c in test.columns]","# Only treat a column as the row id when the submission actually names it AND",'# both files carry it. Falling back to "first shared column" silently spent a',"# real feature as an id on tasks whose id lives only in test.csv.","ID = SUB_ID if SUB_ID in shared else None",'assert TARGET in train.columns, f"cannot find the label column in {list(train.columns)}"',"","# Regression or classification? Decided from the labels, not from metadata —","# several tasks ship continuous labels, and handing those to a classifier",'# raises "Unknown label type: continuous".',"REG = is_numeric_dtype(train[TARGET]) and train[TARGET].nunique() > 20",'print(f"train {train.shape} · test {test.shape} · predicting {TARGET!r} "'," f\"({'regression' if REG else 'classification'})\")","# 前几行 —— 看一眼真实数据长什么样,比看列名有用得多","print(train.head(3).to_string(max_colwidth=24)[:700])"]),u=e(s.comp_id),d=u?.media,m="audio"===d?.kind?"scipy.io.wavfile.read(path) -> numpy, then scipy.signal for a spectrogram":"image"===d?.kind?"PIL.Image.open(path) -> numpy":"weights"===d?.kind?"torch.load(path, weights_only=True) — the model itself is the input here":"unpack the archive inside the pack, then read what is in it",h=l(["# FEATURES — turn raw columns into numbers a model can use (improve THIS cell).","# Numbers: fill gaps with the median. Category (<= 20 distinct): one-hot.","# Free text: TF-IDF — on a text task the sentences ARE the signal, and dropping",'# them as "high-cardinality" leaves nothing to train on (that used to crash the','# whole notebook with "No objects to concatenate").',"# only columns present in BOTH files — a train-only column cannot be a feature","# at prediction time, and indexing test with it raises KeyError.","feat = [c for c in shared if c not in (ID, TARGET)]","Xtr_raw, Xte_raw = train[feat].copy(), test[feat].copy()","num = [c for c in feat if is_numeric_dtype(Xtr_raw[c])]","cat = [c for c in feat if c not in num and Xtr_raw[c].nunique() <= 20]","# Everything else is vectorised as text. Requiring a long average length here","# used to throw away high-cardinality SHORT strings — ingredient names, single","# words, category codes — which on several tasks are the entire signal, leaving","# the notebook with zero features.","txt = [c for c in feat if c not in num and c not in cat]","for c in num:"," med = Xtr_raw[c].median()"," Xtr_raw[c] = Xtr_raw[c].fillna(med)"," Xte_raw[c] = Xte_raw[c].fillna(med)","blocks_tr, blocks_te = [], []","if num or cat:"," d_tr = pd.get_dummies(Xtr_raw[num + cat], columns=cat, dummy_na=True)"," d_te = pd.get_dummies(Xte_raw[num + cat], columns=cat, dummy_na=True)",' d_tr, d_te = d_tr.align(d_te, join="left", axis=1, fill_value=0)'," blocks_tr.append(d_tr.to_numpy(dtype=float))"," blocks_te.append(d_te.to_numpy(dtype=float))","for c in txt:"," # fillna BEFORE astype(str): a real NaN reaching the vectoriser raises",' # "np.nan is an invalid document", and astype alone does not catch it.',' tr_txt = Xtr_raw[c].fillna("").astype(str)',' te_txt = Xte_raw[c].fillna("").astype(str)'," # min_df=1: on a short-token column (one ingredient per row) min_df=2 can"," # filter the vocabulary down to nothing."," long_col = tr_txt.str.len().mean() >= 12"," # Try the good settings, then a permissive fallback, then give up on THIS"," # column only. A column whose vocabulary prunes to nothing used to abort the",' # whole run with "After pruning, no terms remain".',' for kw in ({"min_df": 2 if long_col else 1,',' "analyzer": "word" if long_col else "char_wb"},',' {"min_df": 1, "analyzer": "char_wb"}):'," try:"," vec = TfidfVectorizer(max_features=3000, ngram_range=(1, 2), **kw)"," b_tr = vec.fit_transform(tr_txt).toarray()"," blocks_tr.append(b_tr)"," blocks_te.append(vec.transform(te_txt).toarray())"," break"," except ValueError as e:"," last = e"," else:",' print(f" skipped text column {c!r}: {last}")',"if not blocks_tr:"," raise SystemExit(",' f"No usable feature columns. The shared columns are {feat} — none of them "',' f"is numeric, categorical or text.\\n"',...d?[` "The signal for this task is in ${d.kind} files, not in the CSVs.\\n"`,` " 1. fetch them (${d.mb}MB): teleload ${d.pack}\\n"`,...d.glob?[` " files land at <pack dir>/${d.glob}\\n"`]:[],` " 2. replace this cell: ${m}\\n"`,' " build one feature row per file, then keep the rest of the notebook.\\n"']:[' f"Two kinds of task land here, and both are real work rather than a bug:\\n"',' f" 1. audio/image — train.csv only lists sample ids and labels and the "',' f"signal is in media files. Read them with scipy.io.wavfile (audio) or "',' f"PIL (images) and turn each file into a feature row.\\n"',' f" 2. train.csv and test.csv describe different things (a retrieval or "',' f"matching task). Read both files, work out what links a test row to a "',' f"train row, and build that mapping yourself.\\n"'],...d?[' f"columns — train={list(train.columns)} test={list(test.columns)}"']:[' f"Either way: replace this cell. train={list(train.columns)} "',' f"test={list(test.columns)}"']," )","X = np.hstack(blocks_tr)","X_test = np.hstack(blocks_te)","y = train[TARGET]","X_tr, X_val, y_tr, y_val = train_test_split(X, y, test_size=0.2, random_state=0)",'print(f"{X.shape[1]} model-ready features "',' f"({len(num)} numeric, {len(cat)} one-hot, {len(txt)} TF-IDF text)")']),f=l(["# EDA — look at the labels before you model. Produces ONE figure:","# left = what you are predicting (class balance / value spread)","# right = what the FEATURES cell will have to work with","# icoa ipynb saves it as a .png and opens your image viewer (type `open` to reopen).","import matplotlib.pyplot as plt","try:"," fig, ax = plt.subplots(1, 2, figsize=(11, 4))"," if REG:",' vals = pd.to_numeric(train[TARGET], errors="coerce").dropna()'," ax[0].hist(vals, bins=30)",' ax[0].set_title(f"{TARGET} — {len(vals)} values, mean {vals.mean():.3g}")'," else:"," vc = train[TARGET].astype(str).value_counts().head(12)"," ax[0].bar(range(len(vc)), vc.values)"," ax[0].set_xticks(range(len(vc)))",' ax[0].set_xticklabels([s[:14] for s in vc.index], rotation=45, ha="right")',' # An imbalanced target is the single most common reason a "good"'," # accuracy means nothing — show the majority share right in the title."," top = vc.iloc[0] / len(train)",' ax[0].set_title(f"{TARGET} — {train[TARGET].nunique()} classes · biggest {top:.0%}")',' kinds = {"numeric": 0, "category": 0, "text": 0}'," for c in [c for c in shared if c not in (ID, TARGET)]:"," if is_numeric_dtype(train[c]):",' kinds["numeric"] += 1'," elif train[c].nunique() <= 20:",' kinds["category"] += 1'," else:",' kinds["text"] += 1'," miss = train.isna().mean()"," miss = miss[miss > 0].sort_values(ascending=False).head(10)"," if len(miss) > 0:"," ax[1].barh(range(len(miss)), miss.values)"," ax[1].set_yticks(range(len(miss)))"," ax[1].set_yticklabels([s[:16] for s in miss.index])",' ax[1].set_title("missing rate (top columns)")'," else:"," ax[1].bar(list(kinds), list(kinds.values()))",' ax[1].set_title(f"{sum(kinds.values())} usable columns · no missing values")'," plt.tight_layout()"," plt.show()",' print("columns by kind:", kinds)',"except Exception as e:"," # EDA is never allowed to stop the run — `run all` halts on the first"," # error, and a plotting hiccup must not cost the student their baseline.",' print("EDA skipped:", type(e).__name__, e)']),g=l(["# MODEL — a working baseline. Improve THIS cell to climb the board.","from sklearn.linear_model import LogisticRegression, Ridge","# REG was decided from the labels back in setup.","model = Ridge() if REG else LogisticRegression(max_iter=2000)"]),_=l(["# validate — quick local score on a held-out fifth of train","model.fit(X_tr, y_tr)","p_val = model.predict(X_val)","if REG:",' print("val RMSE:", round(mean_squared_error(y_val, p_val) ** 0.5, 4))',"else:"," acc = accuracy_score(y_val, p_val)",' print("val accuracy:", round(acc, 4))'," if acc < 0.3:"," # A near-zero baseline is the expected result on several of these tasks,"," # not a broken notebook — say so, or the student reads it as a bug.",' print(" A score this low usually means the linear baseline cannot "',' "represent the pattern at all (combination rules, sequences, "',' "spelling). That IS the task: build features that expose it, "',' "or switch to a model that can. The chain itself works — "',' "submission.csv is written either way.")']),b=l(["# submission — retrain on ALL data, write submission.csv (Kaggle format)","model.fit(X, y)","pred = model.predict(X_test)",'out = OUT + "/submission.csv"',"# Copy the layout of sample_submission.csv and swap in the predictions, rather","# than rebuilding the file from column names. Some tasks want more than two","# columns (e.g. subtaskID,datapointID,answer) and a hand-built 2-column frame","# is rejected by the grader even when every prediction is right.","if len(sub_fmt) == len(pred):"," sub = sub_fmt.copy()"," sub[sub.columns[-1]] = pred","else:"," keys = {}"," if ID is not None and ID in test.columns:"," keys[SUB_ID] = test[ID]"," keys[SUB_TARGET] = pred"," sub = pd.DataFrame(keys)",' print(f"NOTE: sample_submission has {len(sub_fmt)} rows but test has "',' f"{len(pred)} — built the file from column names instead; "',' f"check it against the task page before submitting.")',"sub.to_csv(out, index=False)",'print("wrote", out, "·", list(sub.columns))',o?`print("score it: icoa kaggle submit ${s.comp_id}")`:'print("format check: icoa kaggle check")']),y=o?["## Submit to ICOA (scored on the server)","",`1. In the ICOA CLI run \`icoa kaggle submit ${s.comp_id}\``,"2. The server scores `submission.csv` against the secret test labels"," and your rank lands on the live board (`icoa board`).","3. Improve the MODEL cell, re-run, submit again — best score counts."]:"nitro"===s.judge?["## Where this one gets scored","","This task comes from **judge.nitro-ai.org** and the answer key stays on","their server, so ICOA cannot score it for you. That does not make it a","practice stub — it is a real task, just judged elsewhere.","",`1. \`icoa kaggle check ${s.comp_id}\` — checks the FORMAT of`," `submission.csv` (headers, row count, ids). Format errors are the most"," common way a correct answer still scores zero.","2. Watch the **val score** printed above — that is your real feedback loop"," during the sprint, and it needs no account anywhere.","3. Want the official number? Register at judge.nitro-ai.org and submit"," there. Otherwise compare against the official solution, or ask"," `ai4ioai` to review your approach."]:s.kaggle_url?["## Submit on Kaggle (manual, your own account)","",`1. Open ${s.kaggle_url}`,"2. **Submit Predictions** → upload `submission.csv`","3. Read your leaderboard score, come back, improve the MODEL cell, repeat."]:["## Submit on Kaggle (manual, your own account)","","_This dataset has no live Kaggle page linked yet._","The loop is identical: upload `submission.csv`, read the score, improve","the MODEL cell, repeat. Meanwhile the **val score** printed above is a","real signal you can work against with no account at all."];return[r(c),p,f,h,g,_,b,r(y.join("\n"))]}export function parseSubmitResponse(e){const t=e&&"object"==typeof e?e:{},s=t.data??t,a=s&&"object"==typeof s?s:{};return"number"==typeof a.score&&"string"==typeof a.metric?{ok:!0,score:a.score,metric:a.metric,rank:"number"==typeof a.rank_at_time?a.rank_at_time:null,fieldSize:"number"==typeof a.field_size?a.field_size:null,deduped:!0===a.deduped,boardEvent:"string"==typeof a.board_event?a.board_event:null,used:"number"==typeof a.submissions_used?a.submissions_used:null,cap:"number"==typeof a.submissions_cap?a.submissions_cap:null}:"string"==typeof a.reason&&""!==a.reason?{ok:!1,reason:a.reason,error:"string"==typeof a.error?a.error:void 0,problems:Array.isArray(a.problems)?a.problems.filter(e=>"string"==typeof e):void 0}:{ok:!1,reason:"network"}}export function validateSubmissionText(e,t){const s=[],a=e.trim().split(/\r?\n/),i=t.trim().split(/\r?\n/),n=a[0]??"",o=i[0]??"";n.trim()!==o.trim()&&s.push(`header mismatch: expected "${o}", got "${n}"`);const r=a.slice(1).filter(e=>""!==e.trim()),l=i.slice(1).filter(e=>""!==e.trim());r.length!==l.length&&s.push(`row count mismatch: expected ${l.length}, got ${r.length}`);const c=e=>new Set(e.map(e=>(e.split(",")[0]??"").trim())),p=c(r),u=c(l),d=[...u].filter(e=>!p.has(e)),m=[...p].filter(e=>!u.has(e));if(d.length>0||m.length>0){const e=[];d.length>0&&e.push(`${d.length} missing (e.g. ${d[0]})`),m.length>0&&e.push(`${m.length} unknown (e.g. ${m[0]})`),s.push(`id mismatch vs sample_submission: ${e.join(", ")}`)}for(let e=0;e<r.length;e++)if(r[e].split(",").some(e=>""===e.trim())){s.push(`empty cell in data row ${e+1}`);break}return{ok:0===s.length,problems:s}}export function buildMediaStarterCells(e,t){const s=e=>({kind:"markdown",source:e,result:null}),a=e=>({kind:"code",source:e.join("\n"),result:null}),i=t.media?.kind??"archive",n=t.title??"ICOA sprint task",o=[`# ${t.seq?`${t.seq} · `:""}${n}`,"",...t.topic_cn?[t.topic_cn,""]:[],"This task ships **data, not a baseline** — the CSV starter cannot help here",`because the signal lives in the ${i} files you just pulled.`,"","Run all cells: they inventory the pack and draw one picture of what is inside,","so you start from evidence instead of from the folder name. The last cell says","what you have to build — that part is the task.","","**Reading the files:** on your laptop the notebook env has numpy / scipy /","pandas / scikit-learn / torch / transformers / Pillow — but NOT librosa,","torchaudio or soundfile. The GPU contest box has librosa and torchaudio too."].join("\n"),r=a(["# inventory — what is actually in this pack (counts, sizes, a few real names)","import os","import numpy as np",`DIR = os.environ.get("ICOA_PACK_DIR") or r"${e}"`,"by_ext, total, sample = {}, 0, {}","for root, _dirs, files in os.walk(DIR):"," for f in files:",' ext = os.path.splitext(f)[1].lower() or "(no ext)"'," p = os.path.join(root, f)"," by_ext[ext] = by_ext.get(ext, 0) + 1"," total += os.path.getsize(p)"," sample.setdefault(ext, p)",'print(f"{DIR}\\n{sum(by_ext.values())} files · {total/1048576:.0f} MB")',"for ext, n in sorted(by_ext.items(), key=lambda kv: -kv[1])[:8]:",' print(f" {ext:>10} {n:>6} e.g. {os.path.relpath(sample[ext], DIR)}")',"# 🔴 a leftover .zip means the pack still needs unpacking before you can read it",'zips = [p for e, p in sample.items() if e == ".zip"]',"if zips:",' print("\\nNOTE: there is still a .zip in here — unpack it first:")',' print(f" import zipfile; zipfile.ZipFile(r\\"{zips[0]}\\").extractall(DIR)")']),l=["# EDA — one picture of what is inside. icoa ipynb saves it as a .png and","# opens your image viewer (`open` reopens it).","import matplotlib.pyplot as plt","try:"];"image"===i?l.push(" from PIL import Image"," imgs = []"," for root, _d, files in os.walk(DIR):"," for f in sorted(files):",' if os.path.splitext(f)[1].lower() in (".jpg", ".jpeg", ".png"):'," imgs.append(os.path.join(root, f))"," if len(imgs) >= 9:"," break"," fig, axes = plt.subplots(3, 3, figsize=(7, 7))"," for ax, p in zip(axes.ravel(), imgs[:9]):"," ax.imshow(Image.open(p))"," ax.set_title(os.path.basename(p)[:18], fontsize=8)"," for ax in axes.ravel():",' ax.axis("off")',' plt.suptitle(f"{len(imgs)}+ images · first 9")'):"weights"===i?l.push(" import torch"," wfiles = []"," for root, _d, files in os.walk(DIR):"," for f in sorted(files):",' if os.path.splitext(f)[1].lower() in (".pt", ".pth"):'," wfiles.append(os.path.join(root, f))"," fig, ax = plt.subplots(1, max(1, min(2, len(wfiles))), figsize=(10, 4), squeeze=False)"," for i, p in enumerate(wfiles[:2]):"," # weights_only=True: never unpickle arbitrary objects from a data file",' obj = torch.load(p, map_location="cpu", weights_only=True)',' t = obj if hasattr(obj, "flatten") else list(obj.values())[0]'," v = np.asarray(t, dtype=float).ravel()"," ax[0][i].hist(v, bins=60)",' ax[0][i].set_title(f"{os.path.basename(p)} · shape {tuple(np.shape(t))}", fontsize=9)',' print(os.path.basename(p), "shape", tuple(np.shape(t)))'):l.push(" import pandas as pd"," csvs = []"," for root, _d, files in os.walk(DIR):"," for f in files:",' if f.lower().endswith(".csv"):'," csvs.append(os.path.join(root, f))"," csvs.sort(key=os.path.getsize, reverse=True)"," df = pd.read_csv(csvs[0])"," print(os.path.basename(csvs[0]), df.shape)"," print(df.head(3).to_string(max_colwidth=24)[:600])"," # the last low-cardinality column is the usual label; if there is none,"," # plot the row-length spread so the picture still says something true"," cand = [c for c in df.columns if df[c].nunique() <= 30]"," fig, ax = plt.subplots(figsize=(8, 4))"," if cand:"," vc = df[cand[-1]].astype(str).value_counts().head(12)"," ax.bar(range(len(vc)), vc.values)"," ax.set_xticks(range(len(vc)))",' ax.set_xticklabels([s[:14] for s in vc.index], rotation=45, ha="right")',' ax.set_title(f"{cand[-1]} — {df[cand[-1]].nunique()} values")'," else:"," ax.hist([len(str(x)) for x in df[df.columns[-1]]], bins=30)",' ax.set_title(f"length of {df.columns[-1]}")'),l.push(" plt.tight_layout()"," plt.show()","except Exception as e:"," # never stop the run on a plotting problem — `run all` halts on first error",' print("EDA skipped:", type(e).__name__, e)');const c=["## Your job","","There is no baseline to beat here — you build the first one. The shape of it:","","1. **turn each file into a row of numbers** — that is the whole trick","image"===i?" (`PIL.Image.open` → resize → `np.asarray` → flatten, or a pretrained encoder)":"weights"===i?" (`torch.load(..., weights_only=True)` → the tensors themselves ARE the features)":" (read the CSVs / unpack the archive, then vectorise the text columns)","2. keep a held-out fifth of the data and print a val score every time","3. write your predictions in exactly the format the task page asks for","","`add` makes a new code cell · `add md` a note cell · `run all` runs everything ·","a cell that raises offers `ai N`, which sends that cell and its traceback to the AI."].join("\n");return[s(o),r,a(l),s(c)]}