Upload code/build_sft_v18_dataset.py with huggingface_hub
Browse files158 unmodified lines1591601611621631641657 unmodified lines173174175176177178348 unmodified lines527528529530531532116 unmodified lines64965065165265365465565610 unmodified lines66766866967067167267367486 unmodified lines7617627637647657667674 unmodified lines772773774775776777158 unmodified lines# ------------------------------------------------------------------------------# 4. Strict Deduplication & Formatting Engine# ------------------------------------------------------------------------------GLOBAL_SEEN_HASHES = set()7 unmodified linesreturn False# ------------------------------------------------------------------------------# 5. Real-World Open-Source Dataset Ingestion Functions# ------------------------------------------------------------------------------348 unmodified linesreturn samplesdef get_curated_identity_and_greetings_pack(target_count=3500) -> list:"""Curates distinct, non-repeating greetings (Eng, Hin, Hinglish) and ViuAI Sarus persona anchors."""print(f"⬇️ Curating Distinct Persona & Clean Salutations (Target: {target_count:,} unique)...")116 unmodified linesif "conversations" in item:# Multi-Turn Conversationfor turn_idx, (u_msg, th_msg, a_msg) in enumerate(item["conversations"]):# Format user turnu_clean = u_msg.strip()u_turn_text = f"{USER_TOKEN}\n{u_clean}{EOT_TOKEN}\n{ASSISTANT_TOKEN}\n"u_ids = TOKENIZER.encode(u_turn_text, add_special_tokens=False)10 unmodified linesfull_ids.extend(a_ids)labels.extend(a_ids)else:# Single-Turn Interactioninst = item["instruction"].strip()th = item.get("thinking", "").strip()resp = item["response"].strip()86 unmodified linesmaster_pool = []# 1. Ingest all 10 real-world open-source datasetsmaster_pool.extend(ingest_ultrachat_and_chitchat(DOMAIN_TARGET_CAPS["empathetic_chitchat"]))master_pool.extend(get_curated_identity_and_greetings_pack(DOMAIN_TARGET_CAPS["identity_greetings"]))master_pool.extend(ingest_codealpaca(DOMAIN_TARGET_CAPS["coding_tech"]))4 unmodified linesmaster_pool.extend(ingest_health_and_wellness(DOMAIN_TARGET_CAPS["finance_health_wellness"]))master_pool.extend(ingest_recipes_and_lifestyle(DOMAIN_TARGET_CAPS["recipes_indian_utility"]))master_pool.extend(ingest_reasoning_and_deductions(DOMAIN_TARGET_CAPS["reasoning_domain"]))random.shuffle(master_pool)print(f"\n🎉 Total 100% Unique Master Pool Collected: {len(master_pool):,} Samples!")158 unmodified lines1591601611621631641657 unmodified lines173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202348 unmodified lines551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608116 unmodified lines72572672772872973073173210 unmodified lines74374474574674774874975086 unmodified lines8378388398408418428434 unmodified lines848849850851852853854158 unmodified lines# ------------------------------------------------------------------------------# 4. Strict Deduplication & Typo Perturbation Engine# ------------------------------------------------------------------------------GLOBAL_SEEN_HASHES = set()7 unmodified linesreturn Falsedef inject_realistic_typos(text: str, typo_prob: float = 0.15) -> str:"""Injects realistic human fast-typing perturbations (dropped vowels, character swaps, double keys)."""if random.random() > typo_prob or len(text) < 10:return textwords = text.split()if not words:return textidx = random.randint(0, len(words) - 1)w = words[idx]if len(w) > 3 and w.isalpha():op = random.choice(["swap", "drop", "double"])if op == "swap" and len(w) > 2:i = random.randint(0, len(w) - 2)w = w[:i] + w[i+1] + w[i] + w[i+2:]elif op == "drop" and len(w) > 3:i = random.randint(1, len(w) - 2)w = w[:i] + w[i+1:]elif op == "double":i = random.randint(0, len(w) - 1)w = w[:i] + w[i] + w[i:]words[idx] = wreturn " ".join(words)# ------------------------------------------------------------------------------# 5. Real-World Open-Source Dataset Ingestion Functions# ------------------------------------------------------------------------------348 unmodified linesreturn samplesdef ingest_clarifications_and_disambiguations(target_count=6500) -> list:"""Ingests proactive follow-ups, multi-option disambiguations, and anti-ambiguity clarifications."""print(f"⬇️ Ingesting Clarification & Anti-Ambiguity Pack (Target: {target_count:,} unique)...")samples = []raw_path = os.path.join(PROJECT_ROOT, "data", "raw_data", "export_all_v1.json")if not os.path.exists(raw_path):try:dl = hf_hub_download(repo_id=DATA_REPO_ID, filename="raw_data/export_all_v1.json", repo_type="dataset", token=HF_TOKEN)shutil.copy(dl, raw_path)except Exception:passif os.path.exists(raw_path):try:with open(raw_path, "r", encoding="utf-8") as f:data = json.load(f)for item in data:cat = item.get("category", "")if any(w in cat for w in ["missing_context", "multi_option", "ambiguous", "clarification", "underspecified", "dilemma"]):inst = item.get("prompt", item.get("instruction", "")).strip()resp = item.get("response", "").strip()if not inst or len(resp) < MIN_TARGET_TOKENS or is_duplicate(inst):continue# Map to appropriate domainif "tech" in cat or "code" in cat:dom = "coding_tech"elif "health" in cat:dom = "finance_health_wellness"elif "career" in cat or "buying" in cat:dom = "career_productivity"elif "recipe" in cat:dom = "recipes_indian_utility"else:dom = "reasoning_domain"th = item.get("thinking", "").strip() or "Clarify underspecified request by offering structured options or polite follow-up questions."samples.append({"instruction": inst,"thinking": th,"response": resp,"domain": dom})if len(samples) >= target_count:breakexcept Exception as e:print(f" ⚠️ Error parsing clarification pack: {e}")print(f" ✅ [Clarification & Disambiguation] Loaded: {len(samples):,} unique samples")return samplesdef get_curated_identity_and_greetings_pack(target_count=3500) -> list:"""Curates distinct, non-repeating greetings (Eng, Hin, Hinglish) and ViuAI Sarus persona anchors."""print(f"⬇️ Curating Distinct Persona & Clean Salutations (Target: {target_count:,} unique)...")116 unmodified linesif "conversations" in item:# Multi-Turn Conversationfor turn_idx, (u_msg, th_msg, a_msg) in enumerate(item["conversations"]):# Format user turn with typo robustnessu_clean = inject_realistic_typos(u_msg.strip(), typo_prob=0.15)u_turn_text = f"{USER_TOKEN}\n{u_clean}{EOT_TOKEN}\n{ASSISTANT_TOKEN}\n"u_ids = TOKENIZER.encode(u_turn_text, add_special_tokens=False)10 unmodified linesfull_ids.extend(a_ids)labels.extend(a_ids)else:# Single-Turn Interaction with typo robustnessinst = inject_realistic_typos(item["instruction"].strip(), typo_prob=0.15)th = item.get("thinking", "").strip()resp = item["response"].strip()86 unmodified linesmaster_pool = []# 1. Ingest all 10 real-world open-source datasets + clarificationsmaster_pool.extend(ingest_ultrachat_and_chitchat(DOMAIN_TARGET_CAPS["empathetic_chitchat"]))master_pool.extend(get_curated_identity_and_greetings_pack(DOMAIN_TARGET_CAPS["identity_greetings"]))master_pool.extend(ingest_codealpaca(DOMAIN_TARGET_CAPS["coding_tech"]))4 unmodified linesmaster_pool.extend(ingest_health_and_wellness(DOMAIN_TARGET_CAPS["finance_health_wellness"]))master_pool.extend(ingest_recipes_and_lifestyle(DOMAIN_TARGET_CAPS["recipes_indian_utility"]))master_pool.extend(ingest_reasoning_and_deductions(DOMAIN_TARGET_CAPS["reasoning_domain"]))master_pool.extend(ingest_clarifications_and_disambiguations(5000))random.shuffle(master_pool)print(f"\n🎉 Total 100% Unique Master Pool Collected: {len(master_pool):,} Samples!")
code/build_sft_v18_dataset.py+83-6