Upload code/build_sft_data_v6.py with huggingface_hub
Browse files66 unmodified lines67686970717273749 unmodified lines848586878889909153 unmodified lines1451461471481491501511521531541551561571581597 unmodified lines16716816917017117216 unmodified lines189190191192193194195196197198199200201202203204205206120 unmodified lines3273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593605 unmodified lines36636736836937037137237337437537617 unmodified lines39439539639739839940040140240340440540640740840941041141241341441566 unmodified linesdef build_simple_example(user_text, assistant_text, category):style_rand = random.random()if style_rand < 0.1: style_idx = 1elif style_rand < 0.2: style_idx = 2else: style_idx = 0prefix = get_prompt_format(user_text, style_idx)9 unmodified linesdef build_search_example(user_text, search_query, search_result_text, final_answer, category):style_rand = random.random()if style_rand < 0.1: style_idx = 1elif style_rand < 0.2: style_idx = 2else: style_idx = 0prefix = get_prompt_format(user_text, style_idx)53 unmodified lines# Generate relevant synthetic contextif "gold" in user_query:base_context = f"Gold price today {today} is around 72,000 INR per 10 gram in Delhi. Market up by 200 INR due to global demand. "elif "india news" in user_query or "khabar" in user_query or "news" in user_query:base_context = f"Today India news {today}: PM Modi addressed nation, GDP growth 7.2%, Sensex up 300 points, monsoon expected. "elif "weather" in user_query or "mausam" in user_query:base_context = f"Weather in Delhi today {today}: 34C, partly cloudy, 70% humidity, light rain expected. "else:base_context = f"Latest update on {user_query} on {today}: New developments emerged, more details expected soon per sources. "context = (base_context * 5)[:500]else:user_query = row["question"].strip()context = row["context"].strip()7 unmodified linestoday = datetime.now().strftime("%d %B %Y")# Format explicitly 3 resultsddg_result = (f"[Today: {today}] Results:\n"f"1. {title1}: {context[:150]}\n"16 unmodified linesif is_hindi:ans_body = (f"Aaj ke search results [Today: {today}] ke mutabiq, yahan kuch mukhy baatein hain:\n"f"1. Result 1 ke anusaar, {context[:100]}...\n"f"2. Result 2 ke mutabiq aur bhi details hain jaise ki {context[150:250]}...\n"f"3. Result 3 batata hai ki {context[300:400]}...\n\n"f"Summary: In sabhi sources ko dekh kar, hum keh sakte hain ki {search_q} ke baare mein taza jankari yahi bata rahi hai ki situation aage badh rahi hai aur nayi updates aati rahengi. Mujhe ummeed hai ye aapke liye helpful hoga!")else:ans_body = (f"Based on today's results [Today: {today}], here are the detailed findings:\n"f"1. According to Result 1, {context[:100]}...\n"f"2. From Result 2, we can see additional details such as {context[150:250]}...\n"f"3. Result 3 highlights that {context[300:400]}...\n\n"f"Summary: Synthesizing these three sources, it is evident that the situation regarding '{search_q}' involves multiple facets. The sources agree on the general premise but provide different granular details. I hope this detailed breakdown helps answer your query comprehensively!")final_answer = think_str + ans_body120 unmodified lines# 3. EMPATHETIC DIALOGUES# =========================================================================def build_empathetic():print("\n[3/5] Empathetic Dialogues (18,000)...")examples = []base_templates = [("I am feeling low today", "It's okay to feel low sometimes. Want to talk about it?"),("I had a bad day at work", "Work can be draining. Take rest, you deserve it."),("I am anxious about exam", "Exams are stressful. Take deep breaths, you prepared well."),("I feel lonely", "You are not alone, I am here. What happened?"),("Bhai kaisa hai?", "Main badhiya! Aap batao kya chal raha hai?"),("I am happy today!", "That's wonderful! What's making you happy?"),("I am tired", "Rest a bit, you have been working hard."),("I am angry at my friend", "It's natural to feel angry. Want to share what happened?"),]emotions = ["happy","sad","tired","bored","excited","anxious","angry","lonely","stressed"]# Generate diverse 18kfor i in range(18000):if i < 5000:q,a = random.choice(base_templates)# Add variationif random.random() < 0.3:q = q + " yaar"else:emo = random.choice(emotions)q = f"I am feeling {emo} today"a = f"I understand feeling {emo} is tough. Take care of yourself. I'm here to listen."ex = build_simple_example(q, a, "empathetic")if ex: examples.append(ex)random.shuffle(examples)return examples[:17100], examples[17100:18000] # 900 val5 unmodified linesexamples = []try:ds = load_dataset("databricks/databricks-dolly-15k", split="train", trust_remote_code=True)# Duplicate to reach 18kpool = list(ds)pool = pool + pool[:4000]for row in tqdm(pool[:19000], desc="Dolly"):q = row["instruction"].strip()if row.get("input", "").strip(): q += "\n" + row["input"].strip()a = row["response"].strip()17 unmodified linesif row.get("input", "").strip(): q += "\n" + row["input"].strip()ans = row["output"].strip()# Long Thinking for general prompts (60-80 words)think_parts = ["I need to carefully evaluate this request.",f"The user is asking to process: '{q[:30]}...'.","First, I should break down the core instruction.","Let me consider the constraints and necessary steps.","Step 1: Identify the key entities and the required format.","Step 2: Retrieve any relevant internal knowledge.","Step 3: Draft a response that is logically structured.","I must ensure that my tone is helpful, polite, and directly addresses the prompt.","This seems straightforward, but I will double check my logic.","Let's finalize the answer structure before generating the final output."]random.shuffle(think_parts)think_str = f"[THINK]\n{' '.join(think_parts[:7])}\n[/THINK]\n"asst_text = think_str + ans66 unmodified lines67686970717273749 unmodified lines848586878889909153 unmodified lines1451461471481491501511521531541551561577 unmodified lines16516616716816917017117217316 unmodified lines190191192193194195196197198199200201202203204205206207120 unmodified lines3283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773785 unmodified lines38438538638738838939039139239339417 unmodified lines41241341441541641741841942042142266 unmodified linesdef build_simple_example(user_text, assistant_text, category):style_rand = random.random()if style_rand < 0.03: style_idx = 1elif style_rand < 0.05: style_idx = 2else: style_idx = 0prefix = get_prompt_format(user_text, style_idx)9 unmodified linesdef build_search_example(user_text, search_query, search_result_text, final_answer, category):style_rand = random.random()if style_rand < 0.03: style_idx = 1elif style_rand < 0.05: style_idx = 2else: style_idx = 0prefix = get_prompt_format(user_text, style_idx)53 unmodified lines# Generate relevant synthetic contextif "gold" in user_query:context = f"Gold price today {today} is 72,000 INR per 10g in Delhi. Silver at 85,000 per kg. Market experts say prices up due to USD weakness and festive demand. MCX gold futures trading higher. This represents a solid growth curve recently. The local markets are buzzing with new investments."elif "india news" in user_query or "khabar" in user_query or "news" in user_query:context = f"India news {today}: PM Modi launched new infra projects worth 10k crore. Sensex up 300 pts, Nifty at 22k. IMD predicts rain in north India. ISRO announces new mission. Analysts consider these developments highly positive for the economy and tech sectors across the nation."elif "weather" in user_query or "mausam" in user_query:context = f"Weather in Delhi today {today}: 34C, partly cloudy, 70% humidity, light rain expected. Similar conditions are expected for the upcoming weekend. The air quality index remains moderate, so normal outdoor activities are generally safe for most healthy individuals."else:context = f"Latest update on {user_query} on {today}: New developments emerged, more details expected soon per sources. Experts suggest significant impacts from these events. Local authorities have already started deploying additional resources to handle any unprecedented changes in the current landscape."else:user_query = row["question"].strip()context = row["context"].strip()7 unmodified linestoday = datetime.now().strftime("%d %B %Y")# Format explicitly 3 results# Make sure context strings are decently padded to avoid empty stringscontext = (context * 5)[:500] if len(context) < 300 else contextddg_result = (f"[Today: {today}] Results:\n"f"1. {title1}: {context[:150]}\n"16 unmodified linesif is_hindi:ans_body = (f"Aaj ke search results [Today: {today}] ke mutabiq, yahan kuch mukhy baatein hain:\n"f"1. According to Result 1, {context[:120]}. Yeh darshata hai ki situation kaafi interesting tarike se aage badh rahi hai.\n"f"2. Result 2 ke mutabiq aur bhi details hain jaise ki {context[150:270]}. Experts ka manna hai ki yeh trend mahatvapurn hai.\n"f"3. Result 3 batata hai ki {context[300:420]}. Yeh situation ko samajhne me aur context add karta hai.\n\n"f"Summary: In sabhi sources ko dekh kar, hum keh sakte hain ki '{search_q}' ke baare mein taza jankari yahi bata rahi hai ki alag alag factors kaam kar rahe hain. For instance, Result 1 immediate facts pe focus karta hai, jabki Result 2 background add karta hai. Mujhe ummeed hai ye 2-3 paragraph breakdown aapke liye helpful hoga!")else:ans_body = (f"Based on today's results [Today: {today}], here are the detailed findings:\n"f"1. According to Result 1, {context[:120]}. This indicates a significant development.\n"f"2. From Result 2, we can see additional details such as {context[150:270]}. Experts note this trend is important.\n"f"3. Result 3 highlights that {context[300:420]}. This adds further context to the situation.\n\n"f"Summary: Synthesizing these three sources, it is evident that '{search_q}' involves multiple facets. The sources agree on core facts but provide different angles. For instance, Result 1 focuses on immediate facts, Result 2 adds background, Result 3 mentions future implications. Overall, situation is evolving and more updates expected. I hope this detailed 2-3 paragraph breakdown helps answer your query comprehensively with proper citations.\n")final_answer = think_str + ans_body120 unmodified lines# 3. EMPATHETIC DIALOGUES# =========================================================================def build_empathetic():print("\n[3/5] Empathetic Dialogues (18,000 examples)...")examples = []# Load real empathetic dataset if availabletry:from datasets import load_dataset# Try to load from HF - use daily_dialog which works, or use facebook dataset via csv fallbackds = load_dataset("daily_dialog", split="train", trust_remote_code=False)# daily_dialog format: dialog is list of utterancesfor i in range(min(12000, len(ds))):dialog = ds[i]["dialog"]if len(dialog) >= 2:q = dialog[-2].strip()a = dialog[-1].strip()if len(q) > 5 and len(a) > 10:ex = build_simple_example(q, a, "empathetic")if ex: examples.append(ex)print(f" Loaded {len(examples)} from daily_dialog")except Exception as e:print(f" daily_dialog failed: {e}")# Fill remaining with diverse synthetic - NOT same template repeatdiverse_q = ["I had a really bad day", "I feel so alone lately", "I'm stressed about work","My friend ignored me", "I'm nervous for interview tomorrow", "I miss my family","Bhai bore ho raha hu", "Aaj bohot thak gaya yaar", "Kuch samajh nahi aa raha","I am feeling happy today!", "I got promoted!", "I am worried about health","Exam ka tension ho raha hai", "Girlfriend se jhagda ho gaya", "I feel excited about trip"]diverse_a = ["I hear you, it sounds tough. Want to talk more about it?","It's okay to feel this way. Take a deep breath, I'm here.","That must be hard. Remember to take care of yourself.","I understand, sometimes things get overwhelming. How can I help?","Congrats! That's amazing news, tell me more!","Arre tension mat le yaar, sab theek ho jayega. Bata kya hua?","Take some rest, you deserve a break. Chai pee le thodi.","Main samajh sakta hu, aisa kabhi kabhi hota hai. Baat karein?",]import random as rndwhile len(examples) < 18000:q = rnd.choice(diverse_q) + (rnd.choice(["", " yaar", " bhai", " today"]) if rnd.random()<0.5 else "")a = rnd.choice(diverse_a)ex = build_simple_example(q, a, "empathetic")if ex: examples.append(ex)random.shuffle(examples)return examples[:17100], examples[17100:18000] # 900 val5 unmodified linesexamples = []try:ds = load_dataset("databricks/databricks-dolly-15k", split="train", trust_remote_code=True)pool = list(ds)if len(pool) < 18000:pool = pool + pool[:18000 - len(pool)]for row in tqdm(pool[:18000], desc="Dolly"):q = row["instruction"].strip()if row.get("input", "").strip(): q += "\n" + row["input"].strip()a = row["response"].strip()17 unmodified linesif row.get("input", "").strip(): q += "\n" + row["input"].strip()ans = row["output"].strip()# Query-specific THINK, not generic shuffleif len(q) < 50:think_str = f"[THINK]\nUser asks short question: '{q[:80]}'. Need concise factual answer. Plan: Identify key term, give direct answer.\n[/THINK]\n"else:think_str = f"[THINK]\nUser query: '{q[:100]}...'. This requires step-by-step reasoning. Steps: 1) Understand intent, 2) Recall relevant knowledge, 3) Structure answer clearly.\n[/THINK]\n"asst_text = think_str + ans
code/build_sft_data_v6.py+69-62