scn-consultation-api / src /nodes /consultation /script_generator.py
SS-2005's picture
Initial HF Space deployment
59ec65a
Raw
History Blame Contribute Delete
50.8 kB
import os
import json
import logging
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,
allow_hindi: bool = False
) -> bool:
if not text:
return False
cleaned = text.strip()
if len(cleaned) < 120:
return False
words = cleaned.split()
if len(words) < min_words:
return False
if max_words is not None and len(words) > max_words:
return False
sentence_count = (
cleaned.count(".")
+ cleaned.count("!")
+ cleaned.count("?")
)
if sentence_count < 3:
return False
if _looks_truncated(cleaned):
return False
if not allow_hindi 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,
allow_hindi: bool = False,
attempts: int = 3,
max_tokens: int = 700
):
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,
allow_hindi=allow_hindi
):
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"
)
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,
) -> dict:
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,
}
def _consultation_prompt(
beat_id: str,
context: dict,
instructions: str,
min_words: int,
max_words: int,
) -> str:
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.
- 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,
) -> 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,
attempts=3,
max_tokens=max_tokens,
)
def _beat5_section_prompt(
section_id: str,
context: dict,
instructions: str,
min_words: int,
max_words: int,
) -> str:
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.
- 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,
) -> 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,
attempts=3,
max_tokens=max_tokens,
)
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 _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"
logger.info(f"[SCRIPT GEN] name={name}, goal={goal}, timeline={timeline}")
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
# 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,
)
beat1_fallback = (
f"{name}. "
f"You told us you work with {skills}. "
f"You are putting in {hours_clean} hours a week. "
f"Your goal is {goal}, in {timeline}. "
f"We went through every answer you gave us and built something specific to you, not from a template."
)
beat1_instructions = (
f"Mirror the learner's profile back in a human, direct way. Mention the name, skills, hours per week, and timeline. "
f"Make it sound like a consultation, not a form readout. Keep the tone specific and personal."
)
beat1_narration = _generate_beat_narration(
beat_id="beat_1_mirror",
context=shared_context,
instructions=beat1_instructions,
fallback=beat1_fallback,
min_words=45,
max_words=60,
max_tokens=450,
)
beat2_fallback = _generate_future_self_narration(
name, goal, timeline, milestone_ladder[0]["statement"] if milestone_ladder else "", first_milestone_value, skills
)
beat2_instructions = (
f"Show the gap between today and the future self. Start from a concrete current-work situation, then move into how life and work change after {timeline}. "
f"Reference the market value naturally in INR / rupees, not dollars. Turn the identity statement into a consequence, not a quote. "
f"Avoid repeating the same sentence structure used in Beat 1."
)
beat2_narration = _generate_beat_narration(
beat_id="beat_2_future_self",
context=shared_context,
instructions=beat2_instructions,
fallback=beat2_fallback,
min_words=70,
max_words=80,
max_tokens=550,
)
beat3_fallback = _generate_stakes_narration(goal, module_count, skills)
beat3_instructions = (
f"Explain why the gap is reachable. Mention the number of learnable capability layers if useful, but keep it natural. "
f"Acknowledge the learner's existing foundation and make the path feel crossable, not vague."
)
beat3_narration = _generate_beat_narration(
beat_id="beat_3_stakes_gap",
context=shared_context,
instructions=beat3_instructions,
fallback=beat3_fallback,
min_words=85,
max_words=95,
max_tokens=600,
)
beat4_fallback = _normalize_spaces(
" ".join([
f"This is the roadmap we built around your goal.",
f"It contains {len(milestone_ladder)} milestone(s), each showing a different stage of job readiness.",
*[
(
f"The first milestone {card.get('label') or f'Milestone {idx}'}"
f" ({card.get('value') or ''}) opens into a stage where {card.get('statement') or 'job-ready progress'}"
)
for idx, card in enumerate(milestone_ladder, start=1)
][:3],
f"This was built from your answers, not from a template.",
])
)
beat4_instructions = (
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. Do not reuse the same sentence or the same closing phrase for multiple milestones. "
f"If the milestone statement is vague, infer a different consequence from the label and milestone order so each stage feels unique."
)
beat4_narration = _generate_beat_narration(
beat_id="beat_4_reveal",
context=shared_context,
instructions=beat4_instructions,
fallback=beat4_fallback,
min_words=85,
max_words=95,
max_tokens=650,
)
# 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(
" ".join([
f"Your learning path begins with {_join_phrases(module_names_beat5)}.",
f"{beat5_modules[0].get('title') if beat5_modules else 'The first module'} gives you the starting layer, so the work feels familiar instead of abstract.",
f"{beat5_modules[1].get('title') if len(beat5_modules) > 1 else 'The next module'} extends that foundation into a more practical layer, so the path feels like a real progression instead of a list of topics.",
f"That is why this section matters: it shows you how the modules are arranged before the practice starts.",
f"You are not being handed random lessons. You are being shown the order that helps the skills stack up in a way that makes sense."
])
)
beat5a_instructions = (
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 it feel like the learner is moving through useful layers of skill, not browsing a catalog. Mention only the modules shown on the slide."
)
beat5a_narration = _generate_beat5_section_narration(
section_id="beat_5a_modules",
context={**beat5_context, "section": "modules"},
instructions=beat5a_instructions,
fallback=beat5a_fallback,
min_words=80,
max_words=95,
max_tokens=700,
)
beat5b_fallback = _normalize_spaces(
f"By the end of this milestone, you will complete a realistic work simulation that combines {_join_phrases(module_names_beat5[:2]) or 'the core modules'} into one practical workflow used in {goal}. "
f"You will plan the task, use the modules in the right order, check the result, and finish with something you can actually show. "
f"Each step feeds the next one, so you can see the workflow as a whole rather than isolated tasks. "
f"The point is not to hear a summary of the course. The point is to see how the pieces become one usable workflow."
)
beat5b_instructions = (
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. Keep the title concise and the wording tightly aligned with the slide."
)
beat5b_narration = _generate_beat5_section_narration(
section_id="beat_5b_project",
context={**beat5_context, "section": "project"},
instructions=beat5b_instructions,
fallback=beat5b_fallback,
min_words=70,
max_words=85,
max_tokens=650,
)
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 not dealing with theory on a slide. You are under pressure to inspect the failure, figure out where the break happened, make the smallest useful fix, and confirm the result still works. "
f"That is why this step matters: {skill_why or f'the capability {goal}s get hired for'}. It turns the skill into a work habit, and it shows why this capability matters in real interviews and real jobs."
)
beat5c_instructions = (
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."
)
beat5c_narration = _generate_beat5_section_narration(
section_id="beat_5c_scenario",
context={**beat5_context, "section": "scenario"},
instructions=beat5c_instructions,
fallback=beat5c_fallback,
min_words=90,
max_words=105,
max_tokens=750,
)
beat5d_fallback = _normalize_spaces(
f"{_derive_checkpoint_teaser(roadmap)} {_derive_mock_teaser(goal, roadmap, scenario_title or '')} "
f"The checkpoint proves you can apply the skill, and the mock question checks judgment instead of memorization. "
f"That keeps the next module earned instead of accidental."
)
beat5d_instructions = (
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."
)
beat5d_narration = _generate_beat5_section_narration(
section_id="beat_5d_checkpoint",
context={**beat5_context, "section": "checkpoint"},
instructions=beat5d_instructions,
fallback=beat5d_fallback,
min_words=75,
max_words=90,
max_tokens=600,
)
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. "
f"You stop starting from zero each time because the pattern becomes familiar, the steps become clearer, and the work feels more manageable when pressure shows up. "
f"The repetition gives you cleaner instincts, faster recovery, and more confidence when the task changes under pressure."
)
beat5e_instructions = (
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."
)
beat5e_narration = _generate_beat5_section_narration(
section_id="beat_5e_outcomes",
context={**beat5_context, "section": "outcomes"},
instructions=beat5e_instructions,
fallback=beat5e_fallback,
min_words=75,
max_words=90,
max_tokens=600,
)
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. "
f"It is there to keep you moving when the lesson feels crowded, not to replace the work that makes the skill stick. "
f"When the work gets noisy, the tutor helps you step back, simplify the next action, and keep moving without freezing."
)
beat5f_instructions = (
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."
)
beat5f_narration = _generate_beat5_section_narration(
section_id="beat_5f_ai_tutor",
context={**beat5_context, "section": "ai_tutor"},
instructions=beat5f_instructions,
fallback=beat5f_fallback,
min_words=60,
max_words=75,
max_tokens=550,
)
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))
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": _generate_beat_narration(
beat_id="beat_6_how_it_unlocks",
context=shared_context,
instructions=(
"Explain how mastery checkpoints work, how levels unlock, and why the tutor is built into the lesson. "
"Keep it crisp and reassuring. Avoid sounding like a policy memo."
),
fallback=(
f"Here is how this works. You do not buy lessons and hope something sticks. Every skill in your roadmap has a mastery checkpoint. "
f"Ninety percent mastery before you move on, not because we want to slow you down, but because the next level is built on the current one, and skipping it costs you later. "
f"Your AI tutor is available inside every lesson in your language. You are not watching a course. You are building the capability to do the job."
),
min_words=75,
max_words=85,
max_tokens=550,
),
"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": _generate_beat_narration(
beat_id="beat_7_cta",
context=shared_context,
instructions=(
f"Close with the {offer['price']} rupees, the anchor, the refund window, and the CTA. The currency is Indian Rupees (INR).Never mention dollars, USD, or any foreign currency.Always say rupees. Make it confident and calm, not pushy. "
"End with the learner's name, future title, and date."
),
fallback=(
f"The roadmap already exists. The milestones are already mapped. The question is no longer whether a path exists. "
f"The question is whether you want the version of yourself that comes after it. If you begin today, your first milestone is waiting. "
f"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. "
f"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,
),
"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