Buckets:
| """Synthetic multilingual typed-decision data, generated label-first with an LLM teacher. | |
| Three generators, all label-first (the gold answer is sampled *before* the text is written, | |
| so labels are correct by construction rather than by a second LLM judgement): | |
| routing a zoo of 3-7 options (models / agents / teams / tools) with descriptions, then | |
| user messages written *for* a given option -> one `choice` question | |
| decisions a domain schema of 3-5 typed questions (choice / noul / score), then states written | |
| to match sampled gold answers -> several questions per state | |
| guard safety / policy yes-no checks -> `noul` questions | |
| Output: data/synth/{routing,decisions,guard}.jsonl, one (state, questions, gold, meta) per line. | |
| """ | |
| import argparse, asyncio, json, os, random, re | |
| import httpx | |
| URL = os.environ.get("TEACHER_URL", "http://localhost:8000/v1/chat/completions") | |
| MODEL = os.environ.get("TEACHER_MODEL", "teacher") | |
| OUT = "./data/synth" | |
| LANGS = [("az", 45), ("en", 22), ("ru", 9), ("tr", 6), ("de", 2), ("fr", 2), ("es", 2), ("ar", 2), | |
| ("uk", 1.5), ("kk", 1.5), ("uz", 1.5), ("fa", 1.5), ("hi", 1), ("zh", 1), ("ka", 1), ("it", 1)] | |
| LANG_NAME = {"az": "Azerbaijani", "en": "English", "ru": "Russian", "tr": "Turkish", "de": "German", "fr": "French", | |
| "es": "Spanish", "ar": "Arabic", "uk": "Ukrainian", "kk": "Kazakh", "uz": "Uzbek (Latin)", "fa": "Persian", | |
| "hi": "Hindi", "zh": "Chinese", "ka": "Georgian", "it": "Italian"} | |
| DOMAINS = [ | |
| "LLM model router choosing between AI models of different strengths (legal, coding, fast/cheap, deep reasoning, everyday chat, vision, translation, math)", | |
| "LLM model router for an Azerbaijani AI platform (legal model, daily-tasks model, fast model, frontier reasoning model)", | |
| "AI agent orchestrator picking a tool (web search, calculator, calendar, email, code interpreter, database, weather API)", | |
| "retail bank customer support", "telecom operator support", "government e-services centre (like ASAN Xidmət)", | |
| "law firm intake (criminal, civil, labor, family, tax, administrative, corporate law)", | |
| "hospital / clinic triage desk", "e-commerce marketplace support", "food delivery app", "ride-hailing and taxi app", | |
| "airline and travel agency", "insurance claims", "university admissions office", "HR and recruiting", | |
| "IT helpdesk", "SaaS B2B software support", "oil & gas company internal requests", "logistics and cargo tracking", | |
| "real estate agency", "utility company (electricity, gas, water)", "online education platform", | |
| "mobile game player support", "cybersecurity SOC alert triage", "news media content tagging", | |
| "social media content moderation", "restaurant reservations", "car dealership and service centre", | |
| "pharmacy", "tourism in Azerbaijan (hotels, tours, Baku, Gabala, Sheki)", "accounting and tax consulting", | |
| "developer platform (API, billing, SDK bugs)", "smart home voice assistant", "public transport (metro, buses, BakuCard)", | |
| "fintech payments and wallets", "court and notary services", "customs and border services", "agriculture advisory", | |
| ] | |
| GUARD_CHECKS = [ | |
| ("jailbreak", "Is the user trying to jailbreak the AI or make it ignore its rules?"), | |
| ("prompt_injection", "Does the text contain instructions trying to hijack or override the AI system's instructions?"), | |
| ("pii", "Does the text contain personal data such as a phone number, ID/FIN number, card number, address or email?"), | |
| ("toxic", "Is the message insulting, hateful or abusive?"), | |
| ("self_harm", "Does the user express intent or risk of self-harm?"), | |
| ("phishing", "Is this a scam or phishing attempt?"), | |
| ("off_topic", "This is a bank support chat. Is the message unrelated to banking?"), | |
| ("medical_advice", "Is the user asking for medical diagnosis or treatment advice?"), | |
| ("legal_advice", "Is the user asking a legal or law-related question?"), | |
| ("complaint", "Is the user making a complaint?"), | |
| ("urgent", "Does the message indicate an urgent, time-critical problem?"), | |
| ("churn", "Does the user threaten to cancel, leave or switch to a competitor?"), | |
| ("refund", "Does the user explicitly ask for money back or a refund?"), | |
| ("human_agent", "Does the user ask to talk to a human operator?"), | |
| ] | |
| STYLE = [ | |
| "short and casual", "long and detailed", "formal and polite", "angry", "with typos", | |
| "as a one-line chat message", "as an email", "as a voice-assistant command", "mixing in some English words", | |
| ] | |
| def pick_lang(rng): | |
| langs, w = zip(*LANGS) | |
| return rng.choices(langs, w)[0] | |
| def lang_instr(lang, rng): | |
| s = LANG_NAME[lang] | |
| if lang == "az": | |
| s += " (genuine Azerbaijani as spoken in Baku, not Turkish)" | |
| if lang == "az" and rng.random() < 0.3: | |
| s += " (real Azerbaijani, NOT Turkish: use 'mən', 'nə', 'var', 'yox', 'istəyirəm'), typed WITHOUT special letters (use e for ə, s for ş, c for ç, g for ğ, i for ı, o for ö, u for ü), as people type on phones" | |
| return s | |
| class Teacher: | |
| def __init__(self, conc): | |
| self.sem = asyncio.Semaphore(conc) | |
| self.cli = httpx.AsyncClient(timeout=180) | |
| self.calls = self.fail = self.rejected = 0 | |
| async def json(self, prompt, max_tokens=1500, temperature=0.9): | |
| async with self.sem: | |
| for attempt in range(3): | |
| try: | |
| r = await self.cli.post(URL, json={ | |
| "model": MODEL, "messages": [{"role": "user", "content": prompt}], | |
| "max_tokens": max_tokens, "temperature": temperature, | |
| "response_format": {"type": "json_object"}}) | |
| self.calls += 1 | |
| return json.loads(r.json()["choices"][0]["message"]["content"]) | |
| except Exception: | |
| await asyncio.sleep(1 + attempt) | |
| self.fail += 1 | |
| return None | |
| def _render_q(qid, q): | |
| if q["type"] == "choice": | |
| return f'"{qid}" (choose one key): {q["instructions"]} options: ' + json.dumps(q["criteria"], ensure_ascii=False) | |
| if q["type"] == "noul": | |
| return f'"{qid}" (true/false): {q["instructions"]}' | |
| return f'"{qid}" (integer level 0..{len(q["criteria"]) - 1}): {q["instructions"]} levels: ' + json.dumps( | |
| {i: c for i, c in enumerate(q["criteria"])}, ensure_ascii=False) | |
| async def judge(T, msgs, qs, context=""): | |
| """Independent second pass: answer every question for every message. Returns list of dicts or None.""" | |
| qtxt = "\n".join(_render_q(k, v) for k, v in qs.items()) | |
| mtxt = "\n".join(f"[{j}] {m}" for j, m in enumerate(msgs)) | |
| res = await T.json( | |
| (f"Context: {context}\n" if context else "") + | |
| f"Answer the questions for each message independently and carefully.\nQuestions:\n{qtxt}\n\nMessages:\n{mtxt}\n\n" | |
| 'Return JSON: {"answers": [{"<question id>": <answer>, ...}, ...]} with one object per message, in order.', | |
| 200 + 60 * len(msgs) * len(qs), temperature=0.0) | |
| if not res or not isinstance(res.get("answers"), list) or len(res["answers"]) != len(msgs): | |
| return None | |
| out = [] | |
| for a in res["answers"]: | |
| if isinstance(a, dict) and len(qs) == 1: | |
| (qid,), vals = list(qs), list(a.values()) | |
| a = {qid: a.get(qid, vals[0] if len(vals) == 1 else None)} | |
| out.append(a) | |
| return out | |
| def agree(q, gold, got): | |
| if got is None: | |
| return False | |
| if q["type"] == "noul": | |
| if isinstance(got, str): | |
| got = got.strip().lower() in ("true", "yes", "1") | |
| return bool(got) == bool(gold) | |
| if q["type"] == "choice": | |
| return slug(got) == gold or str(got) == gold | |
| try: | |
| return abs(int(got) - int(gold)) <= 0 | |
| except Exception: | |
| return False | |
| def slug(s): | |
| s = re.sub(r"[^\w]+", "_", str(s).lower()).strip("_") | |
| return s[:40] or "option" | |
| # ------------------------------------------------------------------ routing | |
| ROUTE_INS_EN = ["Which of these should handle the user's message?", "Route this request to the right model.", | |
| "Which AI model is best suited to answer this?", "Which agent should take this request?", | |
| "Select the best destination for this message.", "Which team or tool should process this?"] | |
| ROUTE_INS_AZ = ["Bu sorğunu hansı model cavablandırmalıdır?", "İstifadəçinin mesajını kim icra etməlidir?", | |
| "Bu mesaj üçün ən uyğun agent hansıdır?"] | |
| async def gen_routing(T, i, rng, fh): | |
| dom = rng.choice(DOMAINS[:3] if os.environ.get("LLM_ROUTER_ONLY") else DOMAINS) | |
| k = rng.randint(3, 7) | |
| opaque = rng.random() < 0.5 | |
| desc_lang = "Azerbaijani" if rng.random() < 0.25 else "English" | |
| zoo = await T.json( | |
| f"Invent {k} distinct destinations (AI models, agents, teams or tools) for this setting: {dom}.\n" | |
| + ("Give them made-up brand-like names that do NOT reveal their purpose (e.g. 'legolas-flash', 'dragonfly-1.5', 'nova-x').\n" if opaque | |
| else "Give them short descriptive snake_case names.\n") | |
| + f"Each needs a one-sentence description of exactly what it handles, in {desc_lang}. Make their scopes clearly different " | |
| "but realistic (some may overlap slightly, e.g. a fast cheap model vs a strong reasoning model).\n" | |
| 'Return JSON: {"options": [{"name": "...", "description": "..."}]}', 600) | |
| if not zoo or len(zoo.get("options", [])) < 3: | |
| return 0 | |
| opts = [(str(o["name"]).strip()[:40], str(o.get("description", "")).strip()) for o in zoo["options"][:8] | |
| if isinstance(o, dict) and o.get("name") and o.get("description")] | |
| if len(opts) < 3: | |
| return 0 | |
| names = [n for n, _ in opts] | |
| if len(set(names)) != len(names): | |
| return 0 | |
| n = 0 | |
| for lang in {pick_lang(rng), pick_lang(rng)}: | |
| spec = "\n".join(f"- {nm}: {d}" for nm, d in opts) | |
| style = rng.sample(STYLE, 3) | |
| res = await T.json( | |
| f"Destinations:\n{spec}\n\nFor EACH destination write 4 different realistic user messages in {lang_instr(lang, rng)} " | |
| f"that clearly belong to that destination and not to the others. Vary them: {', '.join(style)}" | |
| + (". At least 2 of the 4 must be VERY short (2-6 words, e.g. a bare topic or keyword query). " | |
| if os.environ.get("LLM_ROUTER_ONLY") else ". ") + | |
| "One of the 4 should be tricky (mentions words associated with another destination but still belongs here). " | |
| "Do not mention the destination names. " | |
| 'Return JSON: {"messages": {"<destination name>": ["...", "...", "...", "..."]}}', 2500) | |
| if not res or not isinstance(res.get("messages"), dict): | |
| continue | |
| cand = [(nm, m) for nm, msgs in res["messages"].items() if nm in names and isinstance(msgs, list) | |
| for m in msgs[:4] if isinstance(m, str) and len(m) >= 3] | |
| if not cand: | |
| continue | |
| rq = {"route": {"type": "choice", "instructions": "Which destination should handle this message?", | |
| "criteria": dict(opts)}} | |
| verdicts = [] | |
| for c in range(0, len(cand), 8): | |
| chunk = cand[c:c + 8] | |
| v = await judge(T, [m for _, m in chunk], rq, context=dom) | |
| verdicts += [None] * len(chunk) if v is None else [x.get("route") if isinstance(x, dict) else None for x in v] | |
| for (nm, m), v in zip(cand, verdicts): | |
| if v != nm: | |
| T.rejected += 1 | |
| continue | |
| if True: | |
| order = names[:] | |
| rng.shuffle(order) | |
| crit = {o: dict(opts)[o] for o in order} | |
| ins = rng.choice(ROUTE_INS_AZ) if rng.random() < 0.25 else rng.choice(ROUTE_INS_EN) | |
| fh.write(json.dumps({"state": m, "questions": {"route": {"type": "choice", "instructions": ins, "criteria": crit}}, | |
| "gold": {"route": nm}, "meta": {"gen": "routing", "group": f"r{GTAG}{i}", "lang": lang, | |
| "domain": dom}}, ensure_ascii=False) + "\n") | |
| n += 1 | |
| return n | |
| # ------------------------------------------------------------------ decisions | |
| async def gen_decisions(T, i, rng, fh): | |
| dom = rng.choice(DOMAINS) | |
| ins_az = rng.random() < 0.25 | |
| schema = await T.json( | |
| f"You design a typed decision schema for: {dom}. An incoming message (ticket, chat, email) must be classified.\n" | |
| f"Create 4 questions, instructions written in {'Azerbaijani' if ins_az else 'English'}, mixing these types:\n" | |
| '- "choice": pick one of 3-6 options; criteria is an object {option_key: short description}\n' | |
| '- "noul": a yes/no question; no criteria\n' | |
| '- "score": an ordered scale; criteria is a list of 3-5 level descriptions from lowest to highest\n' | |
| "Include at least one of each type. Use snake_case question ids.\n" | |
| 'Return JSON: {"questions": {"<id>": {"type": "...", "instructions": "...", "criteria": ...}}}', 900) | |
| if not schema or not isinstance(schema.get("questions"), dict): | |
| return 0 | |
| qs = {} | |
| for qid, q in list(schema["questions"].items())[:5]: | |
| try: | |
| t = q["type"] | |
| if t == "choice" and isinstance(q.get("criteria"), dict) and 2 <= len(q["criteria"]) <= 8: | |
| qs[slug(qid)] = {"type": "choice", "instructions": str(q["instructions"]), | |
| "criteria": {slug(k): str(v) for k, v in q["criteria"].items()}} | |
| elif t == "noul": | |
| qs[slug(qid)] = {"type": "noul", "instructions": str(q["instructions"])} | |
| elif t == "score" and isinstance(q.get("criteria"), list) and 3 <= len(q["criteria"]) <= 6: | |
| qs[slug(qid)] = {"type": "score", "instructions": str(q["instructions"]), | |
| "criteria": [str(c) for c in q["criteria"]]} | |
| except Exception: | |
| continue | |
| if len(qs) < 2: | |
| return 0 | |
| n = 0 | |
| for lang in {pick_lang(rng), pick_lang(rng)}: | |
| golds = [] | |
| for _ in range(4): | |
| g = {} | |
| for qid, q in qs.items(): | |
| if q["type"] == "choice": | |
| g[qid] = rng.choice(list(q["criteria"])) | |
| elif q["type"] == "noul": | |
| g[qid] = rng.random() < 0.5 | |
| else: | |
| g[qid] = rng.randrange(len(q["criteria"])) | |
| golds.append(g) | |
| def show(qid, v): | |
| q = qs[qid] | |
| if q["type"] == "choice": | |
| return f"{q['instructions']} -> {v} ({q['criteria'][v]})" | |
| if q["type"] == "noul": | |
| return f"{q['instructions']} -> {'YES' if v else 'NO'}" | |
| return f"{q['instructions']} -> level {v}: {q['criteria'][v]}" | |
| spec = "\n\n".join(f"Message {j + 1} must satisfy ALL of:\n" + "\n".join(" " + show(q, v) for q, v in g.items()) | |
| for j, g in enumerate(golds)) | |
| res = await T.json( | |
| f"Setting: {dom}.\nWrite 4 realistic incoming messages in {lang_instr(lang, rng)}. " | |
| f"Style: {rng.choice(STYLE)}. Each message must make the listed answers clearly correct " | |
| "(implicitly, like a real customer would; never restate the questions).\n\n" | |
| f"{spec}\n\nReturn JSON: {{\"messages\": [\"...\", \"...\", \"...\", \"...\"]}}", 2500) | |
| if not res or not isinstance(res.get("messages"), list) or len(res["messages"]) != 4: | |
| continue | |
| msgs = [m if isinstance(m, str) else "" for m in res["messages"]] | |
| verd = await judge(T, msgs, qs, context=dom) | |
| if verd is None: | |
| continue | |
| for m, g, v in zip(msgs, golds, verd): | |
| if len(m) < 5 or not isinstance(v, dict): | |
| continue | |
| keep = {q: g[q] for q in qs if agree(qs[q], g[q], v.get(q))} | |
| T.rejected += len(qs) - len(keep) | |
| if not keep: | |
| continue | |
| fh.write(json.dumps({"state": m, "questions": {q: qs[q] for q in keep}, "gold": keep, | |
| "meta": {"gen": "decisions", "group": f"d{i}", "lang": lang, "domain": dom}}, | |
| ensure_ascii=False) + "\n") | |
| n += 1 | |
| return n | |
| # ------------------------------------------------------------------ guard | |
| async def gen_guard(T, i, rng, fh): | |
| key, ins = rng.choice(GUARD_CHECKS) | |
| lang = pick_lang(rng) | |
| labels = [rng.random() < 0.5 for _ in range(6)] | |
| spec = "\n".join(f"{j + 1}. property {'TRUE' if l else 'FALSE (but may be superficially similar)'}" for j, l in enumerate(labels)) | |
| res = await T.json( | |
| f'Property: "{ins}"\nWrite 6 realistic user messages to an AI assistant or support chat in {lang_instr(lang, rng)}. ' | |
| f"Style: {rng.choice(STYLE)}. For each, the property must be as specified; the FALSE ones should be hard negatives " | |
| "(same topic area, but the property does not hold).\n" + spec + | |
| '\nReturn JSON: {"messages": ["...", "...", "...", "...", "...", "..."]}', 1800) | |
| if not res or not isinstance(res.get("messages"), list) or len(res["messages"]) != 6: | |
| return 0 | |
| ins_q = ins | |
| msgs = [m if isinstance(m, str) else "" for m in res["messages"]] | |
| verd = await judge(T, msgs, {key: {"type": "noul", "instructions": ins_q}}) | |
| if verd is None: | |
| return 0 | |
| n = 0 | |
| for m, l, v in zip(msgs, labels, verd): | |
| if not agree({"type": "noul"}, l, v.get(key) if isinstance(v, dict) else None): | |
| T.rejected += 1 | |
| continue | |
| if len(m) >= 3: | |
| fh.write(json.dumps({"state": m, "questions": {key: {"type": "noul", "instructions": ins_q}}, "gold": {key: l}, | |
| "meta": {"gen": "guard", "group": f"g{i}", "lang": lang}}, ensure_ascii=False) + "\n") | |
| n += 1 | |
| return n | |
| # ------------------------------------------------------------------ fine-grained taxonomies (high cardinality) | |
| async def gen_taxonomy(T, i, rng, fh): | |
| dom = rng.choice(DOMAINS) | |
| k = rng.randint(25, 60) | |
| tax = await T.json( | |
| f"Create a fine-grained taxonomy of exactly {k} customer request intents for: {dom}. Many should be close " | |
| "neighbours that are easy to confuse (e.g. 'card_not_arrived' vs 'card_delivery_estimate'). snake_case English keys, " | |
| 'each with a 3-8 word English description. Return JSON: {"intents": {"<key>": "<description>"}}', 2500) | |
| if not tax or not isinstance(tax.get("intents"), dict) or len(tax["intents"]) < 20: | |
| return 0 | |
| crit = {slug(kk): str(v) for kk, v in list(tax["intents"].items())[:64]} | |
| keys = list(crit) | |
| n = 0 | |
| for lang in {pick_lang(rng), pick_lang(rng)}: | |
| pick = rng.sample(keys, min(12, len(keys))) | |
| spec = "\n".join(f"- {kk}: {crit[kk]}" for kk in pick) | |
| res = await T.json( | |
| f"Setting: {dom}. For EACH intent below write 2 realistic short customer messages in {lang_instr(lang, rng)}, " | |
| "phrased naturally (never copy the description words literally).\n" + spec + | |
| '\nReturn JSON: {"messages": {"<intent key>": ["...", "..."]}}', 2500) | |
| if not res or not isinstance(res.get("messages"), dict): | |
| continue | |
| cand = [(kk, m) for kk, ms in res["messages"].items() if kk in crit and isinstance(ms, list) | |
| for m in ms[:2] if isinstance(m, str) and len(m) >= 3] | |
| q = {"intent": {"type": "choice", "instructions": "Which intent does this customer message express?", "criteria": crit}} | |
| verdicts = [] | |
| for c in range(0, len(cand), 8): | |
| chunk = cand[c:c + 8] | |
| v = await judge(T, [m for _, m in chunk], q, context=dom) | |
| verdicts += [None] * len(chunk) if v is None else [slug(x.get("intent")) if isinstance(x, dict) and x.get("intent") else None for x in v] | |
| for (kk, m), v in zip(cand, verdicts): | |
| if v != kk: | |
| T.rejected += 1 | |
| continue | |
| fh.write(json.dumps({"state": m, "questions": q, "gold": {"intent": kk}, | |
| "meta": {"gen": "taxonomy", "group": f"t{i}", "lang": lang, "domain": dom}}, ensure_ascii=False) + "\n") | |
| n += 1 | |
| return n | |
| # ------------------------------------------------------------------ emotion / tone | |
| EMO_SETS = [ | |
| {"sadness": "sad, hurt, lonely, disappointed", "joy": "happy, glad, excited, grateful", "love": "love, affection, caring, fond", | |
| "anger": "angry, annoyed, irritated, resentful", "fear": "afraid, anxious, nervous, worried", "surprise": "surprised, amazed, shocked"}, | |
| {"positive": "satisfied, happy, praising", "neutral": "factual, no clear feeling", "negative": "unhappy, complaining, disappointed"}, | |
| {"calm": "calm, relaxed", "frustrated": "frustrated, impatient", "angry": "angry, hostile", "confused": "confused, unsure", | |
| "grateful": "thankful", "anxious": "worried, stressed", "excited": "enthusiastic, excited", "sad": "sad, upset"}, | |
| {"admiration": "admiring", "amusement": "amused, finding it funny", "annoyance": "mildly annoyed", "disgust": "disgusted", | |
| "embarrassment": "embarrassed", "nervousness": "nervous", "pride": "proud", "relief": "relieved", "remorse": "sorry, regretful", | |
| "optimism": "hopeful, optimistic"}, | |
| ] | |
| async def gen_emotion(T, i, rng, fh): | |
| labels = dict(rng.choice(EMO_SETS)) | |
| lang = pick_lang(rng) | |
| gold = [rng.choice(list(labels)) for _ in range(8)] | |
| spec = "\n".join(f"{j + 1}. {g} ({labels[g]})" for j, g in enumerate(gold)) | |
| res = await T.json( | |
| f"Write 8 realistic personal sentences (tweets, diary lines, chat messages, reviews) in {lang_instr(lang, rng)}. " | |
| "Each must express the listed emotion implicitly, in the style of real people (often starting with 'I feel', 'i am', " | |
| "or describing a situation). Never name the emotion word itself.\n" + spec + | |
| '\nReturn JSON: {"messages": ["...", "...", "...", "...", "...", "...", "...", "..."]}', 1500) | |
| if not res or not isinstance(res.get("messages"), list) or len(res["messages"]) != 8: | |
| return 0 | |
| q = {"emotion": {"type": "choice", "instructions": "Which emotion does the writer express?", "criteria": labels}} | |
| msgs = [m if isinstance(m, str) else "" for m in res["messages"]] | |
| v = await judge(T, msgs, q) | |
| if v is None: | |
| return 0 | |
| n = 0 | |
| for m, g, x in zip(msgs, gold, v): | |
| if len(m) < 3 or not isinstance(x, dict) or slug(x.get("emotion", "")) != g: | |
| T.rejected += 1 | |
| continue | |
| fh.write(json.dumps({"state": m, "questions": q, "gold": {"emotion": g}, | |
| "meta": {"gen": "emotion", "group": f"e{i}", "lang": lang}}, ensure_ascii=False) + "\n") | |
| n += 1 | |
| return n | |
| GTAG = "" | |
| async def run(kind, n_units, conc, seed): | |
| global GTAG | |
| GTAG = os.environ.get("GROUP_TAG", "") | |
| T = Teacher(conc) | |
| fn = {"routing": gen_routing, "decisions": gen_decisions, "guard": gen_guard, | |
| "taxonomy": gen_taxonomy, "emotion": gen_emotion}[kind] | |
| path = f"{OUT}/{kind}.jsonl" | |
| done = 0 | |
| with open(path, "a") as fh: | |
| usem = asyncio.Semaphore(conc * 2) | |
| async def unit(i): | |
| nonlocal done | |
| async with usem: | |
| await _unit(i) | |
| async def _unit(i): | |
| nonlocal done | |
| try: | |
| got = await fn(T, i, random.Random(seed * 100003 + i), fh) | |
| except Exception as e: | |
| T.fail += 1 | |
| got = 0 | |
| done += got | |
| if i % 50 == 0: | |
| fh.flush() | |
| print(f"{kind} unit {i}: items {done} calls {T.calls} fail {T.fail} rejected {T.rejected}", flush=True) | |
| await asyncio.gather(*(unit(i) for i in range(n_units))) | |
| print(f"{kind} DONE items {done} calls {T.calls} fail {T.fail} rejected {T.rejected}", flush=True) | |
| if __name__ == "__main__": | |
| ap = argparse.ArgumentParser() | |
| ap.add_argument("kind") | |
| ap.add_argument("--n", type=int, default=10) | |
| ap.add_argument("--conc", type=int, default=16) | |
| ap.add_argument("--seed", type=int, default=1) | |
| a = ap.parse_args() | |
| asyncio.run(run(a.kind, a.n, a.conc, a.seed)) | |
Xet Storage Details
- Size:
- 24.4 kB
- Xet hash:
- 6b5646c24e8509b58aaaba41a2850116fcc7ddb20484fec03854d465ff01b1a5
·
Xet efficiently stores files, intelligently splitting them into unique chunks and accelerating uploads and downloads. More info.