Upload code/build_sft_v16_dataset.py with huggingface_hub
Browse files1234567891011121314151637 unmodified lines5455565758593 unmodified lines636465666768697071727374132 unmodified lines207208209210211212213148 unmodified lines3623633643653663673683693703713723733743753763773783793806 unmodified lines3873883893903913923933943952 unmodified lines39839940040140240340440540640740840941041141241341441541641741841942042142242342442542642742842943043143243343443543643743843944044144244344444544644744844945045145245345445545645745845946046146246346446546646746846947047147247347447547647747847948048148248348413 unmodified lines4984995005015025035045055065078 unmodified lines51651751851952052152252352452552610 unmodified lines53753853954054154254354454554654710 unmodified lines5585595605615625635645655665675685695705715725735745755765775782 unmodified lines5815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206216226236246256266273 unmodified lines63163263363463563663716 unmodified lines6546556566576586596602 unmodified lines66366466566666766866967067167267367467517 unmodified lines693694695696697698699700701702703704# ==============================================================================# 🚀 ViuAI Sarus-500M — SFT v16 Master Dataset Builder (~91,000 Samples)# ==============================================================================# PERFECT EQUAL ALL-ROUNDER MULTI-DOMAIN BALANCE:# 0. 📚 GK, Polity, Indian History & Updated 2024-26 Milestones (~11k)# 1. 💻 Core Coding, Python, Web Dev, SQL, Git & Linux Debugging (~11k)# 2. 🔢 Math & Arithmetic Step-by-Step Logic (~11k)# 3. 🧠 Logical Reasoning & Deductive Puzzles (~10k)# 4. 💬 Empathetic Chit-Chat, Emotions & Natural Life Conversations (~11k)# 5. 💼 Professional Career, Emails, Resume & Text Polishing (~10k)# 6. 🇮🇳 Indian Daily Utility, Culture & Authentic Recipes (Chai, Food, Life) (~8.5k)# 7. 💰 Personal Finance, Fitness & Wellness Awareness (~5.5k)# 8. 👑 100% AUTHENTIC Sarus Identity (from final_viuai_dataset_identity.json) (~3k)# ==============================================================================import os37 unmodified linesREPO_ID = "ViuAI/ViuAI-500M"DATA_REPO_ID = "ViuAI/viuai-500m-sft-tokenized"DOMAIN_MAP = {"gk_polity_history": 0,"coding_tech": 1,3 unmodified lines"career_productivity": 5,"recipes_indian_utility": 6,"finance_health_wellness": 7,"identity_greetings": 8}print("=" * 85)print("🚀 ViuAI Sarus-500M — SFT v16 Master Dataset Builder (~91,000 Scale)")print(" All-Rounder Uniform Equal Balance | 100% Authentic Identity | 2024-26 GK")print("=" * 85)132 unmodified lines# ------------------------------------------------------------------------------# 5. Handcrafted Core Anchor Packs (Empathy, Recipes, Coding, Math, Contemporary GK)# ------------------------------------------------------------------------------def get_empathy_and_chitchat_pack():148 unmodified linesreturn [{"instruction": inst, "thinking": th, "response": resp, "language": "english", "domain": "math_logic"} for inst, th, resp in items]def get_gk_polity_pack():items = [("Who is known as the Father of the Indian Constitution?","Identify the primary architect of the Constitution of India: Dr. B.R. Ambedkar.","**Dr. B. R. Ambedkar** (Bhimrao Ramji Ambedkar) is known as the **Father of the Indian Constitution**. He served as the Chairman of the Drafting Committee (Praroop Samiti) which prepared the final draft of the Constitution of India."),("Bharat ka sabse lamba national highway kaunsa hai?","Identify the longest national highway in India: NH 44 (Srinagar to Kanyakumari).","Bharat ka sabse lamba National Highway **NH 44** (National Highway 44) hai. Yeh **Srinagar (Jammu & Kashmir)** se shuru hokar **Kanyakumari (Tamil Nadu)** tak jata hai, aur iski kul lambai lagbhag **3,745 kilometers** hai."),]return [{"instruction": inst, "thinking": th, "response": resp, "language": "hinglish", "domain": "gk_polity_history"} for inst, th, resp in items]def get_updated_contemporary_gk_pack():items = [("Chandrayaan-3 kab land hua tha aur iski kya uplabdhi thi?",6 unmodified lines("ISRO ka Aditya-L1 mission kya hai aur ye kaha sthit hai?","Explain ISRO Aditya-L1 solar mission: launch in Sept 2023, placement at Sun-Earth Lagrange Point 1 (L1), and scientific objectives.","**Aditya-L1** Bharat ka **pehla Solar Observatory mission** hai jise ISRO ne Surya ka adhyayan karne ke liye bheja hai:\n\n""• **Location**: Yeh prithvi se lagbhag **15 lakh kilometers** door Sun-Earth system ke **Lagrange Point 1 (L1)** ke halo orbit me sthit hai.\n""• **Fayda**: L1 point par sthit hone ki wajah se bina kisi grahan ke Surya ko 24x7 lagatar observe kiya ja sakta hai.\n""• **Objectives**: Solar flares, coronal mass ejections (CME) aur space weather ka deep analysis karna."),("ICC Men's T20 World Cup 2024 kisne jeeta aur captain kaun the?",2 unmodified lines"• **Final Match**: 29 June 2024 ko Bridgetown (Barbados) me Bharat ne South Africa ko 7 runs se haraya.\n""• **Captain**: **Rohit Sharma** ki kaptani me Bharat ne ye trophy jeeti.\n""• **Player of the Final**: **Virat Kohli** (76 runs).\n""• **Player of the Tournament**: **Jasprit Bumrah** (15 wickets, economy 4.17)."),("Paris Olympics 2024 me Bharat ke pramukh medals kaunse the?","Summarize India's achievements in Paris 2024 Olympics: Neeraj Chopra (Silver), Manu Bhaker (2 Bronze medals), Hockey team (Bronze).","**Paris Olympics 2024** me Bharat ke pramukh itihaasik pal:\n\n""• **Neeraj Chopra**: Men's Javelin Throw me **Silver Medal** jeeta (89.45m throw ke sath).\n""• **Manu Bhaker**: Ek hi Olympics me **2 medals** jeetne wali azaad Bharat ki pehli athlete bani.\n""• **Indian Hockey Team**: PR Sreejesh ki shandar goalkeeping ke sath **Bronze Medal** jeeta.\n""• **Aman Sehrawat**: Wrestling (57kg) me Bronze jeetkar sabse kam umar ke Indian Olympic medalist bane."),("Bharat me huye G20 Summit 2023 ka theme aur pramukh faisla kya tha?","Explain G20 New Delhi Summit 2023: theme 'Vasudhaiva Kutumbakam' (One Earth, One Family, One Future), venue Bharat Mandapam, and historic inclusion of African Union (AU).","**G20 Summit 2023** Bharat ki adhyakshata me New Delhi ke **Bharat Mandapam** me aayojit hua tha:\n\n""• **Theme**: **'Vasudhaiva Kutumbakam'** ya **'One Earth · One Family · One Future'**.\n""• **Aitihasik Faisla**: **African Union (AU)** ko G20 ka permanent member banaya gaya.\n""• **IMEC**: India-Middle East-Europe Economic Corridor ka ailaan kiya gaya."),("Bharat ke naye Sansad Bhavan ki kya visheshataen hain?","Describe India's New Parliament Building: triangular design by Bimal Patel, Lok Sabha (Peacock theme), Rajya Sabha (Lotus theme), and installation of Sengol.","Bharat ka **Naya Sansad Bhavan (New Parliament House)** New Delhi me sthit hai:\n\n""• **Shape & Architect**: Triangular shape me bana hai, architect **Bimal Patel** hain.\n""• **Lok Sabha Chamber**: Rashtriya pakshi **Mor (Peacock)** theme par aadharit hai (888 seating capacity).\n""• **Rajya Sabha Chamber**: Rashtriya phool **Kamal (Lotus)** theme par aadharit hai (384 seating capacity).\n""• **Sengol**: Speaker ki seat ke paas aitihasik **'Sengol'** sthapit kiya gaya hai."),("Atal Setu (Mumbai Trans Harbour Link) kya hai aur iski lambai kitni hai?","Explain Atal Setu (MTHL): longest sea bridge in India, connecting Sewri in Mumbai to Chirle in Navi Mumbai, length ~21.8 km.","**Atal Setu (Mumbai Trans Harbour Link - MTHL)** Bharat ka **sabse lamba samundri pul** hai:\n\n""• **Lambai**: Lagbhag **21.8 kilometers** (16.5 km samundar ke upar).\n""• **Connectivity**: South Mumbai ke **Sewri** ko Navi Mumbai ke **Chirle** se jodta hai.\n""• **Fayda**: Travel time 2 ghante se ghat kar sirf 15-20 minute ho gaya hai."),("Bharat me naye kanoon BNS, BNSS aur BSA kab lagu huye aur unhone kinhe replace kiya?","Explain implementation of 3 new criminal laws on 1 July 2024: BNS replacing IPC, BNSS replacing CrPC, and BSA replacing Indian Evidence Act.","Bharat me **1 July 2024** se 3 naye criminal kanoon lagu huye hain:\n\n""1. **Bharatiya Nyaya Sanhita (BNS, 2023)**: Isne **IPC (1860)** ko replace kiya.\n""2. **Bharatiya Nagarik Suraksha Sanhita (BNSS, 2023)**: Isne **CrPC (1973)** ko replace kiya.\n""3. **Bharatiya Sakshya Adhiniyam (BSA, 2023)**: Isne **Indian Evidence Act (1872)** ko replace kiya."),("Nari Shakti Vandan Adhiniyam (Women's Reservation Bill) kya hai?","Explain 106th Constitutional Amendment Act: 33% reservation for women in Lok Sabha and State Legislative Assemblies.","**Nari Shakti Vandan Adhiniyam (106th Constitutional Amendment Act)**:\n\n""• **Uddeshya**: Lok Sabha aur Vidhan Sabhao me mahilaon ke liye **33% (one-third) seats reserve** karna.\n""• **Significance**: Naye Sansad Bhavan me pass hone wala pehla aitihasik bill tha."),("Bharat ka UPI kin-kin deshon me chal raha hai?","List foreign countries supporting Indian UPI payments: France, UAE, Singapore, Sri Lanka, Mauritius, Nepal, Bhutan.","Bharat ka digital payment system **UPI** ab kai deshon me accept hota hai:\n\n""• **Major Countries**: France (Eiffel Tower), UAE (Dubai), Singapore, Sri Lanka, Mauritius, Nepal, aur Bhutan.\n""• **Fayda**: Tourists bina currency exchange kiye seedha QR code scan karke Indian bank apps se payment kar sakte hain."),("D. Gukesh ne chess me kya itihaas racha?","Explain D. Gukesh's historic achievement: winning FIDE Candidates Tournament 2024 at age 17 to become youngest challenger in World Chess Championship history.","**Dommaraju Gukesh (D. Gukesh)** ne 2024 me FIDE Candidates Tournament jeet kar itihaas racha:\n\n""• **Record**: Sirf **17 saal ki umar** me World Chess Championship ke sabse young challenger bane.\n""• Unhone 45th Chess Olympiad 2024 me Bharat ko historic Gold medal dilane me leading role nibhaya.")]return [{"instruction": inst, "thinking": th, "response": resp, "language": "hinglish", "domain": "gk_polity_history"} for inst, th, resp in items]# ------------------------------------------------------------------------------# 6. Ingestion of Authentic Clean Datasets & Open-Source Repos (Equally Balanced)# ------------------------------------------------------------------------------def load_master_dataset_pool(local_data_dir=None):print("\n📦 Step 2/5: Building Balanced Multi-Domain Master Pool (~91k Target)...")master_pool = []# 1. Inject Handcrafted Core Anchor Packs (including Updated Contemporary GK)print(" -> Ingesting 15x Reinforcement Handcrafted Anchor Packs (Empathy, Food, Code, Math, Updated GK)...")for pack in [get_empathy_and_chitchat_pack(), get_authentic_recipes_pack(),get_coding_essentials_pack(), get_math_logic_pack(), get_gk_polity_pack(),get_updated_contemporary_gk_pack()]:for rep in range(15):for item in pack:master_pool.append(dict(item))print(f" Reinforced {len(master_pool):,} clean anchor samples.")# 2. Authentic Clean Datasets (Local or Cloud Auto-Downloaded)if local_data_dir and os.path.exists(local_data_dir):# 2a. 100% AUTHENTIC Sarus Identity Dataset (2,213 samples)id_path = os.path.join(local_data_dir, "final_viuai_dataset_identity.json")if os.path.exists(id_path):print(f" -> Ingesting 100% Authentic Sarus Identity: {id_path}...")13 unmodified linesid_count += 1print(f" ✅ Loaded {id_count:,} Authentic Sarus Identity samples.")# 2b. Authentic Cleaned Chit-Chat (~10,000 quota)cc_path = os.path.join(local_data_dir, "final_viuai_dataset_chit_chat.json")if os.path.exists(cc_path):print(f" -> Ingesting Authentic Chit-Chat: {cc_path}...")with open(cc_path, "r", encoding="utf-8") as f:cc_data = json.load(f)cc_clean = 08 unmodified lines"language": lang, "domain": "empathetic_chitchat"})cc_clean += 1if cc_clean >= 10000:breakprint(f" ✅ Loaded {cc_clean:,} Authentic Chit-Chat samples.")# 2c. Authentic Math Domain (~5,000 quota)math_path = os.path.join(local_data_dir, "final_viuai_dataset_math_domain.json")if os.path.exists(math_path):print(f" -> Ingesting Authentic Math Domain: {math_path}...")10 unmodified lines"language": "english", "domain": "math_logic"})m_count += 1if m_count >= 5000:breakprint(f" ✅ Loaded {m_count:,} Authentic Math samples.")# 2d. Authentic Reasoning Domain (~5,000 quota)reason_path = os.path.join(local_data_dir, "final_viuai_dataset_reasoning_domain.json")if os.path.exists(reason_path):print(f" -> Ingesting Authentic Reasoning Domain: {reason_path}...")10 unmodified lines"language": "english", "domain": "reasoning_domain"})r_count += 1if r_count >= 5000:breakprint(f" ✅ Loaded {r_count:,} Authentic Reasoning samples.")# 2e. Authentic Master Export Pool (Stratified across GK, Career, Food, Finance, Reasoning)export_path = os.path.join(local_data_dir, "export_all_v1.json")if os.path.exists(export_path):print(f" -> Stratified Ingestion from export_all_v1.json: {export_path}...")with open(export_path, "r", encoding="utf-8") as f:exp_data = json.load(f)buckets = defaultdict(list)for d in exp_data:cat = d.get("category", "").lower()dom = d.get("domain", "").lower()inst = clean_text(d.get("instruction", d.get("prompt", "")))th = clean_text(d.get("thinking", ""))resp = clean_text(d.get("response", d.get("output", "")))2 unmodified linesif not is_clean_sample(inst, resp, th):continueitem = {"instruction": inst, "thinking": th, "response": resp, "language": lang}if "instruction" in dom:item["domain"] = "career_productivity"buckets["career"].append(item)elif "reasoning" in dom:item["domain"] = "reasoning_domain"buckets["reasoning"].append(item)elif "food" in cat or "recipe" in cat or "daily_life" in cat:item["domain"] = "recipes_indian_utility"buckets["food_life"].append(item)elif "finance" in cat or "money" in cat or "health" in cat:item["domain"] = "finance_health_wellness"buckets["finance_health"].append(item)elif "clarification" in dom or "uncertainty" in dom:item["domain"] = "gk_polity_history"buckets["gk"].append(item)for k in buckets:random.shuffle(buckets[k])master_pool.extend(buckets["career"][:10000])master_pool.extend(buckets["reasoning"][:5000])master_pool.extend(buckets["food_life"][:8000])master_pool.extend(buckets["finance_health"][:5000])master_pool.extend(buckets["gk"][:5000])print(f" ✅ Ingested Balanced Subsets: Career={min(len(buckets['career']),10000):,}, "f"Reasoning={min(len(buckets['reasoning']),5000):,}, Food/Life={min(len(buckets['food_life']),8000):,}, "f"Finance/Health={min(len(buckets['finance_health']),5000):,}, GK={min(len(buckets['gk']),5000):,}")# 3. Open-Source High-Quality Datasets (CodeAlpaca / GSM8K / Samvaad)print(" -> Loading Hugging Face Balanced Code, Math & GK Repos...")# 3a. Coding (~11,000 quota)try:code_ds = load_dataset("sahil2801/CodeAlpaca-20k", split="train")c_count = 0for item in code_ds:inst = clean_text(item.get("instruction", "") + ("\n" + item.get("input", "") if item.get("input") else ""))resp = clean_text(item.get("output", ""))th = "Understand programming task. Write clean, working, idiomatic code with clear explanation."if is_clean_sample(inst, resp, th):master_pool.append({"instruction": inst, "thinking": th, "response": resp, "language": "english", "domain": "coding_tech"})c_count += 13 unmodified linesexcept Exception as e:print(f" (CodeAlpaca fallback: {e})")# 3b. Math (GSM8K ~6,000 quota)try:gsm = load_dataset("openai/gsm8k", "main", split="train")g_count = 016 unmodified linesexcept Exception as e:print(f" (GSM8K fallback: {e})")# 3c. Samvaad Hindi GK & Dialogue (~6,000 quota)try:samvaad = load_dataset("sarvamai/samvaad-hi-v1", split="train")sam_count = 02 unmodified linesif len(convs) >= 2:inst = clean_text(convs[0].get("content", ""))resp = clean_text(convs[1].get("content", ""))th = "उपयोगकर्ता के प्रश्न का विश्लेषण करें और शुद्ध, स्वाभाविक हिंदी में उत्तर दें।"if is_clean_sample(inst, resp, th):master_pool.append({"instruction": inst, "thinking": th, "response": resp, "language": "hindi", "domain": "gk_polity_history"})sam_count += 1if sam_count >= 6000:breakprint(f" Loaded {sam_count:,} Samvaad Hindi GK samples.")except Exception as e:print(f" (Samvaad fallback: {e})")17 unmodified linesval_data = []print("\n--- Stratified Split Summary ---")for dom, items in sorted(domain_buckets.items()):random.shuffle(items)n_val = max(10, int(len(items) * VAL_SPLIT_RATIO))val_data.extend(items[:n_val])train_data.extend(items[n_val:])print(f" • {dom:25s}: Train = {len(items)-n_val:5,} | Val = {n_val:4,} (Total: {len(items):,})")random.shuffle(train_data)random.shuffle(val_data)123456789101112131415161737 unmodified lines555657585960613 unmodified lines65666768697071727374757677132 unmodified lines210211212213214215216148 unmodified lines3653663673683693706 unmodified lines3773783793803813823833843852 unmodified lines38838939039139239339439539639739839940040140240340440540640740840941041141241341441541641741841942042142242342442542642742842943043143243343443543643743843944044144244344444544644744844945045145245345445545645745845946046146246346446546646746846947047147247347447513 unmodified lines4894904914924934944954964974988 unmodified lines50750850951051151251351451551651710 unmodified lines52852953053153253353453553610 unmodified lines5475485495505515525535545555565575585595605615625635645655665675685695705715725732 unmodified lines5765775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206216226236246253 unmodified lines62963063163263363463516 unmodified lines6526536546556566576582 unmodified lines66166266366466566666766866967067167267317 unmodified lines691692693694695696697698699700701702# ==============================================================================# 🚀 ViuAI Sarus-500M — SFT v16 Master Dataset Builder (~91,000 Samples)# ==============================================================================# 10 PERFECTLY BALANCED ALL-ROUNDER DOMAINS:# 0. 📚 GK, Indian History, Samvidhan & Updated 2024-26 Milestones (~11k)# 1. 💻 Python Coding, Web Dev, SQL & Linux Debugging (~11k)# 2. 🔢 Step-by-Step Math, Arithmetic & Word Problems (~11k)# 3. 🧠 Logical Reasoning, Blood Relations & Syllogisms (~10k)# 4. 💬 Empathetic Chit-Chat & Casual Banter (~11k)# 5. 💼 Career, Emails & Strict Instruction Following (~10k)# 6. ☕ Indian Real-World Utility, Food & Chai Recipes (~8.5k)# 7. 💰 Personal Finance, Health & Wellness Basics (~5.5k)# 8. 🌐 Natural Multilingual Translation (Eng <-> Hin <-> HG) (~10k)# 9. 👑 100% Authentic Sarus Identity & Persona (~3k)# ==============================================================================import os37 unmodified linesREPO_ID = "ViuAI/ViuAI-500M"DATA_REPO_ID = "ViuAI/viuai-500m-sft-tokenized"# Clear, un-conflated 10-Domain All-Rounder MapDOMAIN_MAP = {"gk_polity_history": 0,"coding_tech": 1,3 unmodified lines"career_productivity": 5,"recipes_indian_utility": 6,"finance_health_wellness": 7,"translation_multilingual": 8,"identity_greetings": 9}print("=" * 85)print("🚀 ViuAI Sarus-500M — SFT v16 Master Dataset Builder (~91,000 Scale)")print(" 100% Balanced All-Rounder Mix | Authentic ViuAI Identity | Updated GK")print("=" * 85)132 unmodified lines# ------------------------------------------------------------------------------# 5. Handcrafted Core Anchor Packs# ------------------------------------------------------------------------------def get_empathy_and_chitchat_pack():148 unmodified linesreturn [{"instruction": inst, "thinking": th, "response": resp, "language": "english", "domain": "math_logic"} for inst, th, resp in items]def get_updated_contemporary_gk_pack():items = [("Chandrayaan-3 kab land hua tha aur iski kya uplabdhi thi?",6 unmodified lines("ISRO ka Aditya-L1 mission kya hai aur ye kaha sthit hai?","Explain ISRO Aditya-L1 solar mission: launch in Sept 2023, placement at Sun-Earth Lagrange Point 1 (L1), and scientific objectives.","**Aditya-L1** Bharat ka **pehla Solar Observatory mission** hai jise ISRO ne Surya ka adhyayan (study) karne ke liye bheja hai:\n\n""• **Location**: Yeh prithvi se lagbhag **15 lakh kilometers** door Sun-Earth system ke **Lagrange Point 1 (L1)** ke halo orbit me sthit hai.\n""• **Fayda**: L1 point par sthit hone ki wajah se bina kisi grahan (eclipse) ke Surya ko 24x7 lagatar observe kiya ja sakta hai.\n""• **Objectives**: Solar flares, coronal mass ejections (CME) aur space weather ka deep analysis karna."),("ICC Men's T20 World Cup 2024 kisne jeeta aur captain kaun the?",2 unmodified lines"• **Final Match**: 29 June 2024 ko Bridgetown (Barbados) me Bharat ne South Africa ko 7 runs se haraya.\n""• **Captain**: **Rohit Sharma** ki kaptani me Bharat ne ye trophy jeeti.\n""• **Player of the Final**: **Virat Kohli** (76 runs).\n""• **Player of the Tournament**: **Jasprit Bumrah** (15 wickets, economy 4.17).\n""• Yeh Bharat ka **doosra T20 World Cup** khitab tha (pehla 2007 me MS Dhoni ki kaptani me jeeta tha)."),("Paris Olympics 2024 me Bharat ke pramukh medals kaunse the?","Summarize India's achievements in Paris 2024 Olympics: Neeraj Chopra (Silver), Manu Bhaker (2 Bronze medals), Hockey team (Bronze).","**Paris Olympics 2024** me Bharat ke pramukh itihaasik pal:\n\n""• **Neeraj Chopra**: Men's Javelin Throw me **Silver Medal** jeeta (89.45m throw ke sath).\n""• **Manu Bhaker**: Ek hi Olympics me **2 medals** (10m Air Pistol Individual & 10m Mixed Team with Sarabjot Singh) jeetne wali azaad Bharat ki pehli athlete bani.\n""• **Indian Hockey Team**: PR Sreejesh ki shandar goalkeeping ke sath **Bronze Medal** jeeta.\n""• **Aman Sehrawat**: Wrestling (57kg) me Bronze jeetkar sabse kam umar ke Indian Olympic medalist bane."),("Bharat me huye G20 Summit 2023 ka theme aur pramukh faisla kya tha?","Explain G20 New Delhi Summit 2023: theme 'Vasudhaiva Kutumbakam' (One Earth, One Family, One Future), venue Bharat Mandapam, and historic inclusion of African Union (AU).","**G20 Summit 2023** Bharat ki adhyakshata (presidency) me New Delhi ke **Bharat Mandapam** me aayojit hua tha:\n\n""• **Theme**: **'Vasudhaiva Kutumbakam'** ya **'One Earth · One Family · One Future'**.\n""• **Aitihasik Faisla**: **African Union (AU)** ko G20 ka permanent member banaya gaya (jisse ye G21 ban gaya).\n""• **IMEC**: India-Middle East-Europe Economic Corridor ka ailaan kiya gaya."),("Bharat ke naye Sansad Bhavan (New Parliament House) ki kya visheshataen hain?","Describe India's New Parliament Building: triangular design by Bimal Patel, Lok Sabha (Peacock theme), Rajya Sabha (Lotus theme), and installation of Sengol.","Bharat ka **Naya Sansad Bhavan (New Parliament House)** New Delhi me sthit hai:\n\n""• **Shape & Architect**: Yeh triangular (tribhujaakar) shape me bana hai, jiske architect **Bimal Patel** hain (Central Vista Project).\n""• **Lok Sabha Chamber**: Rashtriya pakshi **Mor (Peacock)** theme par aadharit hai (888 seating capacity).\n""• **Rajya Sabha Chamber**: Rashtriya phool **Kamal (Lotus)** theme par aadharit hai (384 seating capacity).\n""• **Sengol**: Lok Sabha Speaker ki seat ke paas aitihasik **'Sengol'** (nyay aur shasan ka prateek) sthapit kiya gaya hai."),("Atal Setu (Mumbai Trans Harbour Link) kya hai aur iski lambai kitni hai?","Explain Atal Setu (MTHL): longest sea bridge in India, connecting Sewri in Mumbai to Chirle in Navi Mumbai, length ~21.8 km.","**Atal Setu (Mumbai Trans Harbour Link - MTHL)** Bharat ka **sabse lamba samundri pul (longest sea bridge)** hai:\n\n""• **Lambai**: Lagbhag **21.8 kilometers** (jisme se 16.5 km samundar ke upar hai).\n""• **Connectivity**: Yeh South Mumbai ke **Sewri** ko Navi Mumbai ke **Chirle** se jodta hai.\n""• **Fayda**: 2 ghante ka travel time ghat kar sirf 15-20 minute ho gaya hai."),("Bharat me naye kanoon BNS, BNSS aur BSA kab lagu huye aur unhone kinhe replace kiya?","Explain implementation of 3 new criminal laws on 1 July 2024: BNS replacing IPC, BNSS replacing CrPC, and BSA replacing Indian Evidence Act.","Bharat me **1 July 2024** se 3 naye criminal kanoon lagu huye hain jinhone colonial daur ke kanoonon ko replace kiya:\n\n""1. **Bharatiya Nyaya Sanhita (BNS, 2023)**: Isne British-era **Indian Penal Code (IPC, 1860)** ko replace kiya.\n""2. **Bharatiya Nagarik Suraksha Sanhita (BNSS, 2023)**: Isne **Code of Criminal Procedure (CrPC, 1973)** ko replace kiya.\n""3. **Bharatiya Sakshya Adhiniyam (BSA, 2023)**: Isne **Indian Evidence Act (1872)** ko replace kiya."),("Nari Shakti Vandan Adhiniyam (Women's Reservation Bill) kya hai?","Explain 106th Constitutional Amendment Act (Nari Shakti Vandan Adhiniyam): 33% reservation for women in Lok Sabha and State Legislative Assemblies.","**Nari Shakti Vandan Adhiniyam (106th Constitutional Amendment Act)** ek aitihasik kanoon hai:\n\n""• **Uddeshya**: Lok Sabha aur rajyon ki Vidhan Sabhao (State Legislative Assemblies) me mahilaon ke liye **33% (one-third) seats reserve** karna.\n""• **Significance**: Naye Sansad Bhavan me pass hone wala yeh **pehla aitihasik bill** tha."),("Bharat ka UPI (Unified Payments Interface) kin-kin deshon me chal raha hai?","List foreign countries supporting Indian UPI payments: France, UAE, Singapore, Sri Lanka, Mauritius, Nepal, Bhutan.","Bharat ka digital payment system **UPI (Unified Payments Interface)** ab kai deshon me globally accept hota hai:\n\n""• **Major Countries**: France (Eiffel Tower par live), UAE (Dubai/Abu Dhabi), Singapore (PayNow-UPI link), Sri Lanka, Mauritius, Nepal, aur Bhutan.\n""• **Fayda**: Indian tourists aur travellers bina currency exchange kiye seedha apne Indian bank apps (PhonePe, GPay, Paytm) se QR code scan karke payment kar sakte hain."),("D. Gukesh ne chess me kya itihaas racha?","Explain D. Gukesh's historic achievement: winning FIDE Candidates Tournament 2024 at age 17 to become youngest challenger in World Chess Championship history.","**Dommaraju Gukesh (D. Gukesh)** ne 2024 me FIDE Candidates Tournament jeet kar itihaas racha:\n\n""• **Record**: Sirf **17 saal ki umar** me World Chess Championship ke sabse young challenger bane (Viswanathan Anand ke baad Candidates jeetne wale doosre Indian).\n""• Unhone 45th Chess Olympiad 2024 me Bharat ko historic Gold medal dilane me bhi leading role nibhaya."),]return [{"instruction": inst, "thinking": th, "response": resp, "language": "hinglish", "domain": "gk_polity_history"} for inst, th, resp in items]# ------------------------------------------------------------------------------# 6. Ingestion of 10 Perfectly Balanced Domains (~91,000 Total)# ------------------------------------------------------------------------------def load_master_dataset_pool(local_data_dir=None):print("\n📦 Step 2/5: Building Balanced Multi-Domain Master Pool (~91,000 Scale)...")master_pool = []# 1. Inject Handcrafted Core Anchor Packs (15x reinforcement)print(" -> Ingesting 15x Reinforcement Handcrafted Anchor Packs...")for pack in [get_empathy_and_chitchat_pack(), get_authentic_recipes_pack(),get_coding_essentials_pack(), get_math_logic_pack(),get_updated_contemporary_gk_pack()]:for rep in range(15):for item in pack:master_pool.append(dict(item))print(f" Reinforced {len(master_pool):,} clean anchor samples.")# 2. Ingest Authentic Local / Cloud Clean Datasetsif local_data_dir and os.path.exists(local_data_dir):# 2a. 100% AUTHENTIC Sarus Identity Dataset (~2.2k - 3k)id_path = os.path.join(local_data_dir, "final_viuai_dataset_identity.json")if os.path.exists(id_path):print(f" -> Ingesting 100% Authentic Sarus Identity: {id_path}...")13 unmodified linesid_count += 1print(f" ✅ Loaded {id_count:,} Authentic Sarus Identity samples.")# 2b. Authentic Cleaned Chit-Chat (Target: 11,000)cc_path = os.path.join(local_data_dir, "final_viuai_dataset_chit_chat.json")if os.path.exists(cc_path):print(f" -> Ingesting Authentic Chit-Chat (Cap: 11,000): {cc_path}...")with open(cc_path, "r", encoding="utf-8") as f:cc_data = json.load(f)cc_clean = 08 unmodified lines"language": lang, "domain": "empathetic_chitchat"})cc_clean += 1if cc_clean >= 11000:breakprint(f" ✅ Loaded {cc_clean:,} Authentic Chit-Chat samples.")# 2c. Authentic Math Domainmath_path = os.path.join(local_data_dir, "final_viuai_dataset_math_domain.json")if os.path.exists(math_path):print(f" -> Ingesting Authentic Math Domain: {math_path}...")10 unmodified lines"language": "english", "domain": "math_logic"})m_count += 1print(f" ✅ Loaded {m_count:,} Local Math samples.")# 2d. Authentic Reasoning Domain (Target: 5,600)reason_path = os.path.join(local_data_dir, "final_viuai_dataset_reasoning_domain.json")if os.path.exists(reason_path):print(f" -> Ingesting Authentic Reasoning Domain: {reason_path}...")10 unmodified lines"language": "english", "domain": "reasoning_domain"})r_count += 1print(f" ✅ Loaded {r_count:,} Local Reasoning samples.")# 2e. Master Export Pool (Translation, Instruction, Reasoning Puzzles, Recipes, Finance)export_path = os.path.join(local_data_dir, "export_all_v1.json")if os.path.exists(export_path):print(f" -> Stratified Ingestion from Master Export: {export_path}...")with open(export_path, "r", encoding="utf-8") as f:exp_data = json.load(f)buckets = {"translation_multilingual": [],"career_productivity": [],"reasoning_domain": [],"recipes_indian_utility": [],"finance_health_wellness": [],"gk_polity_history": []}for d in exp_data:dom = d.get("domain", "").lower()cat = d.get("category", "").lower()inst = clean_text(d.get("instruction", d.get("prompt", "")))th = clean_text(d.get("thinking", ""))resp = clean_text(d.get("response", d.get("output", "")))2 unmodified linesif not is_clean_sample(inst, resp, th):continuerow = {"instruction": inst, "thinking": th, "response": resp, "language": lang}if "translation" in dom:buckets["translation_multilingual"].append(dict(row, domain="translation_multilingual"))elif "instruction" in dom:buckets["career_productivity"].append(dict(row, domain="career_productivity"))elif "reasoning" in dom:buckets["reasoning_domain"].append(dict(row, domain="reasoning_domain"))elif any(k in cat for k in ["food", "travel", "festival", "living"]):buckets["recipes_indian_utility"].append(dict(row, domain="recipes_indian_utility"))elif any(k in cat for k in ["money", "finance", "health", "fitness"]):buckets["finance_health_wellness"].append(dict(row, domain="finance_health_wellness"))elif "clarification" in dom:buckets["gk_polity_history"].append(dict(row, domain="gk_polity_history"))for k in buckets:random.shuffle(buckets[k])# Ingest balanced quotasmaster_pool.extend(buckets["translation_multilingual"][:10000])master_pool.extend(buckets["career_productivity"][:10000])master_pool.extend(buckets["reasoning_domain"][:5000])master_pool.extend(buckets["recipes_indian_utility"][:8500])master_pool.extend(buckets["finance_health_wellness"][:5500])master_pool.extend(buckets["gk_polity_history"][:5000])print(f" ✅ Balanced Ingestion:")print(f" • Translation : {min(len(buckets['translation_multilingual']), 10000):,}")print(f" • Career/Format: {min(len(buckets['career_productivity']), 10000):,}")print(f" • Reasoning : {min(len(buckets['reasoning_domain']), 5000):,}")print(f" • Recipes/Life : {min(len(buckets['recipes_indian_utility']), 8500):,}")print(f" • Finance/Fit : {min(len(buckets['finance_health_wellness']), 5500):,}")# 3. Open-Source Repos (Coding: 11,000 | Math: 6,000 | GK/Samvaad: 6,000)print(" -> Loading Balanced Open-Source Datasets...")# 3a. Coding (Target: 11,000)try:code_ds = load_dataset("sahil2801/CodeAlpaca-20k", split="train")c_count = 0for item in code_ds:inst = clean_text(item.get("instruction", "") + ("\n" + item.get("input", "") if item.get("input") else ""))resp = clean_text(item.get("output", ""))th = f"Understand programming task. Write clean, working, idiomatic code with clear explanation."if is_clean_sample(inst, resp, th):master_pool.append({"instruction": inst, "thinking": th, "response": resp, "language": "english", "domain": "coding_tech"})c_count += 13 unmodified linesexcept Exception as e:print(f" (CodeAlpaca fallback: {e})")# 3b. Math GSM8K (Target: 6,000)try:gsm = load_dataset("openai/gsm8k", "main", split="train")g_count = 016 unmodified linesexcept Exception as e:print(f" (GSM8K fallback: {e})")# 3c. Samvaad Hindi GK / General Knowledge (Target: 6,000)try:samvaad = load_dataset("sarvamai/samvaad-hi-v1", split="train")sam_count = 02 unmodified linesif len(convs) >= 2:inst = clean_text(convs[0].get("content", ""))resp = clean_text(convs[1].get("content", ""))th = "उपयोगकर्ता के सामान्य ज्ञान / प्रश्न का विश्लेषण करें और शुद्ध, स्वाभाविक हिंदी में उत्तर दें।"if is_clean_sample(inst, resp, th):master_pool.append({"instruction": inst, "thinking": th, "response": resp, "language": "hindi", "domain": "gk_polity_history"})sam_count += 1if sam_count >= 6000:breakprint(f" Loaded {sam_count:,} Samvaad GK samples.")except Exception as e:print(f" (Samvaad fallback: {e})")17 unmodified linesval_data = []print("\n--- Stratified Split Summary ---")for dom, items in domain_buckets.items():random.shuffle(items)n_val = max(10, int(len(items) * VAL_SPLIT_RATIO))val_data.extend(items[:n_val])train_data.extend(items[n_val:])print(f" • {dom:25s}: Train = {len(items)-n_val:5,} | Val = {n_val:4,}")random.shuffle(train_data)random.shuffle(val_data)
code/build_sft_v16_dataset.py+108-110