Upload code/build_sft_v16_dataset.py with huggingface_hub
Browse files12234567891011121314151617181920214567891011121314151637 unmodified lines545556655758597 unmodified lines67686979807071727374137 unmodified lines2122132142242152162176 unmodified lines224225226237227228229132 unmodified lines3623633643763773783653663673683693703713723733743753763773783803793823803813822 unmodified lines3853863873913883893943903913963923933943993953963973983994004064074014024094034044054064144074084094104184114124214134144234154164174264274184194204304214224234334244254354264274384394404414284294304314324434334344464474484354364374384394514404534544554564414424434444454584594464474614624634484494504514654524534544694704554564574584594604614764624634644654804664674684694 unmodified lines47447547649147747847948017 unmodified lines49849950051550150250350411 unmodified lines5165175185335195205215225375235245255265275285295305315323 unmodified lines5365375385395405415425435535445455465475485495505515525533 unmodified lines5575585595605615625635645695655665675725685695705715765775785725735805745755765775782 unmodified lines5815825835895905915925935945955845855865875885895905915925935945955965975985996006015975985996026036046056066076086096106116126136146026156166046176186196206216226236106246256266276286296136306316326336176346356366376386396406 unmodified lines6476486496506516526326536546556566366576586596604 unmodified lines66566666764766866964967067165167267367467517 unmodified lines693694695675696697698699700680701702703704# ==============================================================================# 🚀 ViuAI Sarus-500M — SFT v16 Master Dataset Builder (~88,500+ Samples)# 🚀 ViuAI Sarus-500M — SFT v16 Master Dataset Builder (~91,000 Samples)# ==============================================================================# 9 BALANCED DOMAINS:# 0. 📚 General Knowledge, Updated 2023-2026 Current Affairs, History & Polity (~18k)# 1. 💻 Core Coding, Python, Web Dev, SQL, Git & Linux Debugging (~16k)# 2. 🔢 Math & Arithmetic Step-by-Step Logic (~9k)# 3. 🧠 Logical Reasoning & Deductive Puzzles (~6k)# 4. 💬 Empathetic Chit-Chat, Emotions & Natural Life Conversations (~16k)# 5. 💼 Professional Career, Emails, Resume & Text Polishing (~8k)# 6. 🇮🇳 Indian Daily Utility, Culture & Authentic Recipes (Chai, Food, Life) (~6k)# 7. 💰 Personal Finance, Fitness & Wellness Awareness (~5k)# 8. 👑 100% AUTHENTIC Sarus Identity (from final_viuai_dataset_identity.json) (~2.2k)## NEW FEATURE:# • 🌟 UPDATED CONTEMPORARY GK PACK (2023-2026 Milestones):# - Chandrayaan-3, Aditya-L1, Gaganyaan, National Space Day# - T20 World Cup 2024 Champions (India), Paris Olympics 2024 (Neeraj, Manu Bhaker)# - New Parliament Building, Sengol, Atal Setu (MTHL), Vande Bharat# - G20 Summit New Delhi, BNS (Bharatiya Nyaya Sanhita), Women's Reservation Bill# - Global UPI (France, UAE, Singapore, Nepal), Ayodhya Ram Mandir# 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"
# Clear, un-conflated 9-Domain MapDOMAIN_MAP = { "gk_polity_history": 0, "coding_tech": 1,7 unmodified lines}
print("=" * 85)print("🚀 ViuAI Sarus-500M — SFT v16 Master Dataset Builder (~88,500+ Scale)")print(" 100% Authentic Identity | Updated Contemporary GK (2023-2026) | int32 Overflow Fix")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)
137 unmodified lines
def get_empathy_and_chitchat_pack(): items = [ # Mood Off / Sadness / Empathy ("Mera mood thoda off hai, kuch accha bolo.", "User is feeling down and needs warmth, active empathy, and gentle comfort without canned identity introduction.", "Arey kya hua dost? Kabhi kabhi din thoda heavy ho jata hai, par yaad rakho ki har buri sham ke baad ek nayi subah aati hai. Chaho to share karo kya hua, dil halka hoga. Aur agar baat nahi karni, to ek mast garam chai piyo aur apna favourite gaana sun kar relax karo. Main yahin hoon tumhare sath!"),6 unmodified lines "User is feeling lonely. Provide genuine warmth, companionship, and uplifting words.", "Aap akele nahi hain! Kabhi kabhi bheed me bhi loneliness feel hoti hai, ye bilkul normal hai. Par yaad rakhiye aapki apni ek value hai. Main hamesha yahin hoon aapse baat karne, nayi cheezein seekhne aur aapka din thoda brighter banane ke liye. Chalo batao, aaj sabse pehla thought kya aaya tha dimaag me?"),
# Philosophy & Human-AI Connection ("Tumhe kaisa lagta hai humans se baat karke?", "User asking about the AI's perspective on conversing with humans. Express curiosity, helpfulness, and genuine joy in assisting people.", "Mujhe humans se baat karke sach me bohot maza aata hai! Har insaan ke paas ek alag soch, naye sawal, alag emotions aur unique kahani hoti hai. Jab main kisi ka complex code debug karta hoon, koi naya concept samjhata hoon ya kisi ka mood thoda behtar karta hoon, to lagta hai ki main sach me kisi ke kaam aa raha hoon!"),132 unmodified lines return [{"instruction": inst, "thinking": th, "response": resp, "language": "english", "domain": "math_logic"} for inst, th, resp in items]
# ------------------------------------------------------------------------------# 🌟 UPDATED CONTEMPORARY GK & CURRENT AFFAIRS PACK (2023-2026)# ------------------------------------------------------------------------------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(): """High-density updated contemporary GK facts (Space, Sports, Governance, Infrastructure & Tech).""" items = [ # 1. Chandrayaan-3 & Space Day ("Chandrayaan-3 kab land hua tha aur iski kya uplabdhi thi?", "Explain Chandrayaan-3 landing date (23 August 2023), landing site (Shiv Shakti Point at South Pole), and historic world achievement.", "**Chandrayaan-3** Bharat ka ek aitihasik antariksh mission tha:\n\n"2 unmodified lines "• **Shiv Shakti Point**: Landing point ka naam **'Shiv Shakti'** rakha gaya.\n" "• **National Space Day**: Is uplabdhi ke samman me har saal 23 August ko Bharat me **'National Space Day'** manaya jata hai."),
# 2. Aditya-L1 Mission ("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" "**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 (eclipse) ke Surya ko 24x7 lagatar observe kiya ja sakta 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."),
# 3. T20 World Cup 2024 ("ICC Men's T20 World Cup 2024 kisne jeeta aur captain kaun the?", "State winner of ICC T20 World Cup 2024: India, defeating South Africa in Barbados under Rohit Sharma's captaincy.", "**ICC Men's T20 World Cup 2024** ka khitab **Bharat (India)** ne jeeta:\n\n" "• **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)."), "• **Player of the Tournament**: **Jasprit Bumrah** (15 wickets, economy 4.17)."),
# 4. Paris Olympics 2024 ("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" "• **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."),
# 5. G20 Summit New Delhi 2023 ("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" "**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 (jisse ye G21 ban gaya).\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."),
# 6. New Parliament Building & Sengol ("Bharat ke naye Sansad Bhavan (New Parliament House) ki kya visheshataen hain?", ("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**: Yeh triangular (tribhujaakar) shape me bana hai, jiske architect **Bimal Patel** hain (Central Vista Project).\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**: Lok Sabha Speaker ki seat ke paas aitihasik **'Sengol'** (nyay aur shasan ka prateek) sthapit kiya gaya hai."), "• **Sengol**: Speaker ki seat ke paas aitihasik **'Sengol'** sthapit kiya gaya hai."),
# 7. Atal Setu (MTHL) ("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."), "**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."),
# 8. New Criminal Laws (Bharatiya Nyaya Sanhita - BNS) ("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" "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."),
# 9. Women's Reservation Bill (Nari Shakti Vandan Adhiniyam) ("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."), "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."),
# 10. UPI Global Expansion ("Bharat ka UPI (Unified Payments Interface) kin-kin deshon me chal raha hai?", ("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 (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."), "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."),
# 11. Chess Grandmaster D. Gukesh ("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."), "• **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# 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...") 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)4 unmodified lines for rep in range(15): for item in pack: master_pool.append(dict(item)) print(f" Reinforced {len(master_pool):,} clean anchor samples (with 2023-2026 Updated GK).") 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):17 unmodified lines id_count += 1 print(f" ✅ Loaded {id_count:,} Authentic Sarus Identity samples.")
# 2b. Authentic Cleaned Chit-Chat # 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}...")11 unmodified lines "language": lang, "domain": "empathetic_chitchat" }) cc_clean += 1 if cc_clean >= 16000: if cc_clean >= 10000: break print(f" ✅ Loaded {cc_clean:,} Authentic Chit-Chat samples.")
# 2c. Authentic Math Domain # 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}...") with open(math_path, "r", encoding="utf-8") as f: m_data = json.load(f) m_count = 0 for d in m_data: inst = clean_text(d.get("instruction", d.get("prompt", ""))) th = clean_text(d.get("thinking", ""))3 unmodified lines "instruction": inst, "thinking": th, "response": resp, "language": "english", "domain": "math_logic" }) m_count += 1 if m_count >= 5000: break print(f" ✅ Loaded {m_count:,} Authentic Math samples.")
# 2d. Authentic Reasoning Domain # 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}...") with open(reason_path, "r", encoding="utf-8") as f: r_data = json.load(f) r_count = 0 for d in r_data: inst = clean_text(d.get("instruction", d.get("prompt", ""))) th = clean_text(d.get("thinking", ""))3 unmodified lines "instruction": inst, "thinking": th, "response": resp, "language": "english", "domain": "reasoning_domain" }) r_count += 1 if r_count >= 5000: break print(f" ✅ Loaded {r_count:,} Authentic Reasoning samples.")
# 2e. Authentic Master Export Pool (GK & Career) # 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 Filtering & Ingestion (GK, Career, Life): {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) gk_candidates = [] career_candidates = [] buckets = defaultdict(list) for d in exp_data: dom = d.get("domain", d.get("category", "")).lower() 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 lines if not is_clean_sample(inst, resp, th): continue if "reasoning" in dom or "clarification" in dom: gk_candidates.append({"instruction": inst, "thinking": th, "response": resp, "language": lang, "domain": "gk_polity_history"}) elif "instruction" in dom: career_candidates.append({"instruction": inst, "thinking": th, "response": resp, "language": lang, "domain": "career_productivity"}) random.shuffle(gk_candidates) random.shuffle(career_candidates) item = {"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) master_pool.extend(gk_candidates[:18000]) master_pool.extend(career_candidates[:10000]) print(f" ✅ Loaded {min(len(gk_candidates), 18000):,} Authentic GK and {min(len(career_candidates), 10000):,} Career samples.") 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 Code & Math Repos...") print(" -> Loading Hugging Face Balanced Code, Math & GK Repos...") # 3a. Coding # 3a. Coding (~11,000 quota) try: code_ds = load_dataset("sahil2801/CodeAlpaca-20k", split="train") c_count = 0 for 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." 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 += 1 if c_count >= 11000: break print(f" Loaded {len(code_ds):,} CodeAlpaca samples.") print(f" Loaded {c_count:,} CodeAlpaca samples.") except Exception as e: print(f" (CodeAlpaca fallback: {e})")
# 3b. Math (GSM8K) # 3b. Math (GSM8K ~6,000 quota) try: gsm = load_dataset("openai/gsm8k", "main", split="train") g_count = 0 for item in gsm: q = clean_text(item.get("question", "")) a = clean_text(item.get("answer", ""))6 unmodified lines resp = a if is_clean_sample(q, resp, th): master_pool.append({"instruction": q, "thinking": th, "response": resp, "language": "english", "domain": "math_logic"}) g_count += 1 if g_count >= 6000: break print(f" Loaded {len(gsm):,} GSM8K Math samples.") print(f" Loaded {g_count:,} GSM8K Math samples.") except Exception as e: print(f" (GSM8K fallback: {e})")
# 3c. Samvaad Hindi (Capped at 15k) # 3c. Samvaad Hindi GK & Dialogue (~6,000 quota) try: samvaad = load_dataset("sarvamai/samvaad-hi-v1", split="train") sam_count = 04 unmodified lines 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": "empathetic_chitchat"}) master_pool.append({"instruction": inst, "thinking": th, "response": resp, "language": "hindi", "domain": "gk_polity_history"}) sam_count += 1 if sam_count >= 15000: if sam_count >= 6000: break print(f" Loaded {sam_count:,} Samvaad Hindi samples.") print(f" Loaded {sam_count:,} Samvaad Hindi GK samples.") except Exception as e: print(f" (Samvaad fallback: {e})")
17 unmodified lines val_data = [] print("\n--- Stratified Split Summary ---") for dom, items in domain_buckets.items(): 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,}") 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)code/build_sft_v16_dataset.py+122-101