Datasets:
File size: 437,705 Bytes
57d6347 | 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 214 215 216 217 218 219 220 221 222 223 224 225 226 227 228 229 230 231 232 233 234 235 236 237 238 239 240 241 242 243 244 245 246 247 248 249 250 251 252 253 254 255 256 257 258 259 260 261 262 263 264 265 266 267 268 269 270 271 272 273 274 275 276 277 278 279 | {"task": "code_completion", "language": "python", "instruction": "Complete the following Python code. Return only the continuation, preserving indentation.\n\n```python\ndef _eval_node(node: ast.AST) -> float:\n if isinstance(node, ast.Expression):\n return _eval_node(node.body)\n if isinstance(node, ast.Constant) and isinstance(node.value, (int, float)):\n return node.value\n if isinstance(node, ast.BinOp) and type(node.op) in _BIN_OPS:\n left = _eval_node(node.left)\n right = _eval_node(node.right)\n if isinstance(node.op, ast.Pow) and abs(right) > 64:\n raise ValueError(\"exponent too large\")\n return _BIN_OPS[type(node.op)](left, right)\n```", "response": " if isinstance(node, ast.UnaryOp):\n value = _eval_node(node.operand)\n if isinstance(node.op, ast.UAdd):\n return value\n if isinstance(node.op, ast.USub):\n return -value\n raise ValueError(\"not an arithmetic expression\")", "source_file": "calculator.py", "function_name": "_eval_node", "class_name": null, "line_start": 51, "line_end": 68, "license": "mit", "source": "SadikAI project"}
{"task": "code_completion", "language": "python", "instruction": "Complete the following Python code. Return only the continuation, preserving indentation.\n\n```python\ndef _normalise(text: str) -> str:\n out = text.lower()\n out = (out.replace(\"×\", \"*\").replace(\"÷\", \"/\").replace(\"−\", \"-\")\n .replace(\"–\", \"-\").replace(\"—\", \"-\").replace(\"^\", \"**\"))\n # \"12 x 13\" / \"12x13\" -> multiplication, but leave words like \"x-ray\" alone.\n```", "response": " out = re.sub(r\"(?<=\\d)\\s*[x×]\\s*(?=\\d)\", \"*\", out)\n return out", "source_file": "calculator.py", "function_name": "_normalise", "class_name": null, "line_start": 79, "line_end": 85, "license": "mit", "source": "SadikAI project"}
{"task": "code_completion", "language": "python", "instruction": "Complete the following Python code. Return only the continuation, preserving indentation.\n\n```python\ndef _safe_result(expression: str) -> str | None:\n try:\n value = evaluate(expression)\n except (SyntaxError, ValueError, ZeroDivisionError, OverflowError):\n return None\n```", "response": " if isinstance(value, complex) or not math.isfinite(value):\n return None\n return _fmt(value)", "source_file": "calculator.py", "function_name": "_safe_result", "class_name": null, "line_start": 95, "line_end": 102, "license": "mit", "source": "SadikAI project"}
{"task": "code_completion", "language": "python", "instruction": "Complete the following Python code. Return only the continuation, preserving indentation.\n\n```python\ndef solve_math(text: str) -> str | None:\n \"\"\"Return a short answer line, or None if this is not an arithmetic ask.\"\"\"\n low = _normalise(text)\n if _DATE.search(low) or any(w in low for w in _PHONE_WORDS):\n return None\n\n # square roots\n m = re.search(r\"(?:square root(?:\\s+of)?|sqrt|√)\\s*\\(?\\s*(\\d+(?:\\.\\d+)?)\\s*\\)?\", low)\n if m:\n value = math.sqrt(float(m.group(1)))\n return f\"sqrt({_fmt(float(m.group(1)))}) = {_fmt(value)}\"\n\n # percentages: \"15% of 200\", \"200 ka 15 percent\"\n m = re.search(r\"(\\d+(?:\\.\\d+)?)\\s*(?:%|percent)\\s*(?:of|ka|from)?\\s*(\\d+(?:\\.\\d+)?)\", low)\n if m:\n pct, base = float(m.group(1)), float(m.group(2))\n value = pct / 100.0 * base\n return f\"{_fmt(pct)}% of {_fmt(base)} = {_fmt(value)}\"\n m = re.search(r\"(\\d+(?:\\.\\d+)?)\\s*(?:ka|of)\\s*(\\d+(?:\\.\\d+)?)\\s*(?:%|percent)\", low)\n if m:\n base, pct = float(m.group(1)), float(m.group(2))\n value = pct / 100.0 * base\n return f\"{_fmt(pct)}% of {_fmt(base)} = {_fmt(value)}\"\n```", "response": " expression = _strip_cues(low).replace(\" \", \"\")\n cue = _has_cue(low)\n\n if _PURE.match(expression) and any(op in expression for op in \"+-*/%\") \\\n and any(ch.isdigit() for ch in expression):\n pass\n elif cue:\n found = _EXPR.findall(low)\n if not found:\n return None\n expression = max(found, key=len).replace(\" \", \"\")\n expression = expression.strip(\"+-*/%\")\n if not any(op in expression for op in \"+-*/%\"):\n return None\n else:\n return None\n\n result = _safe_result(expression)\n if result is None:\n return None\n pretty = (expression.replace(\"**\", \"^\")\n .replace(\"*\", \" × \")\n .replace(\"/\", \" ÷ \"))\n return f\"{pretty} = {result}\"", "source_file": "calculator.py", "function_name": "solve_math", "class_name": null, "line_start": 105, "line_end": 152, "license": "mit", "source": "SadikAI project"}
{"task": "code_explanation", "language": "python", "instruction": "Explain what this Python function does.\n\n```python\ndef solve_math(text: str) -> str | None:\n \"\"\"Return a short answer line, or None if this is not an arithmetic ask.\"\"\"\n low = _normalise(text)\n if _DATE.search(low) or any(w in low for w in _PHONE_WORDS):\n return None\n\n # square roots\n m = re.search(r\"(?:square root(?:\\s+of)?|sqrt|√)\\s*\\(?\\s*(\\d+(?:\\.\\d+)?)\\s*\\)?\", low)\n if m:\n value = math.sqrt(float(m.group(1)))\n return f\"sqrt({_fmt(float(m.group(1)))}) = {_fmt(value)}\"\n\n # percentages: \"15% of 200\", \"200 ka 15 percent\"\n m = re.search(r\"(\\d+(?:\\.\\d+)?)\\s*(?:%|percent)\\s*(?:of|ka|from)?\\s*(\\d+(?:\\.\\d+)?)\", low)\n if m:\n pct, base = float(m.group(1)), float(m.group(2))\n value = pct / 100.0 * base\n return f\"{_fmt(pct)}% of {_fmt(base)} = {_fmt(value)}\"\n m = re.search(r\"(\\d+(?:\\.\\d+)?)\\s*(?:ka|of)\\s*(\\d+(?:\\.\\d+)?)\\s*(?:%|percent)\", low)\n if m:\n base, pct = float(m.group(1)), float(m.group(2))\n value = pct / 100.0 * base\n return f\"{_fmt(pct)}% of {_fmt(base)} = {_fmt(value)}\"\n\n expression = _strip_cues(low).replace(\" \", \"\")\n cue = _has_cue(low)\n\n if _PURE.match(expression) and any(op in expression for op in \"+-*/%\") \\\n and any(ch.isdigit() for ch in expression):\n pass\n elif cue:\n found = _EXPR.findall(low)\n if not found:\n return None\n expression = max(found, key=len).replace(\" \", \"\")\n expression = expression.strip(\"+-*/%\")\n if not any(op in expression for op in \"+-*/%\"):\n return None\n else:\n return None\n\n result = _safe_result(expression)\n if result is None:\n return None\n pretty = (expression.replace(\"**\", \"^\")\n .replace(\"*\", \" × \")\n .replace(\"/\", \" ÷ \"))\n return f\"{pretty} = {result}\"\n```", "response": "Return a short answer line, or None if this is not an arithmetic ask.", "source_file": "calculator.py", "function_name": "solve_math", "class_name": null, "line_start": 105, "line_end": 152, "license": "mit", "source": "SadikAI project"}
{"task": "code_generation", "language": "python", "instruction": "Write a Python function `solve_math(text: str)` that does the following:\n\nReturn a short answer line, or None if this is not an arithmetic ask.\n\nReturn only the Python code.", "response": "def solve_math(text: str) -> str | None:\n \"\"\"Return a short answer line, or None if this is not an arithmetic ask.\"\"\"\n low = _normalise(text)\n if _DATE.search(low) or any(w in low for w in _PHONE_WORDS):\n return None\n\n # square roots\n m = re.search(r\"(?:square root(?:\\s+of)?|sqrt|√)\\s*\\(?\\s*(\\d+(?:\\.\\d+)?)\\s*\\)?\", low)\n if m:\n value = math.sqrt(float(m.group(1)))\n return f\"sqrt({_fmt(float(m.group(1)))}) = {_fmt(value)}\"\n\n # percentages: \"15% of 200\", \"200 ka 15 percent\"\n m = re.search(r\"(\\d+(?:\\.\\d+)?)\\s*(?:%|percent)\\s*(?:of|ka|from)?\\s*(\\d+(?:\\.\\d+)?)\", low)\n if m:\n pct, base = float(m.group(1)), float(m.group(2))\n value = pct / 100.0 * base\n return f\"{_fmt(pct)}% of {_fmt(base)} = {_fmt(value)}\"\n m = re.search(r\"(\\d+(?:\\.\\d+)?)\\s*(?:ka|of)\\s*(\\d+(?:\\.\\d+)?)\\s*(?:%|percent)\", low)\n if m:\n base, pct = float(m.group(1)), float(m.group(2))\n value = pct / 100.0 * base\n return f\"{_fmt(pct)}% of {_fmt(base)} = {_fmt(value)}\"\n\n expression = _strip_cues(low).replace(\" \", \"\")\n cue = _has_cue(low)\n\n if _PURE.match(expression) and any(op in expression for op in \"+-*/%\") \\\n and any(ch.isdigit() for ch in expression):\n pass\n elif cue:\n found = _EXPR.findall(low)\n if not found:\n return None\n expression = max(found, key=len).replace(\" \", \"\")\n expression = expression.strip(\"+-*/%\")\n if not any(op in expression for op in \"+-*/%\"):\n return None\n else:\n return None\n\n result = _safe_result(expression)\n if result is None:\n return None\n pretty = (expression.replace(\"**\", \"^\")\n .replace(\"*\", \" × \")\n .replace(\"/\", \" ÷ \"))\n return f\"{pretty} = {result}\"", "source_file": "calculator.py", "function_name": "solve_math", "class_name": null, "line_start": 105, "line_end": 152, "license": "mit", "source": "SadikAI project"}
{"task": "code_completion", "language": "python", "instruction": "Complete the following Python code. Return only the continuation, preserving indentation.\n\n```python\ndef show(reply) -> None:\n emo = reply.emotion\n mood = reply.mood.get(\"label\", \"?\")\n print(f\"\\n{BOLD}{MODEL_NAME}{RESET} {DIM}[{reply.mode} · mood {mood} · \"\n f\"{emo.get('label', '?')} {emo.get('valence', 0):+.2f}]{RESET}\")\n print(reply.text)\n```", "response": " for artifact in reply.artifacts:\n print(f\" {BOLD}saved{RESET} {artifact['name']}\"\n f\" {DIM}({artifact['path']}){RESET}\")\n if reply.sources:\n for src in reply.sources:\n print(f\" {DIM}source: {src['title']} — {src['url']}{RESET}\")\n if reply.memories:\n print(f\" {DIM}recalled: {' | '.join(m[:60] for m in reply.memories)}{RESET}\")", "source_file": "chat.py", "function_name": "show", "class_name": null, "line_start": 27, "line_end": 40, "license": "mit", "source": "SadikAI project"}
{"task": "code_completion", "language": "python", "instruction": "Complete the following Python code. Return only the continuation, preserving indentation.\n\n```python\ndef main() -> None:\n ap = argparse.ArgumentParser(description=__doc__,\n formatter_class=argparse.RawDescriptionHelpFormatter)\n ap.add_argument(\"--checkpoint\", default=\"runs/medium/best.pt\")\n ap.add_argument(\"--tokenizer\", default=\"tokenizer/tokenizer.json\")\n ap.add_argument(\"--memory\", default=\"data/chat/memory.json\")\n ap.add_argument(\"--state\", default=\"data/chat/state.json\")\n ap.add_argument(\"--device\", default=\"auto\")\n ap.add_argument(\"--say\", default=None)\n ap.add_argument(\"--no-web\", action=\"store_true\")\n ap.add_argument(\"--no-model\", action=\"store_true\")\n ap.add_argument(\"--reset\", action=\"store_true\")\n args = ap.parse_args()\n\n engine = ChatEngine(\n checkpoint=args.checkpoint,\n tokenizer=args.tokenizer,\n memory_path=args.memory,\n state_path=args.state,\n device=args.device,\n web=not args.no_web,\n use_model=not args.no_model,\n )\n\n if args.reset:\n engine.reset()\n print(\"conversation cleared (facts kept).\")\n if not args.say:\n return\n\n if args.say is not None:\n show(engine.respond(args.say))\n return\n\n stats = engine.memory.stats()\n profile = engine.memory.profile()\n who = f\" — I remember you as {profile['name']}\" if profile.get(\"name\") else \"\"\n print(f\"{BOLD}{MODEL_NAME}{RESET} · made by {CREATOR_NAME} ({CREATOR_AGE}, {CREATOR_GRADE}) · {PARAMS} params · step {engine.model_step}{who}\")\n print(f\"{DIM}mood: {engine.mood.label()} · memory: {stats['turns']} turns, \"\n f\"{stats['facts']} facts · web: {'on' if engine.web else 'off'}{RESET}\")\n print(f\"{DIM}type /help for commands, Ctrl+C to quit{RESET}\")\n```", "response": " while True:\n try:\n line = input(\"\\nyou › \").strip()\n except (EOFError, KeyboardInterrupt):\n print(\"\\nbye.\")\n break\n if not line:\n continue\n if line in {\"/quit\", \"/exit\", \"/q\"}:\n print(\"bye.\")\n break\n if line == \"/help\":\n print(\"/memory what I remember about you\\n\"\n \"/forget <text> delete matching memories\\n\"\n \"/learn <topic> offline lesson (teamwork, religions, study...)\\n\"\n \"/topics list every lesson I can teach\\n\"\n \"/about who made me\\n\"\n \"/web on|off toggle live web lookup\\n\"\n \"/model on|off toggle the language model (stories/poems)\\n\"\n \"/run <code> run Python/JS/SQL locally (8s timeout)\\n\"\n \"/image <prompt> generate an image (AI online, poster offline)\\n\"\n \"/audio <text> turn text into a spoken WAV file\\n\"\n \"/file <name>|text write a file (txt/md/csv/json/html/pdf/docx/xlsx)\\n\"\n \"/mood current mood and how it got there\\n\"\n \"/reset clear conversation (facts stay)\\n\"\n \"/quit leave\\n\"\n \"\\nAsk 'code for fibonacci', 'teach me about teamwork',\"\n \"\\n'tell me about world religions', 'draw a red fox',\"\n \"\\n'make a csv of the 7 times table', 'create a resume'…\")\n continue\n if line == \"/memory\":\n print(f\"profile: {engine.memory.profile()}\")\n for entry in engine.memory.entries[-10:]:\n print(f\" [{entry.kind}] {entry.text[:90]}\")\n continue\n if line.startswith(\"/forget\"):\n target = line[len(\"/forget\"):].strip()\n removed = engine.memory.forget(target)\n print(f\"forgot {removed} entr{'y' if removed == 1 else 'ies'}.\")\n continue\n if line.startswith(\"/web\"):\n engine.web = line.endswith(\"on\")\n print(f\"web lookup {'on' if engine.web else 'off'}.\")\n continue\n if line.startswith(\"/model\"):\n engine.use_model = line.endswith(\"on\")\n print(f\"language model {'on' if engine.use_model else 'off'}.\")\n continue\n if line == \"/mood\":\n print(engine.mood.to_dict(), \"->\", engine.mood.label())\n continue\n if line == \"/reset\":\n engine.reset()\n print(\"conversation cleared (facts kept).\")\n continue\n\n try:\n show(engine.respond(line))\n except Exception as exc: # keep the REPL alive\n print(f\"{DIM}error: {exc}{RESET}\")", "source_file": "chat.py", "function_name": "main", "class_name": null, "line_start": 43, "line_end": 144, "license": "mit", "source": "SadikAI project"}
{"task": "code_completion", "language": "python", "instruction": "Complete the following Python code. Return only the continuation, preserving indentation.\n\n```python\n def __init__(\n self,\n checkpoint: str | Path = \"runs/medium/best.pt\",\n tokenizer: str | Path = \"tokenizer/tokenizer.json\",\n memory_path: str | Path = \"data/chat/memory.json\",\n state_path: str | Path = \"data/chat/state.json\",\n device: str = \"auto\",\n web: bool = True,\n use_model: bool = True,\n seed: int | None = None,\n ) -> None:\n if device == \"auto\":\n device = \"cuda\" if torch.cuda.is_available() else \"cpu\"\n```", "response": " self.device = torch.device(device)\n self.memory = MemoryStore(memory_path)\n self.state_path = Path(state_path)\n self.mood = self._load_mood()\n self.web = web\n self.use_model = use_model\n self.rng = random.Random(seed)\n self.tok: Tokenizer | None = None\n self.model: GPT | None = None\n self.model_step = \"?\"\n\n if use_model:\n self._load_model(checkpoint, tokenizer)", "source_file": "chat_engine.py", "function_name": "__init__", "class_name": "ChatEngine", "line_start": 146, "line_end": 171, "license": "mit", "source": "SadikAI project"}
{"task": "code_completion", "language": "python", "instruction": "Complete the following Python code. Return only the continuation, preserving indentation.\n\n```python\n def _load_model(self, checkpoint: str | Path, tokenizer: str | Path) -> None:\n checkpoint = ensure_weights(checkpoint)\n ckpt = torch.load(checkpoint, map_location=self.device, weights_only=False)\n self.model = GPT(ModelConfig.from_dict(ckpt[\"model_config\"]))\n state = ckpt[\"model\"]\n```", "response": " if any(k.startswith(\"_orig_mod.\") for k in state):\n state = {k.replace(\"_orig_mod.\", \"\", 1): v for k, v in state.items()}\n self.model.load_state_dict(state)\n self.model.to(self.device).eval()\n self.model_step = str(ckpt.get(\"step\", \"?\"))\n self.tok = Tokenizer(tokenizer)", "source_file": "chat_engine.py", "function_name": "_load_model", "class_name": "ChatEngine", "line_start": 174, "line_end": 184, "license": "mit", "source": "SadikAI project"}
{"task": "code_completion", "language": "python", "instruction": "Complete the following Python code. Return only the continuation, preserving indentation.\n\n```python\n def _save(self) -> None:\n self.memory.save()\n self.state_path.parent.mkdir(parents=True, exist_ok=True)\n```", "response": " payload = {\"mood\": self.mood.to_dict(), \"saved\": time.time()}\n self.state_path.write_text(json.dumps(payload, ensure_ascii=False, indent=1),\n encoding=\"utf-8\")", "source_file": "chat_engine.py", "function_name": "_save", "class_name": "ChatEngine", "line_start": 195, "line_end": 200, "license": "mit", "source": "SadikAI project"}
{"task": "code_completion", "language": "python", "instruction": "Complete the following Python code. Return only the continuation, preserving indentation.\n\n```python\n def respond(self, text: str) -> Reply:\n text = \" \".join(text.split()).strip()\n if not text:\n raise ValueError(\"empty message\")\n\n emotion = detect(text)\n self.mood.update(emotion)\n self.memory.remember_turn(text, emotion.label)\n messages_before = [e.text for e in self.memory.entries\n if e.kind == \"turn\" and e.text != text]\n recalled = self._recall(text, messages_before)\n\n low = text.lower()\n reply: Reply\n```", "response": " if low.startswith(\"/learn\"):\n reply = self._learn_reply(text)\n elif low in {\"/topics\", \"topics\", \"/learn topics\"}:\n reply = Reply(text=list_topics(), mode=\"learn\")\n elif low in {\"/about\", \"/creator\", \"/about me\"}:\n reply = self._creator_reply(emotion)\n elif self._is_run_request(text):\n reply = self._run_reply(text)\n elif self._matches(low, TIME_QUESTIONS):\n reply = self._time_reply(emotion)\n elif (calculation := solve_math(text)) is not None:\n reply = Reply(text=calculation, mode=\"math\")\n elif self._matches(low, CREATOR_QUESTIONS):\n reply = self._creator_reply(emotion)\n elif self._matches(low, IDENTITY_QUESTIONS):\n reply = self._identity_reply(emotion)\n elif self._matches(low, CAPABILITY_QUESTIONS):\n reply = self._capability_reply(emotion)\n elif self._matches(low, MEMORY_QUESTIONS):\n reply = self._memory_reply(emotion, recalled)\n elif (media_request := media.parse_media_request(text)) is not None:\n reply = self._media_reply(media_request, text)\n elif (snippet := answer_code(text)) is not None:\n reply = Reply(text=snippet, mode=\"code\")\n elif (lesson := answer_knowledge(text)) is not None:\n reply = Reply(text=lesson, mode=\"learn\")\n elif any(h in low for h in WEATHER_HINTS):\n reply = self._weather_reply(text, emotion)\n elif self.web and needs_search(text):\n reply = self._web_reply(text, emotion)\n elif is_greeting(text):\n reply = self._greeting_reply(emotion)\n elif _creative_hit(low):\n reply = self._creative_reply(text, emotion)\n elif emotion.label != \"neutral\" and emotion.confidence >= 0.18:\n reply = self._empathy_reply(text, emotion, recalled)\n else:\n reply = self._free_reply(text, emotion, recalled)\n\n reply.emotion = emotion.to_dict()\n reply.mood = {**self.mood.to_dict(), \"label\": self.mood.label()}\n self._save()\n return reply", "source_file": "chat_engine.py", "function_name": "respond", "class_name": "ChatEngine", "line_start": 203, "line_end": 260, "license": "mit", "source": "SadikAI project"}
{"task": "code_completion", "language": "python", "instruction": "Complete the following Python code. Return only the continuation, preserving indentation.\n\n```python\n def _recall(self, text: str, before: list[str]) -> list:\n hits = self.memory.recall(text, k=4)\n out = []\n```", "response": " for entry, score in hits:\n if entry.text == text or entry.kind == \"fact\":\n continue\n if entry.text in before:\n out.append((entry, score))\n return out[:2]", "source_file": "chat_engine.py", "function_name": "_recall", "class_name": "ChatEngine", "line_start": 263, "line_end": 271, "license": "mit", "source": "SadikAI project"}
{"task": "code_completion", "language": "python", "instruction": "Complete the following Python code. Return only the continuation, preserving indentation.\n\n```python\n def _memory_reply(self, emotion: Emotion, recalled: list) -> Reply:\n profile = self.memory.profile()\n stats = self.memory.stats()\n if not profile and not recalled:\n return Reply(\n text=\"I don't know much about you yet. Tell me your name — say \"\n \"'my name is ...' — and I'll keep it for next time.\",\n mode=\"memory\",\n )\n```", "response": " sentences: list[str] = []\n if profile:\n sentences.append(\"Here's what I remember: \" + _profile_sentence(profile) + \".\")\n if recalled:\n lines = \"; \".join(f\"“{_clip(e.text, 90)}”\" for e, _ in recalled)\n sentences.append(f\"I also remember you saying {lines}.\")\n sentences.append(f\"({stats['turns']} messages and {stats['facts']} facts stored \"\n f\"on this PC.)\")\n return Reply(text=\" \".join(sentences), mode=\"memory\",\n memories=[e.text for e, _ in recalled])", "source_file": "chat_engine.py", "function_name": "_memory_reply", "class_name": "ChatEngine", "line_start": 277, "line_end": 296, "license": "mit", "source": "SadikAI project"}
{"task": "code_completion", "language": "python", "instruction": "Complete the following Python code. Return only the continuation, preserving indentation.\n\n```python\n def _web_reply(self, text: str, emotion: Emotion) -> Reply:\n results = search(text)\n if not results:\n return Reply(\n text=\"I looked, but couldn't find a clear answer. Try naming the \"\n \"thing more specifically — for example 'who is Ada Lovelace' \"\n \"instead of 'that person'.\",\n mode=\"web-miss\",\n note=\"web search returned nothing\",\n )\n top = results[0]\n```", "response": " snippet = _two_sentences(top.snippet)\n lead = WEB_LEAD.get(emotion.label, WEB_LEAD[\"neutral\"])\n text_out = f\"{lead}{snippet}\"\n if len(results) > 1 and results[1].title.lower() != top.title.lower():\n text_out += f\" I also saw something about {results[1].title}.\"\n return Reply(\n text=text_out,\n mode=\"web\",\n sources=[{\"title\": r.title, \"url\": r.url, \"source\": r.source}\n for r in results[:3]],\n note=f\"checked {top.source}\",\n )", "source_file": "chat_engine.py", "function_name": "_web_reply", "class_name": "ChatEngine", "line_start": 384, "line_end": 406, "license": "mit", "source": "SadikAI project"}
{"task": "code_completion", "language": "python", "instruction": "Complete the following Python code. Return only the continuation, preserving indentation.\n\n```python\n def _weather_reply(self, text: str, emotion: Emotion) -> Reply:\n city = _extract_city(text)\n if not city:\n return Reply(text=\"Which city? Say something like 'weather in Delhi' \"\n \"or 'Mumbai ka mausam'.\",\n mode=\"weather\", note=\"no city in query\")\n result = weather(city)\n```", "response": " if result is None:\n return Reply(text=f\"I couldn't reach the weather service for {city}. \"\n \"Check the spelling, or try again in a minute.\",\n mode=\"weather-miss\")\n return Reply(text=result.snippet, mode=\"weather\",\n sources=[{\"title\": result.title, \"url\": result.url,\n \"source\": result.source}],\n note=result.source)", "source_file": "chat_engine.py", "function_name": "_weather_reply", "class_name": "ChatEngine", "line_start": 408, "line_end": 422, "license": "mit", "source": "SadikAI project"}
{"task": "code_completion", "language": "python", "instruction": "Complete the following Python code. Return only the continuation, preserving indentation.\n\n```python\n def _identity_reply(self, emotion: Emotion) -> Reply:\n who = self.memory.profile().get(\"name\")\n hello = f\"Hi {who}. \" if who else \"\"\n```", "response": " return Reply(\n text=f\"{hello}I'm {MODEL_NAME} — a {PARAMS}-parameter local language \"\n f\"model made by {CREATOR_NAME} ({CREATOR_AGE}, {CREATOR_GRADE}). I was \"\n f\"trained here on English, Hindi, Hinglish and code. I have persistent \"\n f\"memory, a web lookup, a mood, offline lessons and a small story \"\n f\"library. My weights are small, so the memory, search and lesson \"\n f\"layers do most of the thinking.\",\n mode=\"identity\",\n )", "source_file": "chat_engine.py", "function_name": "_identity_reply", "class_name": "ChatEngine", "line_start": 432, "line_end": 443, "license": "mit", "source": "SadikAI project"}
{"task": "code_completion", "language": "python", "instruction": "Complete the following Python code. Return only the continuation, preserving indentation.\n\n```python\n def _learn_reply(self, text: str) -> Reply:\n topic = text[len(\"/learn\"):].strip(\" :—-\")\n if not topic:\n return Reply(text=list_topics(), mode=\"learn\")\n lesson = answer_knowledge(topic)\n if lesson is None:\n lesson = answer_knowledge(f\"teach me about {topic}\")\n```", "response": " if lesson is None:\n return Reply(\n text=f\"I don't have a lesson on '{topic}' yet. Try one of these:\\n\\n\"\n + list_topics(),\n mode=\"learn\",\n )\n return Reply(text=lesson, mode=\"learn\")", "source_file": "chat_engine.py", "function_name": "_learn_reply", "class_name": "ChatEngine", "line_start": 473, "line_end": 486, "license": "mit", "source": "SadikAI project"}
{"task": "code_completion", "language": "python", "instruction": "Complete the following Python code. Return only the continuation, preserving indentation.\n\n```python\n def _run_reply(self, text: str) -> Reply:\n language, code = extract_code(text)\n if not code.strip():\n return Reply(\n text=\"Paste the code after /run, or send it in a ``` block.\\n\"\n \"Example: /run print(2 + 2)\",\n mode=\"run\",\n )\n```", "response": " result = run_code(code, language)\n return Reply(text=format_result(result), mode=\"run\",\n note=\"executed locally with an 8s timeout\")", "source_file": "chat_engine.py", "function_name": "_run_reply", "class_name": "ChatEngine", "line_start": 496, "line_end": 506, "license": "mit", "source": "SadikAI project"}
{"task": "code_completion", "language": "python", "instruction": "Complete the following Python code. Return only the continuation, preserving indentation.\n\n```python\n def _greeting_reply(self, emotion: Emotion) -> Reply:\n name = self.memory.profile().get(\"name\")\n who = f\" {name}\" if name else \"\"\n mood = self.mood.label()\n```", "response": " opener = self.rng.choice([\"Hey\", \"Hello\", \"Hi\"])\n return Reply(\n text=f\"{opener}{who}. I'm feeling {mood} right now — what's on your mind?\",\n mode=\"greeting\",\n )", "source_file": "chat_engine.py", "function_name": "_greeting_reply", "class_name": "ChatEngine", "line_start": 508, "line_end": 516, "license": "mit", "source": "SadikAI project"}
{"task": "code_completion", "language": "python", "instruction": "Complete the following Python code. Return only the continuation, preserving indentation.\n\n```python\n def _empathy_reply(self, text: str, emotion: Emotion,\n recalled: list) -> Reply:\n head = self.rng.choice(EMPATHY.get(emotion.label, EMPATHY[\"neutral\"]))\n tail = self.rng.choice(FOLLOWUP.get(emotion.label, FOLLOWUP[\"neutral\"]))\n parts = [head]\n```", "response": " if recalled:\n parts.append(f\"Earlier you mentioned “{_clip(recalled[0][0].text, 80)}” — \"\n f\"is this connected?\")\n elif 2 <= len(text.split()) <= 8 and emotion.label in {\"joy\", \"love\"}:\n parts.append(f\"“{text.rstrip('!.?')}” — that's a good line.\")\n parts.append(tail)\n return Reply(text=\" \".join(parts), mode=\"empathy\",\n memories=[e.text for e, _ in recalled])", "source_file": "chat_engine.py", "function_name": "_empathy_reply", "class_name": "ChatEngine", "line_start": 518, "line_end": 530, "license": "mit", "source": "SadikAI project"}
{"task": "code_completion", "language": "python", "instruction": "Complete the following Python code. Return only the continuation, preserving indentation.\n\n```python\n def _free_reply(self, text: str, emotion: Emotion, recalled: list) -> Reply:\n if self.use_model and len(text.split()) >= 12:\n generated = self._generate(text, max_new_tokens=45)\n if generated and _usable(generated, text):\n return Reply(text=_finish(generated), mode=\"model\",\n note=\"continued by the SadikAI Medium LM\")\n```", "response": " if recalled:\n return Reply(\n text=f\"“{_clip(recalled[0][0].text, 80)}” — that connects to what \"\n f\"you just said. Tell me more.\",\n mode=\"memory-chat\",\n memories=[e.text for e, _ in recalled],\n )\n return Reply(text=self.rng.choice(FOLLOWUP[\"neutral\"]), mode=\"chat\")", "source_file": "chat_engine.py", "function_name": "_free_reply", "class_name": "ChatEngine", "line_start": 532, "line_end": 546, "license": "mit", "source": "SadikAI project"}
{"task": "code_completion", "language": "python", "instruction": "Complete the following Python code. Return only the continuation, preserving indentation.\n\n```python\n def _creative_reply(self, text: str, emotion: Emotion) -> Reply:\n tale = answer_tale(text, self.memory.profile().get(\"name\"))\n if tale is not None:\n return Reply(text=tale, mode=\"story\",\n note=\"curated story from SadikAI's library\")\n\n if not self.use_model or self.model is None or self.tok is None:\n return Reply(text=\"My language model isn't loaded, so I can't write \"\n \"that right now.\", mode=\"creative-off\")\n\n low = text.lower()\n```", "response": " prompt, seed_text = _creative_seed(text, low)\n generated = self._generate(prompt, max_new_tokens=90,\n temperature=max(0.7, self.mood.temperature()))\n if not generated or not _usable(generated, prompt):\n return Reply(\n text=\"My 7.9M brain lost the thread on that one. Give me a smaller \"\n \"prompt — 'write a story about a dog' works better than a long \"\n \"brief.\",\n mode=\"creative-miss\",\n )\n body = _finish(generated)\n return Reply(text=(seed_text + body).strip(), mode=\"creative\",\n note=\"generated by the SadikAI Medium LM\")", "source_file": "chat_engine.py", "function_name": "_creative_reply", "class_name": "ChatEngine", "line_start": 548, "line_end": 571, "license": "mit", "source": "SadikAI project"}
{"task": "code_completion", "language": "python", "instruction": "Complete the following Python code. Return only the continuation, preserving indentation.\n\n```python\n def _generate(self, prompt: str, max_new_tokens: int = 60,\n temperature: float | None = None) -> str:\n assert self.model is not None and self.tok is not None\n ids = self.tok.encode(prompt) if prompt else [self.tok.eos_id]\n room = self.model.cfg.block_size - max_new_tokens - 2\n if room > 0 and len(ids) > room:\n ids = ids[-room:]\n x = torch.tensor([ids], dtype=torch.long, device=self.device)\n```", "response": " with torch.no_grad():\n out = self.model.generate(\n x,\n max_new_tokens=max_new_tokens,\n temperature=temperature if temperature is not None else self.mood.temperature(),\n top_k=50,\n top_p=0.92,\n repetition_penalty=1.18,\n eos_id=self.tok.eos_id,\n stop_at_eos=True,\n )\n return self.tok.decode(out[0, len(ids):].tolist())", "source_file": "chat_engine.py", "function_name": "_generate", "class_name": "ChatEngine", "line_start": 574, "line_end": 593, "license": "mit", "source": "SadikAI project"}
{"task": "code_completion", "language": "python", "instruction": "Complete the following Python code. Return only the continuation, preserving indentation.\n\n```python\ndef _profile_sentence(profile: dict[str, str]) -> str:\n parts: list[str] = []\n name = profile.get(\"name\")\n if name:\n parts.append(f\"you're {name}\")\n if profile.get(\"age\"):\n parts.append(f\"{profile['age']} years old\")\n if profile.get(\"city\"):\n parts.append(f\"based in {profile['city']}\")\n sentence = \", \".join(parts)\n```", "response": " extras: list[str] = []\n if profile.get(\"likes\"):\n extras.append(f\"you like {profile['likes']}\")\n if profile.get(\"dislikes\"):\n extras.append(f\"you don't like {profile['dislikes']}\")\n if profile.get(\"work\"):\n extras.append(f\"you work as {profile['work']}\")\n if profile.get(\"goal\"):\n extras.append(f\"you want to {profile['goal']}\")\n if extras:\n sentence += (\". \" if sentence else \"I know \") + \" and \".join(extras)\n return sentence or \"we haven't talked much yet\"", "source_file": "chat_engine.py", "function_name": "_profile_sentence", "class_name": null, "line_start": 603, "line_end": 624, "license": "mit", "source": "SadikAI project"}
{"task": "code_completion", "language": "python", "instruction": "Complete the following Python code. Return only the continuation, preserving indentation.\n\n```python\ndef _extract_city(text: str) -> str:\n lower = \" \".join(text.lower().split())\n for hint in WEATHER_HINTS:\n lower = lower.replace(hint, \" \")\n```", "response": " lower = re.sub(r\"\\b(what|whats|what's|is|the|in|at|of|today|tomorrow|now|\"\n r\"kya|hai|ka|ki|ke|mein|me|aaj|kal|batao|please|tell|me)\\b\",\n \" \", lower)\n words = [w for w in re.findall(r\"[A-Za-z\\u0900-\\u097F]+\", lower) if len(w) > 1]\n return \" \".join(words[:3]).strip()", "source_file": "chat_engine.py", "function_name": "_extract_city", "class_name": null, "line_start": 627, "line_end": 635, "license": "mit", "source": "SadikAI project"}
{"task": "code_completion", "language": "python", "instruction": "Complete the following Python code. Return only the continuation, preserving indentation.\n\n```python\ndef _creative_hit(low: str) -> bool:\n \"\"\"True for a real story/poem/code-generation ask.\n\n Plain substring matching would treat \"history\" as \"story\", so word-shaped\n hints use boundaries and inflections are listed explicitly.\n \"\"\"\n```", "response": " if re.search(\n r\"\\b(story|stories|poem|poems|program|programs|programming|script|\"\n r\"scripts|function|functions|algorithm|algorithms)\\b\", low):\n return True\n return any(phrase in low for phrase in (\n \"write me\", \"write a\", \"code for\", \"kahani\", \"kavita\", \"shayari\",\n \"कहानी\", \"कविता\", \"शायरी\", \"likho\", \"sunao\", \"banao\",\n ))", "source_file": "chat_engine.py", "function_name": "_creative_hit", "class_name": null, "line_start": 638, "line_end": 651, "license": "mit", "source": "SadikAI project"}
{"task": "code_explanation", "language": "python", "instruction": "Explain what this Python function does.\n\n```python\ndef _creative_hit(low: str) -> bool:\n \"\"\"True for a real story/poem/code-generation ask.\n\n Plain substring matching would treat \"history\" as \"story\", so word-shaped\n hints use boundaries and inflections are listed explicitly.\n \"\"\"\n if re.search(\n r\"\\b(story|stories|poem|poems|program|programs|programming|script|\"\n r\"scripts|function|functions|algorithm|algorithms)\\b\", low):\n return True\n return any(phrase in low for phrase in (\n \"write me\", \"write a\", \"code for\", \"kahani\", \"kavita\", \"shayari\",\n \"कहानी\", \"कविता\", \"शायरी\", \"likho\", \"sunao\", \"banao\",\n ))\n```", "response": "True for a real story/poem/code-generation ask.", "source_file": "chat_engine.py", "function_name": "_creative_hit", "class_name": null, "line_start": 638, "line_end": 651, "license": "mit", "source": "SadikAI project"}
{"task": "code_generation", "language": "python", "instruction": "Write a Python function `_creative_hit(low: str)` that does the following:\n\nTrue for a real story/poem/code-generation ask.\n\nReturn only the Python code.", "response": "def _creative_hit(low: str) -> bool:\n \"\"\"True for a real story/poem/code-generation ask.\n\n Plain substring matching would treat \"history\" as \"story\", so word-shaped\n hints use boundaries and inflections are listed explicitly.\n \"\"\"\n if re.search(\n r\"\\b(story|stories|poem|poems|program|programs|programming|script|\"\n r\"scripts|function|functions|algorithm|algorithms)\\b\", low):\n return True\n return any(phrase in low for phrase in (\n \"write me\", \"write a\", \"code for\", \"kahani\", \"kavita\", \"shayari\",\n \"कहानी\", \"कविता\", \"शायरी\", \"likho\", \"sunao\", \"banao\",\n ))", "source_file": "chat_engine.py", "function_name": "_creative_hit", "class_name": null, "line_start": 638, "line_end": 651, "license": "mit", "source": "SadikAI project"}
{"task": "code_completion", "language": "python", "instruction": "Complete the following Python code. Return only the continuation, preserving indentation.\n\n```python\ndef _creative_seed(text: str, low: str) -> tuple[str, str]:\n if \"code\" in low or \"function\" in low or \"program\" in low or \"script\" in low:\n return \"def \", \"\"\n if \"shayari\" in low or \"शायरी\" in low or \"poem\" in low or \"kavita\" in low:\n if re.search(r\"[\\u0900-\\u097F]\", text):\n return \"जिंदगी\", \"\"\n return \"The road at dusk\", \"\\n\"\n```", "response": " if re.search(r\"[\\u0900-\\u097F]\", text):\n return \"एक समय की बात है\", \"\"\n if \"kahani\" in low or \"story\" in low:\n return \"Once upon a time\", \"\"\n return text[:200], \"\"", "source_file": "chat_engine.py", "function_name": "_creative_seed", "class_name": null, "line_start": 654, "line_end": 665, "license": "mit", "source": "SadikAI project"}
{"task": "code_completion", "language": "python", "instruction": "Complete the following Python code. Return only the continuation, preserving indentation.\n\n```python\ndef _two_sentences(text: str) -> str:\n text = \" \".join(text.split())\n parts = re.split(r\"(?<=[.!?।])\\s+\", text)\n```", "response": " out = \" \".join(parts[:2]).strip()\n return _clip(out, 360)", "source_file": "chat_engine.py", "function_name": "_two_sentences", "class_name": null, "line_start": 668, "line_end": 672, "license": "mit", "source": "SadikAI project"}
{"task": "code_completion", "language": "python", "instruction": "Complete the following Python code. Return only the continuation, preserving indentation.\n\n```python\ndef _clip(text: str, limit: int) -> str:\n text = \" \".join(text.split())\n if len(text) <= limit:\n return text\n```", "response": " cut = text[:limit]\n if \" \" in cut:\n cut = cut.rsplit(\" \", 1)[0]\n return cut + \"…\"", "source_file": "chat_engine.py", "function_name": "_clip", "class_name": null, "line_start": 675, "line_end": 682, "license": "mit", "source": "SadikAI project"}
{"task": "code_completion", "language": "python", "instruction": "Complete the following Python code. Return only the continuation, preserving indentation.\n\n```python\ndef _finish(text: str) -> str:\n text = text.replace(\"<|endoftext|>\", \" \").replace(\"<|pad|>\", \" \")\n text = \" \".join(text.split())\n```", "response": " if not text:\n return text\n if text[-1] not in \".!?।\\\"'”’\":\n text += \".\"\n return text[0].upper() + text[1:] if text[0].isalpha() else text", "source_file": "chat_engine.py", "function_name": "_finish", "class_name": null, "line_start": 685, "line_end": 692, "license": "mit", "source": "SadikAI project"}
{"task": "code_completion", "language": "python", "instruction": "Complete the following Python code. Return only the continuation, preserving indentation.\n\n```python\ndef _usable(text: str, prompt: str) -> bool:\n words = text.split()\n if len(words) < 4:\n return False\n letters = sum(ch.isalpha() or ch.isspace() or ch in \".,!?;:'\\\"-—\" for ch in text)\n if letters / max(1, len(text)) < 0.82:\n return False\n lowered = [w.lower().strip(\".,!?;:\\\"'\") for w in words]\n```", "response": " if len(set(lowered)) / max(1, len(lowered)) < 0.35:\n return False\n trigrams = Counter(tuple(lowered[i:i + 3]) for i in range(len(lowered) - 2))\n if trigrams and max(trigrams.values()) >= 3:\n return False\n prompt_words = set(prompt.lower().split())\n if prompt_words and len(prompt_words & set(lowered)) / len(lowered) > 0.7:\n return False\n return True", "source_file": "chat_engine.py", "function_name": "_usable", "class_name": null, "line_start": 695, "line_end": 711, "license": "mit", "source": "SadikAI project"}
{"task": "code_completion", "language": "python", "instruction": "Complete the following Python code. Return only the continuation, preserving indentation.\n\n```python\n def _send(self, code: int, body: bytes, ctype: str) -> None:\n self.send_response(code)\n self.send_header(\"Content-Type\", ctype)\n```", "response": " self.send_header(\"Content-Length\", str(len(body)))\n self.send_header(\"Cache-Control\", \"no-store\")\n self.end_headers()\n self.wfile.write(body)", "source_file": "chat_server.py", "function_name": "_send", "class_name": "Handler", "line_start": 499, "line_end": 505, "license": "mit", "source": "SadikAI project"}
{"task": "code_completion", "language": "python", "instruction": "Complete the following Python code. Return only the continuation, preserving indentation.\n\n```python\n def do_GET(self) -> None: # noqa: N802\n path = urlparse(self.path).path\n if path in (\"/\", \"/index.html\"):\n self._send(200, PAGE.encode(\"utf-8\"), \"text/html; charset=utf-8\")\n return\n if path == \"/api/state\":\n assert ENGINE is not None\n self._json(200, {\n \"mood\": {**ENGINE.mood.to_dict(), \"label\": ENGINE.mood.label()},\n \"profile\": ENGINE.memory.profile(),\n \"stats\": ENGINE.memory.stats(),\n \"web\": ENGINE.web,\n \"model\": ENGINE.use_model,\n \"step\": ENGINE.model_step,\n })\n return\n```", "response": " if path.startswith(\"/files/\"):\n relative = unquote(path[len(\"/files/\"):])\n target = (GENERATED / relative).resolve()\n if GENERATED != target and GENERATED not in target.parents:\n self._json(404, {\"error\": \"not found\"})\n return\n if not target.is_file():\n self._json(404, {\"error\": \"not found\"})\n return\n ctype = mimetypes.guess_type(target.name)[0] or \"application/octet-stream\"\n try:\n body = target.read_bytes()\n except OSError:\n self._json(404, {\"error\": \"not found\"})\n return\n self._send(200, body, ctype)\n return\n self._json(404, {\"error\": \"not found\"})", "source_file": "chat_server.py", "function_name": "do_GET", "class_name": "Handler", "line_start": 511, "line_end": 544, "license": "mit", "source": "SadikAI project"}
{"task": "code_completion", "language": "python", "instruction": "Complete the following Python code. Return only the continuation, preserving indentation.\n\n```python\n def do_POST(self) -> None: # noqa: N802\n path = urlparse(self.path).path\n length = int(self.headers.get(\"Content-Length\") or 0)\n raw = self.rfile.read(length) if length else b\"{}\"\n try:\n payload = json.loads(raw.decode(\"utf-8\"))\n except ValueError:\n self._json(400, {\"error\": \"bad json\"})\n return\n\n assert ENGINE is not None\n```", "response": " try:\n if path == \"/api/chat\":\n text = str(payload.get(\"text\", \"\")).strip()\n if not text:\n self._json(400, {\"error\": \"empty message\"})\n return\n with LOCK:\n ENGINE.web = bool(payload.get(\"web\", True))\n reply = ENGINE.respond(text)\n self._json(200, {**reply.to_dict(), \"stats\": ENGINE.memory.stats()})\n return\n if path == \"/api/reset\":\n with LOCK:\n ENGINE.reset()\n self._json(200, {\"ok\": True})\n return\n if path == \"/api/forget\":\n needle = str(payload.get(\"text\", \"\"))\n with LOCK:\n removed = ENGINE.memory.forget(needle)\n self._json(200, {\"removed\": removed})\n return\n self._json(404, {\"error\": \"not found\"})\n except Exception as exc: # never kill the server\n self._json(500, {\"error\": f\"{type(exc).__name__}: {exc}\"})", "source_file": "chat_server.py", "function_name": "do_POST", "class_name": "Handler", "line_start": 546, "line_end": 581, "license": "mit", "source": "SadikAI project"}
{"task": "code_completion", "language": "python", "instruction": "Complete the following Python code. Return only the continuation, preserving indentation.\n\n```python\ndef main() -> None:\n global ENGINE\n ap = argparse.ArgumentParser(description=__doc__,\n formatter_class=argparse.RawDescriptionHelpFormatter)\n ap.add_argument(\"--checkpoint\", default=\"runs/medium/best.pt\")\n ap.add_argument(\"--tokenizer\", default=\"tokenizer/tokenizer.json\")\n ap.add_argument(\"--memory\", default=\"data/chat/memory.json\")\n ap.add_argument(\"--state\", default=\"data/chat/state.json\")\n ap.add_argument(\"--device\", default=\"auto\")\n ap.add_argument(\"--host\", default=\"127.0.0.1\")\n ap.add_argument(\"--port\", type=int, default=8000)\n ap.add_argument(\"--no-web\", action=\"store_true\")\n ap.add_argument(\"--no-model\", action=\"store_true\")\n ap.add_argument(\"--open\", action=\"store_true\")\n args = ap.parse_args()\n```", "response": " ENGINE = ChatEngine(\n checkpoint=args.checkpoint,\n tokenizer=args.tokenizer,\n memory_path=Path(args.memory),\n state_path=Path(args.state),\n device=args.device,\n web=not args.no_web,\n use_model=not args.no_model,\n )\n\n server = ThreadingHTTPServer((args.host, args.port), Handler)\n url = f\"http://{args.host}:{args.port}\"\n print(f\"SadikAI Medium ready on {url}\")\n print(f\"web {'on' if ENGINE.web else 'off'} · model \"\n f\"{'on' if ENGINE.use_model else 'off'} · memory {ENGINE.memory.stats()['entries']} entries\")\n print(\"Ctrl+C to stop\")\n if args.open:\n threading.Timer(0.8, lambda: webbrowser.open(url)).start()\n try:\n server.serve_forever()\n except KeyboardInterrupt:\n print(\"\\nstopped\")\n finally:\n server.server_close()", "source_file": "chat_server.py", "function_name": "main", "class_name": null, "line_start": 584, "line_end": 623, "license": "mit", "source": "SadikAI project"}
{"task": "code_completion", "language": "python", "instruction": "Complete the following Python code. Return only the continuation, preserving indentation.\n\n```python\ndef _write(path: Path, docs) -> tuple[int, int]:\n path.parent.mkdir(parents=True, exist_ok=True)\n count = 0\n written = 0\n```", "response": " with path.open(\"w\", encoding=\"utf-8\", newline=\"\\n\") as fh:\n for text in docs:\n line = json.dumps({\"text\": text}, ensure_ascii=False) + \"\\n\"\n fh.write(line)\n written += len(line.encode(\"utf-8\"))\n count += 1\n print(f\" {path.name}: {count:,} docs, {written / MB:.2f} MB -> {path}\")\n return count, written", "source_file": "code_curriculum.py", "function_name": "_write", "class_name": null, "line_start": 36, "line_end": 47, "license": "mit", "source": "SadikAI project"}
{"task": "code_completion", "language": "python", "instruction": "Complete the following Python code. Return only the continuation, preserving indentation.\n\n```python\ndef _snippet_docs() -> list[str]:\n docs: list[str] = []\n english = [\n \"Write {lang} code for {topic}.\",\n \"Show me a {lang} example of {topic}.\",\n \"Give me {lang} code for {topic}.\",\n ]\n hinglish = [\n \"{topic} ka {lang} code likho.\",\n \"{lang} mein {topic} kaise karte hain?\",\n \"{topic} ke liye {lang} example do.\",\n ]\n```", "response": " for snippet in SNIPPETS:\n language = _pretty(snippet[\"language\"])\n topic = snippet[\"title\"].rstrip(\".!?\")\n lang_key = snippet[\"language\"].lower()\n\n for template in english[:3]:\n question = template.format(lang=language, topic=topic)\n docs.append(\n f\"Question: {question}\\n\"\n f\"Answer:\\n```{lang_key}\\n{snippet['code']}\\n```\\n\"\n f\"Explanation: {snippet['explain']}\\n\"\n )\n\n # A Hinglish prompt for every fourth snippet keeps the four-language mix.\n if len(docs) % 4 == 0:\n question = hinglish[len(docs) % len(hinglish)].format(\n lang=language, topic=topic)\n docs.append(\n f\"Question: {question}\\n\"\n f\"Answer:\\n```{lang_key}\\n{snippet['code']}\\n```\\n\"\n f\"Explanation: {snippet['explain']}\\n\"\n )\n\n docs.append(\n f\"Question: Explain this {language} code.\\n\"\n f\"Code:\\n```{lang_key}\\n{snippet['code']}\\n```\\n\"\n f\"Explanation: {snippet['explain']}\\n\"\n )\n\n if snippet.get(\"demo\"):\n docs.append(\n f\"Question: What is the output of this {language} code?\\n\"\n f\"```{lang_key}\\n{snippet['code']}\\n```\\n\"\n f\"Answer: {snippet['demo']}\\n\"\n )\n return docs", "source_file": "code_curriculum.py", "function_name": "_snippet_docs", "class_name": null, "line_start": 57, "line_end": 105, "license": "mit", "source": "SadikAI project"}
{"task": "code_completion", "language": "python", "instruction": "Complete the following Python code. Return only the continuation, preserving indentation.\n\n```python\ndef _trace_docs(limit: int = 4000) -> list[str]:\n \"\"\"Execution traces for the operations a small model can actually learn.\"\"\"\n docs: list[str] = []\n\n def add(question: str, answer: str, steps: str = \"\") -> None:\n body = f\"Question: {question}\\n\"\n if steps:\n body += f\"Solution:\\n{steps}\\n\"\n body += f\"Answer: {answer}\\n\"\n docs.append(body)\n\n for n in range(1, 31):\n seq = []\n a, b = 0, 1\n for _ in range(n):\n seq.append(str(a))\n a, b = b, a + b\n add(f\"What are the first {n} Fibonacci numbers?\",\n seq[-1] if n == 1 else \", \".join(seq),\n f\"Start with 0, 1; each next number is the sum of the previous two.\")\n if n <= 20:\n add(f\"What is fib({n})?\", str(seq[-1]),\n f\"The sequence starts {' '.join(seq[:min(n, 12)])}\")\n\n fact = 1\n for n in range(0, 13):\n if n:\n fact *= n\n add(f\"What is {n} factorial?\", str(fact),\n f\"Multiply 1 to {n}.\" if n else \"0! is 1 by definition.\")\n```", "response": " def is_prime(n: int) -> bool:\n if n < 2:\n return False\n for i in range(2, int(math.isqrt(n)) + 1):\n if n % i == 0:\n return False\n return True\n\n for n in range(1, 101):\n add(f\"Is {n} a prime number?\", \"Yes\" if is_prime(n) else \"No\",\n \"Test divisors up to the square root.\")\n\n for n in range(1, 31):\n add(f\"What is {n} squared?\", str(n * n), f\"{n} x {n} = {n * n}\")\n\n for table in range(2, 16):\n lines = [f\"{table} x {i} = {table * i}\" for i in range(1, 11)]\n add(f\"Write the multiplication table of {table}.\",\n f\"{table} x 10 = {table * 10}\", \"\\n\".join(lines))\n\n for g in [(12, 18), (24, 36), (7, 13), (40, 60), (9, 15), (100, 75)]:\n add(f\"What is the GCD of {g[0]} and {g[1]}?\",\n str(math.gcd(*g)), f\"gcd({g[0]}, {g[1]}) = {math.gcd(*g)}\")\n\n for c in range(-40, 101, 5):\n f = c * 9 / 5 + 32\n add(f\"Convert {c} degrees Celsius to Fahrenheit.\",\n f\"{f:g} F\", f\"{c} x 9/5 + 32 = {f:g}\")\n\n rng = random.Random(7)\n for _ in range(60):\n nums = [rng.randint(1, 100) for _ in range(rng.randint(3, 6))]\n total = sum(nums)\n add(f\"What is the sum of {', '.join(map(str, nums))}?\",\n str(total), f\"{' + '.join(map(str, nums))} = {total}\")\n\n return docs[:limit]", "source_file": "code_curriculum.py", "function_name": "_trace_docs", "class_name": null, "line_start": 108, "line_end": 175, "license": "mit", "source": "SadikAI project"}
{"task": "code_explanation", "language": "python", "instruction": "Explain what this Python function does.\n\n```python\ndef _trace_docs(limit: int = 4000) -> list[str]:\n \"\"\"Execution traces for the operations a small model can actually learn.\"\"\"\n docs: list[str] = []\n\n def add(question: str, answer: str, steps: str = \"\") -> None:\n body = f\"Question: {question}\\n\"\n if steps:\n body += f\"Solution:\\n{steps}\\n\"\n body += f\"Answer: {answer}\\n\"\n docs.append(body)\n\n for n in range(1, 31):\n seq = []\n a, b = 0, 1\n for _ in range(n):\n seq.append(str(a))\n a, b = b, a + b\n add(f\"What are the first {n} Fibonacci numbers?\",\n seq[-1] if n == 1 else \", \".join(seq),\n f\"Start with 0, 1; each next number is the sum of the previous two.\")\n if n <= 20:\n add(f\"What is fib({n})?\", str(seq[-1]),\n f\"The sequence starts {' '.join(seq[:min(n, 12)])}\")\n\n fact = 1\n for n in range(0, 13):\n if n:\n fact *= n\n add(f\"What is {n} factorial?\", str(fact),\n f\"Multiply 1 to {n}.\" if n else \"0! is 1 by definition.\")\n\n def is_prime(n: int) -> bool:\n if n < 2:\n return False\n for i in range(2, int(math.isqrt(n)) + 1):\n if n % i == 0:\n return False\n return True\n\n for n in range(1, 101):\n add(f\"Is {n} a prime number?\", \"Yes\" if is_prime(n) else \"No\",\n \"Test divisors up to the square root.\")\n\n for n in range(1, 31):\n add(f\"What is {n} squared?\", str(n * n), f\"{n} x {n} = {n * n}\")\n\n for table in range(2, 16):\n lines = [f\"{table} x {i} = {table * i}\" for i in range(1, 11)]\n add(f\"Write the multiplication table of {table}.\",\n f\"{table} x 10 = {table * 10}\", \"\\n\".join(lines))\n\n for g in [(12, 18), (24, 36), (7, 13), (40, 60), (9, 15), (100, 75)]:\n add(f\"What is the GCD of {g[0]} and {g[1]}?\",\n str(math.gcd(*g)), f\"gcd({g[0]}, {g[1]}) = {math.gcd(*g)}\")\n\n for c in range(-40, 101, 5):\n f = c * 9 / 5 + 32\n add(f\"Convert {c} degrees Celsius to Fahrenheit.\",\n f\"{f:g} F\", f\"{c} x 9/5 + 32 = {f:g}\")\n\n rng = random.Random(7)\n for _ in range(60):\n nums = [rng.randint(1, 100) for _ in range(rng.randint(3, 6))]\n total = sum(nums)\n add(f\"What is the sum of {', '.join(map(str, nums))}?\",\n str(total), f\"{' + '.join(map(str, nums))} = {total}\")\n\n return docs[:limit]\n```", "response": "Execution traces for the operations a small model can actually learn.", "source_file": "code_curriculum.py", "function_name": "_trace_docs", "class_name": null, "line_start": 108, "line_end": 175, "license": "mit", "source": "SadikAI project"}
{"task": "code_generation", "language": "python", "instruction": "Write a Python function `_trace_docs(limit: int=4000)` that does the following:\n\nExecution traces for the operations a small model can actually learn.\n\nReturn only the Python code.", "response": "def _trace_docs(limit: int = 4000) -> list[str]:\n \"\"\"Execution traces for the operations a small model can actually learn.\"\"\"\n docs: list[str] = []\n\n def add(question: str, answer: str, steps: str = \"\") -> None:\n body = f\"Question: {question}\\n\"\n if steps:\n body += f\"Solution:\\n{steps}\\n\"\n body += f\"Answer: {answer}\\n\"\n docs.append(body)\n\n for n in range(1, 31):\n seq = []\n a, b = 0, 1\n for _ in range(n):\n seq.append(str(a))\n a, b = b, a + b\n add(f\"What are the first {n} Fibonacci numbers?\",\n seq[-1] if n == 1 else \", \".join(seq),\n f\"Start with 0, 1; each next number is the sum of the previous two.\")\n if n <= 20:\n add(f\"What is fib({n})?\", str(seq[-1]),\n f\"The sequence starts {' '.join(seq[:min(n, 12)])}\")\n\n fact = 1\n for n in range(0, 13):\n if n:\n fact *= n\n add(f\"What is {n} factorial?\", str(fact),\n f\"Multiply 1 to {n}.\" if n else \"0! is 1 by definition.\")\n\n def is_prime(n: int) -> bool:\n if n < 2:\n return False\n for i in range(2, int(math.isqrt(n)) + 1):\n if n % i == 0:\n return False\n return True\n\n for n in range(1, 101):\n add(f\"Is {n} a prime number?\", \"Yes\" if is_prime(n) else \"No\",\n \"Test divisors up to the square root.\")\n\n for n in range(1, 31):\n add(f\"What is {n} squared?\", str(n * n), f\"{n} x {n} = {n * n}\")\n\n for table in range(2, 16):\n lines = [f\"{table} x {i} = {table * i}\" for i in range(1, 11)]\n add(f\"Write the multiplication table of {table}.\",\n f\"{table} x 10 = {table * 10}\", \"\\n\".join(lines))\n\n for g in [(12, 18), (24, 36), (7, 13), (40, 60), (9, 15), (100, 75)]:\n add(f\"What is the GCD of {g[0]} and {g[1]}?\",\n str(math.gcd(*g)), f\"gcd({g[0]}, {g[1]}) = {math.gcd(*g)}\")\n\n for c in range(-40, 101, 5):\n f = c * 9 / 5 + 32\n add(f\"Convert {c} degrees Celsius to Fahrenheit.\",\n f\"{f:g} F\", f\"{c} x 9/5 + 32 = {f:g}\")\n\n rng = random.Random(7)\n for _ in range(60):\n nums = [rng.randint(1, 100) for _ in range(rng.randint(3, 6))]\n total = sum(nums)\n add(f\"What is the sum of {', '.join(map(str, nums))}?\",\n str(total), f\"{' + '.join(map(str, nums))} = {total}\")\n\n return docs[:limit]", "source_file": "code_curriculum.py", "function_name": "_trace_docs", "class_name": null, "line_start": 108, "line_end": 175, "license": "mit", "source": "SadikAI project"}
{"task": "code_completion", "language": "python", "instruction": "Complete the following Python code. Return only the continuation, preserving indentation.\n\n```python\ndef _docstring_docs(stdlib: Path, limit: int, max_bytes: int) -> list[str]:\n docs: list[str] = []\n written = 0\n skip_parts = {\"test\", \"tests\", \"idlelib\", \"lib2to3\", \"tkinter\",\n \"site-packages\", \"__pycache__\"}\n```", "response": " for path in sorted(stdlib.rglob(\"*.py\")):\n if written >= max_bytes or len(docs) >= limit:\n break\n if any(part.lower() in skip_parts for part in path.parts):\n continue\n try:\n source = path.read_text(encoding=\"utf-8\", errors=\"ignore\")\n except OSError:\n continue\n if len(source) > 500_000:\n continue\n try:\n tree = ast.parse(source)\n except SyntaxError:\n continue\n\n for node in ast.walk(tree):\n if not isinstance(node, (ast.FunctionDef, ast.AsyncFunctionDef)):\n continue\n doc = ast.get_docstring(node, clean=True)\n if not doc:\n continue\n first = doc.strip().splitlines()[0].strip().rstrip(\".\")\n if not (20 <= len(first) <= 160):\n continue\n if first.lower().startswith((\"test \", \"internal\", \"deprecated\")):\n continue\n body = ast.unparse(node) if hasattr(ast, \"unparse\") else ast.get_source_segment(source, node)\n if not body or not (2 <= body.count(\"\\n\") <= 60):\n continue\n if len(body) > 2500:\n continue\n body = textwrap.dedent(body).strip()\n args = \", \".join(a.arg for a in node.args.args)\n rel = path.relative_to(stdlib).as_posix()\n docs.append(\n f\"Question: Write a Python function `{node.name}({args})` with \"\n f\"this docstring: \\\"{first}\\\".\\n\"\n f\"Answer:\\n```python\\n{body}\\n```\\nSource: {rel}\\n\"\n )\n written += len(docs[-1].encode(\"utf-8\"))\n if len(docs) >= limit or written >= max_bytes:\n break\n return docs", "source_file": "code_curriculum.py", "function_name": "_docstring_docs", "class_name": null, "line_start": 178, "line_end": 227, "license": "mit", "source": "SadikAI project"}
{"task": "code_completion", "language": "python", "instruction": "Complete the following Python code. Return only the continuation, preserving indentation.\n\n```python\ndef _source_docs(paths: list[Path], skip: set[str], cap: int) -> list[str]:\n docs: list[str] = []\n written = 0\n```", "response": " for root in paths:\n if not root.exists():\n continue\n for path in sorted(root.rglob(\"*\")):\n if written >= cap:\n return docs\n if not path.is_file() or path.suffix.lower() not in TEXT_SUFFIXES:\n continue\n if any(part.lower() in skip for part in path.parts):\n continue\n try:\n if path.stat().st_size > 300_000:\n continue\n text = path.read_text(encoding=\"utf-8\", errors=\"ignore\")\n except OSError:\n continue\n if len(text) < 400:\n continue\n marker = \"//\" if path.suffix.lower() in {\".js\", \".mjs\", \".cjs\", \".h\"} else \"#\"\n body = f\"{marker} {path.name}\\n{text}\"\n docs.append(body)\n written += len(body.encode(\"utf-8\"))\n return docs", "source_file": "code_curriculum.py", "function_name": "_source_docs", "class_name": null, "line_start": 230, "line_end": 255, "license": "mit", "source": "SadikAI project"}
{"task": "code_completion", "language": "python", "instruction": "Complete the following Python code. Return only the continuation, preserving indentation.\n\n```python\ndef main() -> None:\n if hasattr(sys.stdout, \"reconfigure\"):\n sys.stdout.reconfigure(encoding=\"utf-8\", errors=\"replace\")\n ap = argparse.ArgumentParser(description=__doc__,\n formatter_class=argparse.RawDescriptionHelpFormatter)\n ap.add_argument(\"--out\", default=\"data/raw/code\")\n ap.add_argument(\"--docstrings\", type=int, default=4000)\n ap.add_argument(\"--docstring-mb\", type=float, default=5.0)\n ap.add_argument(\"--js-mb\", type=float, default=6.0)\n ap.add_argument(\"--c-mb\", type=float, default=2.0)\n ap.add_argument(\"--skip-sources\", action=\"store_true\")\n args = ap.parse_args()\n\n out = Path(args.out)\n total_docs = 0\n total_bytes = 0\n\n snippet_docs = _snippet_docs() + _trace_docs()\n docs, size = _write(out / \"curriculum.jsonl\", snippet_docs)\n total_docs += docs\n total_bytes += size\n\n stdlib = Path(sysconfig.get_paths()[\"stdlib\"])\n```", "response": " doc_docs = _docstring_docs(stdlib, args.docstrings,\n int(args.docstring_mb * MB))\n docs, size = _write(out / \"stdlib.jsonl\", doc_docs)\n total_docs += docs\n total_bytes += size\n\n if not args.skip_sources:\n node = shutil.which(\"node\")\n js_roots = []\n if node:\n js_roots.append(Path(node).parent / \"node_modules\" / \"npm\")\n docs = _source_docs(js_roots, {\"test\", \"tests\", \"__pycache__\"},\n int(args.js_mb * MB))\n count, size = _write(out / \"javascript.jsonl\", docs)\n total_docs += count\n total_bytes += size\n\n include = Path(sysconfig.get_paths().get(\"include\", \"\"))\n docs = _source_docs([include], {\"__pycache__\"}, int(args.c_mb * MB))\n count, size = _write(out / \"c_headers.jsonl\", docs)\n total_docs += count\n total_bytes += size\n\n print(f\"\\ndone: {total_docs:,} code documents, {total_bytes / MB:.1f} MB\")\n print(\"next: python prepare_data.py --input data/raw --out-dir data/tokenized \"\n \"--mix configs/corpus_mix.json --overwrite\")", "source_file": "code_curriculum.py", "function_name": "main", "class_name": null, "line_start": 258, "line_end": 306, "license": "mit", "source": "SadikAI project"}
{"task": "code_completion", "language": "python", "instruction": "Complete the following Python code. Return only the continuation, preserving indentation.\n\n```python\ndef extract_code(text: str) -> tuple[str, str]:\n \"\"\"Return (language, code). Language is guessed when not supplied.\"\"\"\n fenced = FENCE.search(text)\n language = \"\"\n if fenced:\n language = (fenced.group(1) or \"\").lower()\n code = fenced.group(2)\n else:\n code = text\n for prefix in (\"/run\", \"run this code:\", \"run this:\", \"run:\"):\n stripped = code.lstrip()\n if stripped.lower().startswith(prefix):\n code = stripped[len(prefix):]\n break\n code = code.strip()\n```", "response": " if not language:\n low = code.lower()\n if \"console.log\" in low or \"function \" in low and \"=>\" in low:\n language = \"javascript\"\n elif \"#include\" in low:\n language = \"cpp\"\n elif low.lstrip().startswith((\"select \", \"insert \", \"update \", \"create \",\n \"drop \", \"alter \", \"with \", \"pragma \")):\n language = \"sql\"\n else:\n language = \"python\"\n\n if language in {\"js\", \"node\", \"nodejs\"}:\n language = \"javascript\"\n if language in {\"py\", \"python3\"}:\n language = \"python\"\n if language in {\"sqlite\", \"sqlite3\"}:\n language = \"sql\"\n return language, code.strip()", "source_file": "code_runner.py", "function_name": "extract_code", "class_name": null, "line_start": 34, "line_end": 68, "license": "mit", "source": "SadikAI project"}
{"task": "code_explanation", "language": "python", "instruction": "Explain what this Python function does.\n\n```python\ndef extract_code(text: str) -> tuple[str, str]:\n \"\"\"Return (language, code). Language is guessed when not supplied.\"\"\"\n fenced = FENCE.search(text)\n language = \"\"\n if fenced:\n language = (fenced.group(1) or \"\").lower()\n code = fenced.group(2)\n else:\n code = text\n for prefix in (\"/run\", \"run this code:\", \"run this:\", \"run:\"):\n stripped = code.lstrip()\n if stripped.lower().startswith(prefix):\n code = stripped[len(prefix):]\n break\n code = code.strip()\n\n if not language:\n low = code.lower()\n if \"console.log\" in low or \"function \" in low and \"=>\" in low:\n language = \"javascript\"\n elif \"#include\" in low:\n language = \"cpp\"\n elif low.lstrip().startswith((\"select \", \"insert \", \"update \", \"create \",\n \"drop \", \"alter \", \"with \", \"pragma \")):\n language = \"sql\"\n else:\n language = \"python\"\n\n if language in {\"js\", \"node\", \"nodejs\"}:\n language = \"javascript\"\n if language in {\"py\", \"python3\"}:\n language = \"python\"\n if language in {\"sqlite\", \"sqlite3\"}:\n language = \"sql\"\n return language, code.strip()\n```", "response": "Return (language, code). Language is guessed when not supplied.", "source_file": "code_runner.py", "function_name": "extract_code", "class_name": null, "line_start": 34, "line_end": 68, "license": "mit", "source": "SadikAI project"}
{"task": "code_generation", "language": "python", "instruction": "Write a Python function `extract_code(text: str)` that does the following:\n\nReturn (language, code). Language is guessed when not supplied.\n\nReturn only the Python code.", "response": "def extract_code(text: str) -> tuple[str, str]:\n \"\"\"Return (language, code). Language is guessed when not supplied.\"\"\"\n fenced = FENCE.search(text)\n language = \"\"\n if fenced:\n language = (fenced.group(1) or \"\").lower()\n code = fenced.group(2)\n else:\n code = text\n for prefix in (\"/run\", \"run this code:\", \"run this:\", \"run:\"):\n stripped = code.lstrip()\n if stripped.lower().startswith(prefix):\n code = stripped[len(prefix):]\n break\n code = code.strip()\n\n if not language:\n low = code.lower()\n if \"console.log\" in low or \"function \" in low and \"=>\" in low:\n language = \"javascript\"\n elif \"#include\" in low:\n language = \"cpp\"\n elif low.lstrip().startswith((\"select \", \"insert \", \"update \", \"create \",\n \"drop \", \"alter \", \"with \", \"pragma \")):\n language = \"sql\"\n else:\n language = \"python\"\n\n if language in {\"js\", \"node\", \"nodejs\"}:\n language = \"javascript\"\n if language in {\"py\", \"python3\"}:\n language = \"python\"\n if language in {\"sqlite\", \"sqlite3\"}:\n language = \"sql\"\n return language, code.strip()", "source_file": "code_runner.py", "function_name": "extract_code", "class_name": null, "line_start": 34, "line_end": 68, "license": "mit", "source": "SadikAI project"}
{"task": "code_completion", "language": "python", "instruction": "Complete the following Python code. Return only the continuation, preserving indentation.\n\n```python\ndef _split_sql(script: str) -> list[str]:\n \"\"\"Split a SQL script on semicolons, ignoring quoted strings and comments.\"\"\"\n statements: list[str] = []\n buffer: list[str] = []\n quote = \"\"\n i = 0\n```", "response": " while i < len(script):\n ch = script[i]\n if quote:\n buffer.append(ch)\n if ch == quote:\n if i + 1 < len(script) and script[i + 1] == quote:\n buffer.append(script[i + 1])\n i += 1\n else:\n quote = \"\"\n elif ch in {\"'\", '\"'}:\n quote = ch\n buffer.append(ch)\n elif script[i:i + 2] == \"--\":\n newline = script.find(\"\\n\", i)\n if newline == -1:\n break\n buffer.append(\" \")\n i = newline\n elif ch == \";\":\n statement = \"\".join(buffer).strip()\n if statement:\n statements.append(statement)\n buffer = []\n else:\n buffer.append(ch)\n i += 1\n last = \"\".join(buffer).strip()\n if last:\n statements.append(last)\n return statements", "source_file": "code_runner.py", "function_name": "_split_sql", "class_name": null, "line_start": 71, "line_end": 107, "license": "mit", "source": "SadikAI project"}
{"task": "code_explanation", "language": "python", "instruction": "Explain what this Python function does.\n\n```python\ndef _split_sql(script: str) -> list[str]:\n \"\"\"Split a SQL script on semicolons, ignoring quoted strings and comments.\"\"\"\n statements: list[str] = []\n buffer: list[str] = []\n quote = \"\"\n i = 0\n while i < len(script):\n ch = script[i]\n if quote:\n buffer.append(ch)\n if ch == quote:\n if i + 1 < len(script) and script[i + 1] == quote:\n buffer.append(script[i + 1])\n i += 1\n else:\n quote = \"\"\n elif ch in {\"'\", '\"'}:\n quote = ch\n buffer.append(ch)\n elif script[i:i + 2] == \"--\":\n newline = script.find(\"\\n\", i)\n if newline == -1:\n break\n buffer.append(\" \")\n i = newline\n elif ch == \";\":\n statement = \"\".join(buffer).strip()\n if statement:\n statements.append(statement)\n buffer = []\n else:\n buffer.append(ch)\n i += 1\n last = \"\".join(buffer).strip()\n if last:\n statements.append(last)\n return statements\n```", "response": "Split a SQL script on semicolons, ignoring quoted strings and comments.", "source_file": "code_runner.py", "function_name": "_split_sql", "class_name": null, "line_start": 71, "line_end": 107, "license": "mit", "source": "SadikAI project"}
{"task": "code_generation", "language": "python", "instruction": "Write a Python function `_split_sql(script: str)` that does the following:\n\nSplit a SQL script on semicolons, ignoring quoted strings and comments.\n\nReturn only the Python code.", "response": "def _split_sql(script: str) -> list[str]:\n \"\"\"Split a SQL script on semicolons, ignoring quoted strings and comments.\"\"\"\n statements: list[str] = []\n buffer: list[str] = []\n quote = \"\"\n i = 0\n while i < len(script):\n ch = script[i]\n if quote:\n buffer.append(ch)\n if ch == quote:\n if i + 1 < len(script) and script[i + 1] == quote:\n buffer.append(script[i + 1])\n i += 1\n else:\n quote = \"\"\n elif ch in {\"'\", '\"'}:\n quote = ch\n buffer.append(ch)\n elif script[i:i + 2] == \"--\":\n newline = script.find(\"\\n\", i)\n if newline == -1:\n break\n buffer.append(\" \")\n i = newline\n elif ch == \";\":\n statement = \"\".join(buffer).strip()\n if statement:\n statements.append(statement)\n buffer = []\n else:\n buffer.append(ch)\n i += 1\n last = \"\".join(buffer).strip()\n if last:\n statements.append(last)\n return statements", "source_file": "code_runner.py", "function_name": "_split_sql", "class_name": null, "line_start": 71, "line_end": 107, "license": "mit", "source": "SadikAI project"}
{"task": "code_completion", "language": "python", "instruction": "Complete the following Python code. Return only the continuation, preserving indentation.\n\n```python\ndef run_sql(code: str, timeout: float = 8.0) -> dict:\n \"\"\"Run a SQL script against a fresh in-memory SQLite database.\"\"\"\n connection = sqlite3.connect(\":memory:\")\n deadline = time.monotonic() + timeout\n expired = False\n\n def progress() -> int:\n nonlocal expired\n if time.monotonic() > deadline:\n expired = True\n return 1\n return 0\n\n connection.set_progress_handler(progress, 10_000)\n lines: list[str] = []\n```", "response": " try:\n for statement in _split_sql(code):\n cursor = connection.execute(statement)\n if cursor.description:\n columns = [d[0] for d in cursor.description]\n rows = cursor.fetchmany(200)\n lines.append(\" | \".join(columns))\n lines.append(\"-\" * min(60, max(8, len(lines[-1]))))\n for row in rows:\n lines.append(\" | \".join(\n \"NULL\" if value is None else str(value) for value in row))\n if len(rows) == 200:\n lines.append(\"… (showing the first 200 rows)\")\n connection.commit()\n except sqlite3.Error as exc:\n if expired:\n return {\"ok\": False,\n \"output\": f\"Stopped after {timeout:g}s (possible runaway query).\",\n \"language\": \"sql\"}\n return {\"ok\": False, \"output\": f\"SQL error: {exc}\", \"language\": \"sql\"}\n finally:\n connection.close()\n\n output = \"\\n\".join(lines).strip() or \"(no output)\"\n if len(output) > MAX_OUTPUT:\n output = output[:MAX_OUTPUT] + \"\\n… (output truncated)\"\n return {\"ok\": True, \"output\": output, \"language\": \"sql\"}", "source_file": "code_runner.py", "function_name": "run_sql", "class_name": null, "line_start": 110, "line_end": 151, "license": "mit", "source": "SadikAI project"}
{"task": "code_explanation", "language": "python", "instruction": "Explain what this Python function does.\n\n```python\ndef run_sql(code: str, timeout: float = 8.0) -> dict:\n \"\"\"Run a SQL script against a fresh in-memory SQLite database.\"\"\"\n connection = sqlite3.connect(\":memory:\")\n deadline = time.monotonic() + timeout\n expired = False\n\n def progress() -> int:\n nonlocal expired\n if time.monotonic() > deadline:\n expired = True\n return 1\n return 0\n\n connection.set_progress_handler(progress, 10_000)\n lines: list[str] = []\n try:\n for statement in _split_sql(code):\n cursor = connection.execute(statement)\n if cursor.description:\n columns = [d[0] for d in cursor.description]\n rows = cursor.fetchmany(200)\n lines.append(\" | \".join(columns))\n lines.append(\"-\" * min(60, max(8, len(lines[-1]))))\n for row in rows:\n lines.append(\" | \".join(\n \"NULL\" if value is None else str(value) for value in row))\n if len(rows) == 200:\n lines.append(\"… (showing the first 200 rows)\")\n connection.commit()\n except sqlite3.Error as exc:\n if expired:\n return {\"ok\": False,\n \"output\": f\"Stopped after {timeout:g}s (possible runaway query).\",\n \"language\": \"sql\"}\n return {\"ok\": False, \"output\": f\"SQL error: {exc}\", \"language\": \"sql\"}\n finally:\n connection.close()\n\n output = \"\\n\".join(lines).strip() or \"(no output)\"\n if len(output) > MAX_OUTPUT:\n output = output[:MAX_OUTPUT] + \"\\n… (output truncated)\"\n return {\"ok\": True, \"output\": output, \"language\": \"sql\"}\n```", "response": "Run a SQL script against a fresh in-memory SQLite database.", "source_file": "code_runner.py", "function_name": "run_sql", "class_name": null, "line_start": 110, "line_end": 151, "license": "mit", "source": "SadikAI project"}
{"task": "code_generation", "language": "python", "instruction": "Write a Python function `run_sql(code: str, timeout: float=8.0)` that does the following:\n\nRun a SQL script against a fresh in-memory SQLite database.\n\nReturn only the Python code.", "response": "def run_sql(code: str, timeout: float = 8.0) -> dict:\n \"\"\"Run a SQL script against a fresh in-memory SQLite database.\"\"\"\n connection = sqlite3.connect(\":memory:\")\n deadline = time.monotonic() + timeout\n expired = False\n\n def progress() -> int:\n nonlocal expired\n if time.monotonic() > deadline:\n expired = True\n return 1\n return 0\n\n connection.set_progress_handler(progress, 10_000)\n lines: list[str] = []\n try:\n for statement in _split_sql(code):\n cursor = connection.execute(statement)\n if cursor.description:\n columns = [d[0] for d in cursor.description]\n rows = cursor.fetchmany(200)\n lines.append(\" | \".join(columns))\n lines.append(\"-\" * min(60, max(8, len(lines[-1]))))\n for row in rows:\n lines.append(\" | \".join(\n \"NULL\" if value is None else str(value) for value in row))\n if len(rows) == 200:\n lines.append(\"… (showing the first 200 rows)\")\n connection.commit()\n except sqlite3.Error as exc:\n if expired:\n return {\"ok\": False,\n \"output\": f\"Stopped after {timeout:g}s (possible runaway query).\",\n \"language\": \"sql\"}\n return {\"ok\": False, \"output\": f\"SQL error: {exc}\", \"language\": \"sql\"}\n finally:\n connection.close()\n\n output = \"\\n\".join(lines).strip() or \"(no output)\"\n if len(output) > MAX_OUTPUT:\n output = output[:MAX_OUTPUT] + \"\\n… (output truncated)\"\n return {\"ok\": True, \"output\": output, \"language\": \"sql\"}", "source_file": "code_runner.py", "function_name": "run_sql", "class_name": null, "line_start": 110, "line_end": 151, "license": "mit", "source": "SadikAI project"}
{"task": "code_completion", "language": "python", "instruction": "Complete the following Python code. Return only the continuation, preserving indentation.\n\n```python\ndef run_code(code: str, language: str = \"python\", timeout: float = 8.0) -> dict:\n \"\"\"Execute code in a temporary directory. Returns {ok, output, language}.\"\"\"\n code = code.strip()\n if not code:\n return {\"ok\": False, \"output\": \"No code to run.\", \"language\": language}\n\n if language == \"sql\":\n return run_sql(code, timeout)\n if language == \"javascript\" and not shutil.which(\"node\"):\n return {\"ok\": False, \"output\": \"Node.js is not installed, so I cannot run JavaScript.\",\n \"language\": language}\n if language not in {\"python\", \"javascript\"}:\n return {\"ok\": False,\n \"output\": f\"I can run Python, JavaScript and SQL here, not {language}.\",\n \"language\": language}\n```", "response": " with tempfile.TemporaryDirectory(prefix=\"sadik_run_\") as tmp:\n suffix = \".py\" if language == \"python\" else \".js\"\n path = Path(tmp) / f\"snippet{suffix}\"\n path.write_text(code, encoding=\"utf-8\")\n command = [sys.executable, str(path)] if language == \"python\" else [\"node\", str(path)]\n env = {**os.environ, \"PYTHONIOENCODING\": \"utf-8\", \"PYTHONUTF8\": \"1\"}\n try:\n proc = subprocess.run(\n command, cwd=tmp, env=env, capture_output=True, text=True,\n encoding=\"utf-8\", errors=\"replace\", timeout=timeout,\n )\n except subprocess.TimeoutExpired:\n return {\"ok\": False, \"output\": f\"Stopped after {timeout:g}s (possible infinite loop).\",\n \"language\": language}\n\n output = (proc.stdout or \"\") + (proc.stderr or \"\")\n output = output.strip()\n if len(output) > MAX_OUTPUT:\n output = output[:MAX_OUTPUT] + \"\\n… (output truncated)\"\n if not output:\n output = \"(no output)\"\n return {\"ok\": proc.returncode == 0, \"output\": output, \"language\": language}", "source_file": "code_runner.py", "function_name": "run_code", "class_name": null, "line_start": 154, "line_end": 191, "license": "mit", "source": "SadikAI project"}
{"task": "code_explanation", "language": "python", "instruction": "Explain what this Python function does.\n\n```python\ndef run_code(code: str, language: str = \"python\", timeout: float = 8.0) -> dict:\n \"\"\"Execute code in a temporary directory. Returns {ok, output, language}.\"\"\"\n code = code.strip()\n if not code:\n return {\"ok\": False, \"output\": \"No code to run.\", \"language\": language}\n\n if language == \"sql\":\n return run_sql(code, timeout)\n if language == \"javascript\" and not shutil.which(\"node\"):\n return {\"ok\": False, \"output\": \"Node.js is not installed, so I cannot run JavaScript.\",\n \"language\": language}\n if language not in {\"python\", \"javascript\"}:\n return {\"ok\": False,\n \"output\": f\"I can run Python, JavaScript and SQL here, not {language}.\",\n \"language\": language}\n\n with tempfile.TemporaryDirectory(prefix=\"sadik_run_\") as tmp:\n suffix = \".py\" if language == \"python\" else \".js\"\n path = Path(tmp) / f\"snippet{suffix}\"\n path.write_text(code, encoding=\"utf-8\")\n command = [sys.executable, str(path)] if language == \"python\" else [\"node\", str(path)]\n env = {**os.environ, \"PYTHONIOENCODING\": \"utf-8\", \"PYTHONUTF8\": \"1\"}\n try:\n proc = subprocess.run(\n command, cwd=tmp, env=env, capture_output=True, text=True,\n encoding=\"utf-8\", errors=\"replace\", timeout=timeout,\n )\n except subprocess.TimeoutExpired:\n return {\"ok\": False, \"output\": f\"Stopped after {timeout:g}s (possible infinite loop).\",\n \"language\": language}\n\n output = (proc.stdout or \"\") + (proc.stderr or \"\")\n output = output.strip()\n if len(output) > MAX_OUTPUT:\n output = output[:MAX_OUTPUT] + \"\\n… (output truncated)\"\n if not output:\n output = \"(no output)\"\n return {\"ok\": proc.returncode == 0, \"output\": output, \"language\": language}\n```", "response": "Execute code in a temporary directory. Returns {ok, output, language}.", "source_file": "code_runner.py", "function_name": "run_code", "class_name": null, "line_start": 154, "line_end": 191, "license": "mit", "source": "SadikAI project"}
{"task": "code_generation", "language": "python", "instruction": "Write a Python function `run_code(code: str, language: str='python', timeout: float=8.0)` that does the following:\n\nExecute code in a temporary directory. Returns {ok, output, language}.\n\nReturn only the Python code.", "response": "def run_code(code: str, language: str = \"python\", timeout: float = 8.0) -> dict:\n \"\"\"Execute code in a temporary directory. Returns {ok, output, language}.\"\"\"\n code = code.strip()\n if not code:\n return {\"ok\": False, \"output\": \"No code to run.\", \"language\": language}\n\n if language == \"sql\":\n return run_sql(code, timeout)\n if language == \"javascript\" and not shutil.which(\"node\"):\n return {\"ok\": False, \"output\": \"Node.js is not installed, so I cannot run JavaScript.\",\n \"language\": language}\n if language not in {\"python\", \"javascript\"}:\n return {\"ok\": False,\n \"output\": f\"I can run Python, JavaScript and SQL here, not {language}.\",\n \"language\": language}\n\n with tempfile.TemporaryDirectory(prefix=\"sadik_run_\") as tmp:\n suffix = \".py\" if language == \"python\" else \".js\"\n path = Path(tmp) / f\"snippet{suffix}\"\n path.write_text(code, encoding=\"utf-8\")\n command = [sys.executable, str(path)] if language == \"python\" else [\"node\", str(path)]\n env = {**os.environ, \"PYTHONIOENCODING\": \"utf-8\", \"PYTHONUTF8\": \"1\"}\n try:\n proc = subprocess.run(\n command, cwd=tmp, env=env, capture_output=True, text=True,\n encoding=\"utf-8\", errors=\"replace\", timeout=timeout,\n )\n except subprocess.TimeoutExpired:\n return {\"ok\": False, \"output\": f\"Stopped after {timeout:g}s (possible infinite loop).\",\n \"language\": language}\n\n output = (proc.stdout or \"\") + (proc.stderr or \"\")\n output = output.strip()\n if len(output) > MAX_OUTPUT:\n output = output[:MAX_OUTPUT] + \"\\n… (output truncated)\"\n if not output:\n output = \"(no output)\"\n return {\"ok\": proc.returncode == 0, \"output\": output, \"language\": language}", "source_file": "code_runner.py", "function_name": "run_code", "class_name": null, "line_start": 154, "line_end": 191, "license": "mit", "source": "SadikAI project"}
{"task": "code_completion", "language": "python", "instruction": "Complete the following Python code. Return only the continuation, preserving indentation.\n\n```python\ndef format_result(result: dict) -> str:\n language = {\"python\": \"Python\", \"javascript\": \"JavaScript\", \"sql\": \"SQL\",\n \"cpp\": \"C++\", \"html\": \"HTML\", \"css\": \"CSS\",\n \"powershell\": \"PowerShell\"}.get(\n result[\"language\"], result[\"language\"])\n```", "response": " status = \"ran\" if result[\"ok\"] else \"failed\"\n return f\"Here's what {language} {status} on this PC:\\n\\n{result['output']}\"", "source_file": "code_runner.py", "function_name": "format_result", "class_name": null, "line_start": 194, "line_end": 200, "license": "mit", "source": "SadikAI project"}
{"task": "code_completion", "language": "python", "instruction": "Complete the following Python code. Return only the continuation, preserving indentation.\n\n```python\ndef main() -> None:\n ap = argparse.ArgumentParser(description=__doc__,\n formatter_class=argparse.RawDescriptionHelpFormatter)\n ap.add_argument(\"--code\", required=True)\n ap.add_argument(\"--language\", default=\"\")\n ap.add_argument(\"--timeout\", type=float, default=8.0)\n```", "response": " args = ap.parse_args()\n\n language, code = extract_code(args.code)\n if args.language:\n language = args.language.lower()\n result = run_code(code, language, args.timeout)\n print(format_result(result))", "source_file": "code_runner.py", "function_name": "main", "class_name": null, "line_start": 203, "line_end": 215, "license": "mit", "source": "SadikAI project"}
{"task": "code_completion", "language": "python", "instruction": "Complete the following Python code. Return only the continuation, preserving indentation.\n\n```python\ndef _iter_text_file(path: Path, chunk_chars: int = CHUNK_CHARS) -> Iterator[str]:\n \"\"\"Group lines into ~chunk_chars documents, preferring paragraph breaks.\"\"\"\n buf: list[str] = []\n size = 0\n```", "response": " with path.open(\"r\", encoding=\"utf-8\", errors=\"ignore\") as fh:\n for line in fh:\n buf.append(line)\n size += len(line)\n if size >= chunk_chars and not line.strip():\n doc = \"\".join(buf).strip()\n if doc:\n yield doc\n buf, size = [], 0\n elif size >= 4 * chunk_chars:\n doc = \"\".join(buf).strip()\n if doc:\n yield doc\n buf, size = [], 0\n if buf:\n doc = \"\".join(buf).strip()\n if doc:\n yield doc", "source_file": "data_sources.py", "function_name": "_iter_text_file", "class_name": null, "line_start": 48, "line_end": 69, "license": "mit", "source": "SadikAI project"}
{"task": "code_explanation", "language": "python", "instruction": "Explain what this Python function does.\n\n```python\ndef _iter_text_file(path: Path, chunk_chars: int = CHUNK_CHARS) -> Iterator[str]:\n \"\"\"Group lines into ~chunk_chars documents, preferring paragraph breaks.\"\"\"\n buf: list[str] = []\n size = 0\n with path.open(\"r\", encoding=\"utf-8\", errors=\"ignore\") as fh:\n for line in fh:\n buf.append(line)\n size += len(line)\n if size >= chunk_chars and not line.strip():\n doc = \"\".join(buf).strip()\n if doc:\n yield doc\n buf, size = [], 0\n elif size >= 4 * chunk_chars:\n doc = \"\".join(buf).strip()\n if doc:\n yield doc\n buf, size = [], 0\n if buf:\n doc = \"\".join(buf).strip()\n if doc:\n yield doc\n```", "response": "Group lines into ~chunk_chars documents, preferring paragraph breaks.", "source_file": "data_sources.py", "function_name": "_iter_text_file", "class_name": null, "line_start": 48, "line_end": 69, "license": "mit", "source": "SadikAI project"}
{"task": "code_generation", "language": "python", "instruction": "Write a Python function `_iter_text_file(path: Path, chunk_chars: int=CHUNK_CHARS)` that does the following:\n\nGroup lines into ~chunk_chars documents, preferring paragraph breaks.\n\nReturn only the Python code.", "response": "def _iter_text_file(path: Path, chunk_chars: int = CHUNK_CHARS) -> Iterator[str]:\n \"\"\"Group lines into ~chunk_chars documents, preferring paragraph breaks.\"\"\"\n buf: list[str] = []\n size = 0\n with path.open(\"r\", encoding=\"utf-8\", errors=\"ignore\") as fh:\n for line in fh:\n buf.append(line)\n size += len(line)\n if size >= chunk_chars and not line.strip():\n doc = \"\".join(buf).strip()\n if doc:\n yield doc\n buf, size = [], 0\n elif size >= 4 * chunk_chars:\n doc = \"\".join(buf).strip()\n if doc:\n yield doc\n buf, size = [], 0\n if buf:\n doc = \"\".join(buf).strip()\n if doc:\n yield doc", "source_file": "data_sources.py", "function_name": "_iter_text_file", "class_name": null, "line_start": 48, "line_end": 69, "license": "mit", "source": "SadikAI project"}
{"task": "code_completion", "language": "python", "instruction": "Complete the following Python code. Return only the continuation, preserving indentation.\n\n```python\ndef _iter_json_file(path: Path, text_key: str) -> Iterator[str]:\n try:\n with path.open(\"r\", encoding=\"utf-8\", errors=\"ignore\") as fh:\n data = json.load(fh)\n except json.JSONDecodeError:\n return\n```", "response": " items = data if isinstance(data, list) else [data]\n for obj in items:\n if isinstance(obj, str):\n yield obj\n elif isinstance(obj, dict) and isinstance(obj.get(text_key), str):\n yield obj[text_key]", "source_file": "data_sources.py", "function_name": "_iter_json_file", "class_name": null, "line_start": 96, "line_end": 107, "license": "mit", "source": "SadikAI project"}
{"task": "code_completion", "language": "python", "instruction": "Complete the following Python code. Return only the continuation, preserving indentation.\n\n```python\ndef _iter_files(root: Path, text_key: str) -> Iterator[str]:\n if root.is_file():\n files = [root]\n else:\n files = sorted(\n p for p in root.rglob(\"*\") if p.is_file() and p.suffix.lower() in TEXT_SUFFIXES\n )\n```", "response": " if not files:\n raise FileNotFoundError(\n f\"no text files found under {root!s} \"\n f\"(looked for {', '.join(sorted(TEXT_SUFFIXES))})\"\n )\n for path in files:\n suffix = path.suffix.lower()\n if suffix == \".jsonl\":\n yield from _iter_jsonl_file(path, text_key)\n elif suffix == \".json\":\n yield from _iter_json_file(path, text_key)\n else:\n yield from _iter_text_file(path)", "source_file": "data_sources.py", "function_name": "_iter_files", "class_name": null, "line_start": 110, "line_end": 129, "license": "mit", "source": "SadikAI project"}
{"task": "code_completion", "language": "python", "instruction": "Complete the following Python code. Return only the continuation, preserving indentation.\n\n```python\ndef _iter_hf(\n dataset: str,\n config: str | None,\n split: str,\n text_key: str,\n) -> Iterator[str]:\n try:\n from datasets import load_dataset\n except ImportError as exc: # pragma: no cover\n raise SystemExit(\n \"the 'datasets' package is required for --source hf:\\n pip install datasets\"\n ) from exc\n```", "response": " ds = load_dataset(dataset, config, split=split, streaming=True)\n for row in ds:\n if isinstance(row, dict):\n text = row.get(text_key)\n if isinstance(text, str) and text:\n yield text\n elif isinstance(row, str):\n yield row", "source_file": "data_sources.py", "function_name": "_iter_hf", "class_name": null, "line_start": 132, "line_end": 152, "license": "mit", "source": "SadikAI project"}
{"task": "code_explanation", "language": "python", "instruction": "Explain what this Python function does.\n\n```python\ndef _repeat_docs(path: Path, text_key: str, times: int) -> Iterator[str]:\n \"\"\"Yield a directory's documents `times` times (true oversampling).\"\"\"\n for _ in range(max(1, times)):\n yield from _iter_files(path, text_key)\n```", "response": "Yield a directory's documents `times` times (true oversampling).", "source_file": "data_sources.py", "function_name": "_repeat_docs", "class_name": null, "line_start": 155, "line_end": 158, "license": "mit", "source": "SadikAI project"}
{"task": "code_generation", "language": "python", "instruction": "Write a Python function `_repeat_docs(path: Path, text_key: str, times: int)` that does the following:\n\nYield a directory's documents `times` times (true oversampling).\n\nReturn only the Python code.", "response": "def _repeat_docs(path: Path, text_key: str, times: int) -> Iterator[str]:\n \"\"\"Yield a directory's documents `times` times (true oversampling).\"\"\"\n for _ in range(max(1, times)):\n yield from _iter_files(path, text_key)", "source_file": "data_sources.py", "function_name": "_repeat_docs", "class_name": null, "line_start": 155, "line_end": 158, "license": "mit", "source": "SadikAI project"}
{"task": "code_completion", "language": "python", "instruction": "Complete the following Python code. Return only the continuation, preserving indentation.\n\n```python\ndef iter_mixed_documents(\n root: str | Path,\n weights: dict[str, float],\n text_key: str = \"text\",\n max_bytes: int | None = None,\n) -> Iterator[str]:\n \"\"\"Interleave sub-directories of `root` and oversample them by weight.\n\n `weights` maps a directory name to a repeat count, e.g.\n ``{\"english\": 1, \"code\": 3, \"math\": 4}`` yields the whole code directory\n three times and maths four times, interleaved one document at a time.\n Interleaving keeps the packed shard mixed, which matters because\n `prepare_data.py` sends every N-th document to the validation split.\n \"\"\"\n root = Path(root)\n streams = {}\n for name, weight in weights.items():\n path = root / name\n if path.exists():\n streams[name] = _repeat_docs(path, text_key, int(round(weight)))\n```", "response": " if not streams:\n raise SystemExit(f\"no weighted sub-directories found under {root}\")\n\n cycle = list(streams)\n dead: set[str] = set()\n seen = 0\n while len(dead) < len(streams):\n progressed = False\n for name in cycle:\n if name in dead:\n continue\n try:\n doc = next(streams[name])\n except StopIteration:\n dead.add(name)\n continue\n progressed = True\n yield doc\n seen += len(doc.encode(\"utf-8\", \"ignore\"))\n if max_bytes is not None and seen >= max_bytes:\n return\n if not progressed:\n return", "source_file": "data_sources.py", "function_name": "iter_mixed_documents", "class_name": null, "line_start": 161, "line_end": 203, "license": "mit", "source": "SadikAI project"}
{"task": "code_explanation", "language": "python", "instruction": "Explain what this Python function does.\n\n```python\ndef iter_mixed_documents(\n root: str | Path,\n weights: dict[str, float],\n text_key: str = \"text\",\n max_bytes: int | None = None,\n) -> Iterator[str]:\n \"\"\"Interleave sub-directories of `root` and oversample them by weight.\n\n `weights` maps a directory name to a repeat count, e.g.\n ``{\"english\": 1, \"code\": 3, \"math\": 4}`` yields the whole code directory\n three times and maths four times, interleaved one document at a time.\n Interleaving keeps the packed shard mixed, which matters because\n `prepare_data.py` sends every N-th document to the validation split.\n \"\"\"\n root = Path(root)\n streams = {}\n for name, weight in weights.items():\n path = root / name\n if path.exists():\n streams[name] = _repeat_docs(path, text_key, int(round(weight)))\n if not streams:\n raise SystemExit(f\"no weighted sub-directories found under {root}\")\n\n cycle = list(streams)\n dead: set[str] = set()\n seen = 0\n while len(dead) < len(streams):\n progressed = False\n for name in cycle:\n if name in dead:\n continue\n try:\n doc = next(streams[name])\n except StopIteration:\n dead.add(name)\n continue\n progressed = True\n yield doc\n seen += len(doc.encode(\"utf-8\", \"ignore\"))\n if max_bytes is not None and seen >= max_bytes:\n return\n if not progressed:\n return\n```", "response": "Interleave sub-directories of `root` and oversample them by weight.", "source_file": "data_sources.py", "function_name": "iter_mixed_documents", "class_name": null, "line_start": 161, "line_end": 203, "license": "mit", "source": "SadikAI project"}
{"task": "code_generation", "language": "python", "instruction": "Write a Python function `iter_mixed_documents(root: str | Path, weights: dict[str, float], text_key: str='text', max_bytes: int | None=None)` that does the following:\n\nInterleave sub-directories of `root` and oversample them by weight.\n\nReturn only the Python code.", "response": "def iter_mixed_documents(\n root: str | Path,\n weights: dict[str, float],\n text_key: str = \"text\",\n max_bytes: int | None = None,\n) -> Iterator[str]:\n \"\"\"Interleave sub-directories of `root` and oversample them by weight.\n\n `weights` maps a directory name to a repeat count, e.g.\n ``{\"english\": 1, \"code\": 3, \"math\": 4}`` yields the whole code directory\n three times and maths four times, interleaved one document at a time.\n Interleaving keeps the packed shard mixed, which matters because\n `prepare_data.py` sends every N-th document to the validation split.\n \"\"\"\n root = Path(root)\n streams = {}\n for name, weight in weights.items():\n path = root / name\n if path.exists():\n streams[name] = _repeat_docs(path, text_key, int(round(weight)))\n if not streams:\n raise SystemExit(f\"no weighted sub-directories found under {root}\")\n\n cycle = list(streams)\n dead: set[str] = set()\n seen = 0\n while len(dead) < len(streams):\n progressed = False\n for name in cycle:\n if name in dead:\n continue\n try:\n doc = next(streams[name])\n except StopIteration:\n dead.add(name)\n continue\n progressed = True\n yield doc\n seen += len(doc.encode(\"utf-8\", \"ignore\"))\n if max_bytes is not None and seen >= max_bytes:\n return\n if not progressed:\n return", "source_file": "data_sources.py", "function_name": "iter_mixed_documents", "class_name": null, "line_start": 161, "line_end": 203, "license": "mit", "source": "SadikAI project"}
{"task": "code_completion", "language": "python", "instruction": "Complete the following Python code. Return only the continuation, preserving indentation.\n\n```python\ndef _iter_synth(total_chars: int) -> Iterator[str]:\n \"\"\"Deterministic pseudo-text; only for testing the pipeline end to end.\"\"\"\n alphabet = \"abcdefghijklmnopqrstuvwxyz .,\\n\"\n import random\n\n rng = random.Random(1234)\n```", "response": " written = 0\n while written < total_chars:\n n = rng.randint(200, 800)\n doc = \"\".join(rng.choice(alphabet) for _ in range(n)).strip()\n if doc:\n yield doc\n written += len(doc)", "source_file": "data_sources.py", "function_name": "_iter_synth", "class_name": null, "line_start": 206, "line_end": 218, "license": "mit", "source": "SadikAI project"}
{"task": "code_explanation", "language": "python", "instruction": "Explain what this Python function does.\n\n```python\ndef _iter_synth(total_chars: int) -> Iterator[str]:\n \"\"\"Deterministic pseudo-text; only for testing the pipeline end to end.\"\"\"\n alphabet = \"abcdefghijklmnopqrstuvwxyz .,\\n\"\n import random\n\n rng = random.Random(1234)\n written = 0\n while written < total_chars:\n n = rng.randint(200, 800)\n doc = \"\".join(rng.choice(alphabet) for _ in range(n)).strip()\n if doc:\n yield doc\n written += len(doc)\n```", "response": "Deterministic pseudo-text; only for testing the pipeline end to end.", "source_file": "data_sources.py", "function_name": "_iter_synth", "class_name": null, "line_start": 206, "line_end": 218, "license": "mit", "source": "SadikAI project"}
{"task": "code_generation", "language": "python", "instruction": "Write a Python function `_iter_synth(total_chars: int)` that does the following:\n\nDeterministic pseudo-text; only for testing the pipeline end to end.\n\nReturn only the Python code.", "response": "def _iter_synth(total_chars: int) -> Iterator[str]:\n \"\"\"Deterministic pseudo-text; only for testing the pipeline end to end.\"\"\"\n alphabet = \"abcdefghijklmnopqrstuvwxyz .,\\n\"\n import random\n\n rng = random.Random(1234)\n written = 0\n while written < total_chars:\n n = rng.randint(200, 800)\n doc = \"\".join(rng.choice(alphabet) for _ in range(n)).strip()\n if doc:\n yield doc\n written += len(doc)", "source_file": "data_sources.py", "function_name": "_iter_synth", "class_name": null, "line_start": 206, "line_end": 218, "license": "mit", "source": "SadikAI project"}
{"task": "code_completion", "language": "python", "instruction": "Complete the following Python code. Return only the continuation, preserving indentation.\n\n```python\ndef iter_documents(\n source: str = \"files\",\n input_path: str | None = None,\n hf_dataset: str = \"wikitext\",\n hf_config: str | None = \"wikitext-103-raw-v1\",\n hf_split: str = \"train\",\n text_key: str = \"text\",\n max_bytes: int | None = None,\n) -> Iterator[str]:\n \"\"\"Yield documents until `max_bytes` of text has been produced (or EOF).\"\"\"\n```", "response": " if source == \"files\":\n if not input_path:\n raise SystemExit(\"--input is required when --source files\")\n stream = _iter_files(Path(input_path), text_key)\n elif source == \"hf\":\n stream = _iter_hf(hf_dataset, hf_config, hf_split, text_key)\n elif source == \"synth\":\n stream = _iter_synth(max_bytes or 50_000_000)\n max_bytes = None # the generator already stops itself\n else:\n raise SystemExit(f\"unknown source: {source}\")\n\n seen = 0\n for doc in stream:\n yield doc\n seen += len(doc.encode(\"utf-8\", \"ignore\"))\n if max_bytes is not None and seen >= max_bytes:\n return", "source_file": "data_sources.py", "function_name": "iter_documents", "class_name": null, "line_start": 221, "line_end": 248, "license": "mit", "source": "SadikAI project"}
{"task": "code_explanation", "language": "python", "instruction": "Explain what this Python function does.\n\n```python\ndef iter_documents(\n source: str = \"files\",\n input_path: str | None = None,\n hf_dataset: str = \"wikitext\",\n hf_config: str | None = \"wikitext-103-raw-v1\",\n hf_split: str = \"train\",\n text_key: str = \"text\",\n max_bytes: int | None = None,\n) -> Iterator[str]:\n \"\"\"Yield documents until `max_bytes` of text has been produced (or EOF).\"\"\"\n if source == \"files\":\n if not input_path:\n raise SystemExit(\"--input is required when --source files\")\n stream = _iter_files(Path(input_path), text_key)\n elif source == \"hf\":\n stream = _iter_hf(hf_dataset, hf_config, hf_split, text_key)\n elif source == \"synth\":\n stream = _iter_synth(max_bytes or 50_000_000)\n max_bytes = None # the generator already stops itself\n else:\n raise SystemExit(f\"unknown source: {source}\")\n\n seen = 0\n for doc in stream:\n yield doc\n seen += len(doc.encode(\"utf-8\", \"ignore\"))\n if max_bytes is not None and seen >= max_bytes:\n return\n```", "response": "Yield documents until `max_bytes` of text has been produced (or EOF).", "source_file": "data_sources.py", "function_name": "iter_documents", "class_name": null, "line_start": 221, "line_end": 248, "license": "mit", "source": "SadikAI project"}
{"task": "code_generation", "language": "python", "instruction": "Write a Python function `iter_documents(source: str='files', input_path: str | None=None, hf_dataset: str='wikitext', hf_config: str | None='wikitext-103-raw-v1', hf_split: str='train', text_key: str='text', max_bytes: int | None=None)` that does the following:\n\nYield documents until `max_bytes` of text has been produced (or EOF).\n\nReturn only the Python code.", "response": "def iter_documents(\n source: str = \"files\",\n input_path: str | None = None,\n hf_dataset: str = \"wikitext\",\n hf_config: str | None = \"wikitext-103-raw-v1\",\n hf_split: str = \"train\",\n text_key: str = \"text\",\n max_bytes: int | None = None,\n) -> Iterator[str]:\n \"\"\"Yield documents until `max_bytes` of text has been produced (or EOF).\"\"\"\n if source == \"files\":\n if not input_path:\n raise SystemExit(\"--input is required when --source files\")\n stream = _iter_files(Path(input_path), text_key)\n elif source == \"hf\":\n stream = _iter_hf(hf_dataset, hf_config, hf_split, text_key)\n elif source == \"synth\":\n stream = _iter_synth(max_bytes or 50_000_000)\n max_bytes = None # the generator already stops itself\n else:\n raise SystemExit(f\"unknown source: {source}\")\n\n seen = 0\n for doc in stream:\n yield doc\n seen += len(doc.encode(\"utf-8\", \"ignore\"))\n if max_bytes is not None and seen >= max_bytes:\n return", "source_file": "data_sources.py", "function_name": "iter_documents", "class_name": null, "line_start": 221, "line_end": 248, "license": "mit", "source": "SadikAI project"}
{"task": "code_completion", "language": "python", "instruction": "Complete the following Python code. Return only the continuation, preserving indentation.\n\n```python\n def update(self, emotion: Emotion) -> None:\n rate = 0.35\n self.valence = (1 - rate) * self.valence + rate * emotion.valence\n```", "response": " self.arousal = (1 - rate) * self.arousal + rate * emotion.arousal\n self.energy = min(1.0, 0.9 * self.energy + 0.1 * (0.35 + 0.65 * emotion.arousal))\n self.turns += 1\n self.last_label = emotion.label", "source_file": "emotion.py", "function_name": "update", "class_name": "Mood", "line_start": 154, "line_end": 160, "license": "mit", "source": "SadikAI project"}
{"task": "code_completion", "language": "python", "instruction": "Complete the following Python code. Return only the continuation, preserving indentation.\n\n```python\n def label(self) -> str:\n v = self.valence\n if v >= 0.30:\n base = \"happy\"\n elif v >= 0.10:\n base = \"warm\"\n elif v <= -0.30:\n base = \"low\"\n elif v <= -0.10:\n base = \"uneasy\"\n else:\n base = \"calm\"\n```", "response": " if self.arousal >= 0.62 and base in {\"happy\", \"calm\", \"warm\"}:\n return f\"{base} and energised\"\n if self.arousal >= 0.62:\n return f\"{base} and agitated\"\n return base", "source_file": "emotion.py", "function_name": "label", "class_name": "Mood", "line_start": 162, "line_end": 178, "license": "mit", "source": "SadikAI project"}
{"task": "code_completion", "language": "python", "instruction": "Complete the following Python code. Return only the continuation, preserving indentation.\n\n```python\ndef is_greeting(text: str) -> bool:\n low = \" \".join(WORD_RE.findall(text.lower()))\n if not low:\n return False\n```", "response": " if low.strip() in GREETINGS:\n return True\n return any(p in low for p in GREETING_PHRASES)", "source_file": "emotion.py", "function_name": "is_greeting", "class_name": null, "line_start": 193, "line_end": 199, "license": "mit", "source": "SadikAI project"}
{"task": "code_completion", "language": "python", "instruction": "Complete the following Python code. Return only the continuation, preserving indentation.\n\n```python\ndef detect(text: str) -> Emotion:\n tokens = [t.lower() for t in WORD_RE.findall(text)]\n if not tokens:\n return Emotion()\n\n scores: dict[str, float] = {k: 0.0 for k in LEXICON}\n hits: list[str] = []\n\n for i, tok in enumerate(tokens):\n window = tokens[max(0, i - 2): i]\n negated = any(w in NEGATIONS for w in window)\n boosted = any(w in INTENSIFIERS for w in window)\n for label, table in LEXICON.items():\n weight = table.get(tok)\n if weight is None:\n continue\n if label == \"surprise\" and weight < 0.5 and not boosted:\n continue\n if boosted:\n weight *= 1.6\n if negated:\n if label in POSITIVE:\n # \"not happy\" is a mild negative, not a positive\n scores[\"sadness\"] += 0.7 * abs(weight)\n hits.append(f\"not {tok}\")\n # \"not angry\" simply cancels the anger\n continue\n scores[label] += weight\n if weight >= 0.7:\n hits.append(tok)\n\n low = \" \" + \" \".join(tokens) + \" \"\n```", "response": " for phrase, (label, weight) in PHRASES.items():\n if phrase in low:\n scores[label] += weight\n hits.append(phrase)\n\n pos = scores[\"joy\"] + scores[\"love\"] + scores[\"gratitude\"]\n neg = scores[\"sadness\"] + scores[\"anger\"] + scores[\"fear\"]\n total = pos + neg + scores[\"surprise\"] * 0.3\n\n if total < 0.55:\n return Emotion(label=\"neutral\", valence=0.0, arousal=0.18,\n confidence=min(1.0, total / 2), hits=hits[:6])\n\n # Surprise borrows the polarity of whatever came with it.\n valence = (pos - neg) / (pos + neg + 1.0)\n if scores[\"surprise\"] >= 1.0 and pos + neg < 0.5:\n valence = 0.1\n\n best_label = max(LEXICON, key=lambda k: scores[k])\n if scores[best_label] < 0.8:\n best_label = \"neutral\"\n if best_label == \"surprise\" and scores[\"surprise\"] < 1.2:\n best_label = \"neutral\"\n\n arousal = LABEL_AROUSAL.get(best_label, 0.2)\n arousal = min(1.0, arousal + 0.06 * min(3, text.count(\"!\")) + 0.05 * min(2, _shout_count(text)))\n confidence = min(1.0, total / 4.0)\n if best_label == \"neutral\" and (pos or neg):\n best_label = \"joy\" if pos > neg else \"sadness\"\n\n return Emotion(label=best_label, valence=round(valence, 3),\n arousal=round(arousal, 3), confidence=round(confidence, 2),\n hits=_dedupe(hits)[:6])", "source_file": "emotion.py", "function_name": "detect", "class_name": null, "line_start": 202, "line_end": 266, "license": "mit", "source": "SadikAI project"}
{"task": "code_completion", "language": "python", "instruction": "Complete the following Python code. Return only the continuation, preserving indentation.\n\n```python\ndef _dedupe(items: list[str]) -> list[str]:\n seen: set[str] = set()\n out: list[str] = []\n```", "response": " for item in items:\n key = item.lower()\n if key not in seen:\n seen.add(key)\n out.append(item)\n return out", "source_file": "emotion.py", "function_name": "_dedupe", "class_name": null, "line_start": 274, "line_end": 282, "license": "mit", "source": "SadikAI project"}
{"task": "code_completion", "language": "python", "instruction": "Complete the following Python code. Return only the continuation, preserving indentation.\n\n```python\ndef _copy(checkpoint: Path) -> Path:\n \"\"\"Copy before loading so a trainer mid-write can't corrupt the read.\"\"\"\n temp = Path(tempfile.gettempdir()) / f\"sadik_export_{checkpoint.name}\"\n```", "response": " shutil.copyfile(checkpoint, temp)\n return temp", "source_file": "export_release.py", "function_name": "_copy", "class_name": null, "line_start": 536, "line_end": 540, "license": "mit", "source": "SadikAI project"}
{"task": "code_explanation", "language": "python", "instruction": "Explain what this Python function does.\n\n```python\ndef _copy(checkpoint: Path) -> Path:\n \"\"\"Copy before loading so a trainer mid-write can't corrupt the read.\"\"\"\n temp = Path(tempfile.gettempdir()) / f\"sadik_export_{checkpoint.name}\"\n shutil.copyfile(checkpoint, temp)\n return temp\n```", "response": "Copy before loading so a trainer mid-write can't corrupt the read.", "source_file": "export_release.py", "function_name": "_copy", "class_name": null, "line_start": 536, "line_end": 540, "license": "mit", "source": "SadikAI project"}
{"task": "code_generation", "language": "python", "instruction": "Write a Python function `_copy(checkpoint: Path)` that does the following:\n\nCopy before loading so a trainer mid-write can't corrupt the read.\n\nReturn only the Python code.", "response": "def _copy(checkpoint: Path) -> Path:\n \"\"\"Copy before loading so a trainer mid-write can't corrupt the read.\"\"\"\n temp = Path(tempfile.gettempdir()) / f\"sadik_export_{checkpoint.name}\"\n shutil.copyfile(checkpoint, temp)\n return temp", "source_file": "export_release.py", "function_name": "_copy", "class_name": null, "line_start": 536, "line_end": 540, "license": "mit", "source": "SadikAI project"}
{"task": "code_completion", "language": "python", "instruction": "Complete the following Python code. Return only the continuation, preserving indentation.\n\n```python\ndef _zip(stage: Path, out_zip: Path) -> None:\n if out_zip.exists():\n out_zip.unlink()\n```", "response": " with zipfile.ZipFile(out_zip, \"w\", zipfile.ZIP_DEFLATED) as bundle:\n for path in sorted(stage.rglob(\"*\")):\n if path.is_file() and \"__pycache__\" not in path.parts and path.suffix != \".pyc\":\n bundle.write(path, path.relative_to(stage).as_posix())", "source_file": "export_release.py", "function_name": "_zip", "class_name": null, "line_start": 556, "line_end": 562, "license": "mit", "source": "SadikAI project"}
{"task": "code_completion", "language": "python", "instruction": "Complete the following Python code. Return only the continuation, preserving indentation.\n\n```python\ndef _write_checksums(stage: Path) -> None:\n \"\"\"SHA-256 for every file in the release, so buyers can verify the unzip.\"\"\"\n lines = []\n```", "response": " for path in sorted(stage.rglob(\"*\")):\n if path.is_file() and path.name != \"SHA256SUMS\" and \"__pycache__\" not in path.parts and path.suffix != \".pyc\":\n lines.append(f\"{_sha256(path)} {path.relative_to(stage).as_posix()}\")\n _write(stage / \"SHA256SUMS\", \"\\n\".join(lines) + \"\\n\")", "source_file": "export_release.py", "function_name": "_write_checksums", "class_name": null, "line_start": 565, "line_end": 571, "license": "mit", "source": "SadikAI project"}
{"task": "code_explanation", "language": "python", "instruction": "Explain what this Python function does.\n\n```python\ndef _write_checksums(stage: Path) -> None:\n \"\"\"SHA-256 for every file in the release, so buyers can verify the unzip.\"\"\"\n lines = []\n for path in sorted(stage.rglob(\"*\")):\n if path.is_file() and path.name != \"SHA256SUMS\" and \"__pycache__\" not in path.parts and path.suffix != \".pyc\":\n lines.append(f\"{_sha256(path)} {path.relative_to(stage).as_posix()}\")\n _write(stage / \"SHA256SUMS\", \"\\n\".join(lines) + \"\\n\")\n```", "response": "SHA-256 for every file in the release, so buyers can verify the unzip.", "source_file": "export_release.py", "function_name": "_write_checksums", "class_name": null, "line_start": 565, "line_end": 571, "license": "mit", "source": "SadikAI project"}
{"task": "code_generation", "language": "python", "instruction": "Write a Python function `_write_checksums(stage: Path)` that does the following:\n\nSHA-256 for every file in the release, so buyers can verify the unzip.\n\nReturn only the Python code.", "response": "def _write_checksums(stage: Path) -> None:\n \"\"\"SHA-256 for every file in the release, so buyers can verify the unzip.\"\"\"\n lines = []\n for path in sorted(stage.rglob(\"*\")):\n if path.is_file() and path.name != \"SHA256SUMS\" and \"__pycache__\" not in path.parts and path.suffix != \".pyc\":\n lines.append(f\"{_sha256(path)} {path.relative_to(stage).as_posix()}\")\n _write(stage / \"SHA256SUMS\", \"\\n\".join(lines) + \"\\n\")", "source_file": "export_release.py", "function_name": "_write_checksums", "class_name": null, "line_start": 565, "line_end": 571, "license": "mit", "source": "SadikAI project"}
{"task": "code_completion", "language": "python", "instruction": "Complete the following Python code. Return only the continuation, preserving indentation.\n\n```python\ndef _find_manifest(folder: Path) -> Path:\n matches = sorted(folder.glob(f\"*{MANIFEST_SUFFIX}\"))\n if not matches:\n raise FileNotFoundError(\n f\"No *{MANIFEST_SUFFIX} file found in {folder}. \"\n \"Download every file from the release folder, including the manifest.\"\n )\n```", "response": " if len(matches) > 1:\n names = \", \".join(path.name for path in matches)\n raise ValueError(\n f\"More than one split manifest found in {folder}: {names}. \"\n \"Keep only one release at a time, or pass --manifest.\"\n )\n return matches[0]", "source_file": "join_release_zip.py", "function_name": "_find_manifest", "class_name": null, "line_start": 41, "line_end": 54, "license": "mit", "source": "SadikAI project"}
{"task": "code_completion", "language": "python", "instruction": "Complete the following Python code. Return only the continuation, preserving indentation.\n\n```python\ndef _load_manifest(path: Path) -> dict:\n try:\n manifest = json.loads(path.read_text(encoding=\"utf-8\"))\n except (OSError, ValueError) as exc:\n raise ValueError(f\"cannot read {path}: {exc}\") from exc\n if manifest.get(\"format\") != FORMAT:\n raise ValueError(f\"{path} is not a SadikAI split-release manifest\")\n```", "response": " if not isinstance(manifest.get(\"parts\"), list) or not manifest[\"parts\"]:\n raise ValueError(f\"{path} has no parts\")\n if not isinstance(manifest.get(\"size\"), int) or manifest[\"size\"] <= 0:\n raise ValueError(f\"{path} has a bad total size\")\n if not isinstance(manifest.get(\"sha256\"), str):\n raise ValueError(f\"{path} has no total SHA-256\")\n if not isinstance(manifest.get(\"file\"), str) or not manifest[\"file\"]:\n raise ValueError(f\"{path} has no final file name\")\n return manifest", "source_file": "join_release_zip.py", "function_name": "_load_manifest", "class_name": null, "line_start": 57, "line_end": 72, "license": "mit", "source": "SadikAI project"}
{"task": "code_completion", "language": "python", "instruction": "Complete the following Python code. Return only the continuation, preserving indentation.\n\n```python\ndef join_release(folder: Path, manifest_path: Path | None = None,\n *, verbose: bool = True) -> Path:\n folder = Path(folder)\n manifest_path = Path(manifest_path) if manifest_path else _find_manifest(folder)\n manifest = _load_manifest(manifest_path)\n target = folder / manifest[\"file\"]\n expected_size = manifest[\"size\"]\n expected_sha = manifest[\"sha256\"].lower()\n\n if target.exists() and target.stat().st_size == expected_size:\n if sha256_file(target) == expected_sha:\n return target\n if verbose:\n print(f\"{target} does not match the manifest; rebuilding it\",\n file=sys.stderr)\n\n parts: list[tuple[Path, int, str]] = []\n for entry in manifest[\"parts\"]:\n name = str(entry.get(\"name\", \"\"))\n if not name or \"/\" in name or \"\\\\\" in name:\n raise ValueError(f\"{manifest_path} has a bad part name: {name!r}\")\n part_path = folder / name\n if not part_path.exists():\n raise FileNotFoundError(\n f\"missing split part: {part_path}\\n\"\n \"Download every part listed in the manifest.\"\n )\n parts.append((part_path, int(entry[\"size\"]), str(entry[\"sha256\"]).lower()))\n\n temp = target.with_name(target.name + \".joining\")\n digest = hashlib.sha256()\n written = 0\n if verbose:\n print(f\"joining {len(parts)} release parts -> {target}\", file=sys.stderr)\n```", "response": " try:\n with temp.open(\"wb\") as out:\n for part_path, part_size, part_sha in parts:\n actual_size = part_path.stat().st_size\n if actual_size != part_size:\n raise ValueError(\n f\"{part_path} is {actual_size} bytes, expected {part_size}; \"\n \"download it again\"\n )\n part_digest = hashlib.sha256()\n with part_path.open(\"rb\") as source:\n for block in iter(lambda: source.read(BLOCK), b\"\"):\n part_digest.update(block)\n digest.update(block)\n out.write(block)\n written += len(block)\n if part_digest.hexdigest() != part_sha:\n raise ValueError(\n f\"{part_path} failed its SHA-256 check; download it again\"\n )\n\n if written != expected_size:\n raise ValueError(f\"joined {written} bytes, expected {expected_size}\")\n actual_sha = digest.hexdigest()\n if actual_sha != expected_sha:\n raise ValueError(\n f\"joined zip SHA-256 is {actual_sha}, expected {expected_sha}\"\n )\n os.replace(temp, target)\n finally:\n if temp.exists():\n temp.unlink(missing_ok=True)\n\n if verbose:\n print(\n f\"release ready: {target} ({written / 1e6:.1f} MB, \"\n f\"sha256 {actual_sha[:16]}...)\",\n file=sys.stderr,\n )\n return target", "source_file": "join_release_zip.py", "function_name": "join_release", "class_name": null, "line_start": 75, "line_end": 149, "license": "mit", "source": "SadikAI project"}
{"task": "code_completion", "language": "python", "instruction": "Complete the following Python code. Return only the continuation, preserving indentation.\n\n```python\ndef main() -> None:\n ap = argparse.ArgumentParser(\n description=__doc__,\n formatter_class=argparse.RawDescriptionHelpFormatter,\n )\n ap.add_argument(\"--dir\", type=Path, default=Path(__file__).resolve().parent,\n help=\"folder containing the parts and manifest (default: script folder)\")\n```", "response": " ap.add_argument(\"--manifest\", type=Path, default=None,\n help=\"exact manifest path, if the folder has more than one\")\n args = ap.parse_args()\n try:\n join_release(args.dir, args.manifest)\n except (OSError, ValueError) as exc:\n raise SystemExit(f\"error: {exc}\") from exc", "source_file": "join_release_zip.py", "function_name": "main", "class_name": null, "line_start": 152, "line_end": 165, "license": "mit", "source": "SadikAI project"}
{"task": "code_completion", "language": "python", "instruction": "Complete the following Python code. Return only the continuation, preserving indentation.\n\n```python\ndef _load_manifest(path: Path) -> dict:\n try:\n manifest = json.loads(path.read_text(encoding=\"utf-8\"))\n except (OSError, ValueError) as exc:\n raise ValueError(f\"cannot read {path}: {exc}\") from exc\n if manifest.get(\"format\") != \"sadik-ai-split-weights-v1\":\n raise ValueError(f\"{path} is not a SadikAI split-weights manifest\")\n```", "response": " if not isinstance(manifest.get(\"parts\"), list) or not manifest[\"parts\"]:\n raise ValueError(f\"{path} has no parts\")\n if not isinstance(manifest.get(\"size\"), int) or not manifest[\"size\"] > 0:\n raise ValueError(f\"{path} has a bad total size\")\n if not isinstance(manifest.get(\"sha256\"), str):\n raise ValueError(f\"{path} has no total SHA-256\")\n return manifest", "source_file": "join_weights.py", "function_name": "_load_manifest", "class_name": null, "line_start": 43, "line_end": 56, "license": "mit", "source": "SadikAI project"}
{"task": "code_completion", "language": "python", "instruction": "Complete the following Python code. Return only the continuation, preserving indentation.\n\n```python\ndef ensure_weights(path: str | Path = \"model/weights.pt\", *, verbose: bool = True) -> Path:\n \"\"\"Return a complete ``weights.pt``, joining split parts when needed.\n\n If no manifest exists next to ``path``, the file is returned unchanged when\n present (normal zip release layout). If the file is missing or does not\n match the manifest, the parts are joined and verified first.\n \"\"\"\n target = Path(path)\n manifest_path = target.parent / MANIFEST_NAME\n\n if not manifest_path.exists():\n if target.exists():\n return target\n raise FileNotFoundError(\n f\"{target} is missing and no {MANIFEST_NAME} was found next to it. \"\n \"Download the release again, or run join_weights.py from its root.\"\n )\n\n manifest = _load_manifest(manifest_path)\n expected_size = manifest[\"size\"]\n expected_sha = manifest[\"sha256\"].lower()\n\n if target.exists() and target.stat().st_size == expected_size:\n if sha256_file(target) == expected_sha:\n return target\n if verbose:\n print(f\"{target} does not match the manifest; rebuilding it\",\n file=sys.stderr)\n\n parts: list[tuple[Path, int, str]] = []\n for entry in manifest[\"parts\"]:\n name = str(entry.get(\"name\", \"\"))\n if not name or \"/\" in name or \"\\\\\" in name:\n raise ValueError(f\"{manifest_path} has a bad part name: {name!r}\")\n part_path = target.parent / name\n if not part_path.exists():\n raise FileNotFoundError(\n f\"missing split part: {part_path}\\n\"\n f\"Download all files from the Hugging Face repo, including {name}.\"\n )\n parts.append((part_path, int(entry[\"size\"]), str(entry[\"sha256\"]).lower()))\n```", "response": " temp = target.parent / (target.name + \".joining\")\n digest = hashlib.sha256()\n written = 0\n if verbose:\n print(f\"joining {len(parts)} weights parts -> {target}\", file=sys.stderr)\n\n try:\n with temp.open(\"wb\") as out:\n for part_path, part_size, part_sha in parts:\n actual_size = part_path.stat().st_size\n if actual_size != part_size:\n raise ValueError(\n f\"{part_path} is {actual_size} bytes, expected {part_size}; \"\n \"download it again\"\n )\n part_digest = hashlib.sha256()\n with part_path.open(\"rb\") as source:\n for block in iter(lambda: source.read(BLOCK), b\"\"):\n part_digest.update(block)\n digest.update(block)\n out.write(block)\n written += len(block)\n if part_digest.hexdigest() != part_sha:\n raise ValueError(f\"{part_path} failed its SHA-256 check; download it again\")\n\n if written != expected_size:\n raise ValueError(f\"joined {written} bytes, expected {expected_size}\")\n actual_sha = digest.hexdigest()\n if actual_sha != expected_sha:\n raise ValueError(\n f\"joined file SHA-256 is {actual_sha}, expected {expected_sha}\"\n )\n os.replace(temp, target)\n finally:\n if temp.exists():\n temp.unlink(missing_ok=True)\n\n if verbose:\n print(\n f\"weights ready: {target} ({written / 1e6:.1f} MB, \"\n f\"sha256 {actual_sha[:16]}...)\",\n file=sys.stderr,\n )\n return target", "source_file": "join_weights.py", "function_name": "ensure_weights", "class_name": null, "line_start": 59, "line_end": 144, "license": "mit", "source": "SadikAI project"}
{"task": "code_explanation", "language": "python", "instruction": "Explain what this Python function does.\n\n```python\ndef ensure_weights(path: str | Path = \"model/weights.pt\", *, verbose: bool = True) -> Path:\n \"\"\"Return a complete ``weights.pt``, joining split parts when needed.\n\n If no manifest exists next to ``path``, the file is returned unchanged when\n present (normal zip release layout). If the file is missing or does not\n match the manifest, the parts are joined and verified first.\n \"\"\"\n target = Path(path)\n manifest_path = target.parent / MANIFEST_NAME\n\n if not manifest_path.exists():\n if target.exists():\n return target\n raise FileNotFoundError(\n f\"{target} is missing and no {MANIFEST_NAME} was found next to it. \"\n \"Download the release again, or run join_weights.py from its root.\"\n )\n\n manifest = _load_manifest(manifest_path)\n expected_size = manifest[\"size\"]\n expected_sha = manifest[\"sha256\"].lower()\n\n if target.exists() and target.stat().st_size == expected_size:\n if sha256_file(target) == expected_sha:\n return target\n if verbose:\n print(f\"{target} does not match the manifest; rebuilding it\",\n file=sys.stderr)\n\n parts: list[tuple[Path, int, str]] = []\n for entry in manifest[\"parts\"]:\n name = str(entry.get(\"name\", \"\"))\n if not name or \"/\" in name or \"\\\\\" in name:\n raise ValueError(f\"{manifest_path} has a bad part name: {name!r}\")\n part_path = target.parent / name\n if not part_path.exists():\n raise FileNotFoundError(\n f\"missing split part: {part_path}\\n\"\n f\"Download all files from the Hugging Face repo, including {name}.\"\n )\n parts.append((part_path, int(entry[\"size\"]), str(entry[\"sha256\"]).lower()))\n\n temp = target.parent / (target.name + \".joining\")\n digest = hashlib.sha256()\n written = 0\n if verbose:\n print(f\"joining {len(parts)} weights parts -> {target}\", file=sys.stderr)\n\n try:\n with temp.open(\"wb\") as out:\n for part_path, part_size, part_sha in parts:\n actual_size = part_path.stat().st_size\n if actual_size != part_size:\n raise ValueError(\n f\"{part_path} is {actual_size} bytes, expected {part_size}; \"\n \"download it again\"\n )\n part_digest = hashlib.sha256()\n with part_path.open(\"rb\") as source:\n for block in iter(lambda: source.read(BLOCK), b\"\"):\n part_digest.update(block)\n digest.update(block)\n out.write(block)\n written += len(block)\n if part_digest.hexdigest() != part_sha:\n raise ValueError(f\"{part_path} failed its SHA-256 check; download it again\")\n\n if written != expected_size:\n raise ValueError(f\"joined {written} bytes, expected {expected_size}\")\n actual_sha = digest.hexdigest()\n if actual_sha != expected_sha:\n raise ValueError(\n f\"joined file SHA-256 is {actual_sha}, expected {expected_sha}\"\n )\n os.replace(temp, target)\n finally:\n if temp.exists():\n temp.unlink(missing_ok=True)\n\n if verbose:\n print(\n f\"weights ready: {target} ({written / 1e6:.1f} MB, \"\n f\"sha256 {actual_sha[:16]}...)\",\n file=sys.stderr,\n )\n return target\n```", "response": "Return a complete ``weights.pt``, joining split parts when needed.", "source_file": "join_weights.py", "function_name": "ensure_weights", "class_name": null, "line_start": 59, "line_end": 144, "license": "mit", "source": "SadikAI project"}
{"task": "code_generation", "language": "python", "instruction": "Write a Python function `ensure_weights(path: str | Path='model/weights.pt', *, verbose: bool=True)` that does the following:\n\nReturn a complete ``weights.pt``, joining split parts when needed.\n\nReturn only the Python code.", "response": "def ensure_weights(path: str | Path = \"model/weights.pt\", *, verbose: bool = True) -> Path:\n \"\"\"Return a complete ``weights.pt``, joining split parts when needed.\n\n If no manifest exists next to ``path``, the file is returned unchanged when\n present (normal zip release layout). If the file is missing or does not\n match the manifest, the parts are joined and verified first.\n \"\"\"\n target = Path(path)\n manifest_path = target.parent / MANIFEST_NAME\n\n if not manifest_path.exists():\n if target.exists():\n return target\n raise FileNotFoundError(\n f\"{target} is missing and no {MANIFEST_NAME} was found next to it. \"\n \"Download the release again, or run join_weights.py from its root.\"\n )\n\n manifest = _load_manifest(manifest_path)\n expected_size = manifest[\"size\"]\n expected_sha = manifest[\"sha256\"].lower()\n\n if target.exists() and target.stat().st_size == expected_size:\n if sha256_file(target) == expected_sha:\n return target\n if verbose:\n print(f\"{target} does not match the manifest; rebuilding it\",\n file=sys.stderr)\n\n parts: list[tuple[Path, int, str]] = []\n for entry in manifest[\"parts\"]:\n name = str(entry.get(\"name\", \"\"))\n if not name or \"/\" in name or \"\\\\\" in name:\n raise ValueError(f\"{manifest_path} has a bad part name: {name!r}\")\n part_path = target.parent / name\n if not part_path.exists():\n raise FileNotFoundError(\n f\"missing split part: {part_path}\\n\"\n f\"Download all files from the Hugging Face repo, including {name}.\"\n )\n parts.append((part_path, int(entry[\"size\"]), str(entry[\"sha256\"]).lower()))\n\n temp = target.parent / (target.name + \".joining\")\n digest = hashlib.sha256()\n written = 0\n if verbose:\n print(f\"joining {len(parts)} weights parts -> {target}\", file=sys.stderr)\n\n try:\n with temp.open(\"wb\") as out:\n for part_path, part_size, part_sha in parts:\n actual_size = part_path.stat().st_size\n if actual_size != part_size:\n raise ValueError(\n f\"{part_path} is {actual_size} bytes, expected {part_size}; \"\n \"download it again\"\n )\n part_digest = hashlib.sha256()\n with part_path.open(\"rb\") as source:\n for block in iter(lambda: source.read(BLOCK), b\"\"):\n part_digest.update(block)\n digest.update(block)\n out.write(block)\n written += len(block)\n if part_digest.hexdigest() != part_sha:\n raise ValueError(f\"{part_path} failed its SHA-256 check; download it again\")\n\n if written != expected_size:\n raise ValueError(f\"joined {written} bytes, expected {expected_size}\")\n actual_sha = digest.hexdigest()\n if actual_sha != expected_sha:\n raise ValueError(\n f\"joined file SHA-256 is {actual_sha}, expected {expected_sha}\"\n )\n os.replace(temp, target)\n finally:\n if temp.exists():\n temp.unlink(missing_ok=True)\n\n if verbose:\n print(\n f\"weights ready: {target} ({written / 1e6:.1f} MB, \"\n f\"sha256 {actual_sha[:16]}...)\",\n file=sys.stderr,\n )\n return target", "source_file": "join_weights.py", "function_name": "ensure_weights", "class_name": null, "line_start": 59, "line_end": 144, "license": "mit", "source": "SadikAI project"}
{"task": "code_completion", "language": "python", "instruction": "Complete the following Python code. Return only the continuation, preserving indentation.\n\n```python\ndef main() -> None:\n ap = argparse.ArgumentParser(description=__doc__,\n formatter_class=argparse.RawDescriptionHelpFormatter)\n ap.add_argument(\"--dir\", type=Path, default=Path(__file__).resolve().parent / \"model\",\n help=\"folder containing weights.parts.json (default: ./model)\")\n ap.add_argument(\"--check\", action=\"store_true\",\n help=\"only verify an existing weights.pt against the manifest\")\n args = ap.parse_args()\n\n target = args.dir / TARGET_NAME\n manifest = args.dir / MANIFEST_NAME\n```", "response": " try:\n if args.check:\n if not target.exists():\n raise FileNotFoundError(f\"{target} is missing\")\n if not manifest.exists():\n raise FileNotFoundError(f\"{manifest} is missing\")\n data = _load_manifest(manifest)\n actual = sha256_file(target)\n if actual != data[\"sha256\"].lower():\n raise ValueError(f\"{target} failed its SHA-256 check\")\n print(f\"ok: {target} ({target.stat().st_size / 1e6:.1f} MB, sha256 {actual[:16]}...)\")\n return\n ensure_weights(target)\n except (OSError, ValueError) as exc:\n raise SystemExit(f\"error: {exc}\") from exc", "source_file": "join_weights.py", "function_name": "main", "class_name": null, "line_start": 147, "line_end": 172, "license": "mit", "source": "SadikAI project"}
{"task": "code_completion", "language": "python", "instruction": "Complete the following Python code. Return only the continuation, preserving indentation.\n\n```python\ndef _hit(haystack: str, keyword: str) -> bool:\n keyword = keyword.lower().strip()\n if not keyword:\n return False\n```", "response": " if \" \" in keyword or any(ord(ch) > 127 for ch in keyword):\n return keyword in haystack\n return re.search(rf\"\\b{re.escape(keyword)}\\b\", haystack) is not None", "source_file": "knowledge.py", "function_name": "_hit", "class_name": null, "line_start": 890, "line_end": 896, "license": "mit", "source": "SadikAI project"}
{"task": "code_completion", "language": "python", "instruction": "Complete the following Python code. Return only the continuation, preserving indentation.\n\n```python\ndef answer_knowledge(text: str) -> str | None:\n \"\"\"Return a curated lesson for a learning question, or None.\"\"\"\n low = _normalise(text)\n if not low:\n return None\n\n first_aid_cues = (\n \"bleeding\", \"choking\", \"unconscious\", \"not breathing\", \"burned my\",\n \"burnt my\", \"cut my finger\", \"cut my hand\", \"cut my leg\", \"cut my foot\",\n )\n if any(cue in low for cue in first_aid_cues):\n for lesson in LESSONS:\n if lesson.key == \"first_aid\":\n return lesson.text\n\n if low in SHORT_TRIGGERS:\n for lesson in LESSONS:\n names = {_normalise(lesson.title), _normalise(lesson.key)}\n keywords = {_normalise(keyword) for keyword in lesson.keywords}\n if low in names or low in keywords:\n return lesson.text\n```", "response": " wants_explanation = any(hint in low for hint in INTENT_HINTS)\n best: Lesson | None = None\n best_score = 0.0\n for lesson in LESSONS:\n score = 0.0\n for keyword in lesson.keywords:\n if _hit(low, keyword):\n score += 1.0 + 0.5 * (len(keyword.split()) - 1)\n if score > best_score:\n best, best_score = lesson, score\n\n if best is None:\n return None\n if not wants_explanation and best_score < 2.0:\n return None\n if wants_explanation and best_score < 1.0:\n return None\n return best.text", "source_file": "knowledge.py", "function_name": "answer_knowledge", "class_name": null, "line_start": 899, "line_end": 938, "license": "mit", "source": "SadikAI project"}
{"task": "code_explanation", "language": "python", "instruction": "Explain what this Python function does.\n\n```python\ndef answer_knowledge(text: str) -> str | None:\n \"\"\"Return a curated lesson for a learning question, or None.\"\"\"\n low = _normalise(text)\n if not low:\n return None\n\n first_aid_cues = (\n \"bleeding\", \"choking\", \"unconscious\", \"not breathing\", \"burned my\",\n \"burnt my\", \"cut my finger\", \"cut my hand\", \"cut my leg\", \"cut my foot\",\n )\n if any(cue in low for cue in first_aid_cues):\n for lesson in LESSONS:\n if lesson.key == \"first_aid\":\n return lesson.text\n\n if low in SHORT_TRIGGERS:\n for lesson in LESSONS:\n names = {_normalise(lesson.title), _normalise(lesson.key)}\n keywords = {_normalise(keyword) for keyword in lesson.keywords}\n if low in names or low in keywords:\n return lesson.text\n\n wants_explanation = any(hint in low for hint in INTENT_HINTS)\n best: Lesson | None = None\n best_score = 0.0\n for lesson in LESSONS:\n score = 0.0\n for keyword in lesson.keywords:\n if _hit(low, keyword):\n score += 1.0 + 0.5 * (len(keyword.split()) - 1)\n if score > best_score:\n best, best_score = lesson, score\n\n if best is None:\n return None\n if not wants_explanation and best_score < 2.0:\n return None\n if wants_explanation and best_score < 1.0:\n return None\n return best.text\n```", "response": "Return a curated lesson for a learning question, or None.", "source_file": "knowledge.py", "function_name": "answer_knowledge", "class_name": null, "line_start": 899, "line_end": 938, "license": "mit", "source": "SadikAI project"}
{"task": "code_generation", "language": "python", "instruction": "Write a Python function `answer_knowledge(text: str)` that does the following:\n\nReturn a curated lesson for a learning question, or None.\n\nReturn only the Python code.", "response": "def answer_knowledge(text: str) -> str | None:\n \"\"\"Return a curated lesson for a learning question, or None.\"\"\"\n low = _normalise(text)\n if not low:\n return None\n\n first_aid_cues = (\n \"bleeding\", \"choking\", \"unconscious\", \"not breathing\", \"burned my\",\n \"burnt my\", \"cut my finger\", \"cut my hand\", \"cut my leg\", \"cut my foot\",\n )\n if any(cue in low for cue in first_aid_cues):\n for lesson in LESSONS:\n if lesson.key == \"first_aid\":\n return lesson.text\n\n if low in SHORT_TRIGGERS:\n for lesson in LESSONS:\n names = {_normalise(lesson.title), _normalise(lesson.key)}\n keywords = {_normalise(keyword) for keyword in lesson.keywords}\n if low in names or low in keywords:\n return lesson.text\n\n wants_explanation = any(hint in low for hint in INTENT_HINTS)\n best: Lesson | None = None\n best_score = 0.0\n for lesson in LESSONS:\n score = 0.0\n for keyword in lesson.keywords:\n if _hit(low, keyword):\n score += 1.0 + 0.5 * (len(keyword.split()) - 1)\n if score > best_score:\n best, best_score = lesson, score\n\n if best is None:\n return None\n if not wants_explanation and best_score < 2.0:\n return None\n if wants_explanation and best_score < 1.0:\n return None\n return best.text", "source_file": "knowledge.py", "function_name": "answer_knowledge", "class_name": null, "line_start": 899, "line_end": 938, "license": "mit", "source": "SadikAI project"}
{"task": "code_explanation", "language": "python", "instruction": "Explain what this Python function does.\n\n```python\ndef creator_reply() -> str:\n \"\"\"Answer 'who made you?' honestly, with the creator credit.\"\"\"\n return (\n f\"{MODEL_NAME} was created by {CREATOR_NAME}. He is {CREATOR_AGE} years old and \"\n f\"studies in {CREATOR_GRADE}. He built this AI as a local project on a home \"\n \"computer, using open-source tools.\\n\\n\"\n f\"'{MODEL_NAME}' is the project name. The language model inside has {PARAMS} \"\n \"parameters, which is small enough to run without a big GPU. The chat layer adds \"\n \"memory, web lookup, maths, coding help, media tools, and lessons on topics like \"\n \"teamwork, world religions, kindness and study skills.\\n\\n\"\n \"So if you ask 'who made you?', the answer is: \"\n f\"{CREATOR_NAME}, {CREATOR_AGE} years old, {CREATOR_GRADE}.\"\n )\n```", "response": "Answer 'who made you?' honestly, with the creator credit.", "source_file": "knowledge.py", "function_name": "creator_reply", "class_name": null, "line_start": 941, "line_end": 953, "license": "mit", "source": "SadikAI project"}
{"task": "code_generation", "language": "python", "instruction": "Write a Python function `creator_reply()` that does the following:\n\nAnswer 'who made you?' honestly, with the creator credit.\n\nReturn only the Python code.", "response": "def creator_reply() -> str:\n \"\"\"Answer 'who made you?' honestly, with the creator credit.\"\"\"\n return (\n f\"{MODEL_NAME} was created by {CREATOR_NAME}. He is {CREATOR_AGE} years old and \"\n f\"studies in {CREATOR_GRADE}. He built this AI as a local project on a home \"\n \"computer, using open-source tools.\\n\\n\"\n f\"'{MODEL_NAME}' is the project name. The language model inside has {PARAMS} \"\n \"parameters, which is small enough to run without a big GPU. The chat layer adds \"\n \"memory, web lookup, maths, coding help, media tools, and lessons on topics like \"\n \"teamwork, world religions, kindness and study skills.\\n\\n\"\n \"So if you ask 'who made you?', the answer is: \"\n f\"{CREATOR_NAME}, {CREATOR_AGE} years old, {CREATOR_GRADE}.\"\n )", "source_file": "knowledge.py", "function_name": "creator_reply", "class_name": null, "line_start": 941, "line_end": 953, "license": "mit", "source": "SadikAI project"}
{"task": "code_completion", "language": "python", "instruction": "Complete the following Python code. Return only the continuation, preserving indentation.\n\n```python\ndef iter_documents():\n for lesson in LESSONS:\n for template in PROMPTS:\n yield {\n \"topic\": lesson.key,\n \"title\": lesson.title,\n \"text\": template.format(title=lesson.title, text=lesson.text),\n }\n```", "response": " yield {\n \"topic\": \"creator\",\n \"title\": \"The creator\",\n \"text\": (\n f\"Who made {MODEL_NAME}?\\n\\n\"\n f\"{MODEL_NAME} was created by {CREATOR_NAME}, who is {CREATOR_AGE} years old \"\n f\"and studies in {CREATOR_GRADE}. The project is a local AI that runs on a \"\n f\"home computer.\\n\\n{creator_reply()}\"\n ),\n }", "source_file": "lessons.py", "function_name": "iter_documents", "class_name": null, "line_start": 30, "line_end": 47, "license": "mit", "source": "SadikAI project"}
{"task": "code_completion", "language": "python", "instruction": "Complete the following Python code. Return only the continuation, preserving indentation.\n\n```python\ndef main() -> None:\n ap = argparse.ArgumentParser(description=__doc__,\n formatter_class=argparse.RawDescriptionHelpFormatter)\n ap.add_argument(\"--out\", type=Path, default=Path(\"data/raw/lessons/lessons.jsonl\"))\n args = ap.parse_args()\n\n args.out.parent.mkdir(parents=True, exist_ok=True)\n```", "response": " count = 0\n chars = 0\n with args.out.open(\"w\", encoding=\"utf-8\", newline=\"\\n\") as handle:\n for doc in iter_documents():\n handle.write(json.dumps(doc, ensure_ascii=False) + \"\\n\")\n count += 1\n chars += len(doc[\"text\"])\n print(f\"wrote {count} lesson documents, {chars / 1000:.1f}K chars -> {args.out}\")", "source_file": "lessons.py", "function_name": "main", "class_name": null, "line_start": 50, "line_end": 64, "license": "mit", "source": "SadikAI project"}
{"task": "code_completion", "language": "python", "instruction": "Complete the following Python code. Return only the continuation, preserving indentation.\n\n```python\ndef _en_sub(a: int, b: int):\n lo, hi = min(a, b), max(a, b)\n q = f\"What is {hi} - {lo}?\"\n```", "response": " steps = [f\"{hi} - {lo} = {hi - lo}\"]\n return q, steps, str(hi - lo)", "source_file": "math_drills.py", "function_name": "_en_sub", "class_name": null, "line_start": 35, "line_end": 39, "license": "mit", "source": "SadikAI project"}
{"task": "code_completion", "language": "python", "instruction": "Complete the following Python code. Return only the continuation, preserving indentation.\n\n```python\ndef _en_div(a: int, b: int):\n \"\"\"Exact division: b divides a.\"\"\"\n q = f\"What is {a} / {b}?\"\n```", "response": " steps = [f\"{b} x {a // b} = {a}\", f\"{a} / {b} = {a // b}\"]\n return q, steps, str(a // b)", "source_file": "math_drills.py", "function_name": "_en_div", "class_name": null, "line_start": 48, "line_end": 52, "license": "mit", "source": "SadikAI project"}
{"task": "code_completion", "language": "python", "instruction": "Complete the following Python code. Return only the continuation, preserving indentation.\n\n```python\ndef _en_percent(p: int, n: int):\n value = n * p / 100\n q = f\"What is {p}% of {n}?\"\n```", "response": " steps = [f\"{p}% = {p}/100\", f\"{p}/100 x {n} = {value:g}\"]\n return q, steps, f\"{value:g}\"", "source_file": "math_drills.py", "function_name": "_en_percent", "class_name": null, "line_start": 55, "line_end": 59, "license": "mit", "source": "SadikAI project"}
{"task": "code_completion", "language": "python", "instruction": "Complete the following Python code. Return only the continuation, preserving indentation.\n\n```python\ndef _en_average(nums: list[int]):\n total = sum(nums)\n q = f\"What is the average of {', '.join(map(str, nums))}?\"\n```", "response": " steps = [f\"sum = {' + '.join(map(str, nums))} = {total}\",\n f\"average = {total} / {len(nums)} = {total / len(nums):g}\"]\n return q, steps, f\"{total / len(nums):g}\"", "source_file": "math_drills.py", "function_name": "_en_average", "class_name": null, "line_start": 62, "line_end": 67, "license": "mit", "source": "SadikAI project"}
{"task": "code_completion", "language": "python", "instruction": "Complete the following Python code. Return only the continuation, preserving indentation.\n\n```python\ndef _en_linear(a: int, x: int, b: int):\n c = a * x + b\n sign = \"+\" if b >= 0 else \"-\"\n```", "response": " q = f\"Solve for x: {a}x {sign} {abs(b)} = {c}\"\n steps = [f\"{a}x = {c} {sign} {abs(b)} = {c - b}\",\n f\"x = {c - b} / {a} = {x}\"]\n return q, steps, str(x)", "source_file": "math_drills.py", "function_name": "_en_linear", "class_name": null, "line_start": 94, "line_end": 100, "license": "mit", "source": "SadikAI project"}
{"task": "code_completion", "language": "python", "instruction": "Complete the following Python code. Return only the continuation, preserving indentation.\n\n```python\ndef _en_word(price: int, qty: int, paid: int):\n cost = price * qty\n change = paid - cost\n```", "response": " q = (f\"A pen costs Rs {price}. Sadik buys {qty} pens and pays \"\n f\"Rs {paid}. How much change does he get?\")\n steps = [f\"cost = {price} x {qty} = {cost}\",\n f\"change = {paid} - {cost} = {change}\"]\n return q, steps, f\"Rs {change}\"", "source_file": "math_drills.py", "function_name": "_en_word", "class_name": null, "line_start": 103, "line_end": 110, "license": "mit", "source": "SadikAI project"}
{"task": "code_completion", "language": "python", "instruction": "Complete the following Python code. Return only the continuation, preserving indentation.\n\n```python\ndef _en_fraction(num: int, den: int):\n from fractions import Fraction\n from math import gcd\n```", "response": " f = Fraction(num, den)\n q = f\"Simplify the fraction {num}/{den}.\"\n steps = [f\"gcd({num}, {den}) = {gcd(num, den)}\",\n f\"{num}/{den} = {f.numerator}/{f.denominator}\"]\n return q, steps, f\"{f.numerator}/{f.denominator}\"", "source_file": "math_drills.py", "function_name": "_en_fraction", "class_name": null, "line_start": 113, "line_end": 121, "license": "mit", "source": "SadikAI project"}
{"task": "code_completion", "language": "python", "instruction": "Complete the following Python code. Return only the continuation, preserving indentation.\n\n```python\ndef _en_time(hours: int, minutes: int):\n total = hours * 60 + minutes\n q = f\"How many minutes are there in {hours} hours and {minutes} minutes?\"\n```", "response": " steps = [f\"{hours} x 60 = {hours * 60}\", f\"{hours * 60} + {minutes} = {total}\"]\n return q, steps, f\"{total} minutes\"", "source_file": "math_drills.py", "function_name": "_en_time", "class_name": null, "line_start": 124, "line_end": 128, "license": "mit", "source": "SadikAI project"}
{"task": "code_completion", "language": "python", "instruction": "Complete the following Python code. Return only the continuation, preserving indentation.\n\n```python\ndef _hi_word(price: int, qty: int):\n q = (f\"Ek pen ki keemat Rs {price} hai. {qty} pen kharidne par kitne rupaye \"\n f\"lagenge?\")\n```", "response": " steps = [f\"{price} x {qty} = {price * qty}\"]\n return q, steps, f\"Rs {price * qty}\"", "source_file": "math_drills.py", "function_name": "_hi_word", "class_name": null, "line_start": 143, "line_end": 147, "license": "mit", "source": "SadikAI project"}
{"task": "code_completion", "language": "python", "instruction": "Complete the following Python code. Return only the continuation, preserving indentation.\n\n```python\ndef _en_code_drill(n: int):\n q = (f\"Write a Python function that returns the sum of the first {n} \"\n f\"positive integers.\")\n```", "response": " steps = [\n \"def sum_first(n):\",\n \" return n * (n + 1) // 2\",\n f\"sum_first({n}) = {n * (n + 1) // 2}\",\n ]\n return q, steps, str(n * (n + 1) // 2)", "source_file": "math_drills.py", "function_name": "_en_code_drill", "class_name": null, "line_start": 150, "line_end": 158, "license": "mit", "source": "SadikAI project"}
{"task": "code_completion", "language": "python", "instruction": "Complete the following Python code. Return only the continuation, preserving indentation.\n\n```python\ndef _build(rng: random.Random, languages: list[str], coding: bool) -> str:\n kind = rng.choices(\n [\"add\", \"sub\", \"mul\", \"div\", \"percent\", \"average\", \"gcd\", \"lcm\",\n \"square\", \"linear\", \"word\", \"fraction\", \"time\", \"code\"],\n weights=[14, 10, 14, 8, 6, 5, 3, 3, 4, 5, 6, 4, 3, 4 if coding else 0],\n )[0]\n\n if kind == \"add\":\n a, b = rng.randint(1, 9999), rng.randint(1, 9999)\n q, s, ans = _en_add(a, b)\n elif kind == \"sub\":\n a, b = rng.randint(1, 9999), rng.randint(1, 9999)\n q, s, ans = _en_sub(a, b)\n elif kind == \"mul\":\n a = rng.choice([rng.randint(2, 12), rng.randint(2, 99), rng.randint(10, 999)])\n b = rng.choice([rng.randint(2, 12), rng.randint(2, 99)])\n q, s, ans = _en_mul(a, b)\n elif kind == \"div\":\n b = rng.randint(2, 12)\n qv = rng.randint(2, 120)\n q, s, ans = _en_div(b * qv, b)\n elif kind == \"percent\":\n p = rng.choice([5, 10, 12, 15, 20, 25, 30, 40, 50, 60, 75, 80, 90])\n n = rng.randint(2, 500) * 4\n q, s, ans = _en_percent(p, n)\n elif kind == \"average\":\n nums = [rng.randint(1, 200) for _ in range(rng.randint(3, 6))]\n q, s, ans = _en_average(nums)\n elif kind == \"gcd\":\n a, b = rng.randint(2, 200), rng.randint(2, 200)\n q, s, ans = _en_gcd(a, b)\n elif kind == \"lcm\":\n a, b = rng.randint(2, 40), rng.randint(2, 40)\n q, s, ans = _en_lcm(a, b)\n elif kind == \"square\":\n n = rng.randint(2, 100)\n q, s, ans = _en_square(n)\n elif kind == \"linear\":\n a = rng.randint(2, 12)\n x = rng.randint(-20, 20)\n b = rng.randint(-50, 50)\n q, s, ans = _en_linear(a, x, b)\n elif kind == \"word\":\n price = rng.randint(2, 50)\n qty = rng.randint(2, 20)\n paid = price * qty + rng.choice([5, 10, 20, 50, 100])\n q, s, ans = _en_word(price, qty, paid)\n elif kind == \"fraction\":\n num = rng.randint(2, 120)\n den = rng.randint(2, 120)\n q, s, ans = _en_fraction(num, den)\n elif kind == \"time\":\n q, s, ans = _en_time(rng.randint(1, 12), rng.randint(0, 59))\n else:\n q, s, ans = _en_code_drill(rng.randint(5, 500))\n```", "response": " text = _render(q, s, ans)\n\n # A slice of the easy operations is echoed in Hindi/Hinglish phrasing so the\n # arithmetic transfers across the four languages instead of staying English.\n if \"hinglish\" in languages and kind in {\"add\", \"mul\", \"word\"} and rng.random() < 0.35:\n if kind == \"add\":\n a, b = rng.randint(2, 999), rng.randint(2, 999)\n q2, s2, ans2 = _hi_add(a, b)\n elif kind == \"mul\":\n a, b = rng.randint(2, 30), rng.randint(2, 12)\n q2, s2, ans2 = _hi_mul(a, b)\n else:\n price, qty = rng.randint(5, 100), rng.randint(2, 12)\n q2, s2, ans2 = _hi_word(price, qty)\n text += \"\\n\" + _render(q2, s2, ans2)\n\n if \"hindi\" in languages and rng.random() < 0.12:\n a, b = rng.randint(2, 999), rng.randint(2, 999)\n q2, s2, ans2 = _hi_add(a, b)\n text += \"\\n\" + _render(q2, s2, ans2)\n\n return text", "source_file": "math_drills.py", "function_name": "_build", "class_name": null, "line_start": 167, "line_end": 244, "license": "mit", "source": "SadikAI project"}
{"task": "code_completion", "language": "python", "instruction": "Complete the following Python code. Return only the continuation, preserving indentation.\n\n```python\ndef main() -> None:\n ap = argparse.ArgumentParser(description=__doc__,\n formatter_class=argparse.RawDescriptionHelpFormatter)\n ap.add_argument(\"--out\", default=\"data/raw/math/drills.jsonl\")\n ap.add_argument(\"--mb\", type=float, default=8.0)\n ap.add_argument(\"--seed\", type=int, default=1234)\n ap.add_argument(\"--languages\", default=\"english,hinglish,hindi\")\n ap.add_argument(\"--no-coding\", action=\"store_true\")\n args = ap.parse_args()\n\n rng = random.Random(args.seed)\n languages = [x.strip() for x in args.languages.split(\",\") if x.strip()]\n limit = int(args.mb * MB)\n dest = Path(args.out)\n```", "response": " dest.parent.mkdir(parents=True, exist_ok=True)\n\n docs = 0\n written = 0\n with dest.open(\"w\", encoding=\"utf-8\", newline=\"\\n\") as fh:\n while written < limit:\n text = _build(rng, languages, coding=not args.no_coding)\n line = json.dumps({\"text\": text}, ensure_ascii=False) + \"\\n\"\n fh.write(line)\n written += len(line.encode(\"utf-8\"))\n docs += 1\n if docs % 20000 == 0:\n print(f\" {docs:,} problems, {written / MB:.1f} MB\", end=\"\\r\",\n flush=True)\n\n print(f\" math drills: {docs:,} worked problems, {written / MB:.2f} MB -> {dest}\")", "source_file": "math_drills.py", "function_name": "main", "class_name": null, "line_start": 247, "line_end": 276, "license": "mit", "source": "SadikAI project"}
{"task": "code_completion", "language": "python", "instruction": "Complete the following Python code. Return only the continuation, preserving indentation.\n\n```python\n def to_dict(self) -> dict:\n try:\n size = self.path.stat().st_size\n except OSError:\n size = 0\n mime = self.mime or mimetypes.guess_type(self.path.name)[0] or \"application/octet-stream\"\n```", "response": " return {\n \"kind\": self.kind,\n \"name\": self.name,\n \"url\": f\"/files/{FOLDERS[self.kind]}/{urllib.parse.quote(self.name)}\",\n \"mime\": mime,\n \"size\": size,\n \"path\": str(self.path),\n \"note\": self.note,\n }", "source_file": "media.py", "function_name": "to_dict", "class_name": "Artifact", "line_start": 76, "line_end": 90, "license": "mit", "source": "SadikAI project"}
{"task": "code_completion", "language": "python", "instruction": "Complete the following Python code. Return only the continuation, preserving indentation.\n\n```python\ndef _clean_prompt(text: str) -> str:\n text = text.strip().strip(\"\\\"'“”\")\n text = re.sub(r\"^(?:of|showing|with|about|for)\\s+\", \"\", text, flags=re.I)\n```", "response": " text = re.sub(r\"\\s+(?:please|karo|banao|bana do)\\s*$\", \"\", text, flags=re.I)\n return text.strip(\" .!,\")", "source_file": "media.py", "function_name": "_clean_prompt", "class_name": null, "line_start": 122, "line_end": 126, "license": "mit", "source": "SadikAI project"}
{"task": "code_completion", "language": "python", "instruction": "Complete the following Python code. Return only the continuation, preserving indentation.\n\n```python\ndef _font(size: int, devanagari: bool = False) -> ImageFont.FreeTypeFont:\n windows = Path(os.environ.get(\"WINDIR\", r\"C:\\Windows\")) / \"Fonts\"\n choices = ([\"nirmala.ttf\", \"segoeui.ttf\", \"arial.ttf\"] if devanagari\n else [\"segoeui.ttf\", \"arial.ttf\"])\n```", "response": " for name in choices:\n path = windows / name\n if path.exists():\n try:\n return ImageFont.truetype(str(path), size)\n except OSError:\n continue\n return ImageFont.load_default()", "source_file": "media.py", "function_name": "_font", "class_name": null, "line_start": 133, "line_end": 144, "license": "mit", "source": "SadikAI project"}
{"task": "code_completion", "language": "python", "instruction": "Complete the following Python code. Return only the continuation, preserving indentation.\n\n```python\ndef _local_image(prompt: str, width: int, height: int) -> Image.Image:\n \"\"\"An offline geometric poster, not AI art: honest and always available.\"\"\"\n rng = random.Random(prompt)\n palette = [\n ((14, 20, 38), (88, 44, 120)),\n ((10, 34, 40), (18, 110, 96)),\n ((44, 18, 20), (190, 90, 40)),\n ((20, 24, 50), (30, 120, 180)),\n ((34, 18, 48), (150, 60, 120)),\n ]\n top, bottom = palette[rng.randrange(len(palette))]\n image = Image.new(\"RGB\", (width, height))\n draw = ImageDraw.Draw(image)\n for y in range(height):\n t = y / max(1, height - 1)\n color = tuple(int(top[i] + (bottom[i] - top[i]) * t) for i in range(3))\n draw.line([(0, y), (width, y)], fill=color)\n\n overlay = Image.new(\"RGBA\", (width, height), (0, 0, 0, 0))\n od = ImageDraw.Draw(overlay)\n for _ in range(16):\n radius = rng.randint(width // 12, width // 3)\n x = rng.randint(-radius, width)\n y = rng.randint(-radius, height)\n color = (rng.randint(120, 255), rng.randint(120, 255), rng.randint(120, 255),\n rng.randint(18, 54))\n od.ellipse([x, y, x + radius, y + radius], fill=color)\n```", "response": " for _ in range(5):\n points = [(rng.randint(0, width), rng.randint(0, height)) for _ in range(3)]\n od.polygon(points, fill=(255, 255, 255, rng.randint(8, 22)))\n image = Image.alpha_composite(image.convert(\"RGBA\"), overlay).convert(\"RGB\")\n\n draw = ImageDraw.Draw(image)\n devanagari = bool(re.search(r\"[\\u0900-\\u097F]\", prompt))\n title_font = _font(max(22, width // 20), devanagari)\n small_font = _font(max(14, width // 40), devanagari)\n wrapped = textwrap.wrap(prompt, width=max(18, width // 22))[:4] or [\"generated poster\"]\n lines = [\"LOCAL POSTER\"] + wrapped\n line_heights = [draw.textbbox((0, 0), line, font=title_font)[3] + 8 for line in lines]\n box_height = sum(line_heights) + 28\n band = Image.new(\"RGBA\", (width, box_height), (0, 0, 0, 150))\n image.paste(Image.alpha_composite(\n image.crop((0, height - box_height, width, height)).convert(\"RGBA\"), band\n ).convert(\"RGB\"), (0, height - box_height))\n\n draw = ImageDraw.Draw(image)\n y = height - box_height + 14\n for index, line in enumerate(lines):\n font = small_font if index == 0 else title_font\n color = (160, 200, 255) if index == 0 else (245, 245, 245)\n draw.text((24, y), line, font=font, fill=color)\n y += line_heights[index]\n return image", "source_file": "media.py", "function_name": "_local_image", "class_name": null, "line_start": 147, "line_end": 199, "license": "mit", "source": "SadikAI project"}
{"task": "code_explanation", "language": "python", "instruction": "Explain what this Python function does.\n\n```python\ndef _local_image(prompt: str, width: int, height: int) -> Image.Image:\n \"\"\"An offline geometric poster, not AI art: honest and always available.\"\"\"\n rng = random.Random(prompt)\n palette = [\n ((14, 20, 38), (88, 44, 120)),\n ((10, 34, 40), (18, 110, 96)),\n ((44, 18, 20), (190, 90, 40)),\n ((20, 24, 50), (30, 120, 180)),\n ((34, 18, 48), (150, 60, 120)),\n ]\n top, bottom = palette[rng.randrange(len(palette))]\n image = Image.new(\"RGB\", (width, height))\n draw = ImageDraw.Draw(image)\n for y in range(height):\n t = y / max(1, height - 1)\n color = tuple(int(top[i] + (bottom[i] - top[i]) * t) for i in range(3))\n draw.line([(0, y), (width, y)], fill=color)\n\n overlay = Image.new(\"RGBA\", (width, height), (0, 0, 0, 0))\n od = ImageDraw.Draw(overlay)\n for _ in range(16):\n radius = rng.randint(width // 12, width // 3)\n x = rng.randint(-radius, width)\n y = rng.randint(-radius, height)\n color = (rng.randint(120, 255), rng.randint(120, 255), rng.randint(120, 255),\n rng.randint(18, 54))\n od.ellipse([x, y, x + radius, y + radius], fill=color)\n for _ in range(5):\n points = [(rng.randint(0, width), rng.randint(0, height)) for _ in range(3)]\n od.polygon(points, fill=(255, 255, 255, rng.randint(8, 22)))\n image = Image.alpha_composite(image.convert(\"RGBA\"), overlay).convert(\"RGB\")\n\n draw = ImageDraw.Draw(image)\n devanagari = bool(re.search(r\"[\\u0900-\\u097F]\", prompt))\n title_font = _font(max(22, width // 20), devanagari)\n small_font = _font(max(14, width // 40), devanagari)\n wrapped = textwrap.wrap(prompt, width=max(18, width // 22))[:4] or [\"generated poster\"]\n lines = [\"LOCAL POSTER\"] + wrapped\n line_heights = [draw.textbbox((0, 0), line, font=title_font)[3] + 8 for line in lines]\n box_height = sum(line_heights) + 28\n band = Image.new(\"RGBA\", (width, box_height), (0, 0, 0, 150))\n image.paste(Image.alpha_composite(\n image.crop((0, height - box_height, width, height)).convert(\"RGBA\"), band\n ).convert(\"RGB\"), (0, height - box_height))\n\n draw = ImageDraw.Draw(image)\n y = height - box_height + 14\n for index, line in enumerate(lines):\n font = small_font if index == 0 else title_font\n color = (160, 200, 255) if index == 0 else (245, 245, 245)\n draw.text((24, y), line, font=font, fill=color)\n y += line_heights[index]\n return image\n```", "response": "An offline geometric poster, not AI art: honest and always available.", "source_file": "media.py", "function_name": "_local_image", "class_name": null, "line_start": 147, "line_end": 199, "license": "mit", "source": "SadikAI project"}
{"task": "code_generation", "language": "python", "instruction": "Write a Python function `_local_image(prompt: str, width: int, height: int)` that does the following:\n\nAn offline geometric poster, not AI art: honest and always available.\n\nReturn only the Python code.", "response": "def _local_image(prompt: str, width: int, height: int) -> Image.Image:\n \"\"\"An offline geometric poster, not AI art: honest and always available.\"\"\"\n rng = random.Random(prompt)\n palette = [\n ((14, 20, 38), (88, 44, 120)),\n ((10, 34, 40), (18, 110, 96)),\n ((44, 18, 20), (190, 90, 40)),\n ((20, 24, 50), (30, 120, 180)),\n ((34, 18, 48), (150, 60, 120)),\n ]\n top, bottom = palette[rng.randrange(len(palette))]\n image = Image.new(\"RGB\", (width, height))\n draw = ImageDraw.Draw(image)\n for y in range(height):\n t = y / max(1, height - 1)\n color = tuple(int(top[i] + (bottom[i] - top[i]) * t) for i in range(3))\n draw.line([(0, y), (width, y)], fill=color)\n\n overlay = Image.new(\"RGBA\", (width, height), (0, 0, 0, 0))\n od = ImageDraw.Draw(overlay)\n for _ in range(16):\n radius = rng.randint(width // 12, width // 3)\n x = rng.randint(-radius, width)\n y = rng.randint(-radius, height)\n color = (rng.randint(120, 255), rng.randint(120, 255), rng.randint(120, 255),\n rng.randint(18, 54))\n od.ellipse([x, y, x + radius, y + radius], fill=color)\n for _ in range(5):\n points = [(rng.randint(0, width), rng.randint(0, height)) for _ in range(3)]\n od.polygon(points, fill=(255, 255, 255, rng.randint(8, 22)))\n image = Image.alpha_composite(image.convert(\"RGBA\"), overlay).convert(\"RGB\")\n\n draw = ImageDraw.Draw(image)\n devanagari = bool(re.search(r\"[\\u0900-\\u097F]\", prompt))\n title_font = _font(max(22, width // 20), devanagari)\n small_font = _font(max(14, width // 40), devanagari)\n wrapped = textwrap.wrap(prompt, width=max(18, width // 22))[:4] or [\"generated poster\"]\n lines = [\"LOCAL POSTER\"] + wrapped\n line_heights = [draw.textbbox((0, 0), line, font=title_font)[3] + 8 for line in lines]\n box_height = sum(line_heights) + 28\n band = Image.new(\"RGBA\", (width, box_height), (0, 0, 0, 150))\n image.paste(Image.alpha_composite(\n image.crop((0, height - box_height, width, height)).convert(\"RGBA\"), band\n ).convert(\"RGB\"), (0, height - box_height))\n\n draw = ImageDraw.Draw(image)\n y = height - box_height + 14\n for index, line in enumerate(lines):\n font = small_font if index == 0 else title_font\n color = (160, 200, 255) if index == 0 else (245, 245, 245)\n draw.text((24, y), line, font=font, fill=color)\n y += line_heights[index]\n return image", "source_file": "media.py", "function_name": "_local_image", "class_name": null, "line_start": 147, "line_end": 199, "license": "mit", "source": "SadikAI project"}
{"task": "code_completion", "language": "python", "instruction": "Complete the following Python code. Return only the continuation, preserving indentation.\n\n```python\ndef generate_image(prompt: str, width: int = 768, height: int = 768,\n allow_network: bool = True, seed: int | None = None) -> Artifact:\n \"\"\"Generate an image from a prompt; fall back to a local poster offline.\"\"\"\n prompt = _clean_prompt(prompt)\n if not prompt:\n raise ValueError(\"an image prompt is required\")\n\n width = max(256, min(IMAGE_MAX, int(width)))\n height = max(256, min(IMAGE_MAX, int(height)))\n folder = _folder(\"image\")\n path = _unique(folder / f\"{_slug(prompt)}_{_stamp()}.png\")\n note = \"\"\n```", "response": " if allow_network:\n params = {\n \"width\": width, \"height\": height, \"nologo\": \"true\",\n \"seed\": seed if seed is not None else random.randint(0, 2**31 - 1),\n }\n url = (\"https://image.pollinations.ai/prompt/\"\n + urllib.parse.quote(prompt, safe=\"\") + \"?\"\n + urllib.parse.urlencode(params))\n request = urllib.request.Request(url, headers={\"User-Agent\": \"sadik-ai/1.0\"})\n try:\n with urllib.request.urlopen(request, timeout=IMAGE_TIMEOUT) as response:\n raw = response.read(12 * 1024 * 1024)\n with Image.open(io.BytesIO(raw)) as downloaded:\n downloaded.convert(\"RGB\").save(path, \"PNG\")\n note = \"AI image from pollinations.ai (the prompt was sent online)\"\n return Artifact(\"image\", path, note=note)\n except Exception as exc: # noqa: BLE001 - any network failure -> local art\n note = f\"image service unavailable ({type(exc).__name__}); local poster instead\"\n\n image = _local_image(prompt, width, height)\n image.save(path, \"PNG\")\n return Artifact(\"image\", path, note=note or \"local poster (no network used)\")", "source_file": "media.py", "function_name": "generate_image", "class_name": null, "line_start": 202, "line_end": 236, "license": "mit", "source": "SadikAI project"}
{"task": "code_explanation", "language": "python", "instruction": "Explain what this Python function does.\n\n```python\ndef generate_image(prompt: str, width: int = 768, height: int = 768,\n allow_network: bool = True, seed: int | None = None) -> Artifact:\n \"\"\"Generate an image from a prompt; fall back to a local poster offline.\"\"\"\n prompt = _clean_prompt(prompt)\n if not prompt:\n raise ValueError(\"an image prompt is required\")\n\n width = max(256, min(IMAGE_MAX, int(width)))\n height = max(256, min(IMAGE_MAX, int(height)))\n folder = _folder(\"image\")\n path = _unique(folder / f\"{_slug(prompt)}_{_stamp()}.png\")\n note = \"\"\n\n if allow_network:\n params = {\n \"width\": width, \"height\": height, \"nologo\": \"true\",\n \"seed\": seed if seed is not None else random.randint(0, 2**31 - 1),\n }\n url = (\"https://image.pollinations.ai/prompt/\"\n + urllib.parse.quote(prompt, safe=\"\") + \"?\"\n + urllib.parse.urlencode(params))\n request = urllib.request.Request(url, headers={\"User-Agent\": \"sadik-ai/1.0\"})\n try:\n with urllib.request.urlopen(request, timeout=IMAGE_TIMEOUT) as response:\n raw = response.read(12 * 1024 * 1024)\n with Image.open(io.BytesIO(raw)) as downloaded:\n downloaded.convert(\"RGB\").save(path, \"PNG\")\n note = \"AI image from pollinations.ai (the prompt was sent online)\"\n return Artifact(\"image\", path, note=note)\n except Exception as exc: # noqa: BLE001 - any network failure -> local art\n note = f\"image service unavailable ({type(exc).__name__}); local poster instead\"\n\n image = _local_image(prompt, width, height)\n image.save(path, \"PNG\")\n return Artifact(\"image\", path, note=note or \"local poster (no network used)\")\n```", "response": "Generate an image from a prompt; fall back to a local poster offline.", "source_file": "media.py", "function_name": "generate_image", "class_name": null, "line_start": 202, "line_end": 236, "license": "mit", "source": "SadikAI project"}
{"task": "code_generation", "language": "python", "instruction": "Write a Python function `generate_image(prompt: str, width: int=768, height: int=768, allow_network: bool=True, seed: int | None=None)` that does the following:\n\nGenerate an image from a prompt; fall back to a local poster offline.\n\nReturn only the Python code.", "response": "def generate_image(prompt: str, width: int = 768, height: int = 768,\n allow_network: bool = True, seed: int | None = None) -> Artifact:\n \"\"\"Generate an image from a prompt; fall back to a local poster offline.\"\"\"\n prompt = _clean_prompt(prompt)\n if not prompt:\n raise ValueError(\"an image prompt is required\")\n\n width = max(256, min(IMAGE_MAX, int(width)))\n height = max(256, min(IMAGE_MAX, int(height)))\n folder = _folder(\"image\")\n path = _unique(folder / f\"{_slug(prompt)}_{_stamp()}.png\")\n note = \"\"\n\n if allow_network:\n params = {\n \"width\": width, \"height\": height, \"nologo\": \"true\",\n \"seed\": seed if seed is not None else random.randint(0, 2**31 - 1),\n }\n url = (\"https://image.pollinations.ai/prompt/\"\n + urllib.parse.quote(prompt, safe=\"\") + \"?\"\n + urllib.parse.urlencode(params))\n request = urllib.request.Request(url, headers={\"User-Agent\": \"sadik-ai/1.0\"})\n try:\n with urllib.request.urlopen(request, timeout=IMAGE_TIMEOUT) as response:\n raw = response.read(12 * 1024 * 1024)\n with Image.open(io.BytesIO(raw)) as downloaded:\n downloaded.convert(\"RGB\").save(path, \"PNG\")\n note = \"AI image from pollinations.ai (the prompt was sent online)\"\n return Artifact(\"image\", path, note=note)\n except Exception as exc: # noqa: BLE001 - any network failure -> local art\n note = f\"image service unavailable ({type(exc).__name__}); local poster instead\"\n\n image = _local_image(prompt, width, height)\n image.save(path, \"PNG\")\n return Artifact(\"image\", path, note=note or \"local poster (no network used)\")", "source_file": "media.py", "function_name": "generate_image", "class_name": null, "line_start": 202, "line_end": 236, "license": "mit", "source": "SadikAI project"}
{"task": "code_completion", "language": "python", "instruction": "Complete the following Python code. Return only the continuation, preserving indentation.\n\n```python\ndef generate_speech(text: str, voice: str = \"female\", rate: int = 0) -> Artifact:\n \"\"\"Render text to a WAV file with the Windows speech engine.\"\"\"\n text = \" \".join(text.split())\n if not text:\n raise ValueError(\"text to speak is required\")\n truncated = len(text) > AUDIO_MAX_CHARS\n if truncated:\n text = text[:AUDIO_MAX_CHARS].rsplit(\" \", 1)[0] + \".\"\n\n folder = _folder(\"audio\")\n stem = _slug(text, 32)\n path = _unique(folder / f\"{stem}_{_stamp()}.wav\")\n voice_name = PREFERRED_VOICES.get(voice.lower(), voice)\n note = f\"spoken locally with {voice_name or 'the default Windows voice'}\"\n if truncated:\n note += f\" (trimmed to {AUDIO_MAX_CHARS} characters)\"\n if re.search(r\"[\\u0900-\\u097F]\", text):\n note += \"; no Hindi voice is installed, so the pronunciation may be rough\"\n```", "response": " with tempfile.TemporaryDirectory(prefix=\"sadik_tts_\") as tmp:\n script = Path(tmp) / \"speak.ps1\"\n text_path = Path(tmp) / \"text.txt\"\n script.write_text(SAPI_SCRIPT, encoding=\"utf-8\")\n text_path.write_text(text, encoding=\"utf-8\")\n powershell = \"powershell\"\n command = [\n powershell, \"-NoProfile\", \"-NonInteractive\",\n \"-ExecutionPolicy\", \"Bypass\", \"-File\", str(script),\n \"-OutPath\", str(path), \"-TextPath\", str(text_path),\n \"-Voice\", voice_name or \"\", \"-Rate\", str(max(-10, min(10, rate))),\n ]\n try:\n process = subprocess.run(command, capture_output=True, text=True,\n timeout=120, encoding=\"utf-8\", errors=\"replace\")\n except (OSError, subprocess.TimeoutExpired) as exc:\n raise RuntimeError(f\"Windows speech failed: {exc}\") from exc\n if process.returncode != 0 or not path.exists() or path.stat().st_size < 1000:\n detail = (process.stderr or process.stdout or \"\").strip().splitlines()\n raise RuntimeError(\"Windows speech failed: \"\n + (detail[-1] if detail else \"unknown error\"))\n\n return Artifact(\"audio\", path, note=note, mime=\"audio/wav\")", "source_file": "media.py", "function_name": "generate_speech", "class_name": null, "line_start": 269, "line_end": 310, "license": "mit", "source": "SadikAI project"}
{"task": "code_explanation", "language": "python", "instruction": "Explain what this Python function does.\n\n```python\ndef generate_speech(text: str, voice: str = \"female\", rate: int = 0) -> Artifact:\n \"\"\"Render text to a WAV file with the Windows speech engine.\"\"\"\n text = \" \".join(text.split())\n if not text:\n raise ValueError(\"text to speak is required\")\n truncated = len(text) > AUDIO_MAX_CHARS\n if truncated:\n text = text[:AUDIO_MAX_CHARS].rsplit(\" \", 1)[0] + \".\"\n\n folder = _folder(\"audio\")\n stem = _slug(text, 32)\n path = _unique(folder / f\"{stem}_{_stamp()}.wav\")\n voice_name = PREFERRED_VOICES.get(voice.lower(), voice)\n note = f\"spoken locally with {voice_name or 'the default Windows voice'}\"\n if truncated:\n note += f\" (trimmed to {AUDIO_MAX_CHARS} characters)\"\n if re.search(r\"[\\u0900-\\u097F]\", text):\n note += \"; no Hindi voice is installed, so the pronunciation may be rough\"\n\n with tempfile.TemporaryDirectory(prefix=\"sadik_tts_\") as tmp:\n script = Path(tmp) / \"speak.ps1\"\n text_path = Path(tmp) / \"text.txt\"\n script.write_text(SAPI_SCRIPT, encoding=\"utf-8\")\n text_path.write_text(text, encoding=\"utf-8\")\n powershell = \"powershell\"\n command = [\n powershell, \"-NoProfile\", \"-NonInteractive\",\n \"-ExecutionPolicy\", \"Bypass\", \"-File\", str(script),\n \"-OutPath\", str(path), \"-TextPath\", str(text_path),\n \"-Voice\", voice_name or \"\", \"-Rate\", str(max(-10, min(10, rate))),\n ]\n try:\n process = subprocess.run(command, capture_output=True, text=True,\n timeout=120, encoding=\"utf-8\", errors=\"replace\")\n except (OSError, subprocess.TimeoutExpired) as exc:\n raise RuntimeError(f\"Windows speech failed: {exc}\") from exc\n if process.returncode != 0 or not path.exists() or path.stat().st_size < 1000:\n detail = (process.stderr or process.stdout or \"\").strip().splitlines()\n raise RuntimeError(\"Windows speech failed: \"\n + (detail[-1] if detail else \"unknown error\"))\n\n return Artifact(\"audio\", path, note=note, mime=\"audio/wav\")\n```", "response": "Render text to a WAV file with the Windows speech engine.", "source_file": "media.py", "function_name": "generate_speech", "class_name": null, "line_start": 269, "line_end": 310, "license": "mit", "source": "SadikAI project"}
{"task": "code_generation", "language": "python", "instruction": "Write a Python function `generate_speech(text: str, voice: str='female', rate: int=0)` that does the following:\n\nRender text to a WAV file with the Windows speech engine.\n\nReturn only the Python code.", "response": "def generate_speech(text: str, voice: str = \"female\", rate: int = 0) -> Artifact:\n \"\"\"Render text to a WAV file with the Windows speech engine.\"\"\"\n text = \" \".join(text.split())\n if not text:\n raise ValueError(\"text to speak is required\")\n truncated = len(text) > AUDIO_MAX_CHARS\n if truncated:\n text = text[:AUDIO_MAX_CHARS].rsplit(\" \", 1)[0] + \".\"\n\n folder = _folder(\"audio\")\n stem = _slug(text, 32)\n path = _unique(folder / f\"{stem}_{_stamp()}.wav\")\n voice_name = PREFERRED_VOICES.get(voice.lower(), voice)\n note = f\"spoken locally with {voice_name or 'the default Windows voice'}\"\n if truncated:\n note += f\" (trimmed to {AUDIO_MAX_CHARS} characters)\"\n if re.search(r\"[\\u0900-\\u097F]\", text):\n note += \"; no Hindi voice is installed, so the pronunciation may be rough\"\n\n with tempfile.TemporaryDirectory(prefix=\"sadik_tts_\") as tmp:\n script = Path(tmp) / \"speak.ps1\"\n text_path = Path(tmp) / \"text.txt\"\n script.write_text(SAPI_SCRIPT, encoding=\"utf-8\")\n text_path.write_text(text, encoding=\"utf-8\")\n powershell = \"powershell\"\n command = [\n powershell, \"-NoProfile\", \"-NonInteractive\",\n \"-ExecutionPolicy\", \"Bypass\", \"-File\", str(script),\n \"-OutPath\", str(path), \"-TextPath\", str(text_path),\n \"-Voice\", voice_name or \"\", \"-Rate\", str(max(-10, min(10, rate))),\n ]\n try:\n process = subprocess.run(command, capture_output=True, text=True,\n timeout=120, encoding=\"utf-8\", errors=\"replace\")\n except (OSError, subprocess.TimeoutExpired) as exc:\n raise RuntimeError(f\"Windows speech failed: {exc}\") from exc\n if process.returncode != 0 or not path.exists() or path.stat().st_size < 1000:\n detail = (process.stderr or process.stdout or \"\").strip().splitlines()\n raise RuntimeError(\"Windows speech failed: \"\n + (detail[-1] if detail else \"unknown error\"))\n\n return Artifact(\"audio\", path, note=note, mime=\"audio/wav\")", "source_file": "media.py", "function_name": "generate_speech", "class_name": null, "line_start": 269, "line_end": 310, "license": "mit", "source": "SadikAI project"}
{"task": "code_completion", "language": "python", "instruction": "Complete the following Python code. Return only the continuation, preserving indentation.\n\n```python\ndef build_table(text: str) -> tuple[list[list], str] | None:\n \"\"\"Deterministic tables for common data requests.\"\"\"\n low = text.lower()\n\n match = re.search(r\"(?:(\\d+)\\s*(?:x|times)\\s*table|table of\\s*(\\d+)|(\\d+)\\s*ka\\s*table)\", low)\n if match:\n n = int(next(group for group in match.groups() if group))\n rows = [[\"Expression\", \"Result\"]]\n rows += [[f\"{n} x {i}\", n * i] for i in range(1, 11)]\n return rows, f\"{n} times table\"\n\n match = re.search(r\"squares?\\s*(?:of|from|for)?\\s*(\\d+)?\\s*(?:to|-|se)\\s*(\\d+)\", low)\n if match or \"square\" in low:\n if match:\n start = int(match.group(1) or 1)\n end = int(match.group(2))\n else:\n start, end = 1, 20\n start = max(0, start)\n end = min(end, 10000, start + 500)\n rows = [[\"n\", \"n squared\"]] + [[n, n * n] for n in range(start, end + 1)]\n return rows, f\"squares {start} to {end}\"\n```", "response": " match = re.search(r\"primes?\\s*(?:numbers?)?\\s*(?:up to|to|below|under)\\s*(\\d+)\", low)\n if match:\n limit = min(int(match.group(1)), 100000)\n sieve = bytearray(b\"\\x01\") * (limit + 1)\n if limit >= 0:\n sieve[:2] = b\"\\x00\\x00\"\n for number in range(2, int(limit ** 0.5) + 1):\n if sieve[number]:\n sieve[number * number:limit + 1:number] = b\"\\x00\" * (((limit - number * number) // number) + 1)\n primes = [i for i in range(2, limit + 1) if sieve[i]]\n rows = [[\"Index\", \"Prime\"]] + [[i + 1, p] for i, p in enumerate(primes)]\n return rows, f\"prime numbers up to {limit}\"\n\n match = re.search(r\"numbers?\\s*(?:from\\s*)?(\\d+)\\s*(?:to|-|se)\\s*(\\d+)\", low)\n if match:\n start, end = int(match.group(1)), int(match.group(2))\n end = min(end, start + 500)\n rows = [[\"n\", \"n squared\"]] + [[n, n * n] for n in range(start, end + 1)]\n return rows, f\"numbers {start} to {end}\"\n\n return None", "source_file": "media.py", "function_name": "build_table", "class_name": null, "line_start": 317, "line_end": 360, "license": "mit", "source": "SadikAI project"}
{"task": "code_explanation", "language": "python", "instruction": "Explain what this Python function does.\n\n```python\ndef build_table(text: str) -> tuple[list[list], str] | None:\n \"\"\"Deterministic tables for common data requests.\"\"\"\n low = text.lower()\n\n match = re.search(r\"(?:(\\d+)\\s*(?:x|times)\\s*table|table of\\s*(\\d+)|(\\d+)\\s*ka\\s*table)\", low)\n if match:\n n = int(next(group for group in match.groups() if group))\n rows = [[\"Expression\", \"Result\"]]\n rows += [[f\"{n} x {i}\", n * i] for i in range(1, 11)]\n return rows, f\"{n} times table\"\n\n match = re.search(r\"squares?\\s*(?:of|from|for)?\\s*(\\d+)?\\s*(?:to|-|se)\\s*(\\d+)\", low)\n if match or \"square\" in low:\n if match:\n start = int(match.group(1) or 1)\n end = int(match.group(2))\n else:\n start, end = 1, 20\n start = max(0, start)\n end = min(end, 10000, start + 500)\n rows = [[\"n\", \"n squared\"]] + [[n, n * n] for n in range(start, end + 1)]\n return rows, f\"squares {start} to {end}\"\n\n match = re.search(r\"primes?\\s*(?:numbers?)?\\s*(?:up to|to|below|under)\\s*(\\d+)\", low)\n if match:\n limit = min(int(match.group(1)), 100000)\n sieve = bytearray(b\"\\x01\") * (limit + 1)\n if limit >= 0:\n sieve[:2] = b\"\\x00\\x00\"\n for number in range(2, int(limit ** 0.5) + 1):\n if sieve[number]:\n sieve[number * number:limit + 1:number] = b\"\\x00\" * (((limit - number * number) // number) + 1)\n primes = [i for i in range(2, limit + 1) if sieve[i]]\n rows = [[\"Index\", \"Prime\"]] + [[i + 1, p] for i, p in enumerate(primes)]\n return rows, f\"prime numbers up to {limit}\"\n\n match = re.search(r\"numbers?\\s*(?:from\\s*)?(\\d+)\\s*(?:to|-|se)\\s*(\\d+)\", low)\n if match:\n start, end = int(match.group(1)), int(match.group(2))\n end = min(end, start + 500)\n rows = [[\"n\", \"n squared\"]] + [[n, n * n] for n in range(start, end + 1)]\n return rows, f\"numbers {start} to {end}\"\n\n return None\n```", "response": "Deterministic tables for common data requests.", "source_file": "media.py", "function_name": "build_table", "class_name": null, "line_start": 317, "line_end": 360, "license": "mit", "source": "SadikAI project"}
{"task": "code_generation", "language": "python", "instruction": "Write a Python function `build_table(text: str)` that does the following:\n\nDeterministic tables for common data requests.\n\nReturn only the Python code.", "response": "def build_table(text: str) -> tuple[list[list], str] | None:\n \"\"\"Deterministic tables for common data requests.\"\"\"\n low = text.lower()\n\n match = re.search(r\"(?:(\\d+)\\s*(?:x|times)\\s*table|table of\\s*(\\d+)|(\\d+)\\s*ka\\s*table)\", low)\n if match:\n n = int(next(group for group in match.groups() if group))\n rows = [[\"Expression\", \"Result\"]]\n rows += [[f\"{n} x {i}\", n * i] for i in range(1, 11)]\n return rows, f\"{n} times table\"\n\n match = re.search(r\"squares?\\s*(?:of|from|for)?\\s*(\\d+)?\\s*(?:to|-|se)\\s*(\\d+)\", low)\n if match or \"square\" in low:\n if match:\n start = int(match.group(1) or 1)\n end = int(match.group(2))\n else:\n start, end = 1, 20\n start = max(0, start)\n end = min(end, 10000, start + 500)\n rows = [[\"n\", \"n squared\"]] + [[n, n * n] for n in range(start, end + 1)]\n return rows, f\"squares {start} to {end}\"\n\n match = re.search(r\"primes?\\s*(?:numbers?)?\\s*(?:up to|to|below|under)\\s*(\\d+)\", low)\n if match:\n limit = min(int(match.group(1)), 100000)\n sieve = bytearray(b\"\\x01\") * (limit + 1)\n if limit >= 0:\n sieve[:2] = b\"\\x00\\x00\"\n for number in range(2, int(limit ** 0.5) + 1):\n if sieve[number]:\n sieve[number * number:limit + 1:number] = b\"\\x00\" * (((limit - number * number) // number) + 1)\n primes = [i for i in range(2, limit + 1) if sieve[i]]\n rows = [[\"Index\", \"Prime\"]] + [[i + 1, p] for i, p in enumerate(primes)]\n return rows, f\"prime numbers up to {limit}\"\n\n match = re.search(r\"numbers?\\s*(?:from\\s*)?(\\d+)\\s*(?:to|-|se)\\s*(\\d+)\", low)\n if match:\n start, end = int(match.group(1)), int(match.group(2))\n end = min(end, start + 500)\n rows = [[\"n\", \"n squared\"]] + [[n, n * n] for n in range(start, end + 1)]\n return rows, f\"numbers {start} to {end}\"\n\n return None", "source_file": "media.py", "function_name": "build_table", "class_name": null, "line_start": 317, "line_end": 360, "license": "mit", "source": "SadikAI project"}
{"task": "code_completion", "language": "python", "instruction": "Complete the following Python code. Return only the continuation, preserving indentation.\n\n```python\ndef _detect_template(text: str) -> str | None:\n low = text.lower()\n if re.search(r\"\\b(resume|cv|curriculum vitae)\\b\", low):\n return \"resume\"\n```", "response": " if re.search(r\"\\b(invoice|bill)\\b\", low):\n return \"invoice\"\n return None", "source_file": "media.py", "function_name": "_detect_template", "class_name": null, "line_start": 398, "line_end": 404, "license": "mit", "source": "SadikAI project"}
{"task": "code_completion", "language": "python", "instruction": "Complete the following Python code. Return only the continuation, preserving indentation.\n\n```python\ndef _plain(text: str) -> str:\n \"\"\"Turn light markdown into text that reads well in PDF/DOCX.\"\"\"\n lines = []\n```", "response": " for line in text.splitlines():\n if line.startswith(\"# \"):\n lines.append(line[2:].strip().upper())\n elif line.startswith(\"## \"):\n lines.append(line[3:].strip())\n elif line.startswith(\"- \"):\n lines.append(\"• \" + line[2:].strip())\n else:\n lines.append(line)\n return \"\\n\".join(lines).strip()", "source_file": "media.py", "function_name": "_plain", "class_name": null, "line_start": 407, "line_end": 419, "license": "mit", "source": "SadikAI project"}
{"task": "code_explanation", "language": "python", "instruction": "Explain what this Python function does.\n\n```python\ndef _plain(text: str) -> str:\n \"\"\"Turn light markdown into text that reads well in PDF/DOCX.\"\"\"\n lines = []\n for line in text.splitlines():\n if line.startswith(\"# \"):\n lines.append(line[2:].strip().upper())\n elif line.startswith(\"## \"):\n lines.append(line[3:].strip())\n elif line.startswith(\"- \"):\n lines.append(\"• \" + line[2:].strip())\n else:\n lines.append(line)\n return \"\\n\".join(lines).strip()\n```", "response": "Turn light markdown into text that reads well in PDF/DOCX.", "source_file": "media.py", "function_name": "_plain", "class_name": null, "line_start": 407, "line_end": 419, "license": "mit", "source": "SadikAI project"}
{"task": "code_generation", "language": "python", "instruction": "Write a Python function `_plain(text: str)` that does the following:\n\nTurn light markdown into text that reads well in PDF/DOCX.\n\nReturn only the Python code.", "response": "def _plain(text: str) -> str:\n \"\"\"Turn light markdown into text that reads well in PDF/DOCX.\"\"\"\n lines = []\n for line in text.splitlines():\n if line.startswith(\"# \"):\n lines.append(line[2:].strip().upper())\n elif line.startswith(\"## \"):\n lines.append(line[3:].strip())\n elif line.startswith(\"- \"):\n lines.append(\"• \" + line[2:].strip())\n else:\n lines.append(line)\n return \"\\n\".join(lines).strip()", "source_file": "media.py", "function_name": "_plain", "class_name": null, "line_start": 407, "line_end": 419, "license": "mit", "source": "SadikAI project"}
{"task": "code_completion", "language": "python", "instruction": "Complete the following Python code. Return only the continuation, preserving indentation.\n\n```python\ndef _write_pdf(path: Path, content: str) -> None:\n from fpdf import FPDF\n\n text = _plain(content)\n windows = Path(os.environ.get(\"WINDIR\", r\"C:\\Windows\")) / \"Fonts\"\n font = windows / (\"nirmala.ttf\" if re.search(r\"[\\u0900-\\u097F]\", text)\n else \"segoeui.ttf\")\n if not font.exists():\n font = windows / \"arial.ttf\"\n```", "response": " pdf = FPDF()\n pdf.set_auto_page_break(auto=True, margin=15)\n pdf.add_page()\n if font.exists():\n pdf.add_font(\"Body\", \"\", str(font))\n pdf.set_font(\"Body\", size=11)\n else:\n pdf.set_font(\"Helvetica\", size=11)\n safe = \"\".join(ch for ch in text if ch == \"\\n\" or ord(ch) <= 0xFFFF)\n pdf.multi_cell(0, 6.5, safe or \"(empty document)\")\n pdf.output(str(path))", "source_file": "media.py", "function_name": "_write_pdf", "class_name": null, "line_start": 422, "line_end": 442, "license": "mit", "source": "SadikAI project"}
{"task": "code_completion", "language": "python", "instruction": "Complete the following Python code. Return only the continuation, preserving indentation.\n\n```python\ndef _write_docx(path: Path, content: str) -> None:\n from docx import Document\n\n document = Document()\n```", "response": " for block in content.split(\"\\n\"):\n stripped = block.strip()\n if not stripped:\n continue\n if stripped.startswith(\"# \"):\n document.add_heading(stripped[2:].strip(), level=1)\n elif stripped.startswith(\"## \"):\n document.add_heading(stripped[3:].strip(), level=2)\n elif stripped.startswith(\"- \"):\n document.add_paragraph(stripped[2:].strip(), style=\"List Bullet\")\n else:\n document.add_paragraph(stripped)\n document.save(str(path))", "source_file": "media.py", "function_name": "_write_docx", "class_name": null, "line_start": 445, "line_end": 461, "license": "mit", "source": "SadikAI project"}
{"task": "code_completion", "language": "python", "instruction": "Complete the following Python code. Return only the continuation, preserving indentation.\n\n```python\ndef _write_xlsx(path: Path, rows: list[list], title: str = \"\") -> None:\n from openpyxl import Workbook\n from openpyxl.styles import Font, PatternFill\n from openpyxl.utils import get_column_letter\n\n workbook = Workbook()\n sheet = workbook.active\n sheet.title = (re.sub(r\"[^A-Za-z0-9 ]\", \"\", title) or \"Sheet1\")[:31]\n for row in rows:\n sheet.append(row)\n```", "response": " if rows:\n for cell in sheet[1]:\n cell.font = Font(bold=True, color=\"FFFFFF\")\n cell.fill = PatternFill(\"solid\", fgColor=\"2F5597\")\n sheet.freeze_panes = \"A2\"\n for index in range(1, len(rows[0]) + 1):\n width = max(len(str(row[index - 1])) if index - 1 < len(row) else 0\n for row in rows)\n sheet.column_dimensions[get_column_letter(index)].width = min(48, max(10, width + 3))\n workbook.save(str(path))", "source_file": "media.py", "function_name": "_write_xlsx", "class_name": null, "line_start": 464, "line_end": 483, "license": "mit", "source": "SadikAI project"}
{"task": "code_completion", "language": "python", "instruction": "Complete the following Python code. Return only the continuation, preserving indentation.\n\n```python\ndef _load_rows(name: str, content: str, rows: list[list] | None) -> list[list]:\n if rows:\n return rows\n```", "response": " lines = [line for line in content.splitlines() if line.strip()]\n parsed = list(csv.reader(lines)) if lines else []\n return parsed or [[\"Content\"], [content]] if content else [[\"Content\"], [\"\"]]", "source_file": "media.py", "function_name": "_load_rows", "class_name": null, "line_start": 486, "line_end": 491, "license": "mit", "source": "SadikAI project"}
{"task": "code_completion", "language": "python", "instruction": "Complete the following Python code. Return only the continuation, preserving indentation.\n\n```python\ndef generate_file(name: str, content: str = \"\", rows: list[list] | None = None,\n template: str | None = None, title: str = \"\",\n profile_name: str = \"\") -> Artifact:\n \"\"\"Write a real text, PDF, Word or Excel file and return its artifact.\"\"\"\n name = Path(name).name.strip() or f\"document_{_stamp()}.txt\"\n suffix = Path(name).suffix.lower()\n if suffix not in FILE_EXTENSIONS:\n name += \".txt\"\n suffix = \".txt\"\n\n if template == \"resume\":\n content = content or RESUME_TEMPLATE.format(\n name=profile_name or \"Your Name\", role=\"Software Developer\")\n if template == \"invoice\":\n title = title or \"Invoice\"\n if suffix in {\".xlsx\", \".csv\"}:\n rows = rows or INVOICE_ROWS\n else:\n content = content or _rows_as_text(INVOICE_ROWS)\n\n if not content.strip() and not rows:\n raise ValueError(\"the file needs some content\")\n\n folder = _folder(\"file\")\n path = _unique(folder / name)\n suffix = path.suffix.lower()\n mime = TEXT_TYPES.get(suffix) or {\n \".pdf\": \"application/pdf\",\n \".docx\": \"application/vnd.openxmlformats-officedocument.wordprocessingml.document\",\n \".xlsx\": \"application/vnd.openxmlformats-officedocument.spreadsheetml.sheet\",\n }.get(suffix, \"application/octet-stream\")\n```", "response": " if suffix == \".pdf\":\n _write_pdf(path, content or _rows_as_text(rows))\n elif suffix == \".docx\":\n _write_docx(path, content or _rows_as_text(rows))\n elif suffix == \".xlsx\":\n _write_xlsx(path, _load_rows(name, content, rows), title)\n elif suffix == \".csv\":\n with path.open(\"w\", encoding=\"utf-8-sig\", newline=\"\") as handle:\n writer = csv.writer(handle)\n if rows:\n writer.writerows(rows)\n else:\n handle.write(content)\n elif suffix == \".json\":\n if rows:\n header, body = rows[0], rows[1:]\n payload = [dict(zip(header, row)) for row in body]\n else:\n try:\n payload = json.loads(content)\n except ValueError:\n payload = {\"content\": content}\n path.write_text(json.dumps(payload, ensure_ascii=False, indent=2),\n encoding=\"utf-8\")\n elif suffix == \".html\":\n if content.lstrip().lower().startswith((\"<!doctype\", \"<html\")):\n path.write_text(content, encoding=\"utf-8\")\n else:\n body = _plain(content).replace(\"\\n\", \"<br>\\n\")\n path.write_text(\n \"<!DOCTYPE html>\\n<html lang=\\\"en\\\">\\n<head>\\n\"\n \" <meta charset=\\\"utf-8\\\">\\n\"\n \" <meta name=\\\"viewport\\\" content=\\\"width=device-width, initial-scale=1\\\">\\n\"\n f\" <title>{title or path.stem}</title>\\n\"\n \" <style>body{font-family:system-ui,sans-serif;max-width:760px;\"\n \"margin:40px auto;padding:0 18px;line-height:1.6;color:#222}</style>\\n\"\n \"</head>\\n<body>\\n\" + body + \"\\n</body>\\n</html>\\n\",\n encoding=\"utf-8\")\n elif suffix == \".svg\":\n if content.lstrip().startswith(\"<svg\"):\n path.write_text(content, encoding=\"utf-8\")\n else:\n escaped = (content.replace(\"&\", \"&\").replace(\"<\", \"<\")\n .replace(\">\", \">\"))\n lines = escaped.splitlines() or [\"\"]\n text_svg = \"\".join(\n f'<text x=\"24\" y=\"{40 + i * 22}\" font-size=\"16\" fill=\"#eee\">{line}</text>'\n for i, line in enumerate(lines[:40]))\n path.write_text(\n '<svg xmlns=\"http://www.w3.org/2000/svg\" width=\"720\" height=\"480\">\\n'\n '<rect width=\"100%\" height=\"100%\" fill=\"#111827\"/>\\n'\n + text_svg + \"\\n</svg>\\n\", encoding=\"utf-8\")\n else:\n path.write_text(content, encoding=\"utf-8\")\n\n note = f\"{suffix.lstrip('.').upper()} file written on this PC\"\n if template:\n note += f\" from the {template} template\"\n return Artifact(\"file\", path, note=note, mime=mime, extra={\"title\": title})", "source_file": "media.py", "function_name": "generate_file", "class_name": null, "line_start": 498, "line_end": 588, "license": "mit", "source": "SadikAI project"}
{"task": "code_explanation", "language": "python", "instruction": "Explain what this Python function does.\n\n```python\ndef generate_file(name: str, content: str = \"\", rows: list[list] | None = None,\n template: str | None = None, title: str = \"\",\n profile_name: str = \"\") -> Artifact:\n \"\"\"Write a real text, PDF, Word or Excel file and return its artifact.\"\"\"\n name = Path(name).name.strip() or f\"document_{_stamp()}.txt\"\n suffix = Path(name).suffix.lower()\n if suffix not in FILE_EXTENSIONS:\n name += \".txt\"\n suffix = \".txt\"\n\n if template == \"resume\":\n content = content or RESUME_TEMPLATE.format(\n name=profile_name or \"Your Name\", role=\"Software Developer\")\n if template == \"invoice\":\n title = title or \"Invoice\"\n if suffix in {\".xlsx\", \".csv\"}:\n rows = rows or INVOICE_ROWS\n else:\n content = content or _rows_as_text(INVOICE_ROWS)\n\n if not content.strip() and not rows:\n raise ValueError(\"the file needs some content\")\n\n folder = _folder(\"file\")\n path = _unique(folder / name)\n suffix = path.suffix.lower()\n mime = TEXT_TYPES.get(suffix) or {\n \".pdf\": \"application/pdf\",\n \".docx\": \"application/vnd.openxmlformats-officedocument.wordprocessingml.document\",\n \".xlsx\": \"application/vnd.openxmlformats-officedocument.spreadsheetml.sheet\",\n }.get(suffix, \"application/octet-stream\")\n\n if suffix == \".pdf\":\n _write_pdf(path, content or _rows_as_text(rows))\n elif suffix == \".docx\":\n _write_docx(path, content or _rows_as_text(rows))\n elif suffix == \".xlsx\":\n _write_xlsx(path, _load_rows(name, content, rows), title)\n elif suffix == \".csv\":\n with path.open(\"w\", encoding=\"utf-8-sig\", newline=\"\") as handle:\n writer = csv.writer(handle)\n if rows:\n writer.writerows(rows)\n else:\n handle.write(content)\n elif suffix == \".json\":\n if rows:\n header, body = rows[0], rows[1:]\n payload = [dict(zip(header, row)) for row in body]\n else:\n try:\n payload = json.loads(content)\n except ValueError:\n payload = {\"content\": content}\n path.write_text(json.dumps(payload, ensure_ascii=False, indent=2),\n encoding=\"utf-8\")\n elif suffix == \".html\":\n if content.lstrip().lower().startswith((\"<!doctype\", \"<html\")):\n path.write_text(content, encoding=\"utf-8\")\n else:\n body = _plain(content).replace(\"\\n\", \"<br>\\n\")\n path.write_text(\n \"<!DOCTYPE html>\\n<html lang=\\\"en\\\">\\n<head>\\n\"\n \" <meta charset=\\\"utf-8\\\">\\n\"\n \" <meta name=\\\"viewport\\\" content=\\\"width=device-width, initial-scale=1\\\">\\n\"\n f\" <title>{title or path.stem}</title>\\n\"\n \" <style>body{font-family:system-ui,sans-serif;max-width:760px;\"\n \"margin:40px auto;padding:0 18px;line-height:1.6;color:#222}</style>\\n\"\n \"</head>\\n<body>\\n\" + body + \"\\n</body>\\n</html>\\n\",\n encoding=\"utf-8\")\n elif suffix == \".svg\":\n if content.lstrip().startswith(\"<svg\"):\n path.write_text(content, encoding=\"utf-8\")\n else:\n escaped = (content.replace(\"&\", \"&\").replace(\"<\", \"<\")\n .replace(\">\", \">\"))\n lines = escaped.splitlines() or [\"\"]\n text_svg = \"\".join(\n f'<text x=\"24\" y=\"{40 + i * 22}\" font-size=\"16\" fill=\"#eee\">{line}</text>'\n for i, line in enumerate(lines[:40]))\n path.write_text(\n '<svg xmlns=\"http://www.w3.org/2000/svg\" width=\"720\" height=\"480\">\\n'\n '<rect width=\"100%\" height=\"100%\" fill=\"#111827\"/>\\n'\n + text_svg + \"\\n</svg>\\n\", encoding=\"utf-8\")\n else:\n path.write_text(content, encoding=\"utf-8\")\n\n note = f\"{suffix.lstrip('.').upper()} file written on this PC\"\n if template:\n note += f\" from the {template} template\"\n return Artifact(\"file\", path, note=note, mime=mime, extra={\"title\": title})\n```", "response": "Write a real text, PDF, Word or Excel file and return its artifact.", "source_file": "media.py", "function_name": "generate_file", "class_name": null, "line_start": 498, "line_end": 588, "license": "mit", "source": "SadikAI project"}
{"task": "code_generation", "language": "python", "instruction": "Write a Python function `generate_file(name: str, content: str='', rows: list[list] | None=None, template: str | None=None, title: str='', profile_name: str='')` that does the following:\n\nWrite a real text, PDF, Word or Excel file and return its artifact.\n\nReturn only the Python code.", "response": "def generate_file(name: str, content: str = \"\", rows: list[list] | None = None,\n template: str | None = None, title: str = \"\",\n profile_name: str = \"\") -> Artifact:\n \"\"\"Write a real text, PDF, Word or Excel file and return its artifact.\"\"\"\n name = Path(name).name.strip() or f\"document_{_stamp()}.txt\"\n suffix = Path(name).suffix.lower()\n if suffix not in FILE_EXTENSIONS:\n name += \".txt\"\n suffix = \".txt\"\n\n if template == \"resume\":\n content = content or RESUME_TEMPLATE.format(\n name=profile_name or \"Your Name\", role=\"Software Developer\")\n if template == \"invoice\":\n title = title or \"Invoice\"\n if suffix in {\".xlsx\", \".csv\"}:\n rows = rows or INVOICE_ROWS\n else:\n content = content or _rows_as_text(INVOICE_ROWS)\n\n if not content.strip() and not rows:\n raise ValueError(\"the file needs some content\")\n\n folder = _folder(\"file\")\n path = _unique(folder / name)\n suffix = path.suffix.lower()\n mime = TEXT_TYPES.get(suffix) or {\n \".pdf\": \"application/pdf\",\n \".docx\": \"application/vnd.openxmlformats-officedocument.wordprocessingml.document\",\n \".xlsx\": \"application/vnd.openxmlformats-officedocument.spreadsheetml.sheet\",\n }.get(suffix, \"application/octet-stream\")\n\n if suffix == \".pdf\":\n _write_pdf(path, content or _rows_as_text(rows))\n elif suffix == \".docx\":\n _write_docx(path, content or _rows_as_text(rows))\n elif suffix == \".xlsx\":\n _write_xlsx(path, _load_rows(name, content, rows), title)\n elif suffix == \".csv\":\n with path.open(\"w\", encoding=\"utf-8-sig\", newline=\"\") as handle:\n writer = csv.writer(handle)\n if rows:\n writer.writerows(rows)\n else:\n handle.write(content)\n elif suffix == \".json\":\n if rows:\n header, body = rows[0], rows[1:]\n payload = [dict(zip(header, row)) for row in body]\n else:\n try:\n payload = json.loads(content)\n except ValueError:\n payload = {\"content\": content}\n path.write_text(json.dumps(payload, ensure_ascii=False, indent=2),\n encoding=\"utf-8\")\n elif suffix == \".html\":\n if content.lstrip().lower().startswith((\"<!doctype\", \"<html\")):\n path.write_text(content, encoding=\"utf-8\")\n else:\n body = _plain(content).replace(\"\\n\", \"<br>\\n\")\n path.write_text(\n \"<!DOCTYPE html>\\n<html lang=\\\"en\\\">\\n<head>\\n\"\n \" <meta charset=\\\"utf-8\\\">\\n\"\n \" <meta name=\\\"viewport\\\" content=\\\"width=device-width, initial-scale=1\\\">\\n\"\n f\" <title>{title or path.stem}</title>\\n\"\n \" <style>body{font-family:system-ui,sans-serif;max-width:760px;\"\n \"margin:40px auto;padding:0 18px;line-height:1.6;color:#222}</style>\\n\"\n \"</head>\\n<body>\\n\" + body + \"\\n</body>\\n</html>\\n\",\n encoding=\"utf-8\")\n elif suffix == \".svg\":\n if content.lstrip().startswith(\"<svg\"):\n path.write_text(content, encoding=\"utf-8\")\n else:\n escaped = (content.replace(\"&\", \"&\").replace(\"<\", \"<\")\n .replace(\">\", \">\"))\n lines = escaped.splitlines() or [\"\"]\n text_svg = \"\".join(\n f'<text x=\"24\" y=\"{40 + i * 22}\" font-size=\"16\" fill=\"#eee\">{line}</text>'\n for i, line in enumerate(lines[:40]))\n path.write_text(\n '<svg xmlns=\"http://www.w3.org/2000/svg\" width=\"720\" height=\"480\">\\n'\n '<rect width=\"100%\" height=\"100%\" fill=\"#111827\"/>\\n'\n + text_svg + \"\\n</svg>\\n\", encoding=\"utf-8\")\n else:\n path.write_text(content, encoding=\"utf-8\")\n\n note = f\"{suffix.lstrip('.').upper()} file written on this PC\"\n if template:\n note += f\" from the {template} template\"\n return Artifact(\"file\", path, note=note, mime=mime, extra={\"title\": title})", "source_file": "media.py", "function_name": "generate_file", "class_name": null, "line_start": 498, "line_end": 588, "license": "mit", "source": "SadikAI project"}
{"task": "code_completion", "language": "python", "instruction": "Complete the following Python code. Return only the continuation, preserving indentation.\n\n```python\ndef _after_content_marker(text: str) -> str:\n markers = [\n r\"containing\", r\"with (?:the )?(?:content|text)\", r\"that says\", r\"says\",\n r\"content\\s*:\", r\"text\\s*:\", r\"\\bwith\\b\", r\"\\blikho\\b\",\n ]\n```", "response": " for marker in markers:\n match = re.search(marker + r\"\\s*(.+)$\", text, re.I | re.S)\n if match:\n return _clean_prompt(match.group(1))\n return \"\"", "source_file": "media.py", "function_name": "_after_content_marker", "class_name": null, "line_start": 667, "line_end": 676, "license": "mit", "source": "SadikAI project"}
{"task": "code_completion", "language": "python", "instruction": "Complete the following Python code. Return only the continuation, preserving indentation.\n\n```python\ndef parse_media_request(text: str) -> dict | None:\n \"\"\"Return an image/audio/file request, or None for an ordinary message.\"\"\"\n original = text.strip()\n if not original:\n return None\n\n prompt = _match(IMAGE_PATTERNS, original)\n if prompt and (\"image\" in original.lower() or \"picture\" in original.lower()\n or \"draw\" in original.lower() or \"photo\" in original.lower()\n or \"tasveer\" in original.lower() or \"chitra\" in original.lower()):\n width = height = 768\n size = re.search(r\"(\\d{3,4})\\s*[x×]\\s*(\\d{3,4})\", original)\n if size:\n width, height = int(size.group(1)), int(size.group(2))\n prompt = re.sub(r\"\\s*(?:in\\s*)?\\d{3,4}\\s*[x×]\\s*\\d{3,4}\\s*\", \" \",\n prompt, flags=re.I).strip()\n elif re.search(r\"\\bwide\\b|\\blandscape\\b\", original, re.I):\n width, height = 1024, 640\n elif re.search(r\"\\bportrait\\b|\\btall\\b\", original, re.I):\n width, height = 640, 1024\n return {\"kind\": \"image\", \"prompt\": prompt, \"width\": width, \"height\": height}\n\n spoken = _match(AUDIO_PATTERNS, original)\n if spoken:\n low = original.lower()\n voice = \"male\" if re.search(r\"\\bmale\\b|\\bdavid\\b\", low) else \"female\"\n rate = -3 if re.search(r\"\\bslow(?:ly)?\\b|\\bdheere\\b\", low) else 3 if re.search(\n r\"\\bfast\\b|\\bjaldi\\b\", low) else 0\n return {\"kind\": \"audio\", \"text\": spoken, \"voice\": voice, \"rate\": rate}\n\n if not (original.startswith(\"/file\") or (FILE_ACTION.search(original)\n and FILE_NOUN.search(original))):\n return None\n\n body = re.sub(r\"^/file\\s*\", \"\", original, flags=re.I)\n explicit_name = \"\"\n name_match = FILENAME.search(body)\n if name_match:\n explicit_name = name_match.group(1)\n else:\n named = re.search(r\"(?:named|called|naam ka|naam se)\\s+([\\w-]+\\.[A-Za-z0-9]+)\",\n body, re.I)\n if named:\n explicit_name = named.group(1)\n\n suffix = Path(explicit_name).suffix.lower() if explicit_name else _file_type(body)\n if suffix not in FILE_EXTENSIONS:\n suffix = _file_type(body)\n```", "response": " table = build_table(body)\n template = _detect_template(body)\n topic = _topic(body)\n\n content = \"\"\n if \"|\" in body:\n head, content = body.split(\"|\", 1)\n content = _clean_prompt(content)\n if not explicit_name:\n candidate = head.strip().split()[0] if head.strip() else \"\"\n if FILENAME.fullmatch(candidate):\n explicit_name = candidate\n elif original.startswith(\"/file\"):\n head, _, rest = body.partition(\" \")\n if FILENAME.fullmatch(head.strip()):\n explicit_name = explicit_name or head.strip()\n content = _clean_prompt(rest)\n else:\n content = _clean_prompt(body)\n else:\n content = _after_content_marker(body)\n if content:\n # Don't treat \"with a resume\" or \"with a CSV\" as the file body.\n if FILE_NOUN.fullmatch(content.strip()) or _detect_template(content):\n content = \"\"\n\n if not explicit_name:\n if template == \"resume\":\n explicit_name = f\"resume{suffix if suffix in {'.pdf', '.docx'} else '.docx'}\"\n suffix = Path(explicit_name).suffix.lower()\n elif template == \"invoice\":\n suffix = \".xlsx\"\n explicit_name = \"invoice.xlsx\"\n elif table:\n explicit_name = f\"{_slug(table[1]) or 'table'}{suffix}\"\n elif topic:\n explicit_name = f\"{_slug(topic)}{suffix}\"\n else:\n explicit_name = f\"document_{_stamp()}{suffix}\"\n\n return {\n \"kind\": \"file\",\n \"name\": explicit_name,\n \"content\": content,\n \"rows\": table[0] if table else None,\n \"title\": table[1] if table else \"\",\n \"template\": template,\n \"topic\": topic if not content and not table else \"\",\n }", "source_file": "media.py", "function_name": "parse_media_request", "class_name": null, "line_start": 684, "line_end": 781, "license": "mit", "source": "SadikAI project"}
{"task": "code_explanation", "language": "python", "instruction": "Explain what this Python function does.\n\n```python\ndef parse_media_request(text: str) -> dict | None:\n \"\"\"Return an image/audio/file request, or None for an ordinary message.\"\"\"\n original = text.strip()\n if not original:\n return None\n\n prompt = _match(IMAGE_PATTERNS, original)\n if prompt and (\"image\" in original.lower() or \"picture\" in original.lower()\n or \"draw\" in original.lower() or \"photo\" in original.lower()\n or \"tasveer\" in original.lower() or \"chitra\" in original.lower()):\n width = height = 768\n size = re.search(r\"(\\d{3,4})\\s*[x×]\\s*(\\d{3,4})\", original)\n if size:\n width, height = int(size.group(1)), int(size.group(2))\n prompt = re.sub(r\"\\s*(?:in\\s*)?\\d{3,4}\\s*[x×]\\s*\\d{3,4}\\s*\", \" \",\n prompt, flags=re.I).strip()\n elif re.search(r\"\\bwide\\b|\\blandscape\\b\", original, re.I):\n width, height = 1024, 640\n elif re.search(r\"\\bportrait\\b|\\btall\\b\", original, re.I):\n width, height = 640, 1024\n return {\"kind\": \"image\", \"prompt\": prompt, \"width\": width, \"height\": height}\n\n spoken = _match(AUDIO_PATTERNS, original)\n if spoken:\n low = original.lower()\n voice = \"male\" if re.search(r\"\\bmale\\b|\\bdavid\\b\", low) else \"female\"\n rate = -3 if re.search(r\"\\bslow(?:ly)?\\b|\\bdheere\\b\", low) else 3 if re.search(\n r\"\\bfast\\b|\\bjaldi\\b\", low) else 0\n return {\"kind\": \"audio\", \"text\": spoken, \"voice\": voice, \"rate\": rate}\n\n if not (original.startswith(\"/file\") or (FILE_ACTION.search(original)\n and FILE_NOUN.search(original))):\n return None\n\n body = re.sub(r\"^/file\\s*\", \"\", original, flags=re.I)\n explicit_name = \"\"\n name_match = FILENAME.search(body)\n if name_match:\n explicit_name = name_match.group(1)\n else:\n named = re.search(r\"(?:named|called|naam ka|naam se)\\s+([\\w-]+\\.[A-Za-z0-9]+)\",\n body, re.I)\n if named:\n explicit_name = named.group(1)\n\n suffix = Path(explicit_name).suffix.lower() if explicit_name else _file_type(body)\n if suffix not in FILE_EXTENSIONS:\n suffix = _file_type(body)\n\n table = build_table(body)\n template = _detect_template(body)\n topic = _topic(body)\n\n content = \"\"\n if \"|\" in body:\n head, content = body.split(\"|\", 1)\n content = _clean_prompt(content)\n if not explicit_name:\n candidate = head.strip().split()[0] if head.strip() else \"\"\n if FILENAME.fullmatch(candidate):\n explicit_name = candidate\n elif original.startswith(\"/file\"):\n head, _, rest = body.partition(\" \")\n if FILENAME.fullmatch(head.strip()):\n explicit_name = explicit_name or head.strip()\n content = _clean_prompt(rest)\n else:\n content = _clean_prompt(body)\n else:\n content = _after_content_marker(body)\n if content:\n # Don't treat \"with a resume\" or \"with a CSV\" as the file body.\n if FILE_NOUN.fullmatch(content.strip()) or _detect_template(content):\n content = \"\"\n\n if not explicit_name:\n if template == \"resume\":\n explicit_name = f\"resume{suffix if suffix in {'.pdf', '.docx'} else '.docx'}\"\n suffix = Path(explicit_name).suffix.lower()\n elif template == \"invoice\":\n suffix = \".xlsx\"\n explicit_name = \"invoice.xlsx\"\n elif table:\n explicit_name = f\"{_slug(table[1]) or 'table'}{suffix}\"\n elif topic:\n explicit_name = f\"{_slug(topic)}{suffix}\"\n else:\n explicit_name = f\"document_{_stamp()}{suffix}\"\n\n return {\n \"kind\": \"file\",\n \"name\": explicit_name,\n \"content\": content,\n \"rows\": table[0] if table else None,\n \"title\": table[1] if table else \"\",\n \"template\": template,\n \"topic\": topic if not content and not table else \"\",\n }\n```", "response": "Return an image/audio/file request, or None for an ordinary message.", "source_file": "media.py", "function_name": "parse_media_request", "class_name": null, "line_start": 684, "line_end": 781, "license": "mit", "source": "SadikAI project"}
{"task": "code_generation", "language": "python", "instruction": "Write a Python function `parse_media_request(text: str)` that does the following:\n\nReturn an image/audio/file request, or None for an ordinary message.\n\nReturn only the Python code.", "response": "def parse_media_request(text: str) -> dict | None:\n \"\"\"Return an image/audio/file request, or None for an ordinary message.\"\"\"\n original = text.strip()\n if not original:\n return None\n\n prompt = _match(IMAGE_PATTERNS, original)\n if prompt and (\"image\" in original.lower() or \"picture\" in original.lower()\n or \"draw\" in original.lower() or \"photo\" in original.lower()\n or \"tasveer\" in original.lower() or \"chitra\" in original.lower()):\n width = height = 768\n size = re.search(r\"(\\d{3,4})\\s*[x×]\\s*(\\d{3,4})\", original)\n if size:\n width, height = int(size.group(1)), int(size.group(2))\n prompt = re.sub(r\"\\s*(?:in\\s*)?\\d{3,4}\\s*[x×]\\s*\\d{3,4}\\s*\", \" \",\n prompt, flags=re.I).strip()\n elif re.search(r\"\\bwide\\b|\\blandscape\\b\", original, re.I):\n width, height = 1024, 640\n elif re.search(r\"\\bportrait\\b|\\btall\\b\", original, re.I):\n width, height = 640, 1024\n return {\"kind\": \"image\", \"prompt\": prompt, \"width\": width, \"height\": height}\n\n spoken = _match(AUDIO_PATTERNS, original)\n if spoken:\n low = original.lower()\n voice = \"male\" if re.search(r\"\\bmale\\b|\\bdavid\\b\", low) else \"female\"\n rate = -3 if re.search(r\"\\bslow(?:ly)?\\b|\\bdheere\\b\", low) else 3 if re.search(\n r\"\\bfast\\b|\\bjaldi\\b\", low) else 0\n return {\"kind\": \"audio\", \"text\": spoken, \"voice\": voice, \"rate\": rate}\n\n if not (original.startswith(\"/file\") or (FILE_ACTION.search(original)\n and FILE_NOUN.search(original))):\n return None\n\n body = re.sub(r\"^/file\\s*\", \"\", original, flags=re.I)\n explicit_name = \"\"\n name_match = FILENAME.search(body)\n if name_match:\n explicit_name = name_match.group(1)\n else:\n named = re.search(r\"(?:named|called|naam ka|naam se)\\s+([\\w-]+\\.[A-Za-z0-9]+)\",\n body, re.I)\n if named:\n explicit_name = named.group(1)\n\n suffix = Path(explicit_name).suffix.lower() if explicit_name else _file_type(body)\n if suffix not in FILE_EXTENSIONS:\n suffix = _file_type(body)\n\n table = build_table(body)\n template = _detect_template(body)\n topic = _topic(body)\n\n content = \"\"\n if \"|\" in body:\n head, content = body.split(\"|\", 1)\n content = _clean_prompt(content)\n if not explicit_name:\n candidate = head.strip().split()[0] if head.strip() else \"\"\n if FILENAME.fullmatch(candidate):\n explicit_name = candidate\n elif original.startswith(\"/file\"):\n head, _, rest = body.partition(\" \")\n if FILENAME.fullmatch(head.strip()):\n explicit_name = explicit_name or head.strip()\n content = _clean_prompt(rest)\n else:\n content = _clean_prompt(body)\n else:\n content = _after_content_marker(body)\n if content:\n # Don't treat \"with a resume\" or \"with a CSV\" as the file body.\n if FILE_NOUN.fullmatch(content.strip()) or _detect_template(content):\n content = \"\"\n\n if not explicit_name:\n if template == \"resume\":\n explicit_name = f\"resume{suffix if suffix in {'.pdf', '.docx'} else '.docx'}\"\n suffix = Path(explicit_name).suffix.lower()\n elif template == \"invoice\":\n suffix = \".xlsx\"\n explicit_name = \"invoice.xlsx\"\n elif table:\n explicit_name = f\"{_slug(table[1]) or 'table'}{suffix}\"\n elif topic:\n explicit_name = f\"{_slug(topic)}{suffix}\"\n else:\n explicit_name = f\"document_{_stamp()}{suffix}\"\n\n return {\n \"kind\": \"file\",\n \"name\": explicit_name,\n \"content\": content,\n \"rows\": table[0] if table else None,\n \"title\": table[1] if table else \"\",\n \"template\": template,\n \"topic\": topic if not content and not table else \"\",\n }", "source_file": "media.py", "function_name": "parse_media_request", "class_name": null, "line_start": 684, "line_end": 781, "license": "mit", "source": "SadikAI project"}
{"task": "code_completion", "language": "python", "instruction": "Complete the following Python code. Return only the continuation, preserving indentation.\n\n```python\n def __post_init__(self) -> None:\n if self.n_embd % self.n_head != 0:\n raise ValueError(\"n_embd must be divisible by n_head\")\n```", "response": " if self.n_head % self.n_kv_head != 0:\n raise ValueError(\"n_head must be divisible by n_kv_head\")\n self.head_dim = self.n_embd // self.n_head\n if self.head_dim % 2 != 0:\n raise ValueError(\"head_dim must be even for RoPE\")\n self.n_rep = self.n_head // self.n_kv_head", "source_file": "model.py", "function_name": "__post_init__", "class_name": "ModelConfig", "line_start": 46, "line_end": 54, "license": "mit", "source": "SadikAI project"}
{"task": "code_completion", "language": "python", "instruction": "Complete the following Python code. Return only the continuation, preserving indentation.\n\n```python\n def to_dict(self) -> dict:\n d = asdict(self)\n d.pop(\"head_dim\", None)\n```", "response": " d.pop(\"n_rep\", None)\n return d", "source_file": "model.py", "function_name": "to_dict", "class_name": "ModelConfig", "line_start": 56, "line_end": 60, "license": "mit", "source": "SadikAI project"}
{"task": "code_completion", "language": "python", "instruction": "Complete the following Python code. Return only the continuation, preserving indentation.\n\n```python\n def forward(self, x: torch.Tensor) -> torch.Tensor:\n dtype = x.dtype\n x = x.float()\n```", "response": " x = x * torch.rsqrt(x.pow(2).mean(-1, keepdim=True) + self.eps)\n return x.to(dtype) * self.weight", "source_file": "model.py", "function_name": "forward", "class_name": "RMSNorm", "line_start": 77, "line_end": 81, "license": "mit", "source": "SadikAI project"}
{"task": "code_completion", "language": "python", "instruction": "Complete the following Python code. Return only the continuation, preserving indentation.\n\n```python\n def __init__(self, head_dim: int, base: float = 10000.0, max_seq_len: int = 2048) -> None:\n super().__init__()\n self.register_buffer(\n \"inv_freq\",\n 1.0 / (base ** (torch.arange(0, head_dim, 2, dtype=torch.float32) / head_dim)),\n persistent=False,\n )\n```", "response": " self.max_seq_len = max_seq_len\n self._cos: torch.Tensor | None = None\n self._sin: torch.Tensor | None = None", "source_file": "model.py", "function_name": "__init__", "class_name": "Rotary", "line_start": 91, "line_end": 100, "license": "mit", "source": "SadikAI project"}
{"task": "code_completion", "language": "python", "instruction": "Complete the following Python code. Return only the continuation, preserving indentation.\n\n```python\n def _build(self, n: int, device: torch.device) -> None:\n t = torch.arange(n, device=device, dtype=torch.float32)\n freqs = torch.outer(t, self.inv_freq.to(device))\n```", "response": " self._cos = freqs.cos()\n self._sin = freqs.sin()", "source_file": "model.py", "function_name": "_build", "class_name": "Rotary", "line_start": 102, "line_end": 106, "license": "mit", "source": "SadikAI project"}
{"task": "code_completion", "language": "python", "instruction": "Complete the following Python code. Return only the continuation, preserving indentation.\n\n```python\n def forward(self, seq_len: int, offset: int, device: torch.device):\n need = offset + seq_len\n if (\n self._cos is None\n or self._cos.shape[0] < need\n or self._cos.device != device\n ):\n self._build(max(need, self.max_seq_len), device)\n```", "response": " cos = self._cos[offset:need]\n sin = self._sin[offset:need]\n return cos[None, None], sin[None, None] # (1, 1, T, head_dim/2)", "source_file": "model.py", "function_name": "forward", "class_name": "Rotary", "line_start": 108, "line_end": 118, "license": "mit", "source": "SadikAI project"}
{"task": "code_completion", "language": "python", "instruction": "Complete the following Python code. Return only the continuation, preserving indentation.\n\n```python\ndef apply_rope(x: torch.Tensor, cos: torch.Tensor, sin: torch.Tensor) -> torch.Tensor:\n half = x.shape[-1] // 2\n x1, x2 = x[..., :half], x[..., half:]\n```", "response": " cos = cos.to(x.dtype)\n sin = sin.to(x.dtype)\n return torch.cat((x1 * cos - x2 * sin, x1 * sin + x2 * cos), dim=-1)", "source_file": "model.py", "function_name": "apply_rope", "class_name": null, "line_start": 121, "line_end": 126, "license": "mit", "source": "SadikAI project"}
{"task": "code_completion", "language": "python", "instruction": "Complete the following Python code. Return only the continuation, preserving indentation.\n\n```python\n def __init__(self, cfg: ModelConfig) -> None:\n super().__init__()\n self.n_head = cfg.n_head\n self.n_kv_head = cfg.n_kv_head\n self.n_rep = cfg.n_rep\n self.head_dim = cfg.head_dim\n```", "response": " self.dropout_p = cfg.dropout\n\n self.q_proj = nn.Linear(cfg.n_embd, cfg.n_head * cfg.head_dim, bias=cfg.bias)\n self.k_proj = nn.Linear(cfg.n_embd, cfg.n_kv_head * cfg.head_dim, bias=cfg.bias)\n self.v_proj = nn.Linear(cfg.n_embd, cfg.n_kv_head * cfg.head_dim, bias=cfg.bias)\n self.o_proj = nn.Linear(cfg.n_head * cfg.head_dim, cfg.n_embd, bias=cfg.bias)\n self.rotary = Rotary(cfg.head_dim, max_seq_len=cfg.block_size)", "source_file": "model.py", "function_name": "__init__", "class_name": "Attention", "line_start": 130, "line_end": 142, "license": "mit", "source": "SadikAI project"}
{"task": "code_completion", "language": "python", "instruction": "Complete the following Python code. Return only the continuation, preserving indentation.\n\n```python\n def forward(\n self,\n x: torch.Tensor,\n past_kv: tuple[torch.Tensor, torch.Tensor] | None = None,\n use_cache: bool = False,\n pos: int = 0,\n ):\n B, T, _ = x.shape\n\n q = self.q_proj(x).view(B, T, self.n_head, self.head_dim).transpose(1, 2)\n k = self.k_proj(x).view(B, T, self.n_kv_head, self.head_dim).transpose(1, 2)\n v = self.v_proj(x).view(B, T, self.n_kv_head, self.head_dim).transpose(1, 2)\n\n cos, sin = self.rotary(T, pos, x.device)\n q = apply_rope(q, cos, sin)\n k = apply_rope(k, cos, sin)\n\n if past_kv is not None:\n k = torch.cat((past_kv[0], k), dim=2)\n v = torch.cat((past_kv[1], v), dim=2)\n\n # Sliding window: never keep more than block_size keys.\n max_ctx = self.rotary.max_seq_len\n if k.shape[2] > max_ctx:\n k = k[:, :, -max_ctx:]\n v = v[:, :, -max_ctx:]\n```", "response": " cache = (k, v) if use_cache else None\n\n if self.n_rep > 1:\n k = k.repeat_interleave(self.n_rep, dim=1)\n v = v.repeat_interleave(self.n_rep, dim=1)\n\n attn_mask = None\n is_causal = pos == 0 and T > 1\n if pos > 0 and T > 1:\n # Queries are at positions pos .. pos+T-1, keys are the last\n # k.shape[2] positions ending at pos+T-1.\n n_keys = k.shape[2]\n qpos = torch.arange(pos, pos + T, device=x.device).unsqueeze(1)\n kpos = torch.arange(pos + T - n_keys, pos + T, device=x.device).unsqueeze(0)\n attn_mask = kpos <= qpos\n\n y = F.scaled_dot_product_attention(\n q,\n k,\n v,\n attn_mask=attn_mask,\n is_causal=is_causal,\n dropout_p=self.dropout_p if self.training else 0.0,\n )\n y = y.transpose(1, 2).contiguous().view(B, T, -1)\n return self.o_proj(y), cache", "source_file": "model.py", "function_name": "forward", "class_name": "Attention", "line_start": 144, "line_end": 196, "license": "mit", "source": "SadikAI project"}
{"task": "code_completion", "language": "python", "instruction": "Complete the following Python code. Return only the continuation, preserving indentation.\n\n```python\n def __init__(self, cfg: ModelConfig) -> None:\n super().__init__()\n hidden = int(8 * cfg.n_embd / 3)\n```", "response": " hidden = ((hidden + 63) // 64) * 64 # round up to a nice multiple\n self.w1 = nn.Linear(cfg.n_embd, hidden, bias=cfg.bias) # gate\n self.w3 = nn.Linear(cfg.n_embd, hidden, bias=cfg.bias) # up\n self.w2 = nn.Linear(hidden, cfg.n_embd, bias=cfg.bias) # down", "source_file": "model.py", "function_name": "__init__", "class_name": "SwiGLU", "line_start": 200, "line_end": 206, "license": "mit", "source": "SadikAI project"}
{"task": "code_completion", "language": "python", "instruction": "Complete the following Python code. Return only the continuation, preserving indentation.\n\n```python\n def __init__(self, cfg: ModelConfig) -> None:\n super().__init__()\n self.norm1 = RMSNorm(cfg.n_embd)\n```", "response": " self.attn = Attention(cfg)\n self.norm2 = RMSNorm(cfg.n_embd)\n self.mlp = SwiGLU(cfg)\n self.drop = nn.Dropout(cfg.dropout) if cfg.dropout > 0 else nn.Identity()", "source_file": "model.py", "function_name": "__init__", "class_name": "Block", "line_start": 213, "line_end": 219, "license": "mit", "source": "SadikAI project"}
{"task": "code_completion", "language": "python", "instruction": "Complete the following Python code. Return only the continuation, preserving indentation.\n\n```python\n def forward(self, x, past_kv=None, use_cache=False, pos=0):\n h, cache = self.attn(self.norm1(x), past_kv, use_cache, pos)\n x = x + self.drop(h)\n```", "response": " x = x + self.drop(self.mlp(self.norm2(x)))\n return x, cache", "source_file": "model.py", "function_name": "forward", "class_name": "Block", "line_start": 221, "line_end": 225, "license": "mit", "source": "SadikAI project"}
{"task": "code_completion", "language": "python", "instruction": "Complete the following Python code. Return only the continuation, preserving indentation.\n\n```python\n def __init__(self, cfg: ModelConfig) -> None:\n super().__init__()\n self.cfg = cfg\n\n self.tok_emb = nn.Embedding(cfg.vocab_size, cfg.n_embd)\n self.drop = nn.Dropout(cfg.dropout) if cfg.dropout > 0 else nn.Identity()\n self.blocks = nn.ModuleList(Block(cfg) for _ in range(cfg.n_layer))\n self.norm_f = RMSNorm(cfg.n_embd)\n self.lm_head = nn.Linear(cfg.n_embd, cfg.vocab_size, bias=False)\n```", "response": " if cfg.tie_embeddings:\n self.lm_head.weight = self.tok_emb.weight\n\n self.apply(self._init_weights)\n # GPT-2 style scaled init for the residual output projections.\n for name, p in self.named_parameters():\n if name.endswith((\"o_proj.weight\", \"w2.weight\")):\n nn.init.normal_(p, mean=0.0, std=0.02 / math.sqrt(2 * cfg.n_layer))\n\n self.grad_checkpoint = cfg.grad_checkpoint", "source_file": "model.py", "function_name": "__init__", "class_name": "GPT", "line_start": 232, "line_end": 250, "license": "mit", "source": "SadikAI project"}
{"task": "code_completion", "language": "python", "instruction": "Complete the following Python code. Return only the continuation, preserving indentation.\n\n```python\n def _chunked_loss(self, hidden: torch.Tensor, targets: torch.Tensor, chunk: int) -> torch.Tensor:\n \"\"\"Cross-entropy without materialising (B*T, vocab) logits at once.\n\n With vocab=65536 and 8k tokens per micro-batch, a full fp32 logits\n tensor is ~2 GB. Chunking keeps the peak proportional to `chunk`.\n \"\"\"\n hidden = hidden.reshape(-1, hidden.size(-1))\n```", "response": " targets = targets.reshape(-1)\n total = hidden.new_zeros((), dtype=torch.float32)\n for i in range(0, hidden.size(0), chunk):\n logits = self.lm_head(hidden[i : i + chunk])\n total = total + F.cross_entropy(\n logits.float(), targets[i : i + chunk], reduction=\"sum\"\n )\n return total / targets.numel()", "source_file": "model.py", "function_name": "_chunked_loss", "class_name": "GPT", "line_start": 262, "line_end": 276, "license": "mit", "source": "SadikAI project"}
{"task": "code_explanation", "language": "python", "instruction": "Explain what this Python method does.\n\n```python\ndef _chunked_loss(self, hidden: torch.Tensor, targets: torch.Tensor, chunk: int) -> torch.Tensor:\n \"\"\"Cross-entropy without materialising (B*T, vocab) logits at once.\n\n With vocab=65536 and 8k tokens per micro-batch, a full fp32 logits\n tensor is ~2 GB. Chunking keeps the peak proportional to `chunk`.\n \"\"\"\n hidden = hidden.reshape(-1, hidden.size(-1))\n targets = targets.reshape(-1)\n total = hidden.new_zeros((), dtype=torch.float32)\n for i in range(0, hidden.size(0), chunk):\n logits = self.lm_head(hidden[i : i + chunk])\n total = total + F.cross_entropy(\n logits.float(), targets[i : i + chunk], reduction=\"sum\"\n )\n return total / targets.numel()\n```", "response": "Cross-entropy without materialising (B*T, vocab) logits at once.", "source_file": "model.py", "function_name": "_chunked_loss", "class_name": "GPT", "line_start": 262, "line_end": 276, "license": "mit", "source": "SadikAI project"}
{"task": "code_generation", "language": "python", "instruction": "Write a Python method `GPT._chunked_loss(self, hidden: torch.Tensor, targets: torch.Tensor, chunk: int)` that does the following:\n\nCross-entropy without materialising (B*T, vocab) logits at once.\n\nReturn only the Python code.", "response": "def _chunked_loss(self, hidden: torch.Tensor, targets: torch.Tensor, chunk: int) -> torch.Tensor:\n \"\"\"Cross-entropy without materialising (B*T, vocab) logits at once.\n\n With vocab=65536 and 8k tokens per micro-batch, a full fp32 logits\n tensor is ~2 GB. Chunking keeps the peak proportional to `chunk`.\n \"\"\"\n hidden = hidden.reshape(-1, hidden.size(-1))\n targets = targets.reshape(-1)\n total = hidden.new_zeros((), dtype=torch.float32)\n for i in range(0, hidden.size(0), chunk):\n logits = self.lm_head(hidden[i : i + chunk])\n total = total + F.cross_entropy(\n logits.float(), targets[i : i + chunk], reduction=\"sum\"\n )\n return total / targets.numel()", "source_file": "model.py", "function_name": "_chunked_loss", "class_name": "GPT", "line_start": 262, "line_end": 276, "license": "mit", "source": "SadikAI project"}
{"task": "code_completion", "language": "python", "instruction": "Complete the following Python code. Return only the continuation, preserving indentation.\n\n```python\n def forward(\n self,\n idx: torch.Tensor,\n targets: torch.Tensor | None = None,\n past_kvs=None,\n use_cache: bool = False,\n pos: int = 0,\n loss_chunk: int = 0,\n ):\n B, T = idx.shape\n if T > self.cfg.block_size:\n raise ValueError(f\"sequence length {T} > block_size {self.cfg.block_size}\")\n\n x = self.drop(self.tok_emb(idx))\n x, caches = self._run_blocks(x, past_kvs, use_cache, pos)\n```", "response": " x = self.norm_f(x)\n\n loss = None\n if targets is not None:\n if loss_chunk and loss_chunk > 0:\n loss = self._chunked_loss(x, targets, loss_chunk)\n return None, loss, caches\n logits = self.lm_head(x)\n loss = F.cross_entropy(\n logits.float().view(-1, logits.size(-1)),\n targets.reshape(-1),\n ignore_index=-1,\n )\n return logits, loss, caches\n\n logits = self.lm_head(x)\n return logits, None, caches", "source_file": "model.py", "function_name": "forward", "class_name": "GPT", "line_start": 292, "line_end": 323, "license": "mit", "source": "SadikAI project"}
{"task": "code_completion", "language": "python", "instruction": "Complete the following Python code. Return only the continuation, preserving indentation.\n\n```python\n def configure_optimizer(\n self,\n lr: float,\n weight_decay: float,\n betas: tuple[float, float],\n device_type: str,\n ) -> torch.optim.Optimizer:\n decay, no_decay = [], []\n for name, p in self.named_parameters():\n if not p.requires_grad:\n continue\n # No weight decay on norms, biases, and embeddings (standard practice).\n if p.ndim < 2 or \"emb\" in name or \"norm\" in name:\n no_decay.append(p)\n else:\n decay.append(p)\n```", "response": " groups = [\n {\"params\": decay, \"weight_decay\": weight_decay},\n {\"params\": no_decay, \"weight_decay\": 0.0},\n ]\n kwargs = {\"lr\": lr, \"betas\": betas}\n if device_type == \"cuda\":\n try:\n return torch.optim.AdamW(groups, fused=True, **kwargs)\n except (RuntimeError, TypeError):\n pass\n return torch.optim.AdamW(groups, **kwargs)", "source_file": "model.py", "function_name": "configure_optimizer", "class_name": "GPT", "line_start": 334, "line_end": 361, "license": "mit", "source": "SadikAI project"}
{"task": "code_completion", "language": "python", "instruction": "Complete the following Python code. Return only the continuation, preserving indentation.\n\n```python\n def generate(\n self,\n idx: torch.Tensor,\n max_new_tokens: int = 256,\n temperature: float = 0.8,\n top_k: int | None = 50,\n top_p: float | None = 0.95,\n repetition_penalty: float = 1.0,\n eos_id: int | None = None,\n stop_at_eos: bool = True,\n on_token=None,\n ) -> torch.Tensor:\n self.eval()\n B = idx.shape[0]\n block = self.cfg.block_size\n pos = 0\n past = None\n finished = torch.zeros(B, dtype=torch.bool, device=idx.device)\n```", "response": " for _ in range(max_new_tokens):\n if past is None:\n inp = idx[:, -block:]\n pos = idx.shape[1] - inp.shape[1]\n else:\n inp = idx[:, -1:]\n\n logits, _, past = self.forward(inp, past_kvs=past, use_cache=True, pos=pos)\n pos += inp.shape[1]\n logits = logits[:, -1, :].float()\n\n if repetition_penalty and repetition_penalty != 1.0:\n window = idx[:, -block:]\n for b in range(B):\n ids = torch.unique(window[b])\n vals = logits[b, ids]\n logits[b, ids] = torch.where(\n vals > 0, vals / repetition_penalty, vals * repetition_penalty\n )\n\n logits = logits / max(temperature, 1e-6)\n\n if top_k is not None and top_k > 0:\n k = min(top_k, logits.size(-1))\n kth = torch.topk(logits, k, dim=-1).values[:, -1:]\n logits = logits.masked_fill(logits < kth, float(\"-inf\"))\n\n if top_p is not None and 0.0 < top_p < 1.0:\n sorted_logits, sorted_idx = torch.sort(logits, descending=True, dim=-1)\n probs = torch.softmax(sorted_logits, dim=-1)\n cumulative = probs.cumsum(dim=-1)\n remove = cumulative - probs > top_p\n sorted_logits = sorted_logits.masked_fill(remove, float(\"-inf\"))\n logits = torch.full_like(logits, float(\"-inf\")).scatter(\n 1, sorted_idx, sorted_logits\n )\n\n probs = torch.softmax(logits, dim=-1)\n nxt = torch.multinomial(probs, num_samples=1)\n\n if eos_id is not None and stop_at_eos:\n finished |= nxt.squeeze(1) == eos_id\n nxt = torch.where(\n finished.unsqueeze(1),\n torch.full_like(nxt, eos_id),\n nxt,\n )\n idx = torch.cat((idx, nxt), dim=1)\n if on_token is not None:\n on_token(nxt[:, 0].tolist())\n if finished.all():\n break\n else:\n idx = torch.cat((idx, nxt), dim=1)\n if on_token is not None:\n on_token(nxt[:, 0].tolist())\n\n return idx", "source_file": "model.py", "function_name": "generate", "class_name": "GPT", "line_start": 364, "line_end": 440, "license": "mit", "source": "SadikAI project"}
{"task": "code_completion", "language": "python", "instruction": "Complete the following Python code. Return only the continuation, preserving indentation.\n\n```python\ndef estimate_params(cfg: ModelConfig) -> dict:\n e = cfg.n_embd\n hd = cfg.head_dim\n hidden = ((int(8 * e / 3) + 63) // 64) * 64\n\n emb = cfg.vocab_size * e\n head = 0 if cfg.tie_embeddings else cfg.vocab_size * e\n\n attn = e * (cfg.n_head * hd) + 2 * e * (cfg.n_kv_head * hd) + (cfg.n_head * hd) * e\n```", "response": " mlp = 3 * e * hidden\n norms = 2 * e\n\n per_layer = attn + mlp + norms\n total = emb + head + cfg.n_layer * per_layer\n return {\n \"embeddings\": emb,\n \"per_layer\": per_layer,\n \"non_embedding\": cfg.n_layer * per_layer,\n \"total\": total,\n }", "source_file": "model.py", "function_name": "estimate_params", "class_name": null, "line_start": 446, "line_end": 465, "license": "mit", "source": "SadikAI project"}
{"task": "code_completion", "language": "python", "instruction": "Complete the following Python code. Return only the continuation, preserving indentation.\n\n```python\ndef plan_row(path: Path, tokens: float, tflops: float, batch_tokens: float | None) -> dict:\n cfg = json.loads(path.read_text(encoding=\"utf-8\"))\n m = ModelConfig.from_dict(cfg[\"model\"])\n p = estimate_params(m)\n train = cfg.get(\"train\", {})\n tok_per_step = (\n train.get(\"batch_size\", 8) * m.block_size * train.get(\"grad_accum\", 1)\n )\n micro_tokens = batch_tokens or train.get(\"batch_size\", 8) * m.block_size\n\n # 16 bytes/param: bf16 weights (2) + fp32 master (4) + Adam m,v (8) + grads (2)\n weights_gb = p[\"total\"] * 16 / GB\n # ~34 bytes of activation per (token * hidden) without activation checkpointing\n act_gb = 34 * micro_tokens * m.n_embd / GB\n if train.get(\"grad_checkpoint\") or m.grad_checkpoint:\n act_gb *= 0.2\n```", "response": " total_gb = weights_gb + act_gb\n\n flops = 6 * p[\"total\"] * tokens\n hours = flops / (tflops * 1e12) / 3600\n steps = tokens / max(tok_per_step, 1)\n return {\n \"name\": cfg.get(\"name\", path.stem),\n \"params\": p[\"total\"],\n \"non_emb\": p[\"non_embedding\"],\n \"layers\": m.n_layer,\n \"embd\": m.n_embd,\n \"ctx\": m.block_size,\n \"tokens\": tokens,\n \"tpp\": tokens / p[\"total\"],\n \"vram\": total_gb,\n \"steps\": steps,\n \"hours\": hours,\n }", "source_file": "param_plan.py", "function_name": "plan_row", "class_name": null, "line_start": 30, "line_end": 63, "license": "mit", "source": "SadikAI project"}
{"task": "code_completion", "language": "python", "instruction": "Complete the following Python code. Return only the continuation, preserving indentation.\n\n```python\ndef main() -> None:\n ap = argparse.ArgumentParser(description=__doc__, formatter_class=argparse.RawDescriptionHelpFormatter)\n ap.add_argument(\"--configs\", default=\"configs/*.json\")\n ap.add_argument(\"--gb\", type=float, default=10.0, help=\"size of your text corpus\")\n ap.add_argument(\"--chars-per-token\", type=float, default=3.6)\n ap.add_argument(\"--tflops\", type=float, default=120.0,\n help=\"effective bf16 throughput you expect (4090 ~ 90, A100 ~ 150, H100 ~ 400)\")\n ap.add_argument(\"--batch-tokens\", type=float, default=None,\n help=\"tokens per micro-batch, for the activation estimate\")\n args = ap.parse_args()\n\n tokens = args.gb * GB / args.chars_per_token\n paths = sorted(Path(p) for p in glob.glob(args.configs))\n if not paths:\n raise SystemExit(f\"no configs matched {args.configs}\")\n\n print(f\"corpus: {args.gb:.2f} GB ~ {human(tokens)} tokens \"\n f\"({args.chars_per_token} chars/token)\")\n print(f\"speed assumption: {args.tflops:.0f} TFLOP/s effective\\n\")\n\n header = f\"{'model':<18}{'params':>9}{'non-emb':>9}{'layers':>7}{'d':>6}{'ctx':>6}\" \\\n f\"{'tok/param':>11}{'train GB':>10}{'steps':>10}{'hours':>9}\"\n print(header)\n```", "response": " print(\"-\" * len(header))\n\n rows = [plan_row(p, tokens, args.tflops, args.batch_tokens) for p in paths]\n for r in rows:\n flag = \" <-- overfit risk\" if r[\"tpp\"] < 5 else \"\"\n print(\n f\"{r['name']:<18}{human(r['params']):>9}{human(r['non_emb']):>9}\"\n f\"{r['layers']:>7}{r['embd']:>6}{r['ctx']:>6}\"\n f\"{r['tpp']:>11.1f}{r['vram']:>10.1f}{r['steps']:>10,.0f}{r['hours']:>9.1f}\"\n )\n if flag:\n print(f\"{'':<18}{flag}\")\n\n chinchilla = tokens / 20\n print(\n f\"\\nChinchilla compute-optimal for {human(tokens)} tokens: \"\n f\"~{human(chinchilla)} parameters (20 tokens/param).\"\n )\n print(\"Compute = 6 * params * tokens. Hours assume 100% of the quoted TFLOP/s;\")\n print(\"real runs land at 30-50% of peak, so double or triple the 'hours' column.\")\n print(\"\\nRules of thumb:\")\n print(\" * tokens/param < 5 -> the model will memorise, not generalise\")\n print(\" * tokens/param 20 -> compute-optimal (Chinchilla)\")\n print(\" * tokens/param > 100 -> overtrained but very strong for its size\")\n print(\" * if train GB is above your VRAM, lower batch_size or set grad_checkpoint\")", "source_file": "param_plan.py", "function_name": "main", "class_name": null, "line_start": 66, "line_end": 113, "license": "mit", "source": "SadikAI project"}
{"task": "code_completion", "language": "python", "instruction": "Complete the following Python code. Return only the continuation, preserving indentation.\n\n```python\ndef parse_mix(spec: str) -> dict[str, float]:\n \"\"\"Parse `english=2,code=3` or a JSON file of {\"english\": 2, ...}.\"\"\"\n spec = spec.strip()\n path = Path(spec)\n if path.suffix.lower() == \".json\" and path.exists():\n raw = json.loads(path.read_text(encoding=\"utf-8\"))\n return {str(k): float(v) for k, v in raw.items()}\n mix: dict[str, float] = {}\n```", "response": " for part in spec.split(\",\"):\n part = part.strip()\n if not part:\n continue\n if \"=\" not in part:\n raise SystemExit(f\"--mix entries need name=weight, got {part!r}\")\n name, weight = part.split(\"=\", 1)\n mix[name.strip()] = float(weight)\n if not mix:\n raise SystemExit(\"--mix was empty\")\n return mix", "source_file": "prepare_data.py", "function_name": "parse_mix", "class_name": null, "line_start": 33, "line_end": 51, "license": "mit", "source": "SadikAI project"}
{"task": "code_explanation", "language": "python", "instruction": "Explain what this Python function does.\n\n```python\ndef parse_mix(spec: str) -> dict[str, float]:\n \"\"\"Parse `english=2,code=3` or a JSON file of {\"english\": 2, ...}.\"\"\"\n spec = spec.strip()\n path = Path(spec)\n if path.suffix.lower() == \".json\" and path.exists():\n raw = json.loads(path.read_text(encoding=\"utf-8\"))\n return {str(k): float(v) for k, v in raw.items()}\n mix: dict[str, float] = {}\n for part in spec.split(\",\"):\n part = part.strip()\n if not part:\n continue\n if \"=\" not in part:\n raise SystemExit(f\"--mix entries need name=weight, got {part!r}\")\n name, weight = part.split(\"=\", 1)\n mix[name.strip()] = float(weight)\n if not mix:\n raise SystemExit(\"--mix was empty\")\n return mix\n```", "response": "Parse `english=2,code=3` or a JSON file of {\"english\": 2, ...}.", "source_file": "prepare_data.py", "function_name": "parse_mix", "class_name": null, "line_start": 33, "line_end": 51, "license": "mit", "source": "SadikAI project"}
{"task": "code_generation", "language": "python", "instruction": "Write a Python function `parse_mix(spec: str)` that does the following:\n\nParse `english=2,code=3` or a JSON file of {\"english\": 2, ...}.\n\nReturn only the Python code.", "response": "def parse_mix(spec: str) -> dict[str, float]:\n \"\"\"Parse `english=2,code=3` or a JSON file of {\"english\": 2, ...}.\"\"\"\n spec = spec.strip()\n path = Path(spec)\n if path.suffix.lower() == \".json\" and path.exists():\n raw = json.loads(path.read_text(encoding=\"utf-8\"))\n return {str(k): float(v) for k, v in raw.items()}\n mix: dict[str, float] = {}\n for part in spec.split(\",\"):\n part = part.strip()\n if not part:\n continue\n if \"=\" not in part:\n raise SystemExit(f\"--mix entries need name=weight, got {part!r}\")\n name, weight = part.split(\"=\", 1)\n mix[name.strip()] = float(weight)\n if not mix:\n raise SystemExit(\"--mix was empty\")\n return mix", "source_file": "prepare_data.py", "function_name": "parse_mix", "class_name": null, "line_start": 33, "line_end": 51, "license": "mit", "source": "SadikAI project"}
{"task": "code_completion", "language": "python", "instruction": "Complete the following Python code. Return only the continuation, preserving indentation.\n\n```python\ndef split_weights(source: Path, out_dir: Path, count: int) -> dict:\n \"\"\"Split *source* into *count* parts and write a join manifest.\"\"\"\n data = source.read_bytes()\n total = len(data)\n if total == 0:\n raise SystemExit(f\"{source} is empty\")\n part_size = (total + count - 1) // count\n\n if out_dir.exists():\n shutil.rmtree(out_dir)\n model_dir = out_dir / \"model\"\n model_dir.mkdir(parents=True)\n\n parts = []\n```", "response": " for index in range(count):\n chunk = data[index * part_size:(index + 1) * part_size]\n name = f\"weights.part{index:02d}.pt\"\n part_path = model_dir / name\n part_path.write_bytes(chunk)\n parts.append({\n \"name\": name,\n \"size\": len(chunk),\n \"sha256\": hashlib.sha256(chunk).hexdigest(),\n })\n\n manifest = {\n \"format\": \"sadik-ai-split-weights-v1\",\n \"file\": \"weights.pt\",\n \"size\": total,\n \"sha256\": hashlib.sha256(data).hexdigest(),\n \"parts\": parts,\n }\n (model_dir / \"weights.parts.json\").write_text(\n json.dumps(manifest, indent=2) + \"\\n\", encoding=\"utf-8\")\n return manifest", "source_file": "publish_hf.py", "function_name": "split_weights", "class_name": null, "line_start": 68, "line_end": 102, "license": "mit", "source": "SadikAI project"}
{"task": "code_explanation", "language": "python", "instruction": "Explain what this Python function does.\n\n```python\ndef split_weights(source: Path, out_dir: Path, count: int) -> dict:\n \"\"\"Split *source* into *count* parts and write a join manifest.\"\"\"\n data = source.read_bytes()\n total = len(data)\n if total == 0:\n raise SystemExit(f\"{source} is empty\")\n part_size = (total + count - 1) // count\n\n if out_dir.exists():\n shutil.rmtree(out_dir)\n model_dir = out_dir / \"model\"\n model_dir.mkdir(parents=True)\n\n parts = []\n for index in range(count):\n chunk = data[index * part_size:(index + 1) * part_size]\n name = f\"weights.part{index:02d}.pt\"\n part_path = model_dir / name\n part_path.write_bytes(chunk)\n parts.append({\n \"name\": name,\n \"size\": len(chunk),\n \"sha256\": hashlib.sha256(chunk).hexdigest(),\n })\n\n manifest = {\n \"format\": \"sadik-ai-split-weights-v1\",\n \"file\": \"weights.pt\",\n \"size\": total,\n \"sha256\": hashlib.sha256(data).hexdigest(),\n \"parts\": parts,\n }\n (model_dir / \"weights.parts.json\").write_text(\n json.dumps(manifest, indent=2) + \"\\n\", encoding=\"utf-8\")\n return manifest\n```", "response": "Split *source* into *count* parts and write a join manifest.", "source_file": "publish_hf.py", "function_name": "split_weights", "class_name": null, "line_start": 68, "line_end": 102, "license": "mit", "source": "SadikAI project"}
{"task": "code_generation", "language": "python", "instruction": "Write a Python function `split_weights(source: Path, out_dir: Path, count: int)` that does the following:\n\nSplit *source* into *count* parts and write a join manifest.\n\nReturn only the Python code.", "response": "def split_weights(source: Path, out_dir: Path, count: int) -> dict:\n \"\"\"Split *source* into *count* parts and write a join manifest.\"\"\"\n data = source.read_bytes()\n total = len(data)\n if total == 0:\n raise SystemExit(f\"{source} is empty\")\n part_size = (total + count - 1) // count\n\n if out_dir.exists():\n shutil.rmtree(out_dir)\n model_dir = out_dir / \"model\"\n model_dir.mkdir(parents=True)\n\n parts = []\n for index in range(count):\n chunk = data[index * part_size:(index + 1) * part_size]\n name = f\"weights.part{index:02d}.pt\"\n part_path = model_dir / name\n part_path.write_bytes(chunk)\n parts.append({\n \"name\": name,\n \"size\": len(chunk),\n \"sha256\": hashlib.sha256(chunk).hexdigest(),\n })\n\n manifest = {\n \"format\": \"sadik-ai-split-weights-v1\",\n \"file\": \"weights.pt\",\n \"size\": total,\n \"sha256\": hashlib.sha256(data).hexdigest(),\n \"parts\": parts,\n }\n (model_dir / \"weights.parts.json\").write_text(\n json.dumps(manifest, indent=2) + \"\\n\", encoding=\"utf-8\")\n return manifest", "source_file": "publish_hf.py", "function_name": "split_weights", "class_name": null, "line_start": 68, "line_end": 102, "license": "mit", "source": "SadikAI project"}
{"task": "code_completion", "language": "python", "instruction": "Complete the following Python code. Return only the continuation, preserving indentation.\n\n```python\ndef _already_uploaded(remote: dict, path_in_repo: str, local: Path) -> bool:\n sibling = remote.get(path_in_repo)\n if sibling is None or sibling.size != local.stat().st_size:\n return False\n```", "response": " if sibling.lfs is not None:\n return sibling.lfs.sha256 == sha256_file(local)\n # Small non-LFS files: same path and size is enough to skip a re-upload.\n return True", "source_file": "publish_hf.py", "function_name": "_already_uploaded", "class_name": null, "line_start": 110, "line_end": 117, "license": "mit", "source": "SadikAI project"}
{"task": "code_completion", "language": "python", "instruction": "Complete the following Python code. Return only the continuation, preserving indentation.\n\n```python\ndef verify_download(api: HfApi, manifest: dict, expected_sha: str) -> Path:\n \"\"\"Download the public parts, join them, and return the verified weights.\"\"\"\n temp = Path(tempfile.mkdtemp(prefix=\"sadik_hf_verify_\"))\n print(f\" downloading public parts into {temp}\", flush=True)\n snapshot_download(\n REPO,\n repo_type=\"model\",\n local_dir=temp,\n allow_patterns=[\"model/weights.part*.pt\", \"model/weights.parts.json\"],\n )\n```", "response": " from join_weights import ensure_weights\n\n joined = ensure_weights(temp / \"model\" / \"weights.pt\")\n actual = sha256_file(joined)\n if actual != expected_sha:\n raise SystemExit(\n f\"public weights SHA-256 {actual} does not match local {expected_sha}\"\n )\n print(f\" public parts joined to {actual[:16]}... (exact match)\", flush=True)\n return joined", "source_file": "publish_hf.py", "function_name": "verify_download", "class_name": null, "line_start": 153, "line_end": 173, "license": "mit", "source": "SadikAI project"}
{"task": "code_explanation", "language": "python", "instruction": "Explain what this Python function does.\n\n```python\ndef verify_download(api: HfApi, manifest: dict, expected_sha: str) -> Path:\n \"\"\"Download the public parts, join them, and return the verified weights.\"\"\"\n temp = Path(tempfile.mkdtemp(prefix=\"sadik_hf_verify_\"))\n print(f\" downloading public parts into {temp}\", flush=True)\n snapshot_download(\n REPO,\n repo_type=\"model\",\n local_dir=temp,\n allow_patterns=[\"model/weights.part*.pt\", \"model/weights.parts.json\"],\n )\n\n from join_weights import ensure_weights\n\n joined = ensure_weights(temp / \"model\" / \"weights.pt\")\n actual = sha256_file(joined)\n if actual != expected_sha:\n raise SystemExit(\n f\"public weights SHA-256 {actual} does not match local {expected_sha}\"\n )\n print(f\" public parts joined to {actual[:16]}... (exact match)\", flush=True)\n return joined\n```", "response": "Download the public parts, join them, and return the verified weights.", "source_file": "publish_hf.py", "function_name": "verify_download", "class_name": null, "line_start": 153, "line_end": 173, "license": "mit", "source": "SadikAI project"}
{"task": "code_generation", "language": "python", "instruction": "Write a Python function `verify_download(api: HfApi, manifest: dict, expected_sha: str)` that does the following:\n\nDownload the public parts, join them, and return the verified weights.\n\nReturn only the Python code.", "response": "def verify_download(api: HfApi, manifest: dict, expected_sha: str) -> Path:\n \"\"\"Download the public parts, join them, and return the verified weights.\"\"\"\n temp = Path(tempfile.mkdtemp(prefix=\"sadik_hf_verify_\"))\n print(f\" downloading public parts into {temp}\", flush=True)\n snapshot_download(\n REPO,\n repo_type=\"model\",\n local_dir=temp,\n allow_patterns=[\"model/weights.part*.pt\", \"model/weights.parts.json\"],\n )\n\n from join_weights import ensure_weights\n\n joined = ensure_weights(temp / \"model\" / \"weights.pt\")\n actual = sha256_file(joined)\n if actual != expected_sha:\n raise SystemExit(\n f\"public weights SHA-256 {actual} does not match local {expected_sha}\"\n )\n print(f\" public parts joined to {actual[:16]}... (exact match)\", flush=True)\n return joined", "source_file": "publish_hf.py", "function_name": "verify_download", "class_name": null, "line_start": 153, "line_end": 173, "license": "mit", "source": "SadikAI project"}
{"task": "code_completion", "language": "python", "instruction": "Complete the following Python code. Return only the continuation, preserving indentation.\n\n```python\ndef main() -> None:\n global REPO\n parser = argparse.ArgumentParser(description=__doc__,\n formatter_class=argparse.RawDescriptionHelpFormatter)\n parser.add_argument(\"--repo\", default=REPO)\n parser.add_argument(\"--folder\", type=Path, default=RELEASE)\n parser.add_argument(\"--parts\", type=int, default=PART_COUNT)\n parser.add_argument(\"--prepare-only\", action=\"store_true\",\n help=\"split weights locally and stop before uploading\")\n parser.add_argument(\"--skip-download-verify\", action=\"store_true\",\n help=\"skip re-downloading the parts after upload\")\n args = parser.parse_args()\n\n REPO = args.repo\n stage: Path = args.folder\n weights = stage / WEIGHTS\n if not weights.exists():\n raise SystemExit(f\"missing {weights}\")\n\n expected_sha = sha256_file(weights)\n expected_size = weights.stat().st_size\n print(f\"repo {REPO}\")\n print(f\"folder {stage}\")\n print(f\"weights {expected_size / 1e6:.1f} MB sha256 {expected_sha[:16]}...\")\n\n print(f\"stage 1/4: split into {args.parts} parts\", flush=True)\n manifest = split_weights(weights, PARTS_DIR, args.parts)\n part_dir = PARTS_DIR / \"model\"\n for part in manifest[\"parts\"]:\n print(f\" {part['name']} {part['size'] / 1e6:.2f} MB {part['sha256'][:16]}...\")\n\n if args.prepare_only:\n print(f\"prepared {part_dir} (not uploaded)\")\n return\n\n api = HfApi()\n who = api.whoami()[\"name\"]\n print(f\"account {who}\", flush=True)\n\n print(\"stage 2/4: docs, app, tokenizer, generate.py\", flush=True)\n api.upload_folder(\n folder_path=str(stage),\n repo_id=REPO,\n repo_type=\"model\",\n ignore_patterns=[\n \"model/weights.pt\",\n \"model/weights.part*.pt\",\n \"model/weights.parts.json\",\n \"**/__pycache__/**\",\n \"*.pyc\",\n ],\n commit_message=\"SadikAI Medium step 4249 - app, docs, tokenizer, split loader\",\n )\n print(\" small files uploaded\", flush=True)\n\n print(\"stage 3/4: weight parts\", flush=True)\n remote = _remote_siblings(api)\n```", "response": " for index, part in enumerate(manifest[\"parts\"], start=1):\n local = part_dir / part[\"name\"]\n path_in_repo = f\"model/{part['name']}\"\n if _already_uploaded(remote, path_in_repo, local):\n print(f\" {path_in_repo} already matches, skipping\", flush=True)\n continue\n print(f\" part {index}/{len(manifest['parts'])}: {path_in_repo}\", flush=True)\n upload_with_retry(api, local, path_in_repo,\n f\"SadikAI Medium weights part {index}/{len(manifest['parts'])}\")\n\n manifest_local = part_dir / \"weights.parts.json\"\n remote = _remote_siblings(api)\n if _already_uploaded(remote, \"model/weights.parts.json\", manifest_local):\n print(\" model/weights.parts.json already matches, skipping\", flush=True)\n else:\n print(\" model/weights.parts.json\", flush=True)\n upload_with_retry(api, manifest_local, \"model/weights.parts.json\",\n \"SadikAI Medium weights manifest\")\n\n print(\"stage 4/4: remove the old single weights file\", flush=True)\n remote = _remote_siblings(api)\n if \"model/weights.pt\" in remote:\n api.create_commit(\n repo_id=REPO,\n repo_type=\"model\",\n operations=[CommitOperationDelete(path_in_repo=\"model/weights.pt\")],\n commit_message=\"SadikAI Medium: replace single weights.pt with split parts\",\n )\n print(\" deleted remote model/weights.pt\", flush=True)\n else:\n print(\" remote model/weights.pt already absent\", flush=True)\n\n print(\"verify remote layout\", flush=True)\n remote = _remote_siblings(api)\n if \"model/weights.pt\" in remote:\n raise SystemExit(\"remote model/weights.pt still exists\")\n for part in manifest[\"parts\"]:\n path_in_repo = f\"model/{part['name']}\"\n sibling = remote.get(path_in_repo)\n if sibling is None:\n raise SystemExit(f\"remote part missing: {path_in_repo}\")\n if sibling.size != part[\"size\"]:\n raise SystemExit(f\"remote part size mismatch: {path_in_repo}\")\n if sibling.lfs is not None and sibling.lfs.sha256 != part[\"sha256\"]:\n raise SystemExit(f\"remote part hash mismatch: {path_in_repo}\")\n if \"model/weights.parts.json\" not in remote:\n raise SystemExit(\"remote weights manifest missing\")\n print(f\" {len(remote)} files on the repo\", flush=True)\n\n config_path = hf_hub_download(REPO, \"model/config.json\", repo_type=\"model\",\n force_download=True)\n config = json.loads(Path(config_path).read_text(encoding=\"utf-8\"))\n print(\" remote config:\", json.dumps({\n \"creator\": config.get(\"creator\"),\n \"step\": config.get(\"step\"),\n \"val_loss\": config.get(\"val_loss\"),\n \"perplexity\": config.get(\"perplexity\"),\n \"total_params\": config.get(\"total_params\"),\n }, ensure_ascii=False), flush=True)\n if config.get(\"step\") != 4249 or abs(float(config.get(\"val_loss\", 0)) - 2.933825445175171) > 1e-9:\n raise SystemExit(\"remote config is not the Medium step-4249 release\")\n\n if not args.skip_download_verify:\n print(\"download and verify the public weights\", flush=True)\n verify_download(api, manifest, expected_sha)\n\n print(f\"done https://huggingface.co/{REPO}\")", "source_file": "publish_hf.py", "function_name": "main", "class_name": null, "line_start": 176, "line_end": 299, "license": "mit", "source": "SadikAI project"}
{"task": "code_completion", "language": "python", "instruction": "Complete the following Python code. Return only the continuation, preserving indentation.\n\n```python\ndef split_release(source: Path, out_dir: Path, count: int) -> dict:\n \"\"\"Split *source* into *count* parts and return the join manifest.\"\"\"\n data = source.read_bytes()\n total = len(data)\n if total == 0:\n raise SystemExit(f\"{source} is empty\")\n part_size = (total + count - 1) // count\n\n if out_dir.exists():\n shutil.rmtree(out_dir)\n out_dir.mkdir(parents=True)\n\n parts = []\n```", "response": " for index in range(count):\n chunk = data[index * part_size:(index + 1) * part_size]\n name = f\"{source.name}.part{index:02d}\"\n (out_dir / name).write_bytes(chunk)\n parts.append({\n \"name\": name,\n \"size\": len(chunk),\n \"sha256\": hashlib.sha256(chunk).hexdigest(),\n })\n\n manifest = {\n \"format\": MANIFEST_FORMAT,\n \"file\": source.name,\n \"size\": total,\n \"sha256\": hashlib.sha256(data).hexdigest(),\n \"parts\": parts,\n }\n (out_dir / f\"{source.name}.parts.json\").write_text(\n json.dumps(manifest, indent=2) + \"\\n\", encoding=\"utf-8\")\n return manifest", "source_file": "publish_zip.py", "function_name": "split_release", "class_name": null, "line_start": 60, "line_end": 92, "license": "mit", "source": "SadikAI project"}
{"task": "code_explanation", "language": "python", "instruction": "Explain what this Python function does.\n\n```python\ndef split_release(source: Path, out_dir: Path, count: int) -> dict:\n \"\"\"Split *source* into *count* parts and return the join manifest.\"\"\"\n data = source.read_bytes()\n total = len(data)\n if total == 0:\n raise SystemExit(f\"{source} is empty\")\n part_size = (total + count - 1) // count\n\n if out_dir.exists():\n shutil.rmtree(out_dir)\n out_dir.mkdir(parents=True)\n\n parts = []\n for index in range(count):\n chunk = data[index * part_size:(index + 1) * part_size]\n name = f\"{source.name}.part{index:02d}\"\n (out_dir / name).write_bytes(chunk)\n parts.append({\n \"name\": name,\n \"size\": len(chunk),\n \"sha256\": hashlib.sha256(chunk).hexdigest(),\n })\n\n manifest = {\n \"format\": MANIFEST_FORMAT,\n \"file\": source.name,\n \"size\": total,\n \"sha256\": hashlib.sha256(data).hexdigest(),\n \"parts\": parts,\n }\n (out_dir / f\"{source.name}.parts.json\").write_text(\n json.dumps(manifest, indent=2) + \"\\n\", encoding=\"utf-8\")\n return manifest\n```", "response": "Split *source* into *count* parts and return the join manifest.", "source_file": "publish_zip.py", "function_name": "split_release", "class_name": null, "line_start": 60, "line_end": 92, "license": "mit", "source": "SadikAI project"}
{"task": "code_generation", "language": "python", "instruction": "Write a Python function `split_release(source: Path, out_dir: Path, count: int)` that does the following:\n\nSplit *source* into *count* parts and return the join manifest.\n\nReturn only the Python code.", "response": "def split_release(source: Path, out_dir: Path, count: int) -> dict:\n \"\"\"Split *source* into *count* parts and return the join manifest.\"\"\"\n data = source.read_bytes()\n total = len(data)\n if total == 0:\n raise SystemExit(f\"{source} is empty\")\n part_size = (total + count - 1) // count\n\n if out_dir.exists():\n shutil.rmtree(out_dir)\n out_dir.mkdir(parents=True)\n\n parts = []\n for index in range(count):\n chunk = data[index * part_size:(index + 1) * part_size]\n name = f\"{source.name}.part{index:02d}\"\n (out_dir / name).write_bytes(chunk)\n parts.append({\n \"name\": name,\n \"size\": len(chunk),\n \"sha256\": hashlib.sha256(chunk).hexdigest(),\n })\n\n manifest = {\n \"format\": MANIFEST_FORMAT,\n \"file\": source.name,\n \"size\": total,\n \"sha256\": hashlib.sha256(data).hexdigest(),\n \"parts\": parts,\n }\n (out_dir / f\"{source.name}.parts.json\").write_text(\n json.dumps(manifest, indent=2) + \"\\n\", encoding=\"utf-8\")\n return manifest", "source_file": "publish_zip.py", "function_name": "split_release", "class_name": null, "line_start": 60, "line_end": 92, "license": "mit", "source": "SadikAI project"}
{"task": "code_completion", "language": "python", "instruction": "Complete the following Python code. Return only the continuation, preserving indentation.\n\n```python\ndef write_readme(manifest: dict, out_dir: Path) -> Path:\n \"\"\"Write the release-folder README shown on the Hub.\"\"\"\n name = manifest[\"file\"]\n total_mb = manifest[\"size\"] / 1e6\n part_mb = manifest[\"parts\"][0][\"size\"] / 1e6\n parts = \"\\n\".join(f\"- `{part['name']}`\" for part in manifest[\"parts\"])\n```", "response": " text = f\"\"\"# SadikAI Medium — split release zip\n\nSadikAI Medium is made by **Sadik Nawaz (11 years old, 6th class)**.\n\n`{name}` is **{total_mb:.1f} MB**. Long uploads from the home connection used\nto publish this project keep dropping, so the Hub stores the zip as\n**{len(manifest['parts'])} parts of about {part_mb:.1f} MB** instead of one file.\n\n## Download\n\nDownload every file in this `release/` folder into one directory:\n\n{parts}\n- `{name}.parts.json`\n- `{name}.sha256`\n- `join_release_zip.py`\n\nKeep the file names exactly as they are. Then run:\n\n```powershell\npython join_release_zip.py\n```\n\nThe script:\n\n1. checks the size and SHA-256 of every part;\n2. joins them into `{name}`;\n3. checks the whole zip against SHA-256\n `{manifest['sha256']}`;\n4. only then writes the final `{name}`.\n\nExpected SHA-256:\n\n```\n{manifest['sha256']} {name}\n```\n\n## What is inside\n\n- step 4249 Medium weights (7.9M parameters, val loss 2.9338, perplexity 18.8)\n- tokenizer, standalone `generate.py`, full offline chat app\n- **113 curated school lessons** (English, Hindi, maths, science, history,\n geography, civics, computers, life skills, arts, sports, world knowledge)\n- story and poem library, model card, data sources and licence\n\nThe zip runs offline on a 4-core CPU with no GPU:\n\n```powershell\npip install -r requirements.txt\npython generate.py --say \"hello\"\npython chat_server.py --open\n```\n\"\"\"\n path = out_dir / \"README.md\"\n path.write_text(text, encoding=\"utf-8\")\n return path", "source_file": "publish_zip.py", "function_name": "write_readme", "class_name": null, "line_start": 95, "line_end": 156, "license": "mit", "source": "SadikAI project"}
{"task": "code_explanation", "language": "python", "instruction": "Explain what this Python function does.\n\n```python\ndef write_readme(manifest: dict, out_dir: Path) -> Path:\n \"\"\"Write the release-folder README shown on the Hub.\"\"\"\n name = manifest[\"file\"]\n total_mb = manifest[\"size\"] / 1e6\n part_mb = manifest[\"parts\"][0][\"size\"] / 1e6\n parts = \"\\n\".join(f\"- `{part['name']}`\" for part in manifest[\"parts\"])\n text = f\"\"\"# SadikAI Medium — split release zip\n\nSadikAI Medium is made by **Sadik Nawaz (11 years old, 6th class)**.\n\n`{name}` is **{total_mb:.1f} MB**. Long uploads from the home connection used\nto publish this project keep dropping, so the Hub stores the zip as\n**{len(manifest['parts'])} parts of about {part_mb:.1f} MB** instead of one file.\n\n## Download\n\nDownload every file in this `release/` folder into one directory:\n\n{parts}\n- `{name}.parts.json`\n- `{name}.sha256`\n- `join_release_zip.py`\n\nKeep the file names exactly as they are. Then run:\n\n```powershell\npython join_release_zip.py\n```\n\nThe script:\n\n1. checks the size and SHA-256 of every part;\n2. joins them into `{name}`;\n3. checks the whole zip against SHA-256\n `{manifest['sha256']}`;\n4. only then writes the final `{name}`.\n\nExpected SHA-256:\n\n```\n{manifest['sha256']} {name}\n```\n\n## What is inside\n\n- step 4249 Medium weights (7.9M parameters, val loss 2.9338, perplexity 18.8)\n- tokenizer, standalone `generate.py`, full offline chat app\n- **113 curated school lessons** (English, Hindi, maths, science, history,\n geography, civics, computers, life skills, arts, sports, world knowledge)\n- story and poem library, model card, data sources and licence\n\nThe zip runs offline on a 4-core CPU with no GPU:\n\n```powershell\npip install -r requirements.txt\npython generate.py --say \"hello\"\npython chat_server.py --open\n```\n\"\"\"\n path = out_dir / \"README.md\"\n path.write_text(text, encoding=\"utf-8\")\n return path\n```", "response": "Write the release-folder README shown on the Hub.", "source_file": "publish_zip.py", "function_name": "write_readme", "class_name": null, "line_start": 95, "line_end": 156, "license": "mit", "source": "SadikAI project"}
{"task": "code_generation", "language": "python", "instruction": "Write a Python function `write_readme(manifest: dict, out_dir: Path)` that does the following:\n\nWrite the release-folder README shown on the Hub.\n\nReturn only the Python code.", "response": "def write_readme(manifest: dict, out_dir: Path) -> Path:\n \"\"\"Write the release-folder README shown on the Hub.\"\"\"\n name = manifest[\"file\"]\n total_mb = manifest[\"size\"] / 1e6\n part_mb = manifest[\"parts\"][0][\"size\"] / 1e6\n parts = \"\\n\".join(f\"- `{part['name']}`\" for part in manifest[\"parts\"])\n text = f\"\"\"# SadikAI Medium — split release zip\n\nSadikAI Medium is made by **Sadik Nawaz (11 years old, 6th class)**.\n\n`{name}` is **{total_mb:.1f} MB**. Long uploads from the home connection used\nto publish this project keep dropping, so the Hub stores the zip as\n**{len(manifest['parts'])} parts of about {part_mb:.1f} MB** instead of one file.\n\n## Download\n\nDownload every file in this `release/` folder into one directory:\n\n{parts}\n- `{name}.parts.json`\n- `{name}.sha256`\n- `join_release_zip.py`\n\nKeep the file names exactly as they are. Then run:\n\n```powershell\npython join_release_zip.py\n```\n\nThe script:\n\n1. checks the size and SHA-256 of every part;\n2. joins them into `{name}`;\n3. checks the whole zip against SHA-256\n `{manifest['sha256']}`;\n4. only then writes the final `{name}`.\n\nExpected SHA-256:\n\n```\n{manifest['sha256']} {name}\n```\n\n## What is inside\n\n- step 4249 Medium weights (7.9M parameters, val loss 2.9338, perplexity 18.8)\n- tokenizer, standalone `generate.py`, full offline chat app\n- **113 curated school lessons** (English, Hindi, maths, science, history,\n geography, civics, computers, life skills, arts, sports, world knowledge)\n- story and poem library, model card, data sources and licence\n\nThe zip runs offline on a 4-core CPU with no GPU:\n\n```powershell\npip install -r requirements.txt\npython generate.py --say \"hello\"\npython chat_server.py --open\n```\n\"\"\"\n path = out_dir / \"README.md\"\n path.write_text(text, encoding=\"utf-8\")\n return path", "source_file": "publish_zip.py", "function_name": "write_readme", "class_name": null, "line_start": 95, "line_end": 156, "license": "mit", "source": "SadikAI project"}
{"task": "code_completion", "language": "python", "instruction": "Complete the following Python code. Return only the continuation, preserving indentation.\n\n```python\ndef verify_download(manifest: dict) -> Path:\n \"\"\"Download the public release folder, join it, and check the zip hash.\"\"\"\n temp = Path(tempfile.mkdtemp(prefix=\"sadik_zip_verify_\"))\n print(f\" downloading public release/ into {temp}\", flush=True)\n snapshot_download(\n REPO,\n repo_type=\"model\",\n local_dir=temp,\n allow_patterns=[f\"{REMOTE_DIR}/*\"],\n )\n\n from join_release_zip import join_release\n```", "response": " folder = temp / REMOTE_DIR\n joined = join_release(folder, verbose=False)\n actual = sha256_file(joined)\n if actual != manifest[\"sha256\"]:\n raise SystemExit(\n f\"public zip SHA-256 {actual} does not match local {manifest['sha256']}\"\n )\n if joined.stat().st_size != manifest[\"size\"]:\n raise SystemExit(\n f\"public zip is {joined.stat().st_size} bytes, \"\n f\"expected {manifest['size']}\"\n )\n print(f\" public parts joined to {actual[:16]}... (exact match)\", flush=True)\n return joined", "source_file": "publish_zip.py", "function_name": "verify_download", "class_name": null, "line_start": 207, "line_end": 233, "license": "mit", "source": "SadikAI project"}
{"task": "code_explanation", "language": "python", "instruction": "Explain what this Python function does.\n\n```python\ndef verify_download(manifest: dict) -> Path:\n \"\"\"Download the public release folder, join it, and check the zip hash.\"\"\"\n temp = Path(tempfile.mkdtemp(prefix=\"sadik_zip_verify_\"))\n print(f\" downloading public release/ into {temp}\", flush=True)\n snapshot_download(\n REPO,\n repo_type=\"model\",\n local_dir=temp,\n allow_patterns=[f\"{REMOTE_DIR}/*\"],\n )\n\n from join_release_zip import join_release\n\n folder = temp / REMOTE_DIR\n joined = join_release(folder, verbose=False)\n actual = sha256_file(joined)\n if actual != manifest[\"sha256\"]:\n raise SystemExit(\n f\"public zip SHA-256 {actual} does not match local {manifest['sha256']}\"\n )\n if joined.stat().st_size != manifest[\"size\"]:\n raise SystemExit(\n f\"public zip is {joined.stat().st_size} bytes, \"\n f\"expected {manifest['size']}\"\n )\n print(f\" public parts joined to {actual[:16]}... (exact match)\", flush=True)\n return joined\n```", "response": "Download the public release folder, join it, and check the zip hash.", "source_file": "publish_zip.py", "function_name": "verify_download", "class_name": null, "line_start": 207, "line_end": 233, "license": "mit", "source": "SadikAI project"}
{"task": "code_generation", "language": "python", "instruction": "Write a Python function `verify_download(manifest: dict)` that does the following:\n\nDownload the public release folder, join it, and check the zip hash.\n\nReturn only the Python code.", "response": "def verify_download(manifest: dict) -> Path:\n \"\"\"Download the public release folder, join it, and check the zip hash.\"\"\"\n temp = Path(tempfile.mkdtemp(prefix=\"sadik_zip_verify_\"))\n print(f\" downloading public release/ into {temp}\", flush=True)\n snapshot_download(\n REPO,\n repo_type=\"model\",\n local_dir=temp,\n allow_patterns=[f\"{REMOTE_DIR}/*\"],\n )\n\n from join_release_zip import join_release\n\n folder = temp / REMOTE_DIR\n joined = join_release(folder, verbose=False)\n actual = sha256_file(joined)\n if actual != manifest[\"sha256\"]:\n raise SystemExit(\n f\"public zip SHA-256 {actual} does not match local {manifest['sha256']}\"\n )\n if joined.stat().st_size != manifest[\"size\"]:\n raise SystemExit(\n f\"public zip is {joined.stat().st_size} bytes, \"\n f\"expected {manifest['size']}\"\n )\n print(f\" public parts joined to {actual[:16]}... (exact match)\", flush=True)\n return joined", "source_file": "publish_zip.py", "function_name": "verify_download", "class_name": null, "line_start": 207, "line_end": 233, "license": "mit", "source": "SadikAI project"}
{"task": "code_completion", "language": "python", "instruction": "Complete the following Python code. Return only the continuation, preserving indentation.\n\n```python\ndef main() -> None:\n global REPO\n parser = argparse.ArgumentParser(\n description=__doc__,\n formatter_class=argparse.RawDescriptionHelpFormatter,\n )\n parser.add_argument(\"zip\", type=Path, nargs=\"?\",\n default=RELEASE_DIR / \"sadik-ai-medium-multilingual-4250step-ppl19.zip\",\n help=\"release zip to publish\")\n parser.add_argument(\"--repo\", default=REPO)\n parser.add_argument(\"--parts\", type=int, default=PART_COUNT)\n parser.add_argument(\"--prepare-only\", action=\"store_true\",\n help=\"split the zip locally and stop before uploading\")\n parser.add_argument(\"--skip-download-verify\", action=\"store_true\",\n help=\"skip re-downloading release/ after upload\")\n args = parser.parse_args()\n\n REPO = args.repo\n source: Path = args.zip\n if not source.exists():\n raise SystemExit(f\"missing {source}\")\n if source.suffix.lower() != \".zip\":\n raise SystemExit(f\"{source} is not a .zip file\")\n if args.parts < 2:\n raise SystemExit(\"--parts must be at least 2\")\n\n expected_sha = sha256_file(source)\n expected_size = source.stat().st_size\n print(f\"repo {REPO}\")\n print(f\"zip {source.name} {expected_size / 1e6:.1f} MB \"\n f\"sha256 {expected_sha[:16]}...\")\n\n sidecar = source.with_name(source.name + \".sha256\")\n if sidecar.exists():\n sidecar_text = sidecar.read_text(encoding=\"utf-8\").strip()\n if expected_sha not in sidecar_text:\n raise SystemExit(f\"{sidecar} does not match {source}; rebuild the sidecar\")\n else:\n sidecar_text = f\"{expected_sha} {source.name}\"\n sidecar.write_text(sidecar_text + \"\\n\", encoding=\"utf-8\")\n print(f\" wrote {sidecar}\")\n\n out_dir = SPLIT_ROOT / source.name\n print(f\"stage 1/5: split into {args.parts} parts\", flush=True)\n manifest = split_release(source, out_dir, args.parts)\n for part in manifest[\"parts\"]:\n print(f\" {part['name']} {part['size'] / 1e6:.2f} MB \"\n f\"{part['sha256'][:16]}...\")\n readme = write_readme(manifest, out_dir)\n (out_dir / \"join_release_zip.py\").write_bytes(\n Path(__file__).with_name(\"join_release_zip.py\").read_bytes())\n\n if args.prepare_only:\n print(f\"prepared {out_dir} (not uploaded)\")\n return\n\n api = HfApi()\n who = api.whoami()[\"name\"]\n print(f\"account {who}\", flush=True)\n```", "response": " print(\"stage 2/5: release README, join script, checksum\", flush=True)\n small_files = [\n (readme, f\"{REMOTE_DIR}/README.md\"),\n (out_dir / \"join_release_zip.py\", f\"{REMOTE_DIR}/join_release_zip.py\"),\n (sidecar, f\"{REMOTE_DIR}/{sidecar.name}\"),\n ]\n remote = _remote_siblings(api)\n for local, path_in_repo in small_files:\n if _already_uploaded(remote, path_in_repo, local):\n print(f\" {path_in_repo} already matches, skipping\", flush=True)\n continue\n print(f\" {path_in_repo}\", flush=True)\n upload_with_retry(api, local, path_in_repo,\n f\"SadikAI Medium release: {Path(path_in_repo).name}\")\n\n print(\"stage 3/5: release zip parts\", flush=True)\n remote = _remote_siblings(api)\n for index, part in enumerate(manifest[\"parts\"], start=1):\n local = out_dir / part[\"name\"]\n path_in_repo = f\"{REMOTE_DIR}/{part['name']}\"\n if _already_uploaded(remote, path_in_repo, local):\n print(f\" {path_in_repo} already matches, skipping\", flush=True)\n continue\n print(f\" part {index}/{len(manifest['parts'])}: {path_in_repo}\", flush=True)\n upload_with_retry(api, local, path_in_repo,\n f\"SadikAI Medium release part {index}/{len(manifest['parts'])}\")\n\n print(\"stage 4/5: manifest (uploaded last, marks the release complete)\", flush=True)\n manifest_local = out_dir / f\"{source.name}.parts.json\"\n manifest_repo = f\"{REMOTE_DIR}/{manifest_local.name}\"\n remote = _remote_siblings(api)\n if _already_uploaded(remote, manifest_repo, manifest_local):\n print(f\" {manifest_repo} already matches, skipping\", flush=True)\n else:\n print(f\" {manifest_repo}\", flush=True)\n upload_with_retry(api, manifest_local, manifest_repo,\n \"SadikAI Medium release manifest\")\n\n print(\"verify remote layout\", flush=True)\n remote = _remote_siblings(api)\n for part in manifest[\"parts\"]:\n path_in_repo = f\"{REMOTE_DIR}/{part['name']}\"\n sibling = remote.get(path_in_repo)\n if sibling is None:\n raise SystemExit(f\"remote part missing: {path_in_repo}\")\n if sibling.size != part[\"size\"]:\n raise SystemExit(f\"remote part size mismatch: {path_in_repo}\")\n if sibling.lfs is not None and sibling.lfs.sha256 != part[\"sha256\"]:\n raise SystemExit(f\"remote part hash mismatch: {path_in_repo}\")\n for required in (manifest_repo,\n f\"{REMOTE_DIR}/README.md\",\n f\"{REMOTE_DIR}/join_release_zip.py\",\n f\"{REMOTE_DIR}/{sidecar.name}\"):\n if required not in remote:\n raise SystemExit(f\"remote file missing: {required}\")\n print(f\" {len(remote)} files on the repo\", flush=True)\n\n if not args.skip_download_verify:\n print(\"stage 5/5: download, join and verify the public release\", flush=True)\n verify_download(manifest)\n\n print(f\"done https://huggingface.co/{REPO}/tree/main/{REMOTE_DIR}\")", "source_file": "publish_zip.py", "function_name": "main", "class_name": null, "line_start": 236, "line_end": 357, "license": "mit", "source": "SadikAI project"}
{"task": "code_completion", "language": "python", "instruction": "Complete the following Python code. Return only the continuation, preserving indentation.\n\n```python\ndef load_model(checkpoint: str | Path, device: torch.device) -> tuple[GPT, dict]:\n ckpt = torch.load(checkpoint, map_location=device, weights_only=False)\n model_cfg = ModelConfig.from_dict(ckpt[\"model_config\"])\n model = GPT(model_cfg)\n```", "response": " state = ckpt[\"model\"]\n if any(k.startswith(\"_orig_mod.\") for k in state):\n state = {k.replace(\"_orig_mod.\", \"\", 1): v for k, v in state.items()}\n model.load_state_dict(state)\n model.to(device).eval()\n return model, ckpt", "source_file": "sample.py", "function_name": "load_model", "class_name": null, "line_start": 23, "line_end": 32, "license": "mit", "source": "SadikAI project"}
{"task": "code_completion", "language": "python", "instruction": "Complete the following Python code. Return only the continuation, preserving indentation.\n\n```python\ndef main() -> None:\n ap = argparse.ArgumentParser(description=__doc__, formatter_class=argparse.RawDescriptionHelpFormatter)\n ap.add_argument(\"--checkpoint\", default=\"runs/small/best.pt\")\n ap.add_argument(\"--tokenizer\", default=\"tokenizer/tokenizer.json\")\n ap.add_argument(\"--prompt\", default=None)\n ap.add_argument(\"--interactive\", action=\"store_true\")\n ap.add_argument(\"--num-samples\", type=int, default=1)\n ap.add_argument(\"--max-new-tokens\", type=int, default=256)\n ap.add_argument(\"--temperature\", type=float, default=0.8)\n ap.add_argument(\"--top-k\", type=int, default=50)\n ap.add_argument(\"--top-p\", type=float, default=0.95)\n ap.add_argument(\"--repetition-penalty\", type=float, default=1.05)\n ap.add_argument(\"--seed\", type=int, default=0)\n ap.add_argument(\"--device\", default=\"auto\")\n args = ap.parse_args()\n\n if args.device == \"auto\":\n device = torch.device(\"cuda\" if torch.cuda.is_available() else \"cpu\")\n else:\n device = torch.device(args.device)\n\n model, ckpt = load_model(args.checkpoint, device)\n tok = Tokenizer(args.tokenizer)\n if tok.vocab_size != model.cfg.vocab_size:\n raise SystemExit(\n f\"tokenizer vocab {tok.vocab_size} != model vocab {model.cfg.vocab_size}\"\n )\n print(\n f\"loaded {args.checkpoint} @ step {ckpt.get('step', '?')} \"\n f\"({model.num_params()/1e6:.1f}M params, ctx {model.cfg.block_size}) on {device}\"\n )\n```", "response": " def run(prompt: str) -> str:\n ids = tok.encode(prompt) if prompt else [tok.eos_id]\n # keep enough room for the completion inside the context window\n room = model.cfg.block_size - args.max_new_tokens\n if room > 0 and len(ids) > room:\n ids = ids[-room:]\n x = torch.tensor([ids], dtype=torch.long, device=device)\n out = model.generate(\n x,\n max_new_tokens=args.max_new_tokens,\n temperature=args.temperature,\n top_k=args.top_k,\n top_p=args.top_p,\n repetition_penalty=args.repetition_penalty,\n eos_id=tok.eos_id,\n stop_at_eos=True,\n )\n text = tok.decode(out[0, len(ids) :].tolist())\n return text\n\n if args.interactive:\n print(\"interactive mode - empty line or Ctrl+C to quit\")\n while True:\n try:\n prompt = input(\"\\n> \")\n except (EOFError, KeyboardInterrupt):\n print()\n break\n print(run(prompt), flush=True)\n return\n\n prompt = args.prompt if args.prompt is not None else \"The\"\n for i in range(args.num_samples):\n torch.manual_seed(args.seed + i)\n print(f\"\\n----- sample {i + 1} -----\")\n print(prompt + run(prompt))", "source_file": "sample.py", "function_name": "main", "class_name": null, "line_start": 35, "line_end": 102, "license": "mit", "source": "SadikAI project"}
{"task": "code_completion", "language": "python", "instruction": "Complete the following Python code. Return only the continuation, preserving indentation.\n\n```python\ndef _clean_topic(text: str, cues: tuple[str, ...]) -> str:\n low = text.lower().strip()\n for cue in sorted(cues, key=len, reverse=True):\n if cue in low:\n low = low.split(cue, 1)[1]\n break\n```", "response": " low = low.strip(\" .,!?:;\\\"'“”‘’—-\")\n words = [word for word in re.split(r\"\\s+\", low) if word not in _STOPWORDS]\n return \" \".join(words).strip()", "source_file": "story_helper.py", "function_name": "_clean_topic", "class_name": null, "line_start": 318, "line_end": 326, "license": "mit", "source": "SadikAI project"}
{"task": "code_completion", "language": "python", "instruction": "Complete the following Python code. Return only the continuation, preserving indentation.\n\n```python\ndef _hit(haystack: str, keyword: str) -> bool:\n keyword = keyword.lower().strip()\n if not keyword:\n return False\n```", "response": " if \" \" in keyword or _has_devanagari(keyword):\n return keyword in haystack\n return re.search(rf\"\\b{re.escape(keyword)}\\b\", haystack) is not None", "source_file": "story_helper.py", "function_name": "_hit", "class_name": null, "line_start": 329, "line_end": 335, "license": "mit", "source": "SadikAI project"}
{"task": "code_completion", "language": "python", "instruction": "Complete the following Python code. Return only the continuation, preserving indentation.\n\n```python\ndef _best(items, topic: str, text: str):\n low = topic.lower()\n full = text.lower()\n best = None\n best_score = 0\n```", "response": " for item in items:\n score = sum(1 for keyword in item.keywords\n if _hit(low, keyword) or _hit(full, keyword))\n if score > best_score:\n best, best_score = item, score\n return best", "source_file": "story_helper.py", "function_name": "_best", "class_name": null, "line_start": 338, "line_end": 348, "license": "mit", "source": "SadikAI project"}
{"task": "code_completion", "language": "python", "instruction": "Complete the following Python code. Return only the continuation, preserving indentation.\n\n```python\ndef _safe_name(name: str | None, hind: bool) -> str:\n fallback = \"आरव\" if hind else \"Aarav\"\n if not name:\n return fallback\n```", "response": " cleaned = re.sub(r\"[{}\\r\\n\\t]\", \"\", str(name)).strip()\n cleaned = \" \".join(cleaned.split())[:40]\n return cleaned.title() if cleaned else fallback", "source_file": "story_helper.py", "function_name": "_safe_name", "class_name": null, "line_start": 351, "line_end": 357, "license": "mit", "source": "SadikAI project"}
{"task": "code_completion", "language": "python", "instruction": "Complete the following Python code. Return only the continuation, preserving indentation.\n\n```python\ndef answer_tale(text: str, name: str | None = None) -> str | None:\n \"\"\"Return a curated story/poem, or None if this is not a creative ask.\"\"\"\n low = text.lower()\n wants_poem = any(cue in low for cue in POEM_CUES)\n wants_story = any(cue in low for cue in STORY_CUES)\n if not wants_poem and not wants_story:\n return None\n\n hind = _has_devanagari(text)\n hindi_requested = hind or \"hindi\" in low\n topic = _clean_topic(text, POEM_CUES if wants_poem else STORY_CUES)\n who = _safe_name(name, hindi_requested)\n```", "response": " if wants_poem:\n poem = _best(POEMS, topic, text)\n if hindi_requested and (poem is None or not _has_devanagari(poem.body)):\n poem = next(item for item in POEMS if _has_devanagari(item.body))\n if poem is None:\n poem = POEMS[-1]\n return f\"**{poem.title}**\\n\\n{poem.body}\"\n\n if hindi_requested:\n return f\"**{HINDI_STORY.title}**\\n\\n{HINDI_STORY.body.format(name=who)}\"\n\n story = _best(STORIES, topic, text)\n if story is None:\n story = next(tale for tale in STORIES if not tale.keywords)\n return f\"**{story.title}**\\n\\n{story.body.format(name=who)}\"", "source_file": "story_helper.py", "function_name": "answer_tale", "class_name": null, "line_start": 360, "line_end": 387, "license": "mit", "source": "SadikAI project"}
{"task": "code_explanation", "language": "python", "instruction": "Explain what this Python function does.\n\n```python\ndef answer_tale(text: str, name: str | None = None) -> str | None:\n \"\"\"Return a curated story/poem, or None if this is not a creative ask.\"\"\"\n low = text.lower()\n wants_poem = any(cue in low for cue in POEM_CUES)\n wants_story = any(cue in low for cue in STORY_CUES)\n if not wants_poem and not wants_story:\n return None\n\n hind = _has_devanagari(text)\n hindi_requested = hind or \"hindi\" in low\n topic = _clean_topic(text, POEM_CUES if wants_poem else STORY_CUES)\n who = _safe_name(name, hindi_requested)\n\n if wants_poem:\n poem = _best(POEMS, topic, text)\n if hindi_requested and (poem is None or not _has_devanagari(poem.body)):\n poem = next(item for item in POEMS if _has_devanagari(item.body))\n if poem is None:\n poem = POEMS[-1]\n return f\"**{poem.title}**\\n\\n{poem.body}\"\n\n if hindi_requested:\n return f\"**{HINDI_STORY.title}**\\n\\n{HINDI_STORY.body.format(name=who)}\"\n\n story = _best(STORIES, topic, text)\n if story is None:\n story = next(tale for tale in STORIES if not tale.keywords)\n return f\"**{story.title}**\\n\\n{story.body.format(name=who)}\"\n```", "response": "Return a curated story/poem, or None if this is not a creative ask.", "source_file": "story_helper.py", "function_name": "answer_tale", "class_name": null, "line_start": 360, "line_end": 387, "license": "mit", "source": "SadikAI project"}
{"task": "code_generation", "language": "python", "instruction": "Write a Python function `answer_tale(text: str, name: str | None=None)` that does the following:\n\nReturn a curated story/poem, or None if this is not a creative ask.\n\nReturn only the Python code.", "response": "def answer_tale(text: str, name: str | None = None) -> str | None:\n \"\"\"Return a curated story/poem, or None if this is not a creative ask.\"\"\"\n low = text.lower()\n wants_poem = any(cue in low for cue in POEM_CUES)\n wants_story = any(cue in low for cue in STORY_CUES)\n if not wants_poem and not wants_story:\n return None\n\n hind = _has_devanagari(text)\n hindi_requested = hind or \"hindi\" in low\n topic = _clean_topic(text, POEM_CUES if wants_poem else STORY_CUES)\n who = _safe_name(name, hindi_requested)\n\n if wants_poem:\n poem = _best(POEMS, topic, text)\n if hindi_requested and (poem is None or not _has_devanagari(poem.body)):\n poem = next(item for item in POEMS if _has_devanagari(item.body))\n if poem is None:\n poem = POEMS[-1]\n return f\"**{poem.title}**\\n\\n{poem.body}\"\n\n if hindi_requested:\n return f\"**{HINDI_STORY.title}**\\n\\n{HINDI_STORY.body.format(name=who)}\"\n\n story = _best(STORIES, topic, text)\n if story is None:\n story = next(tale for tale in STORIES if not tale.keywords)\n return f\"**{story.title}**\\n\\n{story.body.format(name=who)}\"", "source_file": "story_helper.py", "function_name": "answer_tale", "class_name": null, "line_start": 360, "line_end": 387, "license": "mit", "source": "SadikAI project"}
{"task": "code_completion", "language": "python", "instruction": "Complete the following Python code. Return only the continuation, preserving indentation.\n\n```python\ndef test_emotion() -> None:\n cases = [\n (\"I am so happy today, great news!\", \"joy\"),\n (\"bahut khush hoon aaj mazaa aaya\", \"joy\"),\n (\"mera din bahut bura tha, thak gaya hoon\", \"sadness\"),\n (\"gussa aa raha hai, bakwas service\", \"anger\"),\n (\"mujhe tension ho rahi hai\", \"fear\"),\n (\"I love you yaar\", \"love\"),\n (\"thank you so much\", \"gratitude\"),\n ]\n```", "response": " for text, expected in cases:\n got = detect(text)\n check(f\"emotion {expected!r} <- {text[:28]!r}\", got.label == expected,\n f\"got {got.label} (v={got.valence:+.2f})\")\n\n check(\"negation flips positive\", detect(\"I am not happy with this\").valence < 0)\n check(\"greeting detected\", is_greeting(\"hello\") and is_greeting(\"kaise ho bhai\"))\n check(\"plain text is neutral\", detect(\"the table is made of wood\").label == \"neutral\")\n\n mood = Mood()\n mood.update(detect(\"I am so happy today\"))\n check(\"mood follows emotion\", mood.valence > 0 and mood.label() in {\"happy\", \"warm\"})", "source_file": "test_chat.py", "function_name": "test_emotion", "class_name": null, "line_start": 28, "line_end": 49, "license": "mit", "source": "SadikAI project"}
{"task": "code_completion", "language": "python", "instruction": "Complete the following Python code. Return only the continuation, preserving indentation.\n\n```python\ndef test_memory() -> None:\n facts = dict(extract_facts(\"my name is Sadik Nawaz\"))\n check(\"fact: name\", facts.get(\"name\", \"\").lower().startswith(\"sadik\"), str(facts))\n\n facts = dict(extract_facts(\"mera naam Sadik hai\"))\n check(\"fact: hinglish name\", facts.get(\"name\", \"\").lower() == \"sadik\", str(facts))\n\n facts = dict(extract_facts(\"I am 22 years old\"))\n check(\"fact: age\", facts.get(\"age\") == \"22\", str(facts))\n\n facts = dict(extract_facts(\"mujhe biryani pasand hai\"))\n check(\"fact: likes\", facts.get(\"likes\", \"\") == \"biryani\", str(facts))\n\n check(\"no false fact from mood\",\n not extract_facts(\"main khush hoon aaj\"), str(extract_facts(\"main khush hoon aaj\")))\n```", "response": " with tempfile.TemporaryDirectory() as tmp:\n path = Path(tmp) / \"mem.json\"\n mem = MemoryStore(path)\n mem.remember_turn(\"my name is Sadik\", emotion=\"neutral\")\n mem.remember_turn(\"mujhe biryani pasand hai\", emotion=\"joy\")\n mem.remember_turn(\"aaj bahut bura din tha\", emotion=\"sadness\")\n mem.save()\n\n reloaded = MemoryStore(path)\n check(\"memory persists\", reloaded.profile().get(\"name\") == \"Sadik\",\n str(reloaded.profile()))\n\n hits = reloaded.recall(\"what is my name\", k=2)\n check(\"recall finds name fact\", bool(hits) and \"Sadik\" in hits[0][0].text,\n str([h[0].text for h in hits]))\n\n hits = reloaded.recall(\"biryani\", k=2)\n check(\"recall finds likes\", bool(hits) and \"biryani\" in hits[0][0].text)\n\n check(\"dedupe identical turn\",\n (reloaded.remember_turn(\"my name is Sadik\"),\n sum(1 for e in reloaded.entries if e.text == \"my name is Sadik\"))[1] == 1)", "source_file": "test_chat.py", "function_name": "test_memory", "class_name": null, "line_start": 52, "line_end": 89, "license": "mit", "source": "SadikAI project"}
{"task": "code_completion", "language": "python", "instruction": "Complete the following Python code. Return only the continuation, preserving indentation.\n\n```python\ndef test_calculator() -> None:\n check(\"calc multiply\", solve_math(\"what is 12 x 13\") == \"12 × 13 = 156\")\n check(\"calc divide\", solve_math(\"100 / 8\") == \"100 ÷ 8 = 12.5\")\n```", "response": " check(\"calc percent\", solve_math(\"15% of 200\") == \"15% of 200 = 30\")\n check(\"calc sqrt\", solve_math(\"square root of 144\") == \"sqrt(144) = 12\")\n check(\"calc no false positive\", solve_math(\"I have 2 cats\") is None)\n check(\"calc skips dates\", solve_math(\"today is 2026-11-04\") is None)", "source_file": "test_chat.py", "function_name": "test_calculator", "class_name": null, "line_start": 92, "line_end": 98, "license": "mit", "source": "SadikAI project"}
{"task": "code_completion", "language": "python", "instruction": "Complete the following Python code. Return only the continuation, preserving indentation.\n\n```python\ndef test_routing() -> None:\n check(\"question needs search\", needs_search(\"who is Virat Kohli?\"))\n check(\"hindi question needs search\", needs_search(\"भारत की राजधानी क्या है\"))\n```", "response": " check(\"statement does not\", not needs_search(\"I had a long day\"))\n check(\"emotional text does not\", not needs_search(\"I feel very sad today\"))", "source_file": "test_chat.py", "function_name": "test_routing", "class_name": null, "line_start": 101, "line_end": 105, "license": "mit", "source": "SadikAI project"}
{"task": "code_completion", "language": "python", "instruction": "Complete the following Python code. Return only the continuation, preserving indentation.\n\n```python\ndef test_web() -> None:\n results = search(\"who is Virat Kohli\", limit=3)\n check(\"web returns results\", bool(results), f\"{len(results)} results\")\n```", "response": " if results:\n check(\"web result has snippet\", bool(results[0].snippet))\n print(f\" top: {results[0].title} [{results[0].source}] \"\n f\"{results[0].snippet[:90]}…\")", "source_file": "test_chat.py", "function_name": "test_web", "class_name": null, "line_start": 108, "line_end": 114, "license": "mit", "source": "SadikAI project"}
{"task": "code_completion", "language": "python", "instruction": "Complete the following Python code. Return only the continuation, preserving indentation.\n\n```python\ndef test_javascript_snippets() -> None:\n if not shutil.which(\"node\"):\n print(\" node missing, skipping JavaScript execution\")\n return\n checked = 0\n```", "response": " for snippet in SNIPPETS:\n if snippet[\"language\"] != \"javascript\" or not snippet[\"verify\"]:\n continue\n proc = subprocess.run([\"node\", \"-e\", snippet[\"code\"] + \"\\n\" + snippet[\"verify\"]],\n capture_output=True, text=True, timeout=20)\n check(f\"js runs: {snippet['id']}\", proc.returncode == 0,\n (proc.stderr or \"\").strip().splitlines()[-1] if proc.stderr else \"\")\n checked += 1\n check(\"javascript snippets execute\", checked >= 3, f\"{checked} with assertions\")", "source_file": "test_code.py", "function_name": "test_javascript_snippets", "class_name": null, "line_start": 53, "line_end": 66, "license": "mit", "source": "SadikAI project"}
{"task": "code_completion", "language": "python", "instruction": "Complete the following Python code. Return only the continuation, preserving indentation.\n\n```python\ndef test_matching() -> None:\n cases = [\n (\"code for fibonacci in python\", \"Fibonacci\"),\n (\"javascript debounce\", \"Debounce\"),\n (\"sql join two tables\", \"JOIN\"),\n (\"write c++ hello world\", \"Hello\"),\n (\"python bank account class\", \"BankAccount\"),\n (\"how to reverse a string\", \"Reverse\"),\n (\"explain bubble sort\", \"Bubble\"),\n (\"powershell find text in files\", \"Search text\"),\n (\"javascript array sum\", \"Sum an array\"),\n (\"write a regex for email\", \"emails\"),\n ]\n```", "response": " for question, expected in cases:\n out = answer_code(question) or \"\"\n check(f\"match {question!r}\", expected.lower() in out.lower(),\n out.splitlines()[0] if out else \"no match\")\n\n false_cases = [\n \"who is the prime minister?\",\n \"what is the capital of India?\",\n \"hello\",\n \"tell me a story about a dog\",\n \"I feel very sad today\",\n \"who is Ada Lovelace?\",\n ]\n for question in false_cases:\n check(f\"no false match {question!r}\", answer_code(question) is None)", "source_file": "test_code.py", "function_name": "test_matching", "class_name": null, "line_start": 69, "line_end": 96, "license": "mit", "source": "SadikAI project"}
{"task": "code_completion", "language": "python", "instruction": "Complete the following Python code. Return only the continuation, preserving indentation.\n\n```python\ndef test_runner() -> None:\n result = run_code(\"print(6 * 7)\")\n check(\"runner python\", result[\"ok\"] and \"42\" in result[\"output\"], result[\"output\"])\n check(\"runner formats\", \"42\" in format_result(result))\n\n bad = run_code(\"raise SystemExit(3)\")\n check(\"runner reports failure\", not bad[\"ok\"])\n\n slow = run_code(\"while True:\\n pass\", timeout=1.0)\n check(\"runner timeout\", not slow[\"ok\"] and \"Stopped\" in slow[\"output\"])\n\n language, code = extract_code(\"```python\\nprint('hi')\\n```\")\n check(\"extract fenced\", language == \"python\" and code == \"print('hi')\")\n language, code = extract_code(\"/run print('x')\")\n check(\"extract /run\", code == \"print('x')\")\n```", "response": " sql = (\"CREATE TABLE people (name TEXT, age INT);\\n\"\n \"INSERT INTO people VALUES ('Sadik', 22), ('Ada', 36);\\n\"\n \"SELECT name, age FROM people ORDER BY age;\")\n result = run_code(sql, \"sql\")\n check(\"runner sql\", result[\"ok\"] and \"Sadik\" in result[\"output\"]\n and \"Ada\" in result[\"output\"], result[\"output\"].replace(\"\\n\", \" / \"))\n\n bad_sql = run_code(\"SELECT * FROM missing_table;\", \"sql\")\n check(\"runner sql reports errors\", not bad_sql[\"ok\"] and \"SQL error\" in bad_sql[\"output\"])\n\n language, code = extract_code(\"```sql\\nSELECT 1;\\n```\")\n check(\"extract fenced sql\", language == \"sql\" and code == \"SELECT 1;\")\n\n if shutil.which(\"node\"):\n js = run_code(\"console.log(2 + 2)\", \"javascript\")\n check(\"runner javascript\", js[\"ok\"] and \"4\" in js[\"output\"])", "source_file": "test_code.py", "function_name": "test_runner", "class_name": null, "line_start": 99, "line_end": 130, "license": "mit", "source": "SadikAI project"}
{"task": "code_completion", "language": "python", "instruction": "Complete the following Python code. Return only the continuation, preserving indentation.\n\n```python\ndef test_snippet_text() -> None:\n check(\"snippets unique ids\", len({s[\"id\"] for s in SNIPPETS}) == len(SNIPPETS))\n check(\"all have explanations\",\n all(len(s[\"explain\"]) > 20 for s in SNIPPETS))\n```", "response": " empty = [s[\"id\"] for s in SNIPPETS if not s[\"code\"].strip()]\n check(\"all have code\", not empty, \", \".join(empty))\n languages = sorted({s[\"language\"] for s in SNIPPETS})\n print(f\" {len(SNIPPETS)} snippets across: {', '.join(languages)}\")", "source_file": "test_code.py", "function_name": "test_snippet_text", "class_name": null, "line_start": 133, "line_end": 140, "license": "mit", "source": "SadikAI project"}
{"task": "code_completion", "language": "python", "instruction": "Complete the following Python code. Return only the continuation, preserving indentation.\n\n```python\ndef test_parsing() -> None:\n image = media.parse_media_request(\"draw a red fox in the snow\")\n check(\"parse draw\", image and image[\"kind\"] == \"image\"\n and \"red fox\" in image[\"prompt\"], str(image))\n\n image = media.parse_media_request(\"generate an image of a robot in 512x512\")\n check(\"parse image size\", image and image[\"width\"] == 512\n and \"512\" not in image[\"prompt\"], str(image))\n\n spoken = media.parse_media_request(\"say hello, this is my voice\")\n check(\"parse speech\", spoken and spoken[\"kind\"] == \"audio\"\n and spoken[\"text\"].startswith(\"hello\"), str(spoken))\n\n file_request = media.parse_media_request(\"make a csv of the 7 times table\")\n```", "response": " check(\"parse table file\", file_request and file_request[\"kind\"] == \"file\"\n and file_request[\"rows\"] and file_request[\"rows\"][-1][1] == 70,\n str(file_request))\n\n file_request = media.parse_media_request(\"create a pdf about black holes\")\n check(\"parse topic pdf\", file_request and file_request[\"topic\"] == \"black holes\",\n str(file_request))\n\n file_request = media.parse_media_request(\"write a file notes.txt | hello world\")\n check(\"parse explicit file\", file_request and file_request[\"name\"] == \"notes.txt\"\n and file_request[\"content\"] == \"hello world\", str(file_request))\n\n for question in (\"what is an image?\", \"write a story about a dog\",\n \"who is Ada Lovelace?\", \"tell me about audio\"):\n check(f\"no false media match {question!r}\",\n media.parse_media_request(question) is None)", "source_file": "test_media.py", "function_name": "test_parsing", "class_name": null, "line_start": 24, "line_end": 53, "license": "mit", "source": "SadikAI project"}
{"task": "code_completion", "language": "python", "instruction": "Complete the following Python code. Return only the continuation, preserving indentation.\n\n```python\ndef test_tables() -> None:\n rows, title = media.build_table(\"make an excel file of squares from 1 to 20\")\n check(\"squares table\", len(rows) == 21 and rows[-1] == [20, 400], title)\n```", "response": " rows, title = media.build_table(\"csv of prime numbers up to 50\")\n check(\"primes table\", len(rows) == 16 and rows[1][1] == 2 and rows[-1][1] == 47,\n title)\n\n rows, title = media.build_table(\"numbers 5 to 9\")\n check(\"number range\", len(rows) == 6 and rows[0] == [\"n\", \"n squared\"], title)", "source_file": "test_media.py", "function_name": "test_tables", "class_name": null, "line_start": 56, "line_end": 65, "license": "mit", "source": "SadikAI project"}
{"task": "code_completion", "language": "python", "instruction": "Complete the following Python code. Return only the continuation, preserving indentation.\n\n```python\ndef test_image() -> None:\n artifact = media.generate_image(\"a red fox in the snow\", width=640, height=480,\n allow_network=False)\n```", "response": " check(\"local image exists\", artifact.path.exists() and artifact.path.stat().st_size > 5000)\n with media.Image.open(artifact.path) as image:\n check(\"local image size\", image.size == (640, 480), str(image.size))\n check(\"local image png\", image.format == \"PNG\", str(image.format))", "source_file": "test_media.py", "function_name": "test_image", "class_name": null, "line_start": 68, "line_end": 74, "license": "mit", "source": "SadikAI project"}
{"task": "code_completion", "language": "python", "instruction": "Complete the following Python code. Return only the continuation, preserving indentation.\n\n```python\ndef test_speech() -> None:\n artifact = media.generate_speech(\"Hello Sadik. This is a local audio test.\")\n data = artifact.path.read_bytes()[:12]\n```", "response": " check(\"speech wav\", data[:4] == b\"RIFF\" and data[8:12] == b\"WAVE\", str(data))\n check(\"speech has audio\", artifact.path.stat().st_size > 20_000,\n f\"{artifact.path.stat().st_size} bytes\")", "source_file": "test_media.py", "function_name": "test_speech", "class_name": null, "line_start": 77, "line_end": 82, "license": "mit", "source": "SadikAI project"}
{"task": "code_completion", "language": "python", "instruction": "Complete the following Python code. Return only the continuation, preserving indentation.\n\n```python\ndef test_files() -> None:\n text = \"नमस्ते Sadik\\nThis file was generated locally.\\n\\n- first item\\n- second item\"\n\n artifact = media.generate_file(\"notes.txt\", text)\n check(\"txt file\", artifact.path.read_text(encoding=\"utf-8\") == text, artifact.name)\n\n artifact = media.generate_file(\"notes.md\", \"# Title\\n\\nSome **markdown**.\")\n check(\"md file\", \"# Title\" in artifact.path.read_text(encoding=\"utf-8\"))\n\n rows = [[\"n\", \"n squared\"], [1, 1], [2, 4], [3, 9]]\n artifact = media.generate_file(\"squares.csv\", rows=rows)\n body = artifact.path.read_text(encoding=\"utf-8-sig\")\n check(\"csv file\", \"n squared\" in body and \"3,9\" in body, artifact.name)\n\n artifact = media.generate_file(\"data.json\", '{\"name\": \"Sadik\", \"score\": 42}')\n check(\"json file\", '\"Sadik\"' in artifact.path.read_text(encoding=\"utf-8\"))\n\n artifact = media.generate_file(\"page.html\", \"# Hello\\n\\nThis is a page.\")\n html = artifact.path.read_text(encoding=\"utf-8\")\n check(\"html file\", \"<!DOCTYPE html>\" in html and \"<br>\" in html)\n\n artifact = media.generate_file(\"drawing.svg\", \"hello\\nworld\")\n check(\"svg file\", artifact.path.read_text(encoding=\"utf-8\").startswith(\"<svg\"))\n```", "response": " artifact = media.generate_file(\"report.pdf\", text)\n check(\"pdf magic\", artifact.path.read_bytes()[:5] == b\"%PDF-\", artifact.name)\n check(\"pdf has size\", artifact.path.stat().st_size > 1000,\n f\"{artifact.path.stat().st_size} bytes\")\n\n artifact = media.generate_file(\"letter.docx\", text)\n check(\"docx magic\", artifact.path.read_bytes()[:2] == b\"PK\", artifact.name)\n from docx import Document\n document = Document(str(artifact.path))\n check(\"docx readable\", any(\"Sadik\" in p.text for p in document.paragraphs))\n\n artifact = media.generate_file(\"squares.xlsx\", rows=rows)\n from openpyxl import load_workbook\n workbook = load_workbook(str(artifact.path))\n sheet = workbook.active\n check(\"xlsx readable\", sheet[\"A1\"].value == \"n\" and sheet[\"B4\"].value == 9)\n\n artifact = media.generate_file(\"resume.docx\", template=\"resume\", profile_name=\"Sadik\")\n document = Document(str(artifact.path))\n check(\"resume template\", any(\"Sadik\" in p.text for p in document.paragraphs))\n\n artifact = media.generate_file(\"invoice.xlsx\", template=\"invoice\")\n workbook = load_workbook(str(artifact.path))\n sheet = workbook.active\n check(\"invoice template\", sheet[\"A1\"].value == \"Item\" and sheet[\"D6\"].value.startswith(\"=SUM\"))", "source_file": "test_media.py", "function_name": "test_files", "class_name": null, "line_start": 85, "line_end": 133, "license": "mit", "source": "SadikAI project"}
{"task": "code_completion", "language": "python", "instruction": "Complete the following Python code. Return only the continuation, preserving indentation.\n\n```python\ndef test_artifacts() -> None:\n artifact = media.generate_file(\"link.txt\", \"hello\")\n payload = artifact.to_dict()\n```", "response": " check(\"artifact url\", payload[\"url\"] == \"/files/files/link.txt\", payload[\"url\"])\n check(\"artifact size\", payload[\"size\"] > 0, str(payload[\"size\"]))\n check(\"artifact path\", Path(payload[\"path\"]).exists())", "source_file": "test_media.py", "function_name": "test_artifacts", "class_name": null, "line_start": 136, "line_end": 141, "license": "mit", "source": "SadikAI project"}
{"task": "code_completion", "language": "python", "instruction": "Complete the following Python code. Return only the continuation, preserving indentation.\n\n```python\ndef test_causal_mask() -> None:\n \"\"\"Changing a future token must not change earlier logits.\"\"\"\n torch.manual_seed(0)\n model = tiny().eval()\n x = torch.randint(0, 128, (1, 12))\n```", "response": " with torch.no_grad():\n a, _, _ = model(x)\n x2 = x.clone()\n x2[0, -1] = (x2[0, -1] + 1) % 128\n b, _, _ = model(x2)\n diff = (a[0, :-1] - b[0, :-1]).abs().max().item()\n assert diff < 1e-6, f\"information leaked backwards: {diff}\"\n print(\"causal mask ok\")", "source_file": "test_model.py", "function_name": "test_causal_mask", "class_name": null, "line_start": 26, "line_end": 38, "license": "mit", "source": "SadikAI project"}
{"task": "code_explanation", "language": "python", "instruction": "Explain what this Python function does.\n\n```python\ndef test_causal_mask() -> None:\n \"\"\"Changing a future token must not change earlier logits.\"\"\"\n torch.manual_seed(0)\n model = tiny().eval()\n x = torch.randint(0, 128, (1, 12))\n with torch.no_grad():\n a, _, _ = model(x)\n x2 = x.clone()\n x2[0, -1] = (x2[0, -1] + 1) % 128\n b, _, _ = model(x2)\n diff = (a[0, :-1] - b[0, :-1]).abs().max().item()\n assert diff < 1e-6, f\"information leaked backwards: {diff}\"\n print(\"causal mask ok\")\n```", "response": "Changing a future token must not change earlier logits.", "source_file": "test_model.py", "function_name": "test_causal_mask", "class_name": null, "line_start": 26, "line_end": 38, "license": "mit", "source": "SadikAI project"}
{"task": "code_generation", "language": "python", "instruction": "Write a Python function `test_causal_mask()` that does the following:\n\nChanging a future token must not change earlier logits.\n\nReturn only the Python code.", "response": "def test_causal_mask() -> None:\n \"\"\"Changing a future token must not change earlier logits.\"\"\"\n torch.manual_seed(0)\n model = tiny().eval()\n x = torch.randint(0, 128, (1, 12))\n with torch.no_grad():\n a, _, _ = model(x)\n x2 = x.clone()\n x2[0, -1] = (x2[0, -1] + 1) % 128\n b, _, _ = model(x2)\n diff = (a[0, :-1] - b[0, :-1]).abs().max().item()\n assert diff < 1e-6, f\"information leaked backwards: {diff}\"\n print(\"causal mask ok\")", "source_file": "test_model.py", "function_name": "test_causal_mask", "class_name": null, "line_start": 26, "line_end": 38, "license": "mit", "source": "SadikAI project"}
{"task": "code_completion", "language": "python", "instruction": "Complete the following Python code. Return only the continuation, preserving indentation.\n\n```python\ndef test_kv_cache_matches_full_forward() -> None:\n torch.manual_seed(0)\n model = tiny().eval()\n x = torch.randint(0, 128, (2, 20))\n```", "response": " with torch.no_grad():\n full, _, _ = model(x)\n\n past, outs, pos = None, [], 0\n for t in range(x.shape[1]):\n logits, _, past = model(\n x[:, t : t + 1], past_kvs=past, use_cache=True, pos=pos\n )\n pos += 1\n outs.append(logits)\n tokenwise = torch.cat(outs, dim=1)\n\n logits, _, past = model(x[:, :8], use_cache=True, pos=0)\n outs = [logits]\n for t in range(8, x.shape[1]):\n logits, _, past = model(\n x[:, t : t + 1], past_kvs=past, use_cache=True, pos=t\n )\n outs.append(logits)\n prefill = torch.cat(outs, dim=1)\n\n d1 = (full - tokenwise).abs().max().item()\n d2 = (full - prefill).abs().max().item()\n assert d1 < 1e-5, f\"token-wise cache mismatch {d1}\"\n assert d2 < 1e-5, f\"prefill cache mismatch {d2}\"\n print(f\"kv cache ok (max diff {max(d1, d2):.2e})\")", "source_file": "test_model.py", "function_name": "test_kv_cache_matches_full_forward", "class_name": null, "line_start": 41, "line_end": 71, "license": "mit", "source": "SadikAI project"}
{"task": "code_completion", "language": "python", "instruction": "Complete the following Python code. Return only the continuation, preserving indentation.\n\n```python\ndef test_long_generation() -> None:\n \"\"\"Generation must survive sliding past the context window.\"\"\"\n torch.manual_seed(0)\n model = tiny(block_size=16).eval()\n```", "response": " out = model.generate(\n torch.randint(0, 128, (2, 4)),\n max_new_tokens=40,\n top_k=0,\n top_p=1.0,\n temperature=1.0,\n )\n assert out.shape == (2, 44), out.shape\n print(\"sliding-window generation ok\")", "source_file": "test_model.py", "function_name": "test_long_generation", "class_name": null, "line_start": 74, "line_end": 86, "license": "mit", "source": "SadikAI project"}
{"task": "code_explanation", "language": "python", "instruction": "Explain what this Python function does.\n\n```python\ndef test_long_generation() -> None:\n \"\"\"Generation must survive sliding past the context window.\"\"\"\n torch.manual_seed(0)\n model = tiny(block_size=16).eval()\n out = model.generate(\n torch.randint(0, 128, (2, 4)),\n max_new_tokens=40,\n top_k=0,\n top_p=1.0,\n temperature=1.0,\n )\n assert out.shape == (2, 44), out.shape\n print(\"sliding-window generation ok\")\n```", "response": "Generation must survive sliding past the context window.", "source_file": "test_model.py", "function_name": "test_long_generation", "class_name": null, "line_start": 74, "line_end": 86, "license": "mit", "source": "SadikAI project"}
{"task": "code_generation", "language": "python", "instruction": "Write a Python function `test_long_generation()` that does the following:\n\nGeneration must survive sliding past the context window.\n\nReturn only the Python code.", "response": "def test_long_generation() -> None:\n \"\"\"Generation must survive sliding past the context window.\"\"\"\n torch.manual_seed(0)\n model = tiny(block_size=16).eval()\n out = model.generate(\n torch.randint(0, 128, (2, 4)),\n max_new_tokens=40,\n top_k=0,\n top_p=1.0,\n temperature=1.0,\n )\n assert out.shape == (2, 44), out.shape\n print(\"sliding-window generation ok\")", "source_file": "test_model.py", "function_name": "test_long_generation", "class_name": null, "line_start": 74, "line_end": 86, "license": "mit", "source": "SadikAI project"}
{"task": "code_completion", "language": "python", "instruction": "Complete the following Python code. Return only the continuation, preserving indentation.\n\n```python\ndef test_chunked_loss_and_checkpointing() -> None:\n torch.manual_seed(0)\n model = tiny(n_layer=2, block_size=16, grad_ckpt=True).train()\n x = torch.randint(0, 128, (2, 16))\n```", "response": " _, loss_a, _ = model(x, x, loss_chunk=0)\n _, loss_b, _ = model(x, x, loss_chunk=5)\n assert abs(loss_a.item() - loss_b.item()) < 1e-4, (loss_a, loss_b)\n loss_b.backward()\n assert model.tok_emb.weight.grad is not None\n print(\"chunked CE + grad checkpointing ok\")", "source_file": "test_model.py", "function_name": "test_chunked_loss_and_checkpointing", "class_name": null, "line_start": 89, "line_end": 98, "license": "mit", "source": "SadikAI project"}
{"task": "code_completion", "language": "python", "instruction": "Complete the following Python code. Return only the continuation, preserving indentation.\n\n```python\ndef test_param_estimate() -> None:\n cfg = ModelConfig(\n vocab_size=1024, n_layer=2, n_head=4, n_kv_head=2, n_embd=64, block_size=32\n )\n```", "response": " exact = GPT(cfg).num_params()\n est = estimate_params(cfg)[\"total\"]\n assert abs(exact - est) / exact < 0.02, (exact, est)\n print(f\"param estimate ok ({exact:,} exact vs {est:,} estimated)\")", "source_file": "test_model.py", "function_name": "test_param_estimate", "class_name": null, "line_start": 101, "line_end": 108, "license": "mit", "source": "SadikAI project"}
{"task": "code_completion", "language": "python", "instruction": "Complete the following Python code. Return only the continuation, preserving indentation.\n\n```python\n def __init__(self, path: str | Path) -> None:\n path = Path(path)\n if path.is_dir():\n path = path / \"tokenizer.json\"\n if not path.exists():\n raise FileNotFoundError(\n f\"tokenizer not found at {path!s}. Run train_tokenizer.py first.\"\n )\n self.path = path\n self._tok = HFTokenizer.from_file(str(path))\n\n # No truncation / padding here: the training data pipeline handles length.\n```", "response": " self._tok.no_truncation()\n self._tok.no_padding()\n\n self.eos_token = EOS_TOKEN\n self.pad_token = PAD_TOKEN\n self.eos_id = self._tok.token_to_id(EOS_TOKEN)\n if self.eos_id is None:\n raise ValueError(f\"tokenizer is missing the special token {EOS_TOKEN}\")\n self.pad_id = self._tok.token_to_id(PAD_TOKEN)\n\n self.vocab_size = self._tok.get_vocab_size()", "source_file": "tokenizer_utils.py", "function_name": "__init__", "class_name": "Tokenizer", "line_start": 24, "line_end": 46, "license": "mit", "source": "SadikAI project"}
{"task": "code_completion", "language": "python", "instruction": "Complete the following Python code. Return only the continuation, preserving indentation.\n\n```python\ndef load_config(path: str | Path) -> dict:\n cfg = json.loads(Path(path).read_text(encoding=\"utf-8\"))\n cfg.setdefault(\"name\", Path(path).stem)\n```", "response": " cfg.setdefault(\"model\", {})\n train = dict(TRAIN_DEFAULTS)\n train.update(cfg.get(\"train\", {}))\n cfg[\"train\"] = train\n return cfg", "source_file": "train.py", "function_name": "load_config", "class_name": null, "line_start": 55, "line_end": 62, "license": "mit", "source": "SadikAI project"}
{"task": "code_completion", "language": "python", "instruction": "Complete the following Python code. Return only the continuation, preserving indentation.\n\n```python\ndef setup_distributed() -> tuple[int, int, int, bool, str]:\n world_size = int(os.environ.get(\"WORLD_SIZE\", \"1\"))\n rank = int(os.environ.get(\"RANK\", \"0\"))\n local_rank = int(os.environ.get(\"LOCAL_RANK\", \"0\"))\n distributed = world_size > 1\n backend = \"\"\n```", "response": " if distributed:\n if torch.cuda.is_available():\n backend = \"nccl\"\n torch.cuda.set_device(local_rank)\n else:\n backend = \"gloo\"\n dist.init_process_group(backend=backend)\n return rank, local_rank, world_size, distributed, backend", "source_file": "train.py", "function_name": "setup_distributed", "class_name": null, "line_start": 65, "line_end": 78, "license": "mit", "source": "SadikAI project"}
{"task": "code_completion", "language": "python", "instruction": "Complete the following Python code. Return only the continuation, preserving indentation.\n\n```python\ndef pick_device(requested: str, local_rank: int, distributed: bool) -> torch.device:\n if requested == \"auto\":\n if torch.cuda.is_available():\n return torch.device(\"cuda\", local_rank if distributed else 0)\n if getattr(torch.backends, \"mps\", None) and torch.backends.mps.is_available():\n return torch.device(\"mps\")\n return torch.device(\"cpu\")\n```", "response": " device = torch.device(requested)\n if distributed and device.type == \"cuda\":\n device = torch.device(\"cuda\", local_rank)\n return device", "source_file": "train.py", "function_name": "pick_device", "class_name": null, "line_start": 81, "line_end": 91, "license": "mit", "source": "SadikAI project"}
{"task": "code_completion", "language": "python", "instruction": "Complete the following Python code. Return only the continuation, preserving indentation.\n\n```python\ndef resolve_dtype(requested: str, device: torch.device) -> str:\n if requested != \"auto\":\n return requested\n```", "response": " if device.type == \"cuda\":\n return \"bf16\" if torch.cuda.is_bf16_supported() else \"fp16\"\n if device.type == \"mps\":\n return \"fp16\"\n return \"fp32\"", "source_file": "train.py", "function_name": "resolve_dtype", "class_name": null, "line_start": 94, "line_end": 101, "license": "mit", "source": "SadikAI project"}
{"task": "code_completion", "language": "python", "instruction": "Complete the following Python code. Return only the continuation, preserving indentation.\n\n```python\ndef autocast_ctx(dtype: str, device_type: str):\n if dtype == \"bf16\":\n return torch.autocast(device_type=device_type, dtype=torch.bfloat16)\n```", "response": " if dtype == \"fp16\":\n return torch.autocast(device_type=device_type, dtype=torch.float16)\n return contextlib.nullcontext()", "source_file": "train.py", "function_name": "autocast_ctx", "class_name": null, "line_start": 104, "line_end": 109, "license": "mit", "source": "SadikAI project"}
{"task": "code_completion", "language": "python", "instruction": "Complete the following Python code. Return only the continuation, preserving indentation.\n\n```python\n def __init__(self, path: str | Path, dtype: str) -> None:\n self.path = Path(path)\n self.data = np.memmap(self.path, dtype=np.dtype(dtype), mode=\"r\")\n```", "response": " if self.data.size == 0:\n raise SystemExit(f\"{self.path} is empty - run prepare_data.py first\")", "source_file": "train.py", "function_name": "__init__", "class_name": "TokenData", "line_start": 126, "line_end": 130, "license": "mit", "source": "SadikAI project"}
{"task": "code_completion", "language": "python", "instruction": "Complete the following Python code. Return only the continuation, preserving indentation.\n\n```python\n def get_batch(\n self, batch_size: int, block_size: int, device: torch.device\n ) -> tuple[torch.Tensor, torch.Tensor]:\n if len(self) < block_size + 2:\n raise SystemExit(\n f\"{self.path} has only {len(self)} tokens, need > {block_size + 2}\"\n )\n```", "response": " ix = np.random.randint(0, len(self) - block_size - 1, size=batch_size)\n x = np.stack([self.data[i : i + block_size] for i in ix]).astype(np.int64)\n y = np.stack([self.data[i + 1 : i + 1 + block_size] for i in ix]).astype(np.int64)\n return (\n torch.from_numpy(x).to(device, non_blocking=True),\n torch.from_numpy(y).to(device, non_blocking=True),\n )", "source_file": "train.py", "function_name": "get_batch", "class_name": "TokenData", "line_start": 135, "line_end": 148, "license": "mit", "source": "SadikAI project"}
{"task": "code_completion", "language": "python", "instruction": "Complete the following Python code. Return only the continuation, preserving indentation.\n\n```python\ndef lr_at(step: int, base_lr: float, warmup: int, max_steps: int, min_ratio: float) -> float:\n if warmup > 0 and step < warmup:\n return base_lr * (step + 1) / warmup\n```", "response": " if step >= max_steps:\n return base_lr * min_ratio\n span = max(max_steps - warmup, 1)\n t = (step - warmup) / span\n coeff = 0.5 * (1.0 + math.cos(math.pi * t))\n return base_lr * (min_ratio + (1.0 - min_ratio) * coeff)", "source_file": "train.py", "function_name": "lr_at", "class_name": null, "line_start": 154, "line_end": 162, "license": "mit", "source": "SadikAI project"}
{"task": "code_completion", "language": "python", "instruction": "Complete the following Python code. Return only the continuation, preserving indentation.\n\n```python\ndef fmt_time(seconds: float) -> str:\n seconds = int(max(seconds, 0))\n h, rem = divmod(seconds, 3600)\n```", "response": " m, s = divmod(rem, 60)\n return f\"{h}h{m:02d}m\" if h else f\"{m}m{s:02d}s\"", "source_file": "train.py", "function_name": "fmt_time", "class_name": null, "line_start": 165, "line_end": 169, "license": "mit", "source": "SadikAI project"}
{"task": "code_completion", "language": "python", "instruction": "Complete the following Python code. Return only the continuation, preserving indentation.\n\n```python\ndef evaluate(\n model: torch.nn.Module,\n data: TokenData,\n batch_size: int,\n block_size: int,\n eval_batches: int,\n device: torch.device,\n dtype: str,\n loss_chunk: int,\n distributed: bool,\n backend: str,\n) -> float:\n raw = unwrap(model)\n was_training = raw.training\n```", "response": " raw.eval()\n losses = []\n for _ in range(eval_batches):\n x, y = data.get_batch(batch_size, block_size, device)\n with autocast_ctx(dtype, device.type):\n _, loss, _ = model(x, y, loss_chunk=loss_chunk)\n losses.append(float(loss))\n raw.train(was_training)\n\n mean = sum(losses) / max(len(losses), 1)\n if distributed:\n t = torch.tensor(mean, device=device if backend == \"nccl\" else \"cpu\")\n dist.all_reduce(t, op=dist.ReduceOp.SUM)\n mean = float(t) / dist.get_world_size()\n return mean", "source_file": "train.py", "function_name": "evaluate", "class_name": null, "line_start": 176, "line_end": 204, "license": "mit", "source": "SadikAI project"}
{"task": "code_completion", "language": "python", "instruction": "Complete the following Python code. Return only the continuation, preserving indentation.\n\n```python\ndef save_checkpoint(\n path: Path,\n raw_model: GPT,\n optimizer: torch.optim.Optimizer,\n step: int,\n best_val: float,\n model_cfg: ModelConfig,\n cfg: dict,\n) -> None:\n payload = {\n \"model\": raw_model.state_dict(),\n \"optimizer\": optimizer.state_dict(),\n \"step\": step,\n \"best_val\": best_val,\n \"model_config\": model_cfg.to_dict(),\n \"train_config\": cfg[\"train\"],\n \"name\": cfg[\"name\"],\n }\n```", "response": " tmp = path.with_suffix(path.suffix + \".tmp\")\n torch.save(payload, tmp)\n os.replace(tmp, path)", "source_file": "train.py", "function_name": "save_checkpoint", "class_name": null, "line_start": 207, "line_end": 227, "license": "mit", "source": "SadikAI project"}
{"task": "code_completion", "language": "python", "instruction": "Complete the following Python code. Return only the continuation, preserving indentation.\n\n```python\ndef batched(it, size: int):\n batch = []\n for item in it:\n batch.append(item)\n if len(batch) >= size:\n yield batch\n batch = []\n```", "response": " if batch:\n yield batch", "source_file": "train_tokenizer.py", "function_name": "batched", "class_name": null, "line_start": 28, "line_end": 36, "license": "mit", "source": "SadikAI project"}
{"task": "code_completion", "language": "python", "instruction": "Complete the following Python code. Return only the continuation, preserving indentation.\n\n```python\ndef main() -> None:\n p = argparse.ArgumentParser(description=__doc__, formatter_class=argparse.RawDescriptionHelpFormatter)\n p.add_argument(\"--source\", choices=[\"files\", \"hf\", \"synth\"], default=\"files\")\n p.add_argument(\"--input\", default=\"data/raw\", help=\"file or directory (--source files)\")\n p.add_argument(\"--hf-dataset\", default=\"wikitext\")\n p.add_argument(\"--hf-config\", default=\"wikitext-103-raw-v1\")\n p.add_argument(\"--hf-split\", default=\"train\")\n p.add_argument(\"--text-key\", default=\"text\")\n p.add_argument(\"--vocab-size\", type=int, default=65536,\n help=\"65536 is a good default; 100352/131072 = 'big brain'\")\n p.add_argument(\"--min-frequency\", type=int, default=2)\n p.add_argument(\"--sample-gb\", type=float, default=1.0,\n help=\"GB of text used to learn merges (full corpus still gets encoded later)\")\n p.add_argument(\"--batch-docs\", type=int, default=512)\n p.add_argument(\"--out\", default=\"tokenizer\")\n args = p.parse_args()\n\n out = Path(args.out)\n out.mkdir(parents=True, exist_ok=True)\n\n max_bytes = int(args.sample_gb * GB)\n docs = iter_documents(\n source=args.source,\n input_path=args.input,\n hf_dataset=args.hf_dataset,\n hf_config=args.hf_config,\n hf_split=args.hf_split,\n text_key=args.text_key,\n max_bytes=max_bytes,\n )\n\n tok = Tokenizer(models.BPE(unk_token=None))\n tok.pre_tokenizer = pre_tokenizers.ByteLevel(add_prefix_space=False, use_regex=True)\n tok.decoder = decoders.ByteLevel()\n```", "response": " trainer = trainers.BpeTrainer(\n vocab_size=args.vocab_size,\n min_frequency=args.min_frequency,\n special_tokens=SPECIAL_TOKENS,\n initial_alphabet=pre_tokenizers.ByteLevel.alphabet(),\n show_progress=True,\n )\n\n print(f\"training BPE: vocab={args.vocab_size}, sample={args.sample_gb:.2f} GB, source={args.source}\")\n started = time.time()\n tok.train_from_iterator(batched(docs, args.batch_docs), trainer=trainer)\n elapsed = time.time() - started\n\n path = out / \"tokenizer.json\"\n tok.save(str(path))\n\n # ---- sanity checks ------------------------------------------------- #\n probe = (\n \"The quick brown fox jumps over the lazy dog. 1234567890\\n\"\n \"def main() -> int:\\n return 0\\n\"\n \"日本語のテキスト、Ελληνικά, русский текст, emoji 🧠🚀\\n\"\n )\n ids = tok.encode(probe).ids\n decoded = tok.decode(ids)\n assert decoded == probe, \"byte-level round-trip failed\"\n chars_per_token = len(probe) / max(len(ids), 1)\n\n meta = {\n \"type\": \"byte-level-bpe\",\n \"vocab_size\": tok.get_vocab_size(),\n \"requested_vocab_size\": args.vocab_size,\n \"min_frequency\": args.min_frequency,\n \"special_tokens\": SPECIAL_TOKENS,\n \"trained_on_gb\": args.sample_gb,\n \"source\": args.source,\n \"chars_per_token_probe\": round(chars_per_token, 3),\n \"train_seconds\": round(elapsed, 1),\n }\n (out / \"tokenizer_meta.json\").write_text(json.dumps(meta, indent=2), encoding=\"utf-8\")\n\n print(f\"\\nsaved {path} ({path.stat().st_size / 1e6:.1f} MB)\")\n print(f\"vocab {tok.get_vocab_size():,} eos_id={tok.token_to_id(SPECIAL_TOKENS[0])}\")\n print(f\"probe {len(ids)} tokens for {len(probe)} chars -> {chars_per_token:.2f} chars/token\")\n print(f\"time {elapsed:.1f}s\")", "source_file": "train_tokenizer.py", "function_name": "main", "class_name": null, "line_start": 39, "line_end": 117, "license": "mit", "source": "SadikAI project"}
{"task": "code_completion", "language": "python", "instruction": "Complete the following Python code. Return only the continuation, preserving indentation.\n\n```python\n def __init__(self, path: str | Path) -> None:\n self.path = Path(path)\n self.lock = threading.Lock()\n```", "response": " self.data: dict[str, dict] = {}\n self._load()", "source_file": "websearch.py", "function_name": "__init__", "class_name": "_Cache", "line_start": 61, "line_end": 65, "license": "mit", "source": "SadikAI project"}
{"task": "code_completion", "language": "python", "instruction": "Complete the following Python code. Return only the continuation, preserving indentation.\n\n```python\n def _load(self) -> None:\n if not self.path.exists():\n return\n```", "response": " try:\n self.data = json.loads(self.path.read_text(encoding=\"utf-8\"))\n except (OSError, ValueError):\n self.data = {}", "source_file": "websearch.py", "function_name": "_load", "class_name": "_Cache", "line_start": 67, "line_end": 73, "license": "mit", "source": "SadikAI project"}
{"task": "code_completion", "language": "python", "instruction": "Complete the following Python code. Return only the continuation, preserving indentation.\n\n```python\n def get(self, key: str) -> list[Result] | None:\n with self.lock:\n row = self.data.get(key)\n```", "response": " if not row or time.time() - row.get(\"ts\", 0) > CACHE_TTL:\n return None\n return [Result(**r) for r in row.get(\"results\", [])]", "source_file": "websearch.py", "function_name": "get", "class_name": "_Cache", "line_start": 75, "line_end": 80, "license": "mit", "source": "SadikAI project"}
{"task": "code_completion", "language": "python", "instruction": "Complete the following Python code. Return only the continuation, preserving indentation.\n\n```python\ndef _http_json(url: str, timeout: float) -> dict:\n req = urllib.request.Request(url, headers={\"User-Agent\": UA,\n \"Accept\": \"application/json\"})\n```", "response": " with urllib.request.urlopen(req, timeout=timeout) as resp:\n return json.loads(resp.read().decode(\"utf-8\", \"replace\"))", "source_file": "websearch.py", "function_name": "_http_json", "class_name": null, "line_start": 99, "line_end": 103, "license": "mit", "source": "SadikAI project"}
{"task": "code_completion", "language": "python", "instruction": "Complete the following Python code. Return only the continuation, preserving indentation.\n\n```python\ndef _wiki(query: str, lang: str, limit: int, timeout: float) -> list[Result]:\n api = f\"https://{lang}.wikipedia.org/w/api.php\"\n params = {\n \"action\": \"query\", \"list\": \"search\", \"srsearch\": query,\n \"srlimit\": str(limit), \"format\": \"json\", \"srprop\": \"snippet\",\n }\n data = _http_json(api + \"?\" + urllib.parse.urlencode(params), timeout)\n hits = [h[\"title\"] for h in data.get(\"query\", {}).get(\"search\", [])][:limit]\n if not hits:\n return []\n```", "response": " def summary(title: str) -> Result | None:\n slug = urllib.parse.quote(title.replace(\" \", \"_\"), safe=\"\")\n try:\n page = _http_json(\n f\"https://{lang}.wikipedia.org/api/rest_v1/page/summary/{slug}\",\n timeout,\n )\n except Exception:\n return None\n text = (page.get(\"extract\") or \"\").strip()\n if not text:\n return None\n return Result(\n title=page.get(\"title\") or title,\n snippet=_trim(text, 400),\n url=(page.get(\"content_urls\", {}).get(\"desktop\", {}).get(\"page\")\n or f\"https://{lang}.wikipedia.org/wiki/{slug}\"),\n source=f\"wikipedia/{lang}\",\n )\n\n with ThreadPoolExecutor(max_workers=min(3, len(hits))) as pool:\n results = [r for r in pool.map(summary, hits) if r]\n return results", "source_file": "websearch.py", "function_name": "_wiki", "class_name": null, "line_start": 112, "line_end": 145, "license": "mit", "source": "SadikAI project"}
{"task": "code_completion", "language": "python", "instruction": "Complete the following Python code. Return only the continuation, preserving indentation.\n\n```python\ndef _ddg_instant(query: str, timeout: float) -> list[Result]:\n params = {\"q\": query, \"format\": \"json\", \"no_html\": \"1\", \"skip_disambig\": \"1\"}\n data = _http_json(\"https://api.duckduckgo.com/?\" + urllib.parse.urlencode(params),\n timeout)\n out: list[Result] = []\n```", "response": " if data.get(\"AbstractText\"):\n out.append(Result(\n title=data.get(\"Heading\") or query,\n snippet=_trim(data[\"AbstractText\"], 400),\n url=data.get(\"AbstractURL\") or f\"https://duckduckgo.com/?q={urllib.parse.quote(query)}\",\n source=\"duckduckgo\",\n ))\n for topic in data.get(\"RelatedTopics\", [])[:3]:\n if isinstance(topic, dict) and topic.get(\"Text\") and topic.get(\"FirstURL\"):\n out.append(Result(title=topic[\"Text\"].split(\" - \")[0][:80],\n snippet=_trim(topic[\"Text\"], 300),\n url=topic[\"FirstURL\"], source=\"duckduckgo\"))\n return out", "source_file": "websearch.py", "function_name": "_ddg_instant", "class_name": null, "line_start": 148, "line_end": 165, "license": "mit", "source": "SadikAI project"}
{"task": "code_completion", "language": "python", "instruction": "Complete the following Python code. Return only the continuation, preserving indentation.\n\n```python\ndef _ddg_html(query: str, timeout: float) -> list[Result]:\n url = \"https://html.duckduckgo.com/html/?\" + urllib.parse.urlencode({\"q\": query})\n page = _http_text(url, timeout)\n out: list[Result] = []\n pattern = re.compile(\n r'<a[^>]+class=\"result__a\"[^>]+href=\"(?P<url>[^\"]+)\"[^>]*>(?P<title>.*?)</a>'\n r'.*?<a[^>]+class=\"result__snippet\"[^>]*>(?P<snippet>.*?)</a>',\n re.S,\n )\n```", "response": " for m in pattern.finditer(page):\n out.append(Result(\n title=_strip_tags(m.group(\"title\"))[:100],\n snippet=_trim(_strip_tags(m.group(\"snippet\")), 300),\n url=_clean_ddg_url(html.unescape(m.group(\"url\"))),\n source=\"duckduckgo\",\n ))\n if len(out) >= 3:\n break\n return out", "source_file": "websearch.py", "function_name": "_ddg_html", "class_name": null, "line_start": 168, "line_end": 186, "license": "mit", "source": "SadikAI project"}
{"task": "code_completion", "language": "python", "instruction": "Complete the following Python code. Return only the continuation, preserving indentation.\n\n```python\ndef _clean_ddg_url(url: str) -> str:\n if url.startswith(\"//\"):\n url = \"https:\" + url\n parsed = urllib.parse.urlparse(url)\n```", "response": " if \"duckduckgo.com\" in parsed.netloc and parsed.path.startswith(\"/l/\"):\n target = urllib.parse.parse_qs(parsed.query).get(\"uddg\")\n if target:\n return urllib.parse.unquote(target[0])\n return url", "source_file": "websearch.py", "function_name": "_clean_ddg_url", "class_name": null, "line_start": 189, "line_end": 197, "license": "mit", "source": "SadikAI project"}
{"task": "code_completion", "language": "python", "instruction": "Complete the following Python code. Return only the continuation, preserving indentation.\n\n```python\ndef _trim(text: str, limit: int) -> str:\n text = \" \".join(text.split())\n if len(text) <= limit:\n return text\n```", "response": " cut = text[:limit]\n end = max(cut.rfind(\". \"), cut.rfind(\"। \"), cut.rfind(\"? \"))\n return (cut[: end + 1] if end > limit * 0.5 else cut.rsplit(\" \", 1)[0]) + \"…\"", "source_file": "websearch.py", "function_name": "_trim", "class_name": null, "line_start": 204, "line_end": 210, "license": "mit", "source": "SadikAI project"}
{"task": "code_completion", "language": "python", "instruction": "Complete the following Python code. Return only the continuation, preserving indentation.\n\n```python\ndef search(query: str, limit: int = 4, timeout: float = 6.0,\n cache_path: str | Path = \"data/chat/web_cache.json\") -> list[Result]:\n \"\"\"Query Wikipedia (and DuckDuckGo as backup). Never raises.\"\"\"\n query = \" \".join(query.split()).strip()\n if not query:\n return []\n\n cache = _Cache(cache_path)\n key = f\"{query.lower()}|{limit}\"\n cached = cache.get(key)\n if cached is not None:\n return cached\n\n results: list[Result] = []\n langs = _langs_for(query)\n\n with ThreadPoolExecutor(max_workers=3) as pool:\n futures = [pool.submit(_wiki, query, lang, limit, timeout) for lang in langs]\n futures.append(pool.submit(_ddg_instant, query, timeout))\n for fut in futures:\n try:\n results.extend(fut.result(timeout=timeout + 2))\n except Exception:\n continue\n```", "response": " if not results:\n try:\n results.extend(_ddg_html(query, timeout))\n except Exception:\n pass\n\n # de-duplicate titles that are near-identical\n seen: set[str] = set()\n unique: list[Result] = []\n for r in results:\n key_title = re.sub(r\"\\W+\", \"\", r.title.lower())[:40]\n if not key_title or key_title in seen or not r.snippet:\n continue\n seen.add(key_title)\n unique.append(r)\n\n unique = unique[:limit]\n cache.put(key, unique)\n return unique", "source_file": "websearch.py", "function_name": "search", "class_name": null, "line_start": 219, "line_end": 262, "license": "mit", "source": "SadikAI project"}
{"task": "code_explanation", "language": "python", "instruction": "Explain what this Python function does.\n\n```python\ndef search(query: str, limit: int = 4, timeout: float = 6.0,\n cache_path: str | Path = \"data/chat/web_cache.json\") -> list[Result]:\n \"\"\"Query Wikipedia (and DuckDuckGo as backup). Never raises.\"\"\"\n query = \" \".join(query.split()).strip()\n if not query:\n return []\n\n cache = _Cache(cache_path)\n key = f\"{query.lower()}|{limit}\"\n cached = cache.get(key)\n if cached is not None:\n return cached\n\n results: list[Result] = []\n langs = _langs_for(query)\n\n with ThreadPoolExecutor(max_workers=3) as pool:\n futures = [pool.submit(_wiki, query, lang, limit, timeout) for lang in langs]\n futures.append(pool.submit(_ddg_instant, query, timeout))\n for fut in futures:\n try:\n results.extend(fut.result(timeout=timeout + 2))\n except Exception:\n continue\n\n if not results:\n try:\n results.extend(_ddg_html(query, timeout))\n except Exception:\n pass\n\n # de-duplicate titles that are near-identical\n seen: set[str] = set()\n unique: list[Result] = []\n for r in results:\n key_title = re.sub(r\"\\W+\", \"\", r.title.lower())[:40]\n if not key_title or key_title in seen or not r.snippet:\n continue\n seen.add(key_title)\n unique.append(r)\n\n unique = unique[:limit]\n cache.put(key, unique)\n return unique\n```", "response": "Query Wikipedia (and DuckDuckGo as backup). Never raises.", "source_file": "websearch.py", "function_name": "search", "class_name": null, "line_start": 219, "line_end": 262, "license": "mit", "source": "SadikAI project"}
{"task": "code_generation", "language": "python", "instruction": "Write a Python function `search(query: str, limit: int=4, timeout: float=6.0, cache_path: str | Path='data/chat/web_cache.json')` that does the following:\n\nQuery Wikipedia (and DuckDuckGo as backup). Never raises.\n\nReturn only the Python code.", "response": "def search(query: str, limit: int = 4, timeout: float = 6.0,\n cache_path: str | Path = \"data/chat/web_cache.json\") -> list[Result]:\n \"\"\"Query Wikipedia (and DuckDuckGo as backup). Never raises.\"\"\"\n query = \" \".join(query.split()).strip()\n if not query:\n return []\n\n cache = _Cache(cache_path)\n key = f\"{query.lower()}|{limit}\"\n cached = cache.get(key)\n if cached is not None:\n return cached\n\n results: list[Result] = []\n langs = _langs_for(query)\n\n with ThreadPoolExecutor(max_workers=3) as pool:\n futures = [pool.submit(_wiki, query, lang, limit, timeout) for lang in langs]\n futures.append(pool.submit(_ddg_instant, query, timeout))\n for fut in futures:\n try:\n results.extend(fut.result(timeout=timeout + 2))\n except Exception:\n continue\n\n if not results:\n try:\n results.extend(_ddg_html(query, timeout))\n except Exception:\n pass\n\n # de-duplicate titles that are near-identical\n seen: set[str] = set()\n unique: list[Result] = []\n for r in results:\n key_title = re.sub(r\"\\W+\", \"\", r.title.lower())[:40]\n if not key_title or key_title in seen or not r.snippet:\n continue\n seen.add(key_title)\n unique.append(r)\n\n unique = unique[:limit]\n cache.put(key, unique)\n return unique", "source_file": "websearch.py", "function_name": "search", "class_name": null, "line_start": 219, "line_end": 262, "license": "mit", "source": "SadikAI project"}
{"task": "code_explanation", "language": "python", "instruction": "Explain what this Python function does.\n\n```python\ndef weather(city: str, timeout: float = 6.0) -> Result | None:\n \"\"\"Live current weather from Open-Meteo (no key). Returns None on failure.\"\"\"\n try:\n geo = _http_json(\n \"https://geocoding-api.open-meteo.com/v1/search?\"\n + urllib.parse.urlencode({\"name\": city, \"count\": \"1\",\n \"language\": \"en\", \"format\": \"json\"}),\n timeout,\n )\n hits = geo.get(\"results\") or []\n if not hits:\n return None\n place = hits[0]\n params = {\n \"latitude\": place[\"latitude\"], \"longitude\": place[\"longitude\"],\n \"current\": \"temperature_2m,apparent_temperature,weather_code,wind_speed_10m\",\n \"daily\": \"temperature_2m_max,temperature_2m_min\",\n \"timezone\": \"auto\", \"forecast_days\": \"1\",\n }\n data = _http_json(\n \"https://api.open-meteo.com/v1/forecast?\"\n + urllib.parse.urlencode(params), timeout\n )\n current = data.get(\"current\", {})\n daily = data.get(\"daily\", {})\n desc = WMO_CODES.get(int(current.get(\"weather_code\", -1)), \"unclear skies\")\n temp = current.get(\"temperature_2m\")\n feels = current.get(\"apparent_temperature\")\n lo = (daily.get(\"temperature_2m_min\") or [None])[0]\n hi = (daily.get(\"temperature_2m_max\") or [None])[0]\n wind = current.get(\"wind_speed_10m\")\n name = place.get(\"name\", city)\n country = place.get(\"country\", \"\")\n where = f\"{name}, {country}\" if country else name\n snippet = f\"{where}: {desc}, {temp}°C (feels like {feels}°C).\"\n if lo is not None and hi is not None:\n snippet += f\" Today {round(lo)}–{round(hi)}°C.\"\n if wind is not None:\n snippet += f\" Wind {round(wind)} km/h.\"\n return Result(title=f\"Weather in {where}\", snippet=snippet,\n url=\"https://open-meteo.com/\", source=\"open-meteo\")\n except Exception:\n return None\n```", "response": "Live current weather from Open-Meteo (no key). Returns None on failure.", "source_file": "websearch.py", "function_name": "weather", "class_name": null, "line_start": 277, "line_end": 319, "license": "mit", "source": "SadikAI project"}
{"task": "code_generation", "language": "python", "instruction": "Write a Python function `weather(city: str, timeout: float=6.0)` that does the following:\n\nLive current weather from Open-Meteo (no key). Returns None on failure.\n\nReturn only the Python code.", "response": "def weather(city: str, timeout: float = 6.0) -> Result | None:\n \"\"\"Live current weather from Open-Meteo (no key). Returns None on failure.\"\"\"\n try:\n geo = _http_json(\n \"https://geocoding-api.open-meteo.com/v1/search?\"\n + urllib.parse.urlencode({\"name\": city, \"count\": \"1\",\n \"language\": \"en\", \"format\": \"json\"}),\n timeout,\n )\n hits = geo.get(\"results\") or []\n if not hits:\n return None\n place = hits[0]\n params = {\n \"latitude\": place[\"latitude\"], \"longitude\": place[\"longitude\"],\n \"current\": \"temperature_2m,apparent_temperature,weather_code,wind_speed_10m\",\n \"daily\": \"temperature_2m_max,temperature_2m_min\",\n \"timezone\": \"auto\", \"forecast_days\": \"1\",\n }\n data = _http_json(\n \"https://api.open-meteo.com/v1/forecast?\"\n + urllib.parse.urlencode(params), timeout\n )\n current = data.get(\"current\", {})\n daily = data.get(\"daily\", {})\n desc = WMO_CODES.get(int(current.get(\"weather_code\", -1)), \"unclear skies\")\n temp = current.get(\"temperature_2m\")\n feels = current.get(\"apparent_temperature\")\n lo = (daily.get(\"temperature_2m_min\") or [None])[0]\n hi = (daily.get(\"temperature_2m_max\") or [None])[0]\n wind = current.get(\"wind_speed_10m\")\n name = place.get(\"name\", city)\n country = place.get(\"country\", \"\")\n where = f\"{name}, {country}\" if country else name\n snippet = f\"{where}: {desc}, {temp}°C (feels like {feels}°C).\"\n if lo is not None and hi is not None:\n snippet += f\" Today {round(lo)}–{round(hi)}°C.\"\n if wind is not None:\n snippet += f\" Wind {round(wind)} km/h.\"\n return Result(title=f\"Weather in {where}\", snippet=snippet,\n url=\"https://open-meteo.com/\", source=\"open-meteo\")\n except Exception:\n return None", "source_file": "websearch.py", "function_name": "weather", "class_name": null, "line_start": 277, "line_end": 319, "license": "mit", "source": "SadikAI project"}
{"task": "code_completion", "language": "python", "instruction": "Complete the following Python code. Return only the continuation, preserving indentation.\n\n```python\ndef needs_search(text: str) -> bool:\n low = \" \".join(text.lower().split())\n if not low:\n return False\n```", "response": " if \"?\" in text:\n return True\n if any(word in low for word in SEARCH_HINTS):\n return True\n stripped = low.lstrip(\"hey hi hello namaste \")\n return any(stripped.startswith(start) for start in QUESTION_STARTS)", "source_file": "websearch.py", "function_name": "needs_search", "class_name": null, "line_start": 322, "line_end": 331, "license": "mit", "source": "SadikAI project"}
{"task": "code_completion", "language": "python", "instruction": "Complete the following Python code. Return only the continuation, preserving indentation.\n\n```python\ndef _get_json(url: str, timeout: float = 30.0, attempts: int = 4) -> dict:\n \"\"\"GET with backoff: the Wikipedia API answers 429 under bursts.\"\"\"\n last: Exception | None = None\n```", "response": " for attempt in range(attempts):\n try:\n req = urllib.request.Request(url, headers={\"User-Agent\": UA})\n with urllib.request.urlopen(req, timeout=timeout) as resp:\n return json.loads(resp.read().decode(\"utf-8\", \"replace\"))\n except Exception as exc: # noqa: BLE001 - retry any network error\n last = exc\n if attempt + 1 < attempts:\n wait = 1.5 * (2 ** attempt)\n if isinstance(exc, urllib.error.HTTPError) and exc.code == 429:\n retry_after = exc.headers.get(\"Retry-After\") if exc.headers else None\n try:\n wait = max(wait, float(retry_after))\n except (TypeError, ValueError):\n wait = max(wait, 5.0 * (attempt + 1))\n time.sleep(wait)\n raise last # type: ignore[misc]", "source_file": "world_knowledge.py", "function_name": "_get_json", "class_name": null, "line_start": 239, "line_end": 258, "license": "mit", "source": "SadikAI project"}
{"task": "code_explanation", "language": "python", "instruction": "Explain what this Python function does.\n\n```python\ndef _get_json(url: str, timeout: float = 30.0, attempts: int = 4) -> dict:\n \"\"\"GET with backoff: the Wikipedia API answers 429 under bursts.\"\"\"\n last: Exception | None = None\n for attempt in range(attempts):\n try:\n req = urllib.request.Request(url, headers={\"User-Agent\": UA})\n with urllib.request.urlopen(req, timeout=timeout) as resp:\n return json.loads(resp.read().decode(\"utf-8\", \"replace\"))\n except Exception as exc: # noqa: BLE001 - retry any network error\n last = exc\n if attempt + 1 < attempts:\n wait = 1.5 * (2 ** attempt)\n if isinstance(exc, urllib.error.HTTPError) and exc.code == 429:\n retry_after = exc.headers.get(\"Retry-After\") if exc.headers else None\n try:\n wait = max(wait, float(retry_after))\n except (TypeError, ValueError):\n wait = max(wait, 5.0 * (attempt + 1))\n time.sleep(wait)\n raise last\n```", "response": "GET with backoff: the Wikipedia API answers 429 under bursts.", "source_file": "world_knowledge.py", "function_name": "_get_json", "class_name": null, "line_start": 239, "line_end": 258, "license": "mit", "source": "SadikAI project"}
{"task": "code_generation", "language": "python", "instruction": "Write a Python function `_get_json(url: str, timeout: float=30.0, attempts: int=4)` that does the following:\n\nGET with backoff: the Wikipedia API answers 429 under bursts.\n\nReturn only the Python code.", "response": "def _get_json(url: str, timeout: float = 30.0, attempts: int = 4) -> dict:\n \"\"\"GET with backoff: the Wikipedia API answers 429 under bursts.\"\"\"\n last: Exception | None = None\n for attempt in range(attempts):\n try:\n req = urllib.request.Request(url, headers={\"User-Agent\": UA})\n with urllib.request.urlopen(req, timeout=timeout) as resp:\n return json.loads(resp.read().decode(\"utf-8\", \"replace\"))\n except Exception as exc: # noqa: BLE001 - retry any network error\n last = exc\n if attempt + 1 < attempts:\n wait = 1.5 * (2 ** attempt)\n if isinstance(exc, urllib.error.HTTPError) and exc.code == 429:\n retry_after = exc.headers.get(\"Retry-After\") if exc.headers else None\n try:\n wait = max(wait, float(retry_after))\n except (TypeError, ValueError):\n wait = max(wait, 5.0 * (attempt + 1))\n time.sleep(wait)\n raise last", "source_file": "world_knowledge.py", "function_name": "_get_json", "class_name": null, "line_start": 239, "line_end": 258, "license": "mit", "source": "SadikAI project"}
{"task": "code_completion", "language": "python", "instruction": "Complete the following Python code. Return only the continuation, preserving indentation.\n\n```python\ndef _read_cached(title: str, cache: Path, max_chars: int) -> tuple[str, str] | None:\n \"\"\"Local-only lookup of a previously downloaded full article.\"\"\"\n cached = cache / f\"{_safe_name(title)}.json\"\n if not cached.exists():\n return None\n try:\n data = json.loads(cached.read_text(encoding=\"utf-8\"))\n except (OSError, ValueError):\n return None\n```", "response": " pages = data.get(\"query\", {}).get(\"pages\", [])\n if not pages:\n return None\n page = pages[0]\n text = (page.get(\"extract\") or \"\").strip()\n if page.get(\"missing\") or len(text) < 200:\n return None\n return page.get(\"title\") or title, text[:max_chars]", "source_file": "world_knowledge.py", "function_name": "_read_cached", "class_name": null, "line_start": 271, "line_end": 287, "license": "mit", "source": "SadikAI project"}
{"task": "code_explanation", "language": "python", "instruction": "Explain what this Python function does.\n\n```python\ndef _read_cached(title: str, cache: Path, max_chars: int) -> tuple[str, str] | None:\n \"\"\"Local-only lookup of a previously downloaded full article.\"\"\"\n cached = cache / f\"{_safe_name(title)}.json\"\n if not cached.exists():\n return None\n try:\n data = json.loads(cached.read_text(encoding=\"utf-8\"))\n except (OSError, ValueError):\n return None\n pages = data.get(\"query\", {}).get(\"pages\", [])\n if not pages:\n return None\n page = pages[0]\n text = (page.get(\"extract\") or \"\").strip()\n if page.get(\"missing\") or len(text) < 200:\n return None\n return page.get(\"title\") or title, text[:max_chars]\n```", "response": "Local-only lookup of a previously downloaded full article.", "source_file": "world_knowledge.py", "function_name": "_read_cached", "class_name": null, "line_start": 271, "line_end": 287, "license": "mit", "source": "SadikAI project"}
{"task": "code_generation", "language": "python", "instruction": "Write a Python function `_read_cached(title: str, cache: Path, max_chars: int)` that does the following:\n\nLocal-only lookup of a previously downloaded full article.\n\nReturn only the Python code.", "response": "def _read_cached(title: str, cache: Path, max_chars: int) -> tuple[str, str] | None:\n \"\"\"Local-only lookup of a previously downloaded full article.\"\"\"\n cached = cache / f\"{_safe_name(title)}.json\"\n if not cached.exists():\n return None\n try:\n data = json.loads(cached.read_text(encoding=\"utf-8\"))\n except (OSError, ValueError):\n return None\n pages = data.get(\"query\", {}).get(\"pages\", [])\n if not pages:\n return None\n page = pages[0]\n text = (page.get(\"extract\") or \"\").strip()\n if page.get(\"missing\") or len(text) < 200:\n return None\n return page.get(\"title\") or title, text[:max_chars]", "source_file": "world_knowledge.py", "function_name": "_read_cached", "class_name": null, "line_start": 271, "line_end": 287, "license": "mit", "source": "SadikAI project"}
{"task": "code_completion", "language": "python", "instruction": "Complete the following Python code. Return only the continuation, preserving indentation.\n\n```python\ndef fetch_extract(title: str, max_chars: int, cache: Path) -> tuple[str, str] | None:\n \"\"\"One full plain-text article. Returns (resolved_title, text).\"\"\"\n cached_item = _read_cached(title, cache, max_chars)\n if cached_item is not None:\n return cached_item\n\n params = {\n \"action\": \"query\", \"format\": \"json\", \"formatversion\": \"2\",\n \"prop\": \"extracts\", \"explaintext\": \"1\", \"redirects\": \"1\",\n \"exlimit\": \"1\", \"titles\": title,\n }\n```", "response": " data = _get_json(API + \"?\" + urllib.parse.urlencode(params))\n cache.mkdir(parents=True, exist_ok=True)\n (cache / f\"{_safe_name(title)}.json\").write_text(\n json.dumps(data, ensure_ascii=False), encoding=\"utf-8\")\n\n pages = data.get(\"query\", {}).get(\"pages\", [])\n if not pages:\n return None\n page = pages[0]\n text = (page.get(\"extract\") or \"\").strip()\n if page.get(\"missing\") or len(text) < 200:\n return None\n return page.get(\"title\") or title, text[:max_chars]", "source_file": "world_knowledge.py", "function_name": "fetch_extract", "class_name": null, "line_start": 290, "line_end": 313, "license": "mit", "source": "SadikAI project"}
{"task": "code_explanation", "language": "python", "instruction": "Explain what this Python function does.\n\n```python\ndef fetch_extract(title: str, max_chars: int, cache: Path) -> tuple[str, str] | None:\n \"\"\"One full plain-text article. Returns (resolved_title, text).\"\"\"\n cached_item = _read_cached(title, cache, max_chars)\n if cached_item is not None:\n return cached_item\n\n params = {\n \"action\": \"query\", \"format\": \"json\", \"formatversion\": \"2\",\n \"prop\": \"extracts\", \"explaintext\": \"1\", \"redirects\": \"1\",\n \"exlimit\": \"1\", \"titles\": title,\n }\n data = _get_json(API + \"?\" + urllib.parse.urlencode(params))\n cache.mkdir(parents=True, exist_ok=True)\n (cache / f\"{_safe_name(title)}.json\").write_text(\n json.dumps(data, ensure_ascii=False), encoding=\"utf-8\")\n\n pages = data.get(\"query\", {}).get(\"pages\", [])\n if not pages:\n return None\n page = pages[0]\n text = (page.get(\"extract\") or \"\").strip()\n if page.get(\"missing\") or len(text) < 200:\n return None\n return page.get(\"title\") or title, text[:max_chars]\n```", "response": "One full plain-text article. Returns (resolved_title, text).", "source_file": "world_knowledge.py", "function_name": "fetch_extract", "class_name": null, "line_start": 290, "line_end": 313, "license": "mit", "source": "SadikAI project"}
{"task": "code_generation", "language": "python", "instruction": "Write a Python function `fetch_extract(title: str, max_chars: int, cache: Path)` that does the following:\n\nOne full plain-text article. Returns (resolved_title, text).\n\nReturn only the Python code.", "response": "def fetch_extract(title: str, max_chars: int, cache: Path) -> tuple[str, str] | None:\n \"\"\"One full plain-text article. Returns (resolved_title, text).\"\"\"\n cached_item = _read_cached(title, cache, max_chars)\n if cached_item is not None:\n return cached_item\n\n params = {\n \"action\": \"query\", \"format\": \"json\", \"formatversion\": \"2\",\n \"prop\": \"extracts\", \"explaintext\": \"1\", \"redirects\": \"1\",\n \"exlimit\": \"1\", \"titles\": title,\n }\n data = _get_json(API + \"?\" + urllib.parse.urlencode(params))\n cache.mkdir(parents=True, exist_ok=True)\n (cache / f\"{_safe_name(title)}.json\").write_text(\n json.dumps(data, ensure_ascii=False), encoding=\"utf-8\")\n\n pages = data.get(\"query\", {}).get(\"pages\", [])\n if not pages:\n return None\n page = pages[0]\n text = (page.get(\"extract\") or \"\").strip()\n if page.get(\"missing\") or len(text) < 200:\n return None\n return page.get(\"title\") or title, text[:max_chars]", "source_file": "world_knowledge.py", "function_name": "fetch_extract", "class_name": null, "line_start": 290, "line_end": 313, "license": "mit", "source": "SadikAI project"}
{"task": "code_completion", "language": "python", "instruction": "Complete the following Python code. Return only the continuation, preserving indentation.\n\n```python\ndef fetch_world(lists: dict[str, list[str]], wanted: list[str], out: Path,\n max_chars: int, cache: Path, workers: int) -> tuple[int, int]:\n \"\"\"Fetch every unique title once, then write one JSONL per domain.\"\"\"\n order: list[str] = []\n domain_of: dict[str, str] = {}\n for domain in wanted:\n for title in lists.get(domain, []):\n if title not in domain_of:\n domain_of[title] = domain\n order.append(title)\n\n print(f\"fetching {len(order)} unique articles with {workers} workers\")\n results: dict[str, tuple[str, str]] = {}\n done = 0\n lock = threading.Lock()\n started = time.time()\n\n def work(title: str):\n nonlocal done\n try:\n item = fetch_extract(title, max_chars, cache)\n except Exception as exc: # noqa: BLE001\n item = None\n if \"429\" not in str(exc):\n print(f\" {title}: {exc}\")\n with lock:\n done += 1\n if item:\n results[title] = item\n if done % 20 == 0 or done == len(order):\n print(f\" {done}/{len(order)} fetched, {len(results)} usable\",\n end=\"\\r\", flush=True)\n return item\n```", "response": " with ThreadPoolExecutor(max_workers=workers) as pool:\n futures = [pool.submit(work, t) for t in order]\n for fut in as_completed(futures):\n fut.result()\n\n print(f\" fetched {len(results)}/{len(order)} articles \"\n f\"in {time.time() - started:.0f}s\")\n\n total_docs = 0\n total_bytes = 0\n for domain in wanted:\n dest = out / domain / \"wikipedia.jsonl\"\n dest.parent.mkdir(parents=True, exist_ok=True)\n seen: set[str] = set()\n docs = 0\n written = 0\n with dest.open(\"w\", encoding=\"utf-8\", newline=\"\\n\") as fh:\n for title in lists.get(domain, []):\n item = results.get(title)\n if not item:\n continue\n resolved, text = item\n key = resolved.lower()\n if key in seen:\n continue\n seen.add(key)\n body = f\"# {resolved}\\n\\n{text}\\n\"\n line = json.dumps({\"text\": body}, ensure_ascii=False) + \"\\n\"\n fh.write(line)\n docs += 1\n written += len(line.encode(\"utf-8\"))\n print(f\" {domain}: {docs} articles, {written / MB:.1f} MB -> {dest}\")\n total_docs += docs\n total_bytes += written\n return total_docs, total_bytes", "source_file": "world_knowledge.py", "function_name": "fetch_world", "class_name": null, "line_start": 316, "line_end": 384, "license": "mit", "source": "SadikAI project"}
{"task": "code_explanation", "language": "python", "instruction": "Explain what this Python function does.\n\n```python\ndef fetch_world(lists: dict[str, list[str]], wanted: list[str], out: Path,\n max_chars: int, cache: Path, workers: int) -> tuple[int, int]:\n \"\"\"Fetch every unique title once, then write one JSONL per domain.\"\"\"\n order: list[str] = []\n domain_of: dict[str, str] = {}\n for domain in wanted:\n for title in lists.get(domain, []):\n if title not in domain_of:\n domain_of[title] = domain\n order.append(title)\n\n print(f\"fetching {len(order)} unique articles with {workers} workers\")\n results: dict[str, tuple[str, str]] = {}\n done = 0\n lock = threading.Lock()\n started = time.time()\n\n def work(title: str):\n nonlocal done\n try:\n item = fetch_extract(title, max_chars, cache)\n except Exception as exc: # noqa: BLE001\n item = None\n if \"429\" not in str(exc):\n print(f\" {title}: {exc}\")\n with lock:\n done += 1\n if item:\n results[title] = item\n if done % 20 == 0 or done == len(order):\n print(f\" {done}/{len(order)} fetched, {len(results)} usable\",\n end=\"\\r\", flush=True)\n return item\n\n with ThreadPoolExecutor(max_workers=workers) as pool:\n futures = [pool.submit(work, t) for t in order]\n for fut in as_completed(futures):\n fut.result()\n\n print(f\" fetched {len(results)}/{len(order)} articles \"\n f\"in {time.time() - started:.0f}s\")\n\n total_docs = 0\n total_bytes = 0\n for domain in wanted:\n dest = out / domain / \"wikipedia.jsonl\"\n dest.parent.mkdir(parents=True, exist_ok=True)\n seen: set[str] = set()\n docs = 0\n written = 0\n with dest.open(\"w\", encoding=\"utf-8\", newline=\"\\n\") as fh:\n for title in lists.get(domain, []):\n item = results.get(title)\n if not item:\n continue\n resolved, text = item\n key = resolved.lower()\n if key in seen:\n continue\n seen.add(key)\n body = f\"# {resolved}\\n\\n{text}\\n\"\n line = json.dumps({\"text\": body}, ensure_ascii=False) + \"\\n\"\n fh.write(line)\n docs += 1\n written += len(line.encode(\"utf-8\"))\n print(f\" {domain}: {docs} articles, {written / MB:.1f} MB -> {dest}\")\n total_docs += docs\n total_bytes += written\n return total_docs, total_bytes\n```", "response": "Fetch every unique title once, then write one JSONL per domain.", "source_file": "world_knowledge.py", "function_name": "fetch_world", "class_name": null, "line_start": 316, "line_end": 384, "license": "mit", "source": "SadikAI project"}
{"task": "code_generation", "language": "python", "instruction": "Write a Python function `fetch_world(lists: dict[str, list[str]], wanted: list[str], out: Path, max_chars: int, cache: Path, workers: int)` that does the following:\n\nFetch every unique title once, then write one JSONL per domain.\n\nReturn only the Python code.", "response": "def fetch_world(lists: dict[str, list[str]], wanted: list[str], out: Path,\n max_chars: int, cache: Path, workers: int) -> tuple[int, int]:\n \"\"\"Fetch every unique title once, then write one JSONL per domain.\"\"\"\n order: list[str] = []\n domain_of: dict[str, str] = {}\n for domain in wanted:\n for title in lists.get(domain, []):\n if title not in domain_of:\n domain_of[title] = domain\n order.append(title)\n\n print(f\"fetching {len(order)} unique articles with {workers} workers\")\n results: dict[str, tuple[str, str]] = {}\n done = 0\n lock = threading.Lock()\n started = time.time()\n\n def work(title: str):\n nonlocal done\n try:\n item = fetch_extract(title, max_chars, cache)\n except Exception as exc: # noqa: BLE001\n item = None\n if \"429\" not in str(exc):\n print(f\" {title}: {exc}\")\n with lock:\n done += 1\n if item:\n results[title] = item\n if done % 20 == 0 or done == len(order):\n print(f\" {done}/{len(order)} fetched, {len(results)} usable\",\n end=\"\\r\", flush=True)\n return item\n\n with ThreadPoolExecutor(max_workers=workers) as pool:\n futures = [pool.submit(work, t) for t in order]\n for fut in as_completed(futures):\n fut.result()\n\n print(f\" fetched {len(results)}/{len(order)} articles \"\n f\"in {time.time() - started:.0f}s\")\n\n total_docs = 0\n total_bytes = 0\n for domain in wanted:\n dest = out / domain / \"wikipedia.jsonl\"\n dest.parent.mkdir(parents=True, exist_ok=True)\n seen: set[str] = set()\n docs = 0\n written = 0\n with dest.open(\"w\", encoding=\"utf-8\", newline=\"\\n\") as fh:\n for title in lists.get(domain, []):\n item = results.get(title)\n if not item:\n continue\n resolved, text = item\n key = resolved.lower()\n if key in seen:\n continue\n seen.add(key)\n body = f\"# {resolved}\\n\\n{text}\\n\"\n line = json.dumps({\"text\": body}, ensure_ascii=False) + \"\\n\"\n fh.write(line)\n docs += 1\n written += len(line.encode(\"utf-8\"))\n print(f\" {domain}: {docs} articles, {written / MB:.1f} MB -> {dest}\")\n total_docs += docs\n total_bytes += written\n return total_docs, total_bytes", "source_file": "world_knowledge.py", "function_name": "fetch_world", "class_name": null, "line_start": 316, "line_end": 384, "license": "mit", "source": "SadikAI project"}
{"task": "code_completion", "language": "python", "instruction": "Complete the following Python code. Return only the continuation, preserving indentation.\n\n```python\ndef fetch_intros(titles: list[str], domain: str, out: Path, max_chars: int,\n cache: Path) -> tuple[int, int]:\n \"\"\"Fetch lead sections in batches of 20 (exintro allows exlimit=max).\"\"\"\n dest = out / domain / \"wikipedia_intro.jsonl\"\n dest.parent.mkdir(parents=True, exist_ok=True)\n intro_cache = cache / \"intros\"\n intro_cache.mkdir(parents=True, exist_ok=True)\n\n docs = 0\n written = 0\n seen: set[str] = set()\n batches = [titles[i:i + 20] for i in range(0, len(titles), 20)]\n```", "response": " with dest.open(\"w\", encoding=\"utf-8\", newline=\"\\n\") as fh:\n for batch in batches:\n key = hashlib.md5(\"|\".join(batch).encode(\"utf-8\")).hexdigest()[:12]\n cached = intro_cache / f\"{domain}_{key}.json\"\n if cached.exists():\n data = json.loads(cached.read_text(encoding=\"utf-8\"))\n else:\n params = {\n \"action\": \"query\", \"format\": \"json\", \"formatversion\": \"2\",\n \"prop\": \"extracts\", \"explaintext\": \"1\", \"exintro\": \"1\",\n \"redirects\": \"1\", \"exlimit\": \"max\", \"titles\": \"|\".join(batch),\n }\n try:\n data = _get_json(API + \"?\" + urllib.parse.urlencode(params))\n except Exception as exc: # noqa: BLE001\n print(f\" {domain}: intro batch failed ({exc}); skipping\")\n continue\n cached.write_text(json.dumps(data, ensure_ascii=False),\n encoding=\"utf-8\")\n time.sleep(0.3)\n\n for page in data.get(\"query\", {}).get(\"pages\", []):\n title = page.get(\"title\", \"\")\n text = (page.get(\"extract\") or \"\").strip()\n if not text or page.get(\"missing\") or len(text) < 100:\n continue\n if title.lower() in seen:\n continue\n seen.add(title.lower())\n body = f\"# {title}\\n\\n{text[:max_chars]}\\n\"\n line = json.dumps({\"text\": body}, ensure_ascii=False) + \"\\n\"\n fh.write(line)\n docs += 1\n written += len(line.encode(\"utf-8\"))\n\n print(f\" {domain}: {docs} intros, {written / MB:.1f} MB -> {dest}\")\n return docs, written", "source_file": "world_knowledge.py", "function_name": "fetch_intros", "class_name": null, "line_start": 387, "line_end": 436, "license": "mit", "source": "SadikAI project"}
{"task": "code_explanation", "language": "python", "instruction": "Explain what this Python function does.\n\n```python\ndef fetch_intros(titles: list[str], domain: str, out: Path, max_chars: int,\n cache: Path) -> tuple[int, int]:\n \"\"\"Fetch lead sections in batches of 20 (exintro allows exlimit=max).\"\"\"\n dest = out / domain / \"wikipedia_intro.jsonl\"\n dest.parent.mkdir(parents=True, exist_ok=True)\n intro_cache = cache / \"intros\"\n intro_cache.mkdir(parents=True, exist_ok=True)\n\n docs = 0\n written = 0\n seen: set[str] = set()\n batches = [titles[i:i + 20] for i in range(0, len(titles), 20)]\n\n with dest.open(\"w\", encoding=\"utf-8\", newline=\"\\n\") as fh:\n for batch in batches:\n key = hashlib.md5(\"|\".join(batch).encode(\"utf-8\")).hexdigest()[:12]\n cached = intro_cache / f\"{domain}_{key}.json\"\n if cached.exists():\n data = json.loads(cached.read_text(encoding=\"utf-8\"))\n else:\n params = {\n \"action\": \"query\", \"format\": \"json\", \"formatversion\": \"2\",\n \"prop\": \"extracts\", \"explaintext\": \"1\", \"exintro\": \"1\",\n \"redirects\": \"1\", \"exlimit\": \"max\", \"titles\": \"|\".join(batch),\n }\n try:\n data = _get_json(API + \"?\" + urllib.parse.urlencode(params))\n except Exception as exc: # noqa: BLE001\n print(f\" {domain}: intro batch failed ({exc}); skipping\")\n continue\n cached.write_text(json.dumps(data, ensure_ascii=False),\n encoding=\"utf-8\")\n time.sleep(0.3)\n\n for page in data.get(\"query\", {}).get(\"pages\", []):\n title = page.get(\"title\", \"\")\n text = (page.get(\"extract\") or \"\").strip()\n if not text or page.get(\"missing\") or len(text) < 100:\n continue\n if title.lower() in seen:\n continue\n seen.add(title.lower())\n body = f\"# {title}\\n\\n{text[:max_chars]}\\n\"\n line = json.dumps({\"text\": body}, ensure_ascii=False) + \"\\n\"\n fh.write(line)\n docs += 1\n written += len(line.encode(\"utf-8\"))\n\n print(f\" {domain}: {docs} intros, {written / MB:.1f} MB -> {dest}\")\n return docs, written\n```", "response": "Fetch lead sections in batches of 20 (exintro allows exlimit=max).", "source_file": "world_knowledge.py", "function_name": "fetch_intros", "class_name": null, "line_start": 387, "line_end": 436, "license": "mit", "source": "SadikAI project"}
{"task": "code_generation", "language": "python", "instruction": "Write a Python function `fetch_intros(titles: list[str], domain: str, out: Path, max_chars: int, cache: Path)` that does the following:\n\nFetch lead sections in batches of 20 (exintro allows exlimit=max).\n\nReturn only the Python code.", "response": "def fetch_intros(titles: list[str], domain: str, out: Path, max_chars: int,\n cache: Path) -> tuple[int, int]:\n \"\"\"Fetch lead sections in batches of 20 (exintro allows exlimit=max).\"\"\"\n dest = out / domain / \"wikipedia_intro.jsonl\"\n dest.parent.mkdir(parents=True, exist_ok=True)\n intro_cache = cache / \"intros\"\n intro_cache.mkdir(parents=True, exist_ok=True)\n\n docs = 0\n written = 0\n seen: set[str] = set()\n batches = [titles[i:i + 20] for i in range(0, len(titles), 20)]\n\n with dest.open(\"w\", encoding=\"utf-8\", newline=\"\\n\") as fh:\n for batch in batches:\n key = hashlib.md5(\"|\".join(batch).encode(\"utf-8\")).hexdigest()[:12]\n cached = intro_cache / f\"{domain}_{key}.json\"\n if cached.exists():\n data = json.loads(cached.read_text(encoding=\"utf-8\"))\n else:\n params = {\n \"action\": \"query\", \"format\": \"json\", \"formatversion\": \"2\",\n \"prop\": \"extracts\", \"explaintext\": \"1\", \"exintro\": \"1\",\n \"redirects\": \"1\", \"exlimit\": \"max\", \"titles\": \"|\".join(batch),\n }\n try:\n data = _get_json(API + \"?\" + urllib.parse.urlencode(params))\n except Exception as exc: # noqa: BLE001\n print(f\" {domain}: intro batch failed ({exc}); skipping\")\n continue\n cached.write_text(json.dumps(data, ensure_ascii=False),\n encoding=\"utf-8\")\n time.sleep(0.3)\n\n for page in data.get(\"query\", {}).get(\"pages\", []):\n title = page.get(\"title\", \"\")\n text = (page.get(\"extract\") or \"\").strip()\n if not text or page.get(\"missing\") or len(text) < 100:\n continue\n if title.lower() in seen:\n continue\n seen.add(title.lower())\n body = f\"# {title}\\n\\n{text[:max_chars]}\\n\"\n line = json.dumps({\"text\": body}, ensure_ascii=False) + \"\\n\"\n fh.write(line)\n docs += 1\n written += len(line.encode(\"utf-8\"))\n\n print(f\" {domain}: {docs} intros, {written / MB:.1f} MB -> {dest}\")\n return docs, written", "source_file": "world_knowledge.py", "function_name": "fetch_intros", "class_name": null, "line_start": 387, "line_end": 436, "license": "mit", "source": "SadikAI project"}
{"task": "code_completion", "language": "python", "instruction": "Complete the following Python code. Return only the continuation, preserving indentation.\n\n```python\ndef fill_missing(lists: dict[str, list[str]], wanted: list[str], out: Path,\n max_chars: int, cache: Path) -> tuple[int, int]:\n \"\"\"Write cached full articles, then batch-fetch intros for the rest.\"\"\"\n total_docs = 0\n total_bytes = 0\n articles = cache / \"articles\"\n```", "response": " for domain in wanted:\n titles = lists.get(domain, [])\n dest_full = out / domain / \"wikipedia_full.jsonl\"\n dest_full.parent.mkdir(parents=True, exist_ok=True)\n seen: set[str] = set()\n\n existing = out / domain / \"wikipedia.jsonl\"\n if existing.exists():\n for line in existing.read_text(encoding=\"utf-8\", errors=\"ignore\").splitlines():\n try:\n body = json.loads(line).get(\"text\", \"\")\n except ValueError:\n continue\n head = body.split(\"\\n\", 1)[0]\n if head.startswith(\"# \"):\n seen.add(head[2:].strip().lower())\n\n full: list[tuple[str, str]] = []\n for title in titles:\n item = _read_cached(title, articles, max_chars)\n if not item:\n continue\n resolved, text = item\n if title.lower() in seen or resolved.lower() in seen:\n continue\n seen.add(title.lower())\n seen.add(resolved.lower())\n full.append((resolved, text))\n\n written = 0\n with dest_full.open(\"w\", encoding=\"utf-8\", newline=\"\\n\") as fh:\n for resolved, text in full:\n body = f\"# {resolved}\\n\\n{text}\\n\"\n line = json.dumps({\"text\": body}, ensure_ascii=False) + \"\\n\"\n fh.write(line)\n written += len(line.encode(\"utf-8\"))\n print(f\" {domain}: {len(full)} cached full articles, \"\n f\"{written / MB:.1f} MB -> {dest_full}\")\n total_docs += len(full)\n total_bytes += written\n\n missing = [t for t in titles if t.lower() not in seen]\n docs, size = fetch_intros(missing, domain, out, max_chars, cache)\n total_docs += docs\n total_bytes += size\n\n return total_docs, total_bytes", "source_file": "world_knowledge.py", "function_name": "fill_missing", "class_name": null, "line_start": 439, "line_end": 492, "license": "mit", "source": "SadikAI project"}
{"task": "code_explanation", "language": "python", "instruction": "Explain what this Python function does.\n\n```python\ndef fill_missing(lists: dict[str, list[str]], wanted: list[str], out: Path,\n max_chars: int, cache: Path) -> tuple[int, int]:\n \"\"\"Write cached full articles, then batch-fetch intros for the rest.\"\"\"\n total_docs = 0\n total_bytes = 0\n articles = cache / \"articles\"\n\n for domain in wanted:\n titles = lists.get(domain, [])\n dest_full = out / domain / \"wikipedia_full.jsonl\"\n dest_full.parent.mkdir(parents=True, exist_ok=True)\n seen: set[str] = set()\n\n existing = out / domain / \"wikipedia.jsonl\"\n if existing.exists():\n for line in existing.read_text(encoding=\"utf-8\", errors=\"ignore\").splitlines():\n try:\n body = json.loads(line).get(\"text\", \"\")\n except ValueError:\n continue\n head = body.split(\"\\n\", 1)[0]\n if head.startswith(\"# \"):\n seen.add(head[2:].strip().lower())\n\n full: list[tuple[str, str]] = []\n for title in titles:\n item = _read_cached(title, articles, max_chars)\n if not item:\n continue\n resolved, text = item\n if title.lower() in seen or resolved.lower() in seen:\n continue\n seen.add(title.lower())\n seen.add(resolved.lower())\n full.append((resolved, text))\n\n written = 0\n with dest_full.open(\"w\", encoding=\"utf-8\", newline=\"\\n\") as fh:\n for resolved, text in full:\n body = f\"# {resolved}\\n\\n{text}\\n\"\n line = json.dumps({\"text\": body}, ensure_ascii=False) + \"\\n\"\n fh.write(line)\n written += len(line.encode(\"utf-8\"))\n print(f\" {domain}: {len(full)} cached full articles, \"\n f\"{written / MB:.1f} MB -> {dest_full}\")\n total_docs += len(full)\n total_bytes += written\n\n missing = [t for t in titles if t.lower() not in seen]\n docs, size = fetch_intros(missing, domain, out, max_chars, cache)\n total_docs += docs\n total_bytes += size\n\n return total_docs, total_bytes\n```", "response": "Write cached full articles, then batch-fetch intros for the rest.", "source_file": "world_knowledge.py", "function_name": "fill_missing", "class_name": null, "line_start": 439, "line_end": 492, "license": "mit", "source": "SadikAI project"}
{"task": "code_generation", "language": "python", "instruction": "Write a Python function `fill_missing(lists: dict[str, list[str]], wanted: list[str], out: Path, max_chars: int, cache: Path)` that does the following:\n\nWrite cached full articles, then batch-fetch intros for the rest.\n\nReturn only the Python code.", "response": "def fill_missing(lists: dict[str, list[str]], wanted: list[str], out: Path,\n max_chars: int, cache: Path) -> tuple[int, int]:\n \"\"\"Write cached full articles, then batch-fetch intros for the rest.\"\"\"\n total_docs = 0\n total_bytes = 0\n articles = cache / \"articles\"\n\n for domain in wanted:\n titles = lists.get(domain, [])\n dest_full = out / domain / \"wikipedia_full.jsonl\"\n dest_full.parent.mkdir(parents=True, exist_ok=True)\n seen: set[str] = set()\n\n existing = out / domain / \"wikipedia.jsonl\"\n if existing.exists():\n for line in existing.read_text(encoding=\"utf-8\", errors=\"ignore\").splitlines():\n try:\n body = json.loads(line).get(\"text\", \"\")\n except ValueError:\n continue\n head = body.split(\"\\n\", 1)[0]\n if head.startswith(\"# \"):\n seen.add(head[2:].strip().lower())\n\n full: list[tuple[str, str]] = []\n for title in titles:\n item = _read_cached(title, articles, max_chars)\n if not item:\n continue\n resolved, text = item\n if title.lower() in seen or resolved.lower() in seen:\n continue\n seen.add(title.lower())\n seen.add(resolved.lower())\n full.append((resolved, text))\n\n written = 0\n with dest_full.open(\"w\", encoding=\"utf-8\", newline=\"\\n\") as fh:\n for resolved, text in full:\n body = f\"# {resolved}\\n\\n{text}\\n\"\n line = json.dumps({\"text\": body}, ensure_ascii=False) + \"\\n\"\n fh.write(line)\n written += len(line.encode(\"utf-8\"))\n print(f\" {domain}: {len(full)} cached full articles, \"\n f\"{written / MB:.1f} MB -> {dest_full}\")\n total_docs += len(full)\n total_bytes += written\n\n missing = [t for t in titles if t.lower() not in seen]\n docs, size = fetch_intros(missing, domain, out, max_chars, cache)\n total_docs += docs\n total_bytes += size\n\n return total_docs, total_bytes", "source_file": "world_knowledge.py", "function_name": "fill_missing", "class_name": null, "line_start": 439, "line_end": 492, "license": "mit", "source": "SadikAI project"}
{"task": "code_completion", "language": "python", "instruction": "Complete the following Python code. Return only the continuation, preserving indentation.\n\n```python\ndef fetch_gsm8k(out: Path, max_mb: float = 8.0) -> tuple[int, int]:\n \"\"\"Grade-school math word problems with worked solutions (MIT licence).\"\"\"\n dest = out / \"math\" / \"gsm8k.jsonl\"\n dest.parent.mkdir(parents=True, exist_ok=True)\n docs = 0\n written = 0\n limit = int(max_mb * MB)\n```", "response": " with dest.open(\"w\", encoding=\"utf-8\", newline=\"\\n\") as fh:\n for url in GSM8K_URLS:\n if written >= limit:\n break\n try:\n raw = _http_text(url)\n except Exception as exc: # noqa: BLE001\n print(f\" math: could not download {url.split('/')[-1]}: {exc}\")\n continue\n for line in raw.splitlines():\n if not line.strip():\n continue\n try:\n row = json.loads(line)\n except ValueError:\n continue\n question = (row.get(\"question\") or \"\").strip()\n answer = (row.get(\"answer\") or \"\").strip()\n if not question or not answer:\n continue\n body = f\"Question: {question}\\nAnswer: {answer}\\n\"\n out_line = json.dumps({\"text\": body}, ensure_ascii=False) + \"\\n\"\n fh.write(out_line)\n written += len(out_line.encode(\"utf-8\"))\n docs += 1\n if written >= limit:\n break\n print(f\" math: {docs} worked problems, {written / MB:.2f} MB -> {dest}\")\n return docs, written", "source_file": "world_knowledge.py", "function_name": "fetch_gsm8k", "class_name": null, "line_start": 495, "line_end": 530, "license": "mit", "source": "SadikAI project"}
{"task": "code_explanation", "language": "python", "instruction": "Explain what this Python function does.\n\n```python\ndef fetch_gsm8k(out: Path, max_mb: float = 8.0) -> tuple[int, int]:\n \"\"\"Grade-school math word problems with worked solutions (MIT licence).\"\"\"\n dest = out / \"math\" / \"gsm8k.jsonl\"\n dest.parent.mkdir(parents=True, exist_ok=True)\n docs = 0\n written = 0\n limit = int(max_mb * MB)\n with dest.open(\"w\", encoding=\"utf-8\", newline=\"\\n\") as fh:\n for url in GSM8K_URLS:\n if written >= limit:\n break\n try:\n raw = _http_text(url)\n except Exception as exc: # noqa: BLE001\n print(f\" math: could not download {url.split('/')[-1]}: {exc}\")\n continue\n for line in raw.splitlines():\n if not line.strip():\n continue\n try:\n row = json.loads(line)\n except ValueError:\n continue\n question = (row.get(\"question\") or \"\").strip()\n answer = (row.get(\"answer\") or \"\").strip()\n if not question or not answer:\n continue\n body = f\"Question: {question}\\nAnswer: {answer}\\n\"\n out_line = json.dumps({\"text\": body}, ensure_ascii=False) + \"\\n\"\n fh.write(out_line)\n written += len(out_line.encode(\"utf-8\"))\n docs += 1\n if written >= limit:\n break\n print(f\" math: {docs} worked problems, {written / MB:.2f} MB -> {dest}\")\n return docs, written\n```", "response": "Grade-school math word problems with worked solutions (MIT licence).", "source_file": "world_knowledge.py", "function_name": "fetch_gsm8k", "class_name": null, "line_start": 495, "line_end": 530, "license": "mit", "source": "SadikAI project"}
{"task": "code_generation", "language": "python", "instruction": "Write a Python function `fetch_gsm8k(out: Path, max_mb: float=8.0)` that does the following:\n\nGrade-school math word problems with worked solutions (MIT licence).\n\nReturn only the Python code.", "response": "def fetch_gsm8k(out: Path, max_mb: float = 8.0) -> tuple[int, int]:\n \"\"\"Grade-school math word problems with worked solutions (MIT licence).\"\"\"\n dest = out / \"math\" / \"gsm8k.jsonl\"\n dest.parent.mkdir(parents=True, exist_ok=True)\n docs = 0\n written = 0\n limit = int(max_mb * MB)\n with dest.open(\"w\", encoding=\"utf-8\", newline=\"\\n\") as fh:\n for url in GSM8K_URLS:\n if written >= limit:\n break\n try:\n raw = _http_text(url)\n except Exception as exc: # noqa: BLE001\n print(f\" math: could not download {url.split('/')[-1]}: {exc}\")\n continue\n for line in raw.splitlines():\n if not line.strip():\n continue\n try:\n row = json.loads(line)\n except ValueError:\n continue\n question = (row.get(\"question\") or \"\").strip()\n answer = (row.get(\"answer\") or \"\").strip()\n if not question or not answer:\n continue\n body = f\"Question: {question}\\nAnswer: {answer}\\n\"\n out_line = json.dumps({\"text\": body}, ensure_ascii=False) + \"\\n\"\n fh.write(out_line)\n written += len(out_line.encode(\"utf-8\"))\n docs += 1\n if written >= limit:\n break\n print(f\" math: {docs} worked problems, {written / MB:.2f} MB -> {dest}\")\n return docs, written", "source_file": "world_knowledge.py", "function_name": "fetch_gsm8k", "class_name": null, "line_start": 495, "line_end": 530, "license": "mit", "source": "SadikAI project"}
{"task": "code_completion", "language": "python", "instruction": "Complete the following Python code. Return only the continuation, preserving indentation.\n\n```python\ndef fetch_code_extra(out: Path, max_mb: float = 12.0) -> tuple[int, int]:\n \"\"\"Add real-world library code (torch, numpy, ...) from this venv.\"\"\"\n roots = [\n Path(\".venv/Lib/site-packages/torch\"),\n Path(\".venv/Lib/site-packages/numpy\"),\n Path(\".venv/Lib/site-packages/tokenizers\"),\n Path(\".venv/Lib/site-packages/pyarrow\"),\n ]\n dest = out / \"code\" / \"site_packages.jsonl\"\n dest.parent.mkdir(parents=True, exist_ok=True)\n seen: set[str] = set()\n docs = 0\n written = 0\n limit = int(max_mb * MB)\n skip = {\"tests\", \"test\", \"__pycache__\", \"third_party\", \"benchmarks\"}\n```", "response": " with dest.open(\"w\", encoding=\"utf-8\", newline=\"\\n\") as fh:\n for root in roots:\n if not root.exists() or written >= limit:\n continue\n for path in root.rglob(\"*.py\"):\n if written >= limit:\n break\n if any(part.lower() in skip for part in path.parts):\n continue\n try:\n if path.stat().st_size > 200_000:\n continue\n text = path.read_text(encoding=\"utf-8\", errors=\"ignore\")\n except OSError:\n continue\n if len(text) < 300:\n continue\n head = f\"# {path.relative_to(Path('.venv/Lib/site-packages'))}\\n\"\n body = head + text\n key = body[:200]\n if key in seen:\n continue\n seen.add(key)\n line = json.dumps({\"text\": body}, ensure_ascii=False) + \"\\n\"\n fh.write(line)\n written += len(line.encode(\"utf-8\"))\n docs += 1\n print(f\" code: {docs} files, {written / MB:.1f} MB\", end=\"\\r\",\n flush=True)\n\n print(f\" code: {docs} files, {written / MB:.1f} MB -> {dest}\")\n return docs, written", "source_file": "world_knowledge.py", "function_name": "fetch_code_extra", "class_name": null, "line_start": 533, "line_end": 580, "license": "mit", "source": "SadikAI project"}
{"task": "code_explanation", "language": "python", "instruction": "Explain what this Python function does.\n\n```python\ndef fetch_code_extra(out: Path, max_mb: float = 12.0) -> tuple[int, int]:\n \"\"\"Add real-world library code (torch, numpy, ...) from this venv.\"\"\"\n roots = [\n Path(\".venv/Lib/site-packages/torch\"),\n Path(\".venv/Lib/site-packages/numpy\"),\n Path(\".venv/Lib/site-packages/tokenizers\"),\n Path(\".venv/Lib/site-packages/pyarrow\"),\n ]\n dest = out / \"code\" / \"site_packages.jsonl\"\n dest.parent.mkdir(parents=True, exist_ok=True)\n seen: set[str] = set()\n docs = 0\n written = 0\n limit = int(max_mb * MB)\n skip = {\"tests\", \"test\", \"__pycache__\", \"third_party\", \"benchmarks\"}\n\n with dest.open(\"w\", encoding=\"utf-8\", newline=\"\\n\") as fh:\n for root in roots:\n if not root.exists() or written >= limit:\n continue\n for path in root.rglob(\"*.py\"):\n if written >= limit:\n break\n if any(part.lower() in skip for part in path.parts):\n continue\n try:\n if path.stat().st_size > 200_000:\n continue\n text = path.read_text(encoding=\"utf-8\", errors=\"ignore\")\n except OSError:\n continue\n if len(text) < 300:\n continue\n head = f\"# {path.relative_to(Path('.venv/Lib/site-packages'))}\\n\"\n body = head + text\n key = body[:200]\n if key in seen:\n continue\n seen.add(key)\n line = json.dumps({\"text\": body}, ensure_ascii=False) + \"\\n\"\n fh.write(line)\n written += len(line.encode(\"utf-8\"))\n docs += 1\n print(f\" code: {docs} files, {written / MB:.1f} MB\", end=\"\\r\",\n flush=True)\n\n print(f\" code: {docs} files, {written / MB:.1f} MB -> {dest}\")\n return docs, written\n```", "response": "Add real-world library code (torch, numpy, ...) from this venv.", "source_file": "world_knowledge.py", "function_name": "fetch_code_extra", "class_name": null, "line_start": 533, "line_end": 580, "license": "mit", "source": "SadikAI project"}
{"task": "code_generation", "language": "python", "instruction": "Write a Python function `fetch_code_extra(out: Path, max_mb: float=12.0)` that does the following:\n\nAdd real-world library code (torch, numpy, ...) from this venv.\n\nReturn only the Python code.", "response": "def fetch_code_extra(out: Path, max_mb: float = 12.0) -> tuple[int, int]:\n \"\"\"Add real-world library code (torch, numpy, ...) from this venv.\"\"\"\n roots = [\n Path(\".venv/Lib/site-packages/torch\"),\n Path(\".venv/Lib/site-packages/numpy\"),\n Path(\".venv/Lib/site-packages/tokenizers\"),\n Path(\".venv/Lib/site-packages/pyarrow\"),\n ]\n dest = out / \"code\" / \"site_packages.jsonl\"\n dest.parent.mkdir(parents=True, exist_ok=True)\n seen: set[str] = set()\n docs = 0\n written = 0\n limit = int(max_mb * MB)\n skip = {\"tests\", \"test\", \"__pycache__\", \"third_party\", \"benchmarks\"}\n\n with dest.open(\"w\", encoding=\"utf-8\", newline=\"\\n\") as fh:\n for root in roots:\n if not root.exists() or written >= limit:\n continue\n for path in root.rglob(\"*.py\"):\n if written >= limit:\n break\n if any(part.lower() in skip for part in path.parts):\n continue\n try:\n if path.stat().st_size > 200_000:\n continue\n text = path.read_text(encoding=\"utf-8\", errors=\"ignore\")\n except OSError:\n continue\n if len(text) < 300:\n continue\n head = f\"# {path.relative_to(Path('.venv/Lib/site-packages'))}\\n\"\n body = head + text\n key = body[:200]\n if key in seen:\n continue\n seen.add(key)\n line = json.dumps({\"text\": body}, ensure_ascii=False) + \"\\n\"\n fh.write(line)\n written += len(line.encode(\"utf-8\"))\n docs += 1\n print(f\" code: {docs} files, {written / MB:.1f} MB\", end=\"\\r\",\n flush=True)\n\n print(f\" code: {docs} files, {written / MB:.1f} MB -> {dest}\")\n return docs, written", "source_file": "world_knowledge.py", "function_name": "fetch_code_extra", "class_name": null, "line_start": 533, "line_end": 580, "license": "mit", "source": "SadikAI project"}
{"task": "code_completion", "language": "python", "instruction": "Complete the following Python code. Return only the continuation, preserving indentation.\n\n```python\ndef main() -> None:\n if hasattr(sys.stdout, \"reconfigure\"):\n sys.stdout.reconfigure(encoding=\"utf-8\", errors=\"replace\")\n\n ap = argparse.ArgumentParser(description=__doc__,\n formatter_class=argparse.RawDescriptionHelpFormatter)\n ap.add_argument(\"--out\", default=\"data/raw\")\n ap.add_argument(\"--domains\", default=\"people,animals,space,science,math,general\",\n help=\"comma list: people,animals,space,science,math,general,code\")\n ap.add_argument(\"--max-chars\", type=int, default=12_000,\n help=\"trim each article to this many characters\")\n ap.add_argument(\"--code-extra\", action=\"store_true\",\n help=\"also add library sources from .venv (torch, numpy, ...)\")\n ap.add_argument(\"--code-mb\", type=float, default=12.0)\n ap.add_argument(\"--math-datasets\", action=\"store_true\",\n help=\"also download GSM8K worked math problems\")\n ap.add_argument(\"--math-mb\", type=float, default=8.0)\n ap.add_argument(\"--workers\", type=int, default=4,\n help=\"parallel Wikipedia requests (be polite: 2-5)\")\n ap.add_argument(\"--intros-missing\", action=\"store_true\",\n help=\"fast fill: keep cached full articles, batch-fetch lead \"\n \"sections for the rest (20 titles per request)\")\n args = ap.parse_args()\n\n lists = {\"people\": PEOPLE, \"animals\": ANIMALS, \"space\": SPACE,\n \"science\": SCIENCE, \"math\": MATH, \"general\": GENERAL}\n wanted = [d.strip() for d in args.domains.split(\",\") if d.strip()]\n out = Path(args.out)\n cache = Path(\"data/cache/world\")\n cache.mkdir(parents=True, exist_ok=True)\n\n print(f\"world knowledge -> {out}/ domains: {', '.join(wanted)}\")\n total_docs = 0\n```", "response": " total_bytes = 0\n\n wiki_domains = [d for d in wanted if d in lists]\n unknown = [d for d in wanted if d not in lists and d != \"code\"]\n for domain in unknown:\n print(f\" unknown domain {domain!r}, skipping\")\n\n if wiki_domains:\n if args.intros_missing:\n docs, size = fill_missing(lists, wiki_domains, out, args.max_chars,\n cache)\n else:\n docs, size = fetch_world(lists, wiki_domains, out, args.max_chars,\n cache / \"articles\", args.workers)\n total_docs += docs\n total_bytes += size\n\n if \"code\" in wanted:\n docs, size = fetch_code_extra(out, args.code_mb)\n total_docs += docs\n total_bytes += size\n\n if args.math_datasets:\n docs, size = fetch_gsm8k(out, args.math_mb)\n total_docs += docs\n total_bytes += size\n\n if args.code_extra and \"code\" not in wanted:\n docs, size = fetch_code_extra(out, args.code_mb)\n total_docs += docs\n total_bytes += size\n\n print(f\"\\ndone: {total_docs} new documents, {total_bytes / MB:.1f} MB\")\n print(\"next: python prepare_data.py --input data/raw --tokenizer \"\n \"tokenizer/tokenizer.json --out-dir data/tokenized --overwrite\")", "source_file": "world_knowledge.py", "function_name": "main", "class_name": null, "line_start": 583, "line_end": 650, "license": "mit", "source": "SadikAI project"}
|