Download KidsQuestions.py from SMLBuilder/AAC_Children_Conversations: direct link, hf CLI and curl.
- Browser
- Download file 18.8 kB
-
https://huggingface.co/datasets/SMLBuilder/AAC_Children_Conversations/resolve/main/KidsQuestions.py
- Command line
-
hf download hf://datasets/SMLBuilder/AAC_Children_Conversations/KidsQuestions.py
-
curl -L -o KidsQuestions.py https://huggingface.co/datasets/SMLBuilder/AAC_Children_Conversations/resolve/main/KidsQuestions.py
18.8 kB
| #!/usr/bin/env python3 | |
| """ | |
| BRANCHING CONVERSATION TREE HARVESTER | |
| ====================================== | |
| Creates massive conversation trees where each answer spawns a new branch. | |
| Structure: | |
| Question β 6 Answers | |
| Each Answer β AI decides: continue? | |
| If yes β New Question β 6 Answers β repeat | |
| If no β Branch ends | |
| Budget-friendly: Batches API calls efficiently | |
| """ | |
| import sys | |
| import json | |
| import requests | |
| import time | |
| import uuid | |
| import os | |
| from collections import deque | |
| # ---------------------------------------- | |
| # CONFIG | |
| # ---------------------------------------- | |
| GROK_API_KEY = "" | |
| GROK_URL = "https://api.x.ai/v1/chat/completions" | |
| MAX_DEPTH = 7 # Prevent infinite trees (safety) | |
| OUTPUT_DIR = "/Volumes/MacMVP/Harvest/" | |
| # ---------------------------------------- | |
| # CALL GROK | |
| # ---------------------------------------- | |
| def call_grok(prompt): | |
| payload = { | |
| "model": "grok-4-1-fast-reasoning", | |
| "messages": [ | |
| {"role": "system", "content": "You are a High Times Cannabis Cup Strain Winner"}, | |
| {"role": "user", "content": prompt} | |
| ], | |
| "stream": False, | |
| "temperature": 0.8 | |
| } | |
| headers = { | |
| "Content-Type": "application/json", | |
| "Authorization": f"Bearer {GROK_API_KEY}" | |
| } | |
| r = requests.post(GROK_URL, headers=headers, json=payload) | |
| r.raise_for_status() | |
| return r.json()["choices"][0]["message"]["content"] | |
| def generate_simplified_qa(topic, goal, context=""): | |
| """Simplified version with minimal fields for fallback.""" | |
| prompt = f""" | |
| Generate a cannabis shopping conversation. | |
| Topic: {topic} | |
| Goal: {goal} | |
| {f'Context: {context}' if context else ''} | |
| Return ONLY this exact JSON structure: | |
| {{ | |
| "question": {{ | |
| "sentence": "Customer question about cannabis", | |
| "intent": "ask" | |
| }}, | |
| "answers": [ | |
| {{"sentence": "Bud tender response 1", "intent": "inform"}}, | |
| {{"sentence": "Bud tender response 2", "intent": "inform"}}, | |
| {{"sentence": "Bud tender response 3", "intent": "inform"}}, | |
| {{"sentence": "Bud tender response 4", "intent": "inform"}}, | |
| {{"sentence": "Bud tender response 5", "intent": "inform"}}, | |
| {{"sentence": "Bud tender response 6", "intent": "inform"}} | |
| ] | |
| }} | |
| """ | |
| try: | |
| result = call_grok(prompt) | |
| result = extract_json(result) | |
| data = json.loads(result) | |
| # Add default fields to match expected structure | |
| if "question" in data: | |
| data["question"].setdefault("emoji", "πΏ") | |
| data["question"].setdefault("words", "question") | |
| data["question"].setdefault("verb", "ask") | |
| data["question"].setdefault("action", "asking") | |
| data["question"].setdefault("emotion", "curious") | |
| data["question"].setdefault("visual_representation", "person asking") | |
| data["question"].setdefault("entities", []) | |
| data["question"].setdefault("svo_triple", "customer-asks-question") | |
| data["question"].setdefault("complexity_level", "simple") | |
| data["question"].setdefault("reading_level", "8") | |
| data["question"].setdefault("speech_pattern", "normal") | |
| data["question"].setdefault("cognitive_load", "low") | |
| data["question"].setdefault("confidence_score", 0.8) | |
| data["question"].setdefault("learning_objective", "understand options") | |
| data["question"].setdefault("prerequisites", []) | |
| data["question"].setdefault("follow_up_suggestions", []) | |
| data["question"].setdefault("audio_tts_hints", "normal pace") | |
| data["question"].setdefault("visual_aids", []) | |
| data["question"].setdefault("connectors", { | |
| "parent": "cannabis", | |
| "subcategory": "shopping", | |
| "related_to": [], | |
| "causes": [], | |
| "requires": [], | |
| "part_of": [], | |
| "next_step": [], | |
| "previous_step": [] | |
| }) | |
| if "answers" in data: | |
| for i, answer in enumerate(data["answers"]): | |
| answer.setdefault("emoji", "π") | |
| answer.setdefault("words", f"answer {i+1}") | |
| answer.setdefault("verb", "inform") | |
| answer.setdefault("action", "informing") | |
| answer.setdefault("emotion", "helpful") | |
| answer.setdefault("visual_representation", "bud tender explaining") | |
| answer.setdefault("entities", []) | |
| answer.setdefault("svo_triple", "tender-informs-customer") | |
| answer.setdefault("complexity_level", "simple") | |
| answer.setdefault("reading_level", "8") | |
| answer.setdefault("speech_pattern", "friendly") | |
| answer.setdefault("cognitive_load", "low") | |
| answer.setdefault("confidence_score", 0.9) | |
| answer.setdefault("relevance_score", 0.8) | |
| answer.setdefault("learning_objective", "understand strains") | |
| answer.setdefault("prerequisites", []) | |
| answer.setdefault("follow_up_suggestions", []) | |
| answer.setdefault("audio_tts_hints", "warm tone") | |
| answer.setdefault("visual_aids", []) | |
| answer.setdefault("connectors", { | |
| "parent": "cannabis", | |
| "subcategory": "strains", | |
| "related_to": [], | |
| "causes": [], | |
| "requires": [], | |
| "part_of": [], | |
| "next_step": [], | |
| "previous_step": [] | |
| }) | |
| return data | |
| except Exception as e: | |
| print(f" β οΈ Simplified generation also failed: {e}") | |
| return None | |
| def extract_json(result): | |
| """Extract JSON from markdown code blocks or raw text.""" | |
| # Try to extract from markdown code blocks first | |
| if "```json" in result: | |
| result = result.split("```json")[1].split("```")[0].strip() | |
| elif "```" in result: | |
| result = result.split("```")[1].split("```")[0].strip() | |
| # Try to find JSON object boundaries | |
| if not result.startswith("{"): | |
| # Look for the first { and last } | |
| start_idx = result.find("{") | |
| if start_idx != -1: | |
| # Find matching closing brace | |
| depth = 0 | |
| end_idx = -1 | |
| for i in range(start_idx, len(result)): | |
| if result[i] == "{": | |
| depth += 1 | |
| elif result[i] == "}": | |
| depth -= 1 | |
| if depth == 0: | |
| end_idx = i | |
| break | |
| if end_idx != -1: | |
| result = result[start_idx:end_idx+1] | |
| return result.strip() | |
| # ---------------------------------------- | |
| # GENERATE QUESTION + 6 ANSWERS (1 CALL) | |
| # ---------------------------------------- | |
| def generate_question_with_answers(topic, goal, context="", retry_count=0): | |
| """Generate 6 caanbis strain related questions + Bud Tender 6 answers in a SINGLE API call.""" | |
| # Simplify prompt on retries | |
| if retry_count > 0: | |
| return generate_simplified_qa(topic, goal, context) | |
| prompt = f""" | |
| Topic: "{topic}" | |
| Goal: "{goal}" | |
| {f'Context: {context}' if context else ''} | |
| Generate ONE Cannabis Consumer question and SIX different Bud Tender answers. | |
| The structure must include: | |
| 1. ONE Cannabis Consumer question PEEL tile (intent: "ask") | |
| 2. EXACTLY SIX different Bud Tender answer PEEL tiles (intent: "inform") | |
| Make the Bud Tender's answers natural and helpful, steering toward: {goal} | |
| IMPORTANT: | |
| - Each answer should guide toward purchasing/trying recommended strains | |
| - Keep answers conversational and informative | |
| - Focus on benefits and experiences | |
| Return ONLY valid JSON (no markdown): | |
| {{ | |
| "question": {{ | |
| "emoji": "<emoji>", | |
| "words": "<2-4 word simplified version of sentence>", | |
| "sentence": "<question>", | |
| "verb": "<verb>", | |
| "action": "<what action is being performed>", | |
| "intent": "ask", | |
| "emotion": "<emotional state of person saying this>", | |
| "visual_representation": "<visual>", | |
| "entities": ["x","y"], | |
| "svo_triple": "<subject-verb-object>", | |
| "complexity_level": "<simple|medium|complex>", | |
| "reading_level": "<grade level 1-12>", | |
| "speech_pattern": "<how to speak: pace, emphasis>", | |
| "cognitive_load": "<low|medium|high>", | |
| "confidence_score": <0.0-1.0>, | |
| "learning_objective": "<what user should learn>", | |
| "prerequisites": ["<assumed knowledge>"], | |
| "follow_up_suggestions": ["<exploration hints>"], | |
| "audio_tts_hints": "<pronunciation, pauses, emphasis>", | |
| "visual_aids": ["<suggested images/icons>"], | |
| "connectors": {{ | |
| "parent": "<category>", | |
| "subcategory": "<subdomain>", | |
| "related_to": ["x"], | |
| "causes": ["y"], | |
| "requires": ["z"], | |
| "part_of": ["a"], | |
| "next_step": ["b"], | |
| "previous_step": ["c"] | |
| }} | |
| }}, | |
| "answers": [ | |
| {{ | |
| "emoji": "<emoji>", | |
| "words": "<2-4 word simplified version of sentence>", | |
| "sentence": "<answer>", | |
| "verb": "<verb>", | |
| "action": "<what action is being performed>", | |
| "intent": "inform", | |
| "emotion": "<emotional state of person saying this>", | |
| "visual_representation": "<visual>", | |
| "entities": ["x","y"], | |
| "svo_triple": "<subject-verb-object>", | |
| "complexity_level": "<simple|medium|complex>", | |
| "reading_level": "<grade level 1-12>", | |
| "speech_pattern": "<how to speak: pace, emphasis>", | |
| "cognitive_load": "<low|medium|high>", | |
| "confidence_score": <0.0-1.0>, | |
| "relevance_score": <0.0-1.0>, | |
| "learning_objective": "<what user should learn>", | |
| "prerequisites": ["<assumed knowledge>"], | |
| "follow_up_suggestions": ["<exploration hints>"], | |
| "audio_tts_hints": "<pronunciation, pauses, emphasis>", | |
| "visual_aids": ["<suggested images/icons>"], | |
| "connectors": {{ | |
| "parent": "<category>", | |
| "subcategory": "<subdomain>", | |
| "related_to": ["x"], | |
| "causes": ["y"], | |
| "requires": ["z"], | |
| "part_of": ["a"], | |
| "next_step": ["b"], | |
| "previous_step": ["c"] | |
| }} | |
| }} | |
| ] | |
| }} | |
| Make sure "answers" array contains EXACTLY 6 elements, each with different recommendations. | |
| """ | |
| try: | |
| result = call_grok(prompt) | |
| # Handle if API returns an array instead of object | |
| if result.strip().startswith('['): | |
| # Extract first item from array | |
| result = result.strip()[1:-1] if result.strip().endswith(']') else result.strip()[1:] | |
| result = extract_json(result) | |
| data = json.loads(result) | |
| if "question" in data and "answers" in data and len(data["answers"]) == 6: | |
| return data | |
| else: | |
| print(f" β οΈ Invalid structure: got {len(data.get('answers', []))} answers instead of 6") | |
| return None | |
| except json.JSONDecodeError as e: | |
| print(f" β οΈ JSON parsing error: {e}") | |
| return None | |
| except Exception as e: | |
| print(f" β οΈ Failed to generate Q+A: {e}") | |
| if retry_count < 1: | |
| print(f" π Retrying with simplified format...") | |
| return generate_question_with_answers(topic, goal, context, retry_count + 1) | |
| return None | |
| # ---------------------------------------- | |
| # BATCH DECIDE CONTINUATIONS (1 CALL FOR ALL 6) | |
| # ---------------------------------------- | |
| def batch_decide_continuations(topic, answer_tiles): | |
| """Decide if each of 6 Cannabis Shoper answers should continue - ONE API call.""" | |
| answers_text = "\n".join([f"{i+1}. {a['sentence']}" for i, a in enumerate(answer_tiles)]) | |
| prompt = f""" | |
| Topic: "{topic}" | |
| For each answer below, decide if the conversation should naturally continue: | |
| {answers_text} | |
| Return ONLY valid JSON array of 6 booleans (no markdown): | |
| [true, false, true, false, true, false] | |
| Consider for EACH: | |
| - Is there more to explore? | |
| - Would a follow-up feel natural? | |
| - Is this answer complete or needs elaboration? | |
| """ | |
| try: | |
| result = call_grok(prompt) | |
| result = extract_json(result) | |
| decisions = json.loads(result) | |
| if isinstance(decisions, list) and len(decisions) == 6: | |
| return decisions | |
| else: | |
| # Default: first 3 continue, last 3 stop | |
| return [True, True, True, False, False, False] | |
| except Exception as e: | |
| print(f" β οΈ Batch decision failed: {e}") | |
| return [True, True, False, False, False, False] | |
| # ---------------------------------------- | |
| # BUILD CONVERSATION TREE | |
| # ---------------------------------------- | |
| def build_single_tree(topic, goal): | |
| """Build one conversation tree using breadth-first expansion.""" | |
| # Generate unique conversation ID | |
| conversation_id = str(uuid.uuid4()) | |
| # Start with root question | |
| root = generate_question_with_answers(topic, goal) | |
| if not root: | |
| print(" β Failed to generate root") | |
| return None | |
| # Add metadata to root question | |
| root_tile_id = str(uuid.uuid4()) | |
| root["question"]["tile_id"] = root_tile_id | |
| root["question"]["conversation_id"] = conversation_id | |
| root["question"]["depth_level"] = 0 | |
| root["question"]["parent_tile_id"] = None | |
| root["question"]["branch_path"] = "0" | |
| root["question"]["turn_number"] = 0 | |
| tree = { | |
| "conversation_id": conversation_id, | |
| "topic": topic, | |
| "question": root["question"], | |
| "branches": [] | |
| } | |
| # Queue: (answer_tile, depth, parent_branch, parent_tile_id, branch_index, turn_number) | |
| queue = deque() | |
| for idx, answer in enumerate(root["answers"]): | |
| # Add metadata to answer | |
| answer_tile_id = str(uuid.uuid4()) | |
| answer["tile_id"] = answer_tile_id | |
| answer["conversation_id"] = conversation_id | |
| answer["depth_level"] = 1 | |
| answer["parent_tile_id"] = root_tile_id | |
| answer["branch_path"] = f"0β{idx}" | |
| answer["turn_number"] = 1 | |
| branch = { | |
| "answer": answer, | |
| "continuation": None | |
| } | |
| tree["branches"].append(branch) | |
| queue.append((answer, 1, branch, answer_tile_id, idx, 1)) | |
| time.sleep(0.2) | |
| # Process queue breadth-first - ALWAYS generate 6 options for EVERY path | |
| while queue: | |
| item = queue.popleft() | |
| answer_tile, depth, parent_branch, parent_tile_id, branch_idx, turn_num = item | |
| if depth >= MAX_DEPTH: | |
| continue | |
| print(f" π Generating 6 follow-ups for: '{answer_tile['sentence'][:40]}...' (depth {depth})") | |
| context = f"Previous statement: {answer_tile['sentence']}" | |
| follow_up = generate_question_with_answers(topic, goal, context) | |
| if follow_up: | |
| # Add metadata to follow-up question | |
| followup_q_tile_id = str(uuid.uuid4()) | |
| follow_up["question"]["tile_id"] = followup_q_tile_id | |
| follow_up["question"]["conversation_id"] = conversation_id | |
| follow_up["question"]["depth_level"] = depth + 1 | |
| follow_up["question"]["parent_tile_id"] = parent_tile_id | |
| follow_up["question"]["branch_path"] = f"{answer_tile['branch_path']}βQ" | |
| follow_up["question"]["turn_number"] = turn_num + 1 | |
| continuation = { | |
| "question": follow_up["question"], | |
| "branches": [] | |
| } | |
| parent_branch["continuation"] = continuation | |
| # Add ALL 6 answers to queue (no filtering) | |
| for ans_idx, ans in enumerate(follow_up["answers"]): | |
| ans_tile_id = str(uuid.uuid4()) | |
| ans["tile_id"] = ans_tile_id | |
| ans["conversation_id"] = conversation_id | |
| ans["depth_level"] = depth + 2 | |
| ans["parent_tile_id"] = followup_q_tile_id | |
| ans["branch_path"] = f"{follow_up['question']['branch_path']}β{ans_idx}" | |
| ans["turn_number"] = turn_num + 2 | |
| new_branch = { | |
| "answer": ans, | |
| "continuation": None | |
| } | |
| continuation["branches"].append(new_branch) | |
| queue.append((ans, depth + 2, new_branch, ans_tile_id, ans_idx, turn_num + 2)) | |
| time.sleep(0.2) | |
| print(f" β Tree complete!") | |
| return tree | |
| # ---------------------------------------- | |
| # HARVEST | |
| # ---------------------------------------- | |
| def harvest(topic, goal, num_trees=10): | |
| print(f"π Starting harvest for: {topic}", flush=True) | |
| print(f"π― With goal: {goal}", flush=True) | |
| print(f"π² Number of trees to build: {num_trees}", flush=True) | |
| # Create output directory | |
| os.makedirs(OUTPUT_DIR, exist_ok=True) | |
| out = os.path.join(OUTPUT_DIR, f"tree_{topic.replace(' ', '_')}.json") | |
| print(f"π Output file: {out}", flush=True) | |
| # Load existing | |
| try: | |
| with open(out, "r") as f: | |
| all_trees = json.load(f) | |
| print(f"π Resuming: loaded {len(all_trees)} existing trees", flush=True) | |
| except FileNotFoundError: | |
| all_trees = [] | |
| print(f"π Starting fresh harvest", flush=True) | |
| # Build trees ONE AT A TIME and save after each | |
| for i in range(len(all_trees), num_trees): | |
| print(f"\nπ³ Building conversation tree {i+1}/{num_trees}...", flush=True) | |
| print(f" π Topic: {topic}", flush=True) | |
| print(f" π― Goal: {goal}", flush=True) | |
| tree = build_single_tree(topic, goal) | |
| if tree: | |
| all_trees.append(tree) | |
| # Save immediately after each tree | |
| with open(out, "w") as f: | |
| json.dump(all_trees, f, indent=2) | |
| print(f" πΎ Saved! Total trees: {len(all_trees)}") | |
| else: | |
| print(f" β Failed to build tree {i+1}") | |
| # Count total tiles | |
| def count_tiles(node): | |
| count = 1 # question | |
| for branch in node.get("branches", []): | |
| count += 1 # answer | |
| if branch.get("continuation"): | |
| count += count_tiles(branch["continuation"]) | |
| return count | |
| total = sum(count_tiles(t) for t in all_trees) | |
| print(f"\nπ COMPLETE!") | |
| print(f"π Saved {len(all_trees)} conversation trees β {out}") | |
| print(f"π― Total PEEL tiles: {total}\n") | |
| # ---------------------------------------- | |
| # MAIN | |
| # ---------------------------------------- | |
| if __name__ == "__main__": | |
| if len(sys.argv) < 3: | |
| print("Usage: python3 tree_harvester.py \"Topic Here\" \"Goal Here\"") | |
| print("Example: python3 tree_harvester.py \"Old Person Cannabis Shopping\" \"Guide customer to purchase indica strains for pain relief\"") | |
| sys.exit(1) | |
| topic = sys.argv[1] | |
| goal = sys.argv[2] | |
| num_trees = int(sys.argv[3]) if len(sys.argv) > 3 else 2 # Default to 2 trees for testing | |
| harvest(topic, goal, num_trees=num_trees) | |