Spaces:
Runtime error
Runtime error
| import os | |
| import json | |
| import logging | |
| import random | |
| from typing import Optional | |
| from datetime import datetime, timedelta | |
| import re | |
| from google import genai | |
| from google.genai import types | |
| logger = logging.getLogger(__name__) | |
| _gemini_client = genai.Client(api_key=os.environ.get("GEMINI_API_KEY", "").strip()) | |
| _GEMINI_MODEL = os.environ.get("GOOGLE_MODEL", "gemini-2.5-flash").strip().strip("\"'") | |
| def _call_gemini(prompt: str, max_tokens: int = 400) -> str: | |
| """ | |
| Call Gemini with an explicit output-token budget. | |
| The consultation flow uses relatively short, structured narration beats. | |
| We keep the thinking budget effectively off so the model spends more of the | |
| budget on the answer itself instead of on hidden reasoning. | |
| """ | |
| try: | |
| response = _gemini_client.models.generate_content( | |
| model=_GEMINI_MODEL, | |
| contents=prompt, | |
| config=types.GenerateContentConfig( | |
| temperature=0.58, | |
| top_p=0.95, | |
| max_output_tokens=max_tokens, | |
| thinking_config=types.ThinkingConfig(thinking_budget=0), | |
| ) | |
| ) | |
| print("\n") | |
| print("=" * 80) | |
| print("FULL GEMINI RESPONSE") | |
| print(response) | |
| print("=" * 80) | |
| print("\n") | |
| result = "" | |
| try: | |
| result = response.text.strip() | |
| except Exception: | |
| pass | |
| if not result: | |
| try: | |
| parts = [] | |
| for part in response.candidates[0].content.parts: | |
| if hasattr(part, "text") and part.text: | |
| parts.append(part.text) | |
| result = " ".join(parts).strip() | |
| except Exception as e: | |
| logger.warning(f"[SCRIPT GEN] candidate extraction failed: {e}") | |
| logger.info(f"[SCRIPT GEN] response length={len(result)}") | |
| try: | |
| logger.info( | |
| f"[SCRIPT GEN] Finish reason: {response.candidates[0].finish_reason}" | |
| ) | |
| except Exception: | |
| pass | |
| logger.info(f"[SCRIPT GEN] Gemini {len(result)} chars") | |
| logger.info(f"[SCRIPT GEN] Gemini output: {result[:300]}") | |
| return _normalize_currency_mentions(result) | |
| except Exception as e: | |
| logger.error(f"[SCRIPT GEN] Gemini failed: {e}") | |
| return "" | |
| def _looks_truncated(text: str) -> bool: | |
| if not text: | |
| return True | |
| ending = text.strip()[-1:] | |
| if ending not in ".!?": | |
| return True | |
| return False | |
| def _contains_devanagari(text: str) -> bool: | |
| return bool(re.search(r'[\u0900-\u097F]', text)) | |
| def _validate_llm_output( | |
| text: str, | |
| min_words: int = 60, | |
| max_words: Optional[int] = None, | |
| preferred_language: str = "English", | |
| ) -> bool: | |
| if not text: | |
| return False | |
| cleaned = text.strip() | |
| if len(cleaned) < 45: | |
| return False | |
| words = cleaned.split() | |
| word_count = len(words) | |
| relaxed_min = max(14, int(min_words * 0.55)) | |
| if word_count < relaxed_min: | |
| return False | |
| if max_words is not None: | |
| relaxed_max = max_words + max(16, int(max_words * 0.25)) | |
| if word_count > relaxed_max: | |
| return False | |
| sentence_count = cleaned.count(".") + cleaned.count("!") + cleaned.count("?") | |
| if word_count >= 45 and sentence_count < 1: | |
| return False | |
| if word_count >= 90 and sentence_count < 2: | |
| return False | |
| if _looks_truncated(cleaned): | |
| return False | |
| if _is_english_language(preferred_language) and _contains_devanagari(cleaned): | |
| return False | |
| return True | |
| def _generate_with_retry( | |
| prompt: str, | |
| fallback: str, | |
| min_words: int = 60, | |
| max_words: Optional[int] = None, | |
| preferred_language: str = "English", | |
| attempts: int = 3, | |
| max_tokens: int = 700, | |
| fallback_variants: Optional[list[str]] = None, | |
| ): | |
| for attempt in range(attempts): | |
| result = _call_gemini( | |
| prompt, | |
| max_tokens=max_tokens | |
| ) | |
| logger.info( | |
| f"[SCRIPT GEN] Attempt {attempt+1} output: {result}" | |
| ) | |
| result = _normalize_currency_mentions(result) | |
| if _validate_llm_output( | |
| result, | |
| min_words=min_words, | |
| max_words=max_words, | |
| preferred_language=preferred_language | |
| ): | |
| logger.info( | |
| f"[SCRIPT GEN] valid output on attempt {attempt + 1}" | |
| ) | |
| return result | |
| logger.warning( | |
| f"[SCRIPT GEN] invalid output on attempt {attempt + 1}" | |
| ) | |
| logger.warning( | |
| "[SCRIPT GEN] falling back to deterministic narration" | |
| ) | |
| if fallback_variants: | |
| candidates = [variant for variant in fallback_variants if variant] | |
| if candidates: | |
| chosen = random.choice(candidates) | |
| return _normalize_currency_mentions(chosen) | |
| return _normalize_currency_mentions(fallback) | |
| def _consultation_context_payload( | |
| name: str, | |
| goal: str, | |
| skills: str, | |
| hours: str, | |
| timeline: str, | |
| milestone_ladder: list[dict], | |
| roadmap_modules: list[dict], | |
| scenario_title: Optional[str], | |
| skill_why: Optional[str], | |
| offer: dict, | |
| target_date: str, | |
| first_milestone_value: str, | |
| module_count: int, | |
| preferred_language: str, | |
| ) -> dict: | |
| preferred_language = _normalize_preferred_language(preferred_language) | |
| language_mix, language_style = _language_mix_targets(preferred_language) | |
| return { | |
| "name": name, | |
| "goal": goal, | |
| "skills": skills, | |
| "hours_per_week": hours, | |
| "timeline": timeline, | |
| "target_date": target_date, | |
| "offer": offer, | |
| "first_milestone_value": first_milestone_value, | |
| "module_count": module_count, | |
| "scenario_title": scenario_title, | |
| "skill_why": skill_why, | |
| "milestone_ladder": milestone_ladder, | |
| "roadmap_modules": roadmap_modules, | |
| "preferred_language": preferred_language, | |
| "language_mix": language_mix, | |
| "language_style": language_style, | |
| } | |
| def _consultation_prompt( | |
| beat_id: str, | |
| context: dict, | |
| instructions: str, | |
| min_words: int, | |
| max_words: int, | |
| ) -> str: | |
| preferred_language = context.get("preferred_language", "English") | |
| language_block = _language_prompt_block(preferred_language, beat_id=beat_id) | |
| return _normalize_spaces( | |
| f""" | |
| You are writing narration for a premium personalized consultation video. | |
| Beat: {beat_id} | |
| Audience: the specific learner in the context. | |
| Tone and style: | |
| - Speak directly to the learner in second person. | |
| - Sound strategic, warm, confident, and specific. | |
| - Keep the narration distinct from the other beats. | |
| - Do not use the phrase "the learner". | |
| - Do not read the roadmap like a catalog. | |
| - Avoid repeating the same sentence structure as the previous beat. | |
| - Use the learner's currency context in INR / rupees if money is mentioned. | |
| - Make the narration feel personalized to the user's onboarding answers, not like a generic sales pitch. | |
| - Use a human, natural cadence with one beat-specific idea per sentence. | |
| - {language_block} | |
| - Do not use bullet points, headings, markdown, quotes, or labels. | |
| - Write 3 to 5 full sentences in one paragraph. | |
| - Return only the narration paragraph. | |
| Length: | |
| - Target between {min_words} and {max_words} words. | |
| - Stay close to the target; this beat is part of a timed video. | |
| Context: | |
| {json.dumps(context, ensure_ascii=False, indent=2)} | |
| Instructions: | |
| {instructions} | |
| """ | |
| ) | |
| def _generate_beat_narration( | |
| beat_id: str, | |
| context: dict, | |
| instructions: str, | |
| fallback: str, | |
| min_words: int, | |
| max_words: int, | |
| max_tokens: int = 700, | |
| preferred_language: str = "English", | |
| fallback_variants: Optional[list[str]] = None, | |
| ) -> str: | |
| prompt = _consultation_prompt( | |
| beat_id=beat_id, | |
| context=context, | |
| instructions=instructions, | |
| min_words=min_words, | |
| max_words=max_words, | |
| ) | |
| return _generate_with_retry( | |
| prompt=prompt, | |
| fallback=fallback, | |
| min_words=min_words, | |
| max_words=max_words, | |
| preferred_language=preferred_language, | |
| attempts=3, | |
| max_tokens=max_tokens, | |
| fallback_variants=fallback_variants, | |
| ) | |
| def _beat5_section_prompt( | |
| section_id: str, | |
| context: dict, | |
| instructions: str, | |
| min_words: int, | |
| max_words: int, | |
| ) -> str: | |
| preferred_language = context.get("preferred_language", "English") | |
| language_block = _language_prompt_block(preferred_language, beat_id=section_id) | |
| return _normalize_spaces( | |
| f""" | |
| You are writing one section of Beat 5 for a personalized consultation video. | |
| Section: {section_id} | |
| Tone and style: | |
| - Speak directly to the learner in second person. | |
| - Be concrete and vivid. | |
| - Make the slide and narration feel tightly aligned. | |
| - Do not mention other Beat 5 sections. | |
| - Avoid repeated phrases like "the learner", "the roadmap", "the module stack", or "work starts to feel usable" unless the instruction explicitly asks for them. | |
| - Ensure section-specific wording stays unique: the project, scenario, checkpoint, outcomes, and tutor each need different wording and a different final emphasis. | |
| - Make the section feel human, specific, and visibly tied to the user's own inputs. | |
| - {language_block} | |
| - Write 3 to 5 full sentences in one paragraph. | |
| - Return only the narration paragraph. | |
| Length: | |
| - Target between {min_words} and {max_words} words. | |
| - This section must feel like a full part of the story, not a caption. | |
| Context: | |
| {json.dumps(context, ensure_ascii=False, indent=2)} | |
| Instructions: | |
| {instructions} | |
| """ | |
| ) | |
| def _generate_beat5_section_narration( | |
| section_id: str, | |
| context: dict, | |
| instructions: str, | |
| fallback: str, | |
| min_words: int, | |
| max_words: int, | |
| max_tokens: int = 800, | |
| preferred_language: str = "English", | |
| fallback_variants: Optional[list[str]] = None, | |
| ) -> str: | |
| prompt = _beat5_section_prompt( | |
| section_id=section_id, | |
| context=context, | |
| instructions=instructions, | |
| min_words=min_words, | |
| max_words=max_words, | |
| ) | |
| return _generate_with_retry( | |
| prompt=prompt, | |
| fallback=fallback, | |
| min_words=min_words, | |
| max_words=max_words, | |
| preferred_language=preferred_language, | |
| attempts=3, | |
| max_tokens=max_tokens, | |
| fallback_variants=fallback_variants, | |
| ) | |
| def _normalize_spaces(text: str) -> str: | |
| return re.sub(r"\s+", " ", text).strip() | |
| def _normalize_currency_mentions(text: str) -> str: | |
| """ | |
| Normalize accidental USD / dollar wording in generated narration. | |
| Consultation videos are localized for INR-based audiences here. | |
| """ | |
| if not text: | |
| return text | |
| cleaned = text | |
| cleaned = re.sub(r"\bUS\s*dollars?\b", "rupees", cleaned, flags=re.IGNORECASE) | |
| cleaned = re.sub(r"\bdollars?\b", "rupees", cleaned, flags=re.IGNORECASE) | |
| cleaned = re.sub(r"\bUSD\b", "INR", cleaned, flags=re.IGNORECASE) | |
| cleaned = re.sub(r"\$\s*(?=\d)", "₹", cleaned) | |
| return cleaned | |
| def _normalize_preferred_language(language: Optional[str]) -> str: | |
| value = (language or "English").strip() | |
| return value or "English" | |
| def _is_english_language(language: Optional[str]) -> bool: | |
| normalized = _normalize_preferred_language(language).lower() | |
| return normalized in {"english", "en"} | |
| def _language_mix_targets(preferred_language: Optional[str], beat_id: str = "") -> tuple[str, str]: | |
| """ | |
| Return a soft English / preferred-language ratio for the beat. | |
| We vary the target a little so the whole video feels balanced instead of segmented. | |
| """ | |
| preferred = _normalize_preferred_language(preferred_language) | |
| if _is_english_language(preferred): | |
| return ("100% English", "English only") | |
| beat_key = (beat_id or "").lower() | |
| if "beat_1" in beat_key or "beat_7" in beat_key: | |
| return (f"70% English / 30% {preferred}", "Mostly English with a short native-language line for warmth") | |
| if "beat_2" in beat_key or "beat_4" in beat_key: | |
| return (f"65% English / 35% {preferred}", "Balanced code-switching with the preferred language used for emotional emphasis") | |
| if "beat_5" in beat_key: | |
| return (f"60% English / 40% {preferred}", "Natural mixed narration that still keeps English dominant") | |
| return (f"65% English / 35% {preferred}", "Natural mixed narration with English leading") | |
| def _language_prompt_block( | |
| preferred_language: Optional[str], | |
| beat_id: str = "" | |
| ) -> str: | |
| preferred = _normalize_preferred_language(preferred_language) | |
| if _is_english_language(preferred): | |
| return ( | |
| "Language Rules (MANDATORY):\n" | |
| "- Write entirely in English.\n" | |
| "- Keep the narration natural, specific, conversational, and personalized.\n" | |
| "- Avoid generic motivational language.\n" | |
| "- Use the user's onboarding details and roadmap context naturally.\n" | |
| ) | |
| return ( | |
| f""" | |
| Language Rules (MANDATORY): | |
| 1. English MUST be the dominant language. | |
| 2. Approximately 65-70% of all words must be English. | |
| 3. Approximately 30-35% of all words may be {preferred}. | |
| 4. This is a bilingual consultation, NOT a translated consultation. | |
| 5. The FIRST sentence of the beat MUST be written completely in English. | |
| 6. Every beat must contain at least two full English sentences. | |
| 7. Never write more than one consecutive sentence in {preferred}. | |
| 8. Use {preferred} only for: | |
| - emotional emphasis | |
| - reassurance | |
| - conversational transitions | |
| - natural human reactions | |
| - short relational phrases | |
| 9. Keep the following primarily in English: | |
| - roadmap explanation | |
| - milestone explanation | |
| - module explanation | |
| - project explanation | |
| - scenario explanation | |
| - salary discussion | |
| - career guidance | |
| - outcomes | |
| - CTA | |
| 10. Use only English and {preferred}. | |
| Never introduce a third language. | |
| Never introduce a third script. | |
| Never use words or characters from any other language. | |
| 11. Do not write entire paragraphs in {preferred}. | |
| 12. Blend both languages naturally inside the narration. | |
| 13. Do not over-translate: | |
| - technical terms | |
| - module names | |
| - role names | |
| - company names | |
| - salary figures | |
| - software names | |
| 14. The final narration should feel like a professional mentor speaking mostly English while occasionally switching into {preferred} for warmth and human connection. | |
| 15. Avoid sounding like a translated script. | |
| Output only the narration. | |
| """ | |
| ).strip() | |
| def _join_phrases(items: list[str]) -> str: | |
| items = [item for item in items if item] | |
| if not items: | |
| return "" | |
| if len(items) == 1: | |
| return items[0] | |
| if len(items) == 2: | |
| return f"{items[0]} and {items[1]}" | |
| return ", ".join(items[:-1]) + f", and {items[-1]}" | |
| def _module_skill_names(module: dict) -> list[str]: | |
| skill_names = [] | |
| for skill in module.get("skills", []) or []: | |
| skill_name = ( | |
| skill.get("skill_name") | |
| or skill.get("title") | |
| or skill.get("name") | |
| ) | |
| if skill_name: | |
| skill_names.append(skill_name) | |
| return skill_names | |
| def _build_module_card(module: dict) -> dict: | |
| skill_names = _module_skill_names(module) | |
| return { | |
| "title": module.get("title", "Module"), | |
| "skills": skill_names, | |
| "skill_count": len(skill_names), | |
| "preview": _join_phrases(skill_names[:3]) if skill_names else "core capabilities", | |
| } | |
| def _transform_identity_statement( | |
| statement: str, | |
| goal: str = "", | |
| skills: str = "", | |
| label: str = "", | |
| milestone_index: int = 0, | |
| ) -> str: | |
| """ | |
| Convert a roadmap identity statement into a consequence-oriented line. | |
| The goal is to avoid narrating the statement verbatim on screen while still | |
| preserving the intent of each milestone. | |
| """ | |
| goal_phrase = goal or "your target role" | |
| label_text = _normalize_spaces(label or "") | |
| statement_l = _normalize_spaces(statement or "").lower() | |
| label_l = label_text.lower() | |
| if any(token in statement_l for token in ["excel", "email", "computer", "office", "typing", "files", "windows"]): | |
| if milestone_index <= 1: | |
| return _normalize_spaces( | |
| f"{label_text or 'This first milestone'} turns basic computer use into a working routine, so daily office tasks stop feeling intimidating." | |
| ) | |
| return _normalize_spaces( | |
| f"{label_text or 'This milestone'} turns everyday office tools into something you can use with less hesitation and more control." | |
| ) | |
| if any(token in statement_l for token in ["it support", "helpdesk", "troubleshoot", "troubleshooting", "printers", "network"]): | |
| if milestone_index <= 1: | |
| return _normalize_spaces( | |
| f"{label_text or 'This first milestone'} turns troubleshooting into a repeatable habit, so common support issues start feeling manageable." | |
| ) | |
| return _normalize_spaces( | |
| f"{label_text or 'This milestone'} turns support work into a practical response pattern, so problems feel easier to isolate and solve." | |
| ) | |
| if any(token in statement_l for token in ["data", "sql", "dashboard", "analysis", "model", "analytics"]): | |
| if milestone_index <= 1: | |
| return _normalize_spaces( | |
| f"{label_text or 'This first milestone'} turns raw data work into a clearer starting point, so the work starts to feel structured." | |
| ) | |
| return _normalize_spaces( | |
| f"{label_text or 'This milestone'} turns analysis into a more job-facing routine, so you move from clean inputs to useful output with more confidence." | |
| ) | |
| if label_l: | |
| if milestone_index <= 1 or any(token in label_l for token in ["foundation", "foundations", "core", "basics"]): | |
| return _normalize_spaces( | |
| f"{label_text} builds the base that makes {goal_phrase} work feel more familiar and less intimidating." | |
| ) | |
| if any(token in label_l for token in ["job ready", "practical", "ready", "execution"]): | |
| return _normalize_spaces( | |
| f"{label_text} turns that base into job-facing execution, so the work feels more familiar, manageable, and easier to trust." | |
| ) | |
| return _normalize_spaces( | |
| f"{label_text} gives you a more practical layer of capability, so the next step feels easier to trust." | |
| ) | |
| if statement_l: | |
| return _normalize_spaces( | |
| f"The work tied to {goal_phrase} starts to feel more familiar, manageable, and easier to trust." | |
| ) | |
| return _normalize_spaces( | |
| f"Daily work starts to feel more familiar because you have practiced the tools and routines tied to {goal_phrase}." | |
| ) | |
| def _build_milestone_cards(milestones: list, goal: str = "", skills: str = "") -> list[dict]: | |
| cards = [] | |
| for idx, milestone in enumerate(milestones, start=1): | |
| modules = [_build_module_card(mod) for mod in milestone.get("modules", []) or []] | |
| raw_statement = milestone.get("identity_statement", "") or "" | |
| label = milestone.get("identity_label", "") or f"Milestone {idx}" | |
| cards.append({ | |
| "index": idx, | |
| "label": label, | |
| "value": milestone.get("market_value_display", ""), | |
| "statement": _transform_identity_statement( | |
| raw_statement, | |
| goal=goal, | |
| skills=skills, | |
| label=label, | |
| milestone_index=idx, | |
| ), | |
| "statement_raw": raw_statement, | |
| "modules": modules, | |
| "module_count": len(modules), | |
| "module_preview": _join_phrases([m["title"] for m in modules[:4]]), | |
| }) | |
| return cards | |
| def _build_roadmap_summary(milestone_ladder: list[dict]) -> list[str]: | |
| summary_lines = [] | |
| total = len(milestone_ladder) | |
| for card in milestone_ladder: | |
| label = card.get("label") or f"Milestone {card.get('index', '')}".strip() | |
| value = card.get("value") or "open" | |
| module_preview = card.get("module_preview") or "core modules" | |
| statement = card.get("statement") or "This milestone builds a job-ready layer of capability." | |
| summary_lines.append( | |
| f"{label} ({value}) combines {module_preview}. {statement}" | |
| ) | |
| if total: | |
| summary_lines.append( | |
| f"Together these milestones form a step-by-step path instead of a random catalogue of lessons." | |
| ) | |
| return summary_lines | |
| def _estimate_words(*parts: str) -> int: | |
| return len(" ".join(parts).split()) | |
| def _first_nonempty(*values: Optional[str]) -> str: | |
| for value in values: | |
| if isinstance(value, str) and value.strip(): | |
| return value.strip() | |
| return "" | |
| def _iter_nested_items(node): | |
| if isinstance(node, dict): | |
| yield node | |
| for value in node.values(): | |
| yield from _iter_nested_items(value) | |
| elif isinstance(node, list): | |
| for item in node: | |
| yield from _iter_nested_items(item) | |
| def _extract_first_project(roadmap: dict) -> dict: | |
| for node in _iter_nested_items(roadmap or {}): | |
| projects = node.get("projects") | |
| if isinstance(projects, list) and projects: | |
| first = projects[0] | |
| if isinstance(first, dict): | |
| return first | |
| project = node.get("project") | |
| if isinstance(project, dict): | |
| return project | |
| return {} | |
| def _extract_first_mock(roadmap: dict) -> dict: | |
| for milestone in (roadmap or {}).get("milestones", []) or []: | |
| for module in milestone.get("modules", []) or []: | |
| for skill in module.get("skills", []) or []: | |
| flow = skill.get("content_flow", {}) or {} | |
| mock = flow.get("mock") or {} | |
| if isinstance(mock, dict) and mock: | |
| return { | |
| "mock": mock, | |
| "skill": skill, | |
| "module": module, | |
| "milestone": milestone, | |
| "flow": flow, | |
| } | |
| return {} | |
| def _derive_project_teaser(goal: str, module_names: list[str], roadmap: dict) -> str: | |
| project = _extract_first_project(roadmap) | |
| title = _first_nonempty(project.get("title"), project.get("name")) | |
| deliverable = _first_nonempty(project.get("deliverable"), project.get("summary"), project.get("description")) | |
| phases = project.get("phases") if isinstance(project.get("phases"), list) else [] | |
| phase_hint = _join_phrases([str(p).replace("_", " ") for p in phases[:3]]) if phases else "" | |
| if title or deliverable: | |
| parts = [f"Real project teaser: {title or 'your first project'}."] | |
| if deliverable: | |
| parts.append(f"By the end of this milestone, you will complete {deliverable}.") | |
| if phase_hint: | |
| parts.append(f"It moves through {phase_hint} before the final check.") | |
| return _normalize_spaces(" ".join(parts)) | |
| focus = _join_phrases(module_names[:3]) if module_names else "the core modules" | |
| return _normalize_spaces( | |
| f"By the end of this milestone, you will complete a realistic work simulation that combines {focus} into one practical workflow used in {goal}." | |
| ) | |
| def _derive_mock_teaser(goal: str, roadmap: dict, scenario_title: str = "") -> str: | |
| mock_info = _extract_first_mock(roadmap) | |
| mock = mock_info.get("mock", {}) if mock_info else {} | |
| sample_question = _first_nonempty( | |
| mock.get("sample_question"), | |
| mock.get("question"), | |
| mock.get("prompt"), | |
| ) | |
| if sample_question: | |
| return _normalize_spaces( | |
| f"Mock teaser: the checkpoint also includes a question like {sample_question}" | |
| ) | |
| scenario_hint = scenario_title or f"a real task a {goal} handles at work" | |
| return _normalize_spaces( | |
| f"Mock teaser: you will also face a short practice question based on {scenario_hint}, so the feedback checks recall and judgment instead of memorization." | |
| ) | |
| def _derive_checkpoint_teaser(roadmap: dict) -> str: | |
| mock_info = _extract_first_mock(roadmap) | |
| mock = mock_info.get("mock", {}) if mock_info else {} | |
| milestone = mock_info.get("milestone", {}) if mock_info else {} | |
| checkpoint_rule = milestone.get("checkpoint_rule", {}) if isinstance(milestone.get("checkpoint_rule"), dict) else {} | |
| required = checkpoint_rule.get("required_mastery") or mock.get("unlock_mastery") or 0.90 | |
| required_pct = int(round(float(required) * 100)) | |
| return _normalize_spaces( | |
| f"Checkpoint teaser: before the next module unlocks, you complete a practical check at {required_pct}% mastery, so you show the task instead of just recognising it." | |
| ) | |
| def _derive_outcome_line(goal: str, skills: str) -> str: | |
| foundation = skills or "your current foundation" | |
| return _normalize_spaces( | |
| f"Expected outcome: with practice on {foundation}, daily work starts to feel less intimidating, and the same office tasks become more repeatable, steadier, and easier to finish cleanly in {goal} work." | |
| ) | |
| def _derive_ai_tutor_line(goal: str) -> str: | |
| return _normalize_spaces( | |
| f"AI tutor support: the tutor stays inside every lesson, slows things down when needed, gives hints, and can translate the instruction into plain language without removing the practice that builds real confidence for {goal}." | |
| ) | |
| def _generate_future_self_narration( | |
| name: str, goal: str, timeline: str, | |
| identity_statement: str, market_value: str, | |
| skills: str | |
| ) -> str: | |
| """ | |
| Beat 2 — the want. | |
| Keep it concrete, specific, and job-facing. | |
| """ | |
| foundation = skills if skills else "your current foundation" | |
| goal_phrase = goal or "your target role" | |
| future_identity = _transform_identity_statement(identity_statement, goal=goal_phrase, skills=foundation) | |
| current_state = ( | |
| "Right now, a new workplace task can still slow you down because you have not seen that exact situation enough times yet." | |
| ) | |
| future_state = ( | |
| f"In {timeline}, similar situations feel familiar because you have already practiced them repeatedly." | |
| ) | |
| confidence_line = ( | |
| f"That means daily work stops feeling intimidating, and {future_identity[0].lower() + future_identity[1:] if future_identity else 'you start trusting your decisions more.'}" | |
| ) | |
| market_line = ( | |
| f"The market value for this level of judgment sits around {market_value}." | |
| if market_value else | |
| "" | |
| ) | |
| return _normalize_spaces(" ".join([current_state, future_state, confidence_line, market_line])) | |
| def _generate_stakes_narration( | |
| goal: str, | |
| module_count: int, | |
| skills: str | |
| ) -> str: | |
| """ | |
| Beat 3 — why it's reachable (EPPM arc). | |
| Fear -> Efficacy | |
| """ | |
| foundation = skills if skills else "your current foundation" | |
| return _normalize_spaces( | |
| f"Staying still means the gap keeps widening while other candidates keep learning the exact capabilities employers ask for. " | |
| f"Between you and becoming a {goal}, there are only {module_count} learnable capabilities, which is a real gap but not an impossible one. " | |
| f"You already bring {foundation} to the table, so you are not starting from zero. " | |
| f"You are starting from a base that can be sharpened into job-ready judgment, and that is the part most people miss. " | |
| f"The gap is real. It is also crossable." | |
| ) | |
| def _generate_whats_inside_narration( | |
| goal: str, | |
| scenario_title: Optional[str], | |
| skill_why: Optional[str], | |
| roadmap_modules: list, | |
| skills: str | |
| ) -> str: | |
| """ | |
| Legacy single-block narration. The current render path uses split sections, | |
| but we keep this helper for compatibility. | |
| """ | |
| scenario_line = scenario_title or f"a real situation a {goal} faces on the job" | |
| why_line = skill_why or f"the capability that separates {goal}s who get hired" | |
| module_names = [m.get("title", "Module") for m in (roadmap_modules or [])[:4]] | |
| focus = _join_phrases(module_names) if module_names else "the core modules" | |
| foundation = skills if skills else "your current foundation" | |
| return _normalize_spaces( | |
| f"Your learning path begins with {focus}. " | |
| f"Real scenario: {scenario_line}. " | |
| f"Expected outcomes: with practice on {foundation}, daily work starts to feel less intimidating. " | |
| f"AI tutor support: the tutor stays inside every lesson and helps when you get stuck. " | |
| f"Checkpoint teaser: before the next module unlocks, you complete a practical check that proves you can perform the task, not just recognise it. " | |
| f"That is why this step matters: {why_line}." | |
| ) | |
| def _generate_whats_inside_sections( | |
| goal: str, | |
| scenario_title: Optional[str], | |
| skill_why: Optional[str], | |
| roadmap_modules: list, | |
| skills: str, | |
| roadmap: Optional[dict] = None | |
| ) -> list[dict]: | |
| """ | |
| Beat 5 is rendered as separate synchronized sections so each slide | |
| carries a distinct part of the story. | |
| """ | |
| scenario_line = scenario_title or f"a real situation a {goal} faces on the job" | |
| why_line = skill_why or f"the capability that separates {goal}s who get hired" | |
| modules = roadmap_modules[:4] if roadmap_modules else [] | |
| module_names = [m.get("title", "Module") for m in modules] | |
| if modules: | |
| module_overview_parts = [] | |
| for idx, module in enumerate(modules, start=1): | |
| title = module.get("title", f"Module {idx}") | |
| preview = module.get("preview") or _join_phrases(module.get("skills", [])[:3]) or "core practice" | |
| if idx == 1: | |
| tail = "so the first layer feels familiar instead of abstract" | |
| elif idx == 2: | |
| tail = "so the work starts to feel usable in a real setting" | |
| elif idx == 3: | |
| tail = "so the communication layer connects to actual office work" | |
| else: | |
| tail = "so the final layer closes the loop with problem-solving" | |
| module_overview_parts.append(f"{title} opens with {preview}, {tail}.") | |
| module_overview = ( | |
| f"Your learning path begins with {_join_phrases(module_names)}. " | |
| + " ".join(module_overview_parts) | |
| ) | |
| else: | |
| module_overview = ( | |
| f"Your learning path begins with the core modules already mapped out. " | |
| f"The first layer feels familiar instead of abstract. " | |
| f"The second layer makes the work usable in a real setting. " | |
| f"The third layer connects communication to office work. " | |
| f"The final layer closes the loop with problem-solving." | |
| ) | |
| project_line = _derive_project_teaser(goal, module_names, roadmap or {}) | |
| mock_line = _derive_mock_teaser(goal, roadmap or {}, scenario_line) | |
| checkpoint_line = _derive_checkpoint_teaser(roadmap or {}) | |
| outcomes_line = _derive_outcome_line(goal, skills) | |
| tutor_line = _derive_ai_tutor_line(goal) | |
| section_templates = [ | |
| ("beat_5a_modules", "src/template/consultation/beat_5a_modules.html", module_overview), | |
| ("beat_5b_project", "src/template/consultation/beat_5b_project.html", project_line), | |
| ("beat_5c_scenario", "src/template/consultation/beat_5c_scenario.html", f"Real scenario: {scenario_line}. In that moment, you are not watching theory for the sake of theory. You are following a workflow, checking the result, correcting the mistake, and moving the task forward. That is why this step matters: {why_line}."), | |
| ("beat_5d_checkpoint", "src/template/consultation/beat_5d_checkpoint.html", f"{checkpoint_line} {mock_line}"), | |
| ("beat_5e_outcomes", "src/template/consultation/beat_5e_outcomes.html", outcomes_line), | |
| ("beat_5f_ai_tutor", "src/template/consultation/beat_5f_ai_tutor.html", tutor_line), | |
| ] | |
| sections = [] | |
| for beat_id, template_path, narration in section_templates: | |
| sections.append({ | |
| "beat_id": beat_id, | |
| "template_path": template_path, | |
| "narration": _normalize_spaces(narration), | |
| "on_screen": {}, | |
| }) | |
| return sections | |
| def _get_target_date(timeline: str) -> str: | |
| """Convert timeline string to approximate target date for peak-end frame.""" | |
| import re | |
| match = re.search(r'(\d+)', timeline) | |
| if match: | |
| months = int(match.group(1)) | |
| target = datetime.now() + timedelta(days=months * 30) | |
| return target.strftime("%B %Y") | |
| return "your target date" | |
| def build_consultation_script( | |
| onboarding: dict, | |
| roadmap: dict, | |
| offer: dict | |
| ) -> list: | |
| """ | |
| 7-beat consultation video script. | |
| The script must feel personalized, concrete, and earned. | |
| """ | |
| name = onboarding.get("user_name") or "there" | |
| goal = onboarding.get("target_role") or "your target role" | |
| skills_raw = onboarding.get("technical_skills") or "your current skills" | |
| skills = skills_raw if isinstance(skills_raw, str) else ", ".join(skills_raw) | |
| hours = str(onboarding.get("hours_per_week") or "a few") | |
| hours_clean = hours.replace("hours", "").replace("hour", "").strip() | |
| timeline = onboarding.get("goal_timeline") or "a few months" | |
| preferred_language = _normalize_preferred_language( | |
| onboarding.get("preferred_language") or roadmap.get("preferred_language") or "English" | |
| ) | |
| logger.info( | |
| f"[SCRIPT GEN] name={name}, goal={goal}, timeline={timeline}, preferred_language={preferred_language}" | |
| ) | |
| milestones = roadmap.get("milestones", []) or [] | |
| first_milestone = milestones[0] if milestones else {} | |
| first_milestone_value = first_milestone.get("market_value_display", "") | |
| module_count = sum(len(m.get("modules", []) or []) for m in milestones) | |
| roadmap_modules: list[dict] = [] | |
| for milestone in milestones: | |
| for mod in milestone.get("modules", []) or []: | |
| module_card = _build_module_card(mod) | |
| roadmap_modules.append(module_card) | |
| logger.info(f"[ROADMAP MODULE] {mod.get('title')} -> {module_card['skills']}") | |
| module_names = [m["title"] for m in roadmap_modules] | |
| scenario = None | |
| skill_why = None | |
| for module in first_milestone.get("modules", []) or []: | |
| for skill in module.get("skills", []) or []: | |
| flow = skill.get("content_flow", {}) or {} | |
| if not scenario and flow.get("scenario"): | |
| scenario = flow["scenario"] | |
| if not skill_why: | |
| skill_why = skill.get("why_this_skill") | |
| scenario_title = scenario.get("title") if scenario else None | |
| logger.info(f"[SCRIPT GEN] modules={module_count}, modules_list={module_names[:3]}, scenario={scenario_title}") | |
| milestone_ladder = _build_milestone_cards(milestones, goal=goal, skills=skills) | |
| target_date = _get_target_date(timeline) | |
| per_day = offer["price"] // 90 | |
| def _fallback_pack(*variants: str) -> list[str]: | |
| return [_normalize_spaces(v) for v in variants if v and v.strip()] | |
| # LLM-first narration generation with deterministic fallbacks. | |
| shared_context = _consultation_context_payload( | |
| name=name, | |
| goal=goal, | |
| skills=skills, | |
| hours=hours_clean or hours, | |
| timeline=timeline, | |
| milestone_ladder=milestone_ladder, | |
| roadmap_modules=roadmap_modules, | |
| scenario_title=scenario_title, | |
| skill_why=skill_why, | |
| offer=offer, | |
| target_date=target_date, | |
| first_milestone_value=first_milestone_value, | |
| module_count=module_count, | |
| preferred_language=preferred_language, | |
| ) | |
| beat1_fallback = _normalize_spaces( | |
| f"{name}, you told us you work with {skills}, can spend {hours_clean} hours a week, and want {goal} in {timeline}. We used those exact inputs instead of a generic template, so the plan starts from your real situation." | |
| ) | |
| beat1_narration = _generate_beat_narration( | |
| beat_id="beat_1_mirror", | |
| context=shared_context, | |
| instructions=( | |
| f"Mirror the learner's exact onboarding answer set back in a human, direct way. Mention the name, skills, hours per week, timeline, and one concrete detail from the input. " | |
| f"Keep the tone warm and specific, and include a short natural phrase in {preferred_language} only if it helps the line feel more human. " | |
| f"Do not sound like a form recap or a sales pitch." | |
| f"Strictly generate 60-70% of the narration in English and 30-40% in {preferred_language} only; do not introduce any third language, third script, or unrelated regional language. " | |
| ), | |
| fallback=beat1_fallback, | |
| min_words=45, | |
| max_words=60, | |
| max_tokens=450, | |
| preferred_language=preferred_language, | |
| fallback_variants=_fallback_pack( | |
| f"{name}, you told us you work with {skills}, can spend {hours_clean} hours a week, and want {goal} in {timeline}. We used those exact inputs instead of a generic template, so the plan starts from your real situation.", | |
| f"We listened to your skills, your time budget, and your timeline. That is why this consultation feels personal: it is built around what you can actually do next, not around filler.", | |
| f"Nothing here is random. Your name, skills, time budget, and target role shaped the whole path, so the first thing you see is a plan that matches your life.", | |
| ), | |
| ) | |
| beat2_fallback = _normalize_spaces( | |
| f"Right now, some parts of the work still take extra effort because you have not had enough repeated practice in the exact situations that {goal} work demands. In {timeline}, those same situations feel familiar because you will have already built the habit. The market value for that level of judgment sits around {first_milestone_value}." | |
| ) | |
| beat2_narration = _generate_beat_narration( | |
| beat_id="beat_2_future_self", | |
| context=shared_context, | |
| instructions=( | |
| f"Use only English and {preferred_language}; do not introduce any third language, third script, or unrelated regional language. " | |
| f"Show the future self as a working reality, not a motivational poster. Start with a concrete present-day friction point, then show how life and work change after {timeline}. " | |
| f"Use {first_milestone_value} naturally as market context, and turn the identity statement into a consequence the user can feel. " | |
| f"Strictly generate 60-70% of the narration in English and 30-40% in {preferred_language} only; do not introduce any third language, third script, or unrelated regional language." | |
| ), | |
| fallback=beat2_fallback, | |
| min_words=70, | |
| max_words=80, | |
| max_tokens=550, | |
| preferred_language=preferred_language, | |
| fallback_variants=_fallback_pack( | |
| f"Right now, some parts of the work still take extra effort because you have not had enough repeated practice in the exact situations that {goal} work demands. In {timeline}, those same situations feel familiar because you will have already built the habit. The market value for that level of judgment sits around {first_milestone_value}.", | |
| f"In {timeline}, you are not guessing your way through the work anymore. You will have seen the patterns enough times that your decisions feel steadier, your pace feels calmer, and the market reads that difference as {first_milestone_value}.", | |
| f"The next version of you is not a fantasy cutout. It is you, but with the judgment to handle the pressure that comes with {goal}, and that level of work is already priced around {first_milestone_value}.", | |
| ), | |
| ) | |
| beat3_fallback = _normalize_spaces( | |
| f"The gap is real, but it is not absurd. You already bring {skills} with you, and {module_count} focused capabilities are enough to close what is missing without turning this into a never-ending syllabus." | |
| ) | |
| beat3_narration = _generate_beat_narration( | |
| beat_id="beat_3_stakes_gap", | |
| context=shared_context, | |
| instructions=( | |
| f"Explain why the gap is reachable without sounding dramatic. Acknowledge the learner's existing foundation and show that the path is finite, specific, and crossable. " | |
| f"Mention {module_count} as the number of learnable capability layers only if it helps the rhythm. " | |
| f"Strictly generate 60-70% of the narration in English and 30-40% in {preferred_language} only; do not introduce any third language, third script, or unrelated regional language." | |
| ), | |
| fallback=beat3_fallback, | |
| min_words=85, | |
| max_words=95, | |
| max_tokens=600, | |
| preferred_language=preferred_language, | |
| fallback_variants=_fallback_pack( | |
| f"The gap is real, but it is not absurd. You already bring {skills} with you, and {module_count} focused capabilities are enough to close what is missing without turning this into a never-ending syllabus.", | |
| f"This is not a zero-to-hero pitch. You already have a base, and the roadmap turns that base into job-ready judgment step by step.", | |
| f"The path is finite and specific, which is why it is workable. You are not starting from nothing, you are starting from {skills}, and that makes the climb much more practical.", | |
| ), | |
| ) | |
| beat4_fallback = _normalize_spaces( | |
| f"We built this roadmap around your target role, not around a random syllabus. It has {len(milestone_ladder)} milestone(s), and each one changes what you can actually do at work. This was built from your answers, not from a template." | |
| ) | |
| beat4_narration = _generate_beat_narration( | |
| beat_id="beat_4_reveal", | |
| context=shared_context, | |
| instructions=( | |
| f"Strictly generate 60-70% of the narration in English and 30-40% in {preferred_language} only; do not introduce any third language, third script, or unrelated regional language. " | |
| f"Reveal the roadmap as a progression of real capability and life change. Mention the milestone count and each milestone's role, but do not write it like a catalog or use the phrase 'leads to'. " | |
| f"Translate each milestone label into a distinct consequence the learner can feel in work. Keep the language balanced and natural, with English leading and {preferred_language} used as a human accent rather than a separate section." | |
| ), | |
| fallback=beat4_fallback, | |
| min_words=85, | |
| max_words=95, | |
| max_tokens=650, | |
| preferred_language=preferred_language, | |
| fallback_variants=_fallback_pack( | |
| f"We built this roadmap around your target role, not around a random syllabus. It has {len(milestone_ladder)} milestone(s), and each one changes what you can actually do at work. This was built from your answers, not from a template.", | |
| f"Each milestone is there for a reason. The sequence is designed to move you from where you are now to work that feels more controlled, more credible, and more useful on the job.", | |
| f"This is the exact progression your inputs called for. The milestones are not decorative; they are the steps that turn your current skills into a path you can actually walk.", | |
| ), | |
| ) | |
| # Keep Beat 5 aligned as a synchronized sequence, but make the narration LLM-first per slide. | |
| project_title = "Real Work Simulation" | |
| project_why = _normalize_spaces( | |
| f"You will move through plan, build, check, and ship on one realistic task tied to {goal} work." | |
| ) | |
| tutor_headline = "Help when you're stuck" | |
| checkpoint_headline = "Show it to unlock" | |
| outcomes_headline = "Work feels manageable" | |
| beat5_modules = roadmap_modules[:4] | |
| module_names_beat5 = [m["title"] for m in beat5_modules] | |
| beat5_context = { | |
| **shared_context, | |
| "module_names": module_names_beat5, | |
| "project_title": project_title, | |
| "project_why": project_why, | |
| "tutor_headline": tutor_headline, | |
| "checkpoint_headline": checkpoint_headline, | |
| "outcomes_headline": outcomes_headline, | |
| "checkpoint_line": _derive_checkpoint_teaser(roadmap), | |
| "mock_teaser": _derive_mock_teaser(goal, roadmap, scenario_title or ""), | |
| "project_teaser": _derive_project_teaser(goal, module_names, roadmap), | |
| "outcome_line": _derive_outcome_line(goal, skills), | |
| } | |
| beat5a_fallback = _normalize_spaces( | |
| f"Your learning path begins with {_join_phrases(module_names_beat5) or 'the core modules'}. The first layer feels familiar instead of abstract, and the later layers add the kind of practice that makes the work usable." | |
| ) | |
| beat5a_narration = _generate_beat5_section_narration( | |
| section_id="beat_5a_modules", | |
| context={**beat5_context, "section": "modules"}, | |
| instructions=( | |
| f"Strictly generate 60-70% of the narration in English and 30-40% in {preferred_language} only; do not introduce any third language, third script, or unrelated regional language. " | |
| f"Explain the module sequence as a real learning path. The slide shows {', '.join(module_names_beat5) if module_names_beat5 else 'the modules'}. " | |
| f"Make the sequencing feel intentional, and keep the pacing natural with English dominant and {preferred_language} used sparingly for human warmth." | |
| ), | |
| fallback=beat5a_fallback, | |
| min_words=80, | |
| max_words=95, | |
| max_tokens=700, | |
| preferred_language=preferred_language, | |
| fallback_variants=_fallback_pack( | |
| f"Your learning path begins with {_join_phrases(module_names_beat5) or 'the core modules'}. The first layer feels familiar instead of abstract, and the later layers add the kind of practice that makes the work usable.", | |
| f"This section is about sequence, not a catalog. Each module has a job, and the order is there so the skills stack in a way that actually makes sense.", | |
| f"You are not collecting random lessons. You are moving through a stack of capabilities that becomes more useful with every step.", | |
| ), | |
| ) | |
| beat5b_fallback = _normalize_spaces( | |
| f"By the end of this milestone, you complete one realistic workflow in {goal} work. You plan the task, use the modules in the right order, check the result, and finish with something you can actually show." | |
| ) | |
| beat5b_narration = _generate_beat5_section_narration( | |
| section_id="beat_5b_project", | |
| context={**beat5_context, "section": "project"}, | |
| instructions=( | |
| f"Strictly generate 60-70% of the narration in English and 30-40% in {preferred_language} only; do not introduce any third language, third script, or unrelated regional language. " | |
| f"Describe the project simulation in a concrete way. Show that the learner will plan the task, use the modules, check the result, and ship something they can show. " | |
| f"Avoid generic course language and keep the project feeling like a real deliverable, not a demo for its own sake." | |
| ), | |
| fallback=beat5b_fallback, | |
| min_words=70, | |
| max_words=85, | |
| max_tokens=650, | |
| preferred_language=preferred_language, | |
| fallback_variants=_fallback_pack( | |
| f"By the end of this milestone, you complete one realistic workflow in {goal} work. You plan the task, use the modules in the right order, check the result, and finish with something you can actually show.", | |
| f"This is where the modules become a deliverable. The work moves from learning to building, and that is what makes the milestone feel real.", | |
| f"The point here is not to hear about a project. It is to finish a workflow that looks and feels like actual work output.", | |
| ), | |
| ) | |
| beat5c_fallback = _normalize_spaces( | |
| f"Real scenario: {scenario_title or f'a real situation a {goal} faces on the job'}. In that moment, you are under pressure to inspect the failure, make the smallest useful fix, and confirm the result still works." | |
| ) | |
| beat5c_narration = _generate_beat5_section_narration( | |
| section_id="beat_5c_scenario", | |
| context={**beat5_context, "section": "scenario"}, | |
| instructions=( | |
| f"Strictly generate 60-70% of the narration in English and 30-40% in {preferred_language} only; do not introduce any third language, third script, or unrelated regional language. " | |
| f"Describe the real scenario in a workplace tone. Make the pressure and the decision-making feel real, then connect it directly to why the skill matters. " | |
| f"This should feel like a live work moment, not an example from a textbook, and it should sound grounded in the user's current context." | |
| ), | |
| fallback=beat5c_fallback, | |
| min_words=90, | |
| max_words=105, | |
| max_tokens=750, | |
| preferred_language=preferred_language, | |
| fallback_variants=_fallback_pack( | |
| f"Real scenario: {scenario_title or f'a real situation a {goal} faces on the job'}. In that moment, you are under pressure to inspect the failure, make the smallest useful fix, and confirm the result still works.", | |
| f"This is the moment where judgment matters. You are looking at a real problem, deciding what to check first, and fixing the right thing without making the situation worse.", | |
| f"You are not solving a textbook exercise here. You are in a live work moment, with pressure on, and the skill matters because the next step has to be the useful step.", | |
| ), | |
| ) | |
| beat5d_fallback = _normalize_spaces( | |
| f"The checkpoint proves you can apply the skill, and the mock question checks judgment instead of memorization. That keeps the next module earned instead of accidental." | |
| ) | |
| beat5d_narration = _generate_beat5_section_narration( | |
| section_id="beat_5d_checkpoint", | |
| context={**beat5_context, "section": "checkpoint"}, | |
| instructions=( | |
| f"Strictly generate 60-70% of the narration in English and 30-40% in {preferred_language} only; do not introduce any third language, third script, or unrelated regional language. " | |
| f"Explain the checkpoint and mock preview. Make it clear that mastery unlocks progress and that the question checks judgment, not rote memorization. " | |
| f"Keep the pacing crisp and reassuring, and avoid making it sound like a policy memo." | |
| ), | |
| fallback=beat5d_fallback, | |
| min_words=75, | |
| max_words=90, | |
| max_tokens=600, | |
| preferred_language=preferred_language, | |
| fallback_variants=_fallback_pack( | |
| f"The checkpoint proves you can apply the skill, and the mock question checks judgment instead of memorization. That keeps the next module earned instead of accidental.", | |
| f"You do not move forward just because a video ended. You move forward when the work shows mastery, and that is why the checkpoint matters.", | |
| f"This is the gate, not the ceremony. The mock and the checkpoint exist to prove you can do the thing, not just recognise it.", | |
| ), | |
| ) | |
| beat5e_fallback = _normalize_spaces( | |
| f"With practice on {skills}, daily work starts to feel less intimidating, and the same tasks become more repeatable, steadier, and easier to finish cleanly." | |
| ) | |
| beat5e_narration = _generate_beat5_section_narration( | |
| section_id="beat_5e_outcomes", | |
| context={**beat5_context, "section": "outcomes"}, | |
| instructions=( | |
| f"Strictly generate 60-70% of the narration in English and 30-40% in {preferred_language} only; do not introduce any third language, third script, or unrelated regional language. " | |
| f"Describe the outcome after practice. Show how daily work changes, how the learner becomes steadier, and how the same tasks stop feeling intimidating. " | |
| f"Keep it concrete and role-specific, and make the before-versus-after shift obvious." | |
| ), | |
| fallback=beat5e_fallback, | |
| min_words=75, | |
| max_words=90, | |
| max_tokens=600, | |
| preferred_language=preferred_language, | |
| fallback_variants=_fallback_pack( | |
| f"With practice on {skills}, daily work starts to feel less intimidating, and the same tasks become more repeatable, steadier, and easier to finish cleanly.", | |
| f"The repetition gives you cleaner instincts and faster recovery. What used to feel noisy starts to feel manageable because the pattern is familiar now.", | |
| f"Your day-to-day work becomes calmer and more predictable. The same kinds of tasks stop draining you because you have already practiced the shape of the problem.", | |
| ), | |
| ) | |
| beat5f_fallback = _normalize_spaces( | |
| f"The AI tutor stays inside every lesson, slows things down when needed, gives hints, and can translate the instruction into plain language without removing the practice that builds real confidence." | |
| ) | |
| beat5f_narration = _generate_beat5_section_narration( | |
| section_id="beat_5f_ai_tutor", | |
| context={**beat5_context, "section": "ai_tutor"}, | |
| instructions=( | |
| f"Strictly generate 60-70% of the narration in English and 30-40% in {preferred_language} only; do not introduce any third language, third script, or unrelated regional language. " | |
| f"Explain the AI tutor as support that stays inside every lesson. Show that it helps without removing practice, and mention hints, slower explanations, and translation into plain language. " | |
| f"Make it feel useful and calm, not like a chatbot demo, and keep English as the main layer of explanation." | |
| ), | |
| fallback=beat5f_fallback, | |
| min_words=60, | |
| max_words=75, | |
| max_tokens=550, | |
| preferred_language=preferred_language, | |
| fallback_variants=_fallback_pack( | |
| f"The AI tutor stays inside every lesson, slows things down when needed, gives hints, and can translate the instruction into plain language without removing the practice that builds real confidence.", | |
| f"When you get stuck, the tutor does not replace the work. It helps you keep moving, explains the next step more simply, and reduces the chance that you freeze.", | |
| f"This support is there to keep the lesson usable under pressure. It gives hints, simpler explanations, and just enough help to get you unstuck without doing the thinking for you.", | |
| ), | |
| ) | |
| beat5_sections = [ | |
| { | |
| "beat_id": "beat_5a_modules", | |
| "template_path": "src/template/consultation/beat_5a_modules.html", | |
| "narration": beat5a_narration, | |
| "on_screen": {}, | |
| }, | |
| { | |
| "beat_id": "beat_5b_project", | |
| "template_path": "src/template/consultation/beat_5b_project.html", | |
| "narration": beat5b_narration, | |
| "on_screen": {}, | |
| }, | |
| { | |
| "beat_id": "beat_5c_scenario", | |
| "template_path": "src/template/consultation/beat_5c_scenario.html", | |
| "narration": beat5c_narration, | |
| "on_screen": {}, | |
| }, | |
| { | |
| "beat_id": "beat_5d_checkpoint", | |
| "template_path": "src/template/consultation/beat_5d_checkpoint.html", | |
| "narration": beat5d_narration, | |
| "on_screen": {}, | |
| }, | |
| { | |
| "beat_id": "beat_5e_outcomes", | |
| "template_path": "src/template/consultation/beat_5e_outcomes.html", | |
| "narration": beat5e_narration, | |
| "on_screen": {}, | |
| }, | |
| { | |
| "beat_id": "beat_5f_ai_tutor", | |
| "template_path": "src/template/consultation/beat_5f_ai_tutor.html", | |
| "narration": beat5f_narration, | |
| "on_screen": {}, | |
| }, | |
| ] | |
| beat5_narration = _normalize_spaces(" ".join(section["narration"] for section in beat5_sections)) | |
| beat6_narration = _generate_beat_narration( | |
| beat_id="beat_6_how_it_unlocks", | |
| context=shared_context, | |
| instructions=( | |
| f"Strictly generate 60-70% of the narration in English and 30-40% in {preferred_language} only; do not introduce any third language, third script, or unrelated regional language. " | |
| f"Explain how mastery checkpoints work, how levels unlock, and why the tutor is built into the lesson. " | |
| f"Keep it crisp and reassuring, and mention that the user is earning access through proof rather than buying lectures. " | |
| f"The tone should stay calm, strategic, and lightly motivating, with English dominant and {preferred_language} used only as a human accent if it feels natural." | |
| ), | |
| fallback=_normalize_spaces( | |
| f"You do not buy lessons and hope something sticks. Every skill in your roadmap has a mastery checkpoint, and you move on when the work shows 90% mastery. The AI tutor stays inside every lesson in your preferred language, so support is there without removing the practice." | |
| ), | |
| min_words=75, | |
| max_words=85, | |
| max_tokens=550, | |
| preferred_language=preferred_language, | |
| fallback_variants=_fallback_pack( | |
| f"You do not buy lessons and hope something sticks. Every skill in your roadmap has a mastery checkpoint, and you move on when the work shows 90% mastery. The AI tutor stays inside every lesson in your preferred language, so support is there without removing the practice.", | |
| f"The system is simple: show mastery, unlock the next step. That keeps the path honest, and it means the tutor helps you reach the gate instead of replacing the gate.", | |
| f"This is how the learning path stays real. You earn the next module when you can actually do the work, and the tutor is there to help you get there without guessing.", | |
| ), | |
| ) | |
| beat7_narration = _generate_beat_narration( | |
| beat_id="beat_7_cta", | |
| context=shared_context, | |
| instructions=( | |
| f"Close with the {offer['price']} rupees, the {offer['refund_days']} days refund window, and the CTA. The currency is Indian Rupees (INR). Never mention dollars, USD, or any foreign currency. Always say rupees. " | |
| f"End with the learner's name, future title, and date, and keep the CTA calm and confident rather than pushy. " | |
| f"Use English for the main close, then a brief human-sounding line in {preferred_language} if it fits naturally." | |
| f"Dont keep the tone in a sales pitch. Mention why the user needs it." | |
| f"Strictly generate 60-70% of the narration in English and 30-40% in {preferred_language} only; do not introduce any third language, third script, or unrelated regional language. " | |
| ), | |
| fallback=_normalize_spaces( | |
| f"The roadmap already exists. The milestones are already mapped. The question is no longer whether a path exists. The question is whether you want the version of yourself that comes after it. If you begin today, your first milestone is waiting. The full program is {offer['price']} rupees. If it is not right for you, you have {offer['refund_days']} days to walk away with a full refund. But if it is right, then every week you delay is a week the future version of you waits. {name}. {goal}. {target_date}." | |
| ), | |
| min_words=85, | |
| max_words=95, | |
| max_tokens=550, | |
| preferred_language=preferred_language, | |
| fallback_variants=_fallback_pack( | |
| f"The roadmap already exists. The milestones are already mapped. The question is no longer whether a path exists. The question is whether you want the version of yourself that comes after it. If you begin today, your first milestone is waiting. The full program is {offer['price']} rupees. If it is not right for you, you have {offer['refund_days']} days to walk away with a full refund. But if it is right, then every week you delay is a week the future version of you waits. {name}. {goal}. {target_date}." | |
| f"{target_date} will arrive whether you start or not. The question is what arrives with it. If the path feels right, start Milestone 1 and let the next version of you do the work. The price is {offer['price']} rupees ,full refund in {offer['refund_days']} days if it is not right for you. {name}. {goal}. {target_date}." | |
| ), | |
| ) | |
| beats = [ | |
| { | |
| "beat_id": "beat_1_mirror", | |
| "narration": beat1_narration, | |
| "on_screen": { | |
| "name": name, | |
| "goal": goal, | |
| "timeline": timeline, | |
| "hours": hours, | |
| "skills": skills, | |
| }, | |
| "duration_s": 0, | |
| }, | |
| { | |
| "beat_id": "beat_2_future_self", | |
| "narration": beat2_narration, | |
| "on_screen": { | |
| "goal": goal, | |
| "market_value": first_milestone_value, | |
| "identity_statement": milestone_ladder[0]["statement"] if milestone_ladder else "", | |
| "identity_statement_raw": milestone_ladder[0].get("statement_raw", "") if milestone_ladder else "", | |
| }, | |
| "duration_s": 0, | |
| }, | |
| { | |
| "beat_id": "beat_3_stakes_gap", | |
| "narration": beat3_narration, | |
| "on_screen": { | |
| "gap_label": f"Between you and {goal}", | |
| "module_count": module_count, | |
| "target_role": goal, | |
| }, | |
| "duration_s": 0, | |
| }, | |
| { | |
| "beat_id": "beat_4_reveal", | |
| "narration": beat4_narration, | |
| "on_screen": { | |
| "milestones": milestone_ladder, | |
| "module_preview": milestone_ladder[0]["module_preview"] if milestone_ladder else "", | |
| "roadmap_summary": _build_roadmap_summary(milestone_ladder), | |
| }, | |
| "duration_s": 0, | |
| }, | |
| { | |
| "beat_id": "beat_5_whats_inside", | |
| "narration": beat5_narration, | |
| "on_screen": { | |
| "goal": goal, | |
| "scenario_title": scenario_title or f"Real situations a {goal} faces", | |
| "skill_why": skill_why or f"The capability {goal}s get hired for", | |
| "tutor_line": "AI tutor — mid-lesson, in your language", | |
| "module_names": module_names_beat5, | |
| "roadmap_modules": beat5_modules, | |
| "beat_5a_modules": beat5_modules, | |
| "beat_5b_project": { | |
| "title": project_title, | |
| "why": project_why, | |
| "goal": goal, | |
| }, | |
| "beat_5c_scenario": { | |
| "title": scenario_title or f"Real situations a {goal} faces", | |
| "why": skill_why or f"The capability {goal}s get hired for", | |
| "goal": goal, | |
| }, | |
| "beat_5d_checkpoint": { | |
| "headline": checkpoint_headline, | |
| "checkpoint_line": _derive_checkpoint_teaser(roadmap), | |
| "mock_line": _derive_mock_teaser(goal, roadmap, scenario_title or ""), | |
| "goal": goal, | |
| }, | |
| "beat_5e_outcomes": { | |
| "headline": outcomes_headline, | |
| "summary": _derive_outcome_line(goal, skills), | |
| "skills": skills, | |
| "goal": goal, | |
| }, | |
| "beat_5f_ai_tutor": { | |
| "headline": tutor_headline, | |
| "prompts": [ | |
| "Explain it simply", | |
| "Give me a hint", | |
| "Show me an example", | |
| "Translate it", | |
| ], | |
| }, | |
| "beat_5_sections": beat5_sections, | |
| "project_teaser": _derive_project_teaser(goal, module_names, roadmap), | |
| "checkpoint_teaser": _derive_checkpoint_teaser(roadmap), | |
| "mock_teaser": _derive_mock_teaser(goal, roadmap, scenario_title or ""), | |
| "outcome_line": _derive_outcome_line(goal, skills), | |
| }, | |
| "duration_s": 0, | |
| "beat_5_sections": beat5_sections, | |
| }, | |
| { | |
| "beat_id": "beat_6_how_it_unlocks", | |
| "narration": beat6_narration, | |
| "on_screen": { | |
| "unlock_line": "You don't buy lessons. You earn levels.", | |
| "gate_label": "90% mastery unlocks the next module", | |
| "module_names": module_names[:3], | |
| }, | |
| "duration_s": 0, | |
| }, | |
| { | |
| "beat_id": "beat_7_cta", | |
| "narration": beat7_narration, | |
| "on_screen": { | |
| "price": offer["price"], | |
| "anchor": offer["anchor"], | |
| "per_day": per_day, | |
| "refund_days": offer["refund_days"], | |
| "cta_label": "Begin Milestone 1", | |
| "user_name": name, | |
| "future_title": goal, | |
| "target_date": target_date, | |
| }, | |
| "duration_s": 0, | |
| }, | |
| ] | |
| logger.info(f"[SCRIPT GEN] Built {len(beats)} beats for: {name}") | |
| return beats | |