Spaces:
Sleeping
Sleeping
Download app.py from Becio/scriptwriter_thesaster: direct link, hf CLI and curl.
- Browser
- Download file 98.3 kB
-
https://huggingface.co/spaces/Becio/scriptwriter_thesaster/resolve/main/app.py
- Command line
-
hf download hf://spaces/Becio/scriptwriter_thesaster/app.py
-
curl -L -o app.py https://huggingface.co/spaces/Becio/scriptwriter_thesaster/resolve/main/app.py
98.3 kB
import os
import re
import time
from datetime import date, datetime, timedelta
from pathlib import Path
from typing import Generator, Optional
import anthropic
import gradio as gr
from anthropic import Anthropic
from docx import Document
# =========================================================
# SETTINGS
# =========================================================
MIN_WORDS = 2000
MAX_WORDS = 2400
TARGET_WORDS = 2300
CHANNEL_NAME = "The Saster"
API_TIMEOUT_SECONDS = 420
MAX_WEB_SEARCHES = 10
MAX_STYLE_CHARACTERS = 50_000
STREAM_UPDATE_INTERVAL = 0.8
RESEARCH_MAX_TOKENS = 12_000
PLAN_MAX_TOKENS = 12_000
CHUNK_MAX_TOKENS = 11_000
REVISION_MAX_TOKENS = 12_000
MAX_HISTORICAL_CONTEXT_PERCENT = 10
MAX_OLD_YEAR_MENTIONS = 2
MODEL_OPTIONS = [
"claude-sonnet-5",
"claude-opus-5",
]
RECENCY_OPTIONS = {
"Last 30 days": 30,
"Last 90 days": 90,
"Last 180 days": 180,
"Last 365 days": 365,
}
DEFAULT_RECENCY_OPTION = "Last 90 days"
NEWS_BALANCE_OPTIONS = {
"Historical disaster β no current-news requirement": {
"recent_anchor_min": 0,
"recent_anchor_max": 0,
"recent_narration_share": "0 percent required",
"date_mentions_min": 4,
"date_mentions_max": 18,
"current_source_target": "0",
"description": (
"Reconstruct the disaster itself using the strongest available historical evidence, "
"official reports, archives, scientific records, eyewitness material, and later "
"investigations. Do not search for or force a current-news angle. Present-day context "
"may appear only when it genuinely helps the ending."
),
},
"Historical + optional present-day context": {
"recent_anchor_min": 0,
"recent_anchor_max": 1,
"recent_narration_share": "roughly 0β10 percent",
"date_mentions_min": 4,
"date_mentions_max": 18,
"current_source_target": "0β3",
"description": (
"Tell the historical disaster as a complete reconstruction first. Optionally add a "
"brief present-day update about rebuilding, changed defenses, surviving risks, or new "
"research when it materially improves the ending."
),
},
"Balanced β documentary + recent updates": {
"recent_anchor_min": 1,
"recent_anchor_max": 3,
"recent_narration_share": "roughly 15β35 percent",
"date_mentions_min": 4,
"date_mentions_max": 16,
"current_source_target": "3β6",
"description": (
"Tell the disaster as a complete narrative first, then weave in a small number of "
"meaningful current developments, rebuilt systems, new findings, anniversaries, "
"or present-day risks."
),
},
"News-first β more current detail": {
"recent_anchor_min": 3,
"recent_anchor_max": 5,
"recent_narration_share": "roughly 35β55 percent",
"date_mentions_min": 5,
"date_mentions_max": 18,
"current_source_target": "5β9",
"description": (
"Use a current development as the reason to revisit the disaster, while still "
"telling the historical event as a coherent human and technical story."
),
},
}
DEFAULT_NEWS_BALANCE_OPTION = "Historical disaster β no current-news requirement"
HOOK_OPTIONS = [
"Auto β choose the strongest cinematic opening",
"Cinematic date + place opening",
"Immediate disaster scene",
"Warning / failure foreshadowing",
"News clip continuation",
"Hard fact / consequence opening",
]
DEFAULT_HOOK_OPTION = "Auto β choose the strongest cinematic opening"
VIDEO_FORMAT_OPTIONS = {
"Standard documentary β 7 sections": {
"section_count": 7,
"chunk_sections": [2, 3, 2],
"list_mode": False,
"label": "sections",
},
"List documentary β 10 subtopics": {
"section_count": 10,
"chunk_sections": [3, 4, 3],
"list_mode": True,
"label": "subtopics",
},
"List documentary β 20 subtopics": {
"section_count": 20,
"chunk_sections": [7, 7, 6],
"list_mode": True,
"label": "subtopics",
},
"List documentary β 30 subtopics": {
"section_count": 30,
"chunk_sections": [10, 10, 10],
"list_mode": True,
"label": "subtopics",
},
}
DEFAULT_VIDEO_FORMAT_OPTION = "Standard documentary β 7 sections"
# The three minimum values add up to exactly 2,900 words.
# The maximum values add up to exactly 3,200 words.
CHUNK_SPECS = [
{
"number": 1,
"minimum": 900,
"maximum": 1000,
"target": 950,
"purpose": (
"Write a cinematic cold-open introduction of 130β180 words and the first "
"two titled sections. Do not mention the channel in the introduction. Follow "
"the selected hook strategy. Begin inside a specific moment, place, warning, "
"failure, or consequence, then widen into the context needed to understand what "
"is about to happen. Make the first two sections deliberately unequal in length."
),
},
{
"number": 2,
"minimum": 1000,
"maximum": 1100,
"target": 1050,
"purpose": (
"Write the next three titled sections. This is the core escalation of the "
"documentary: track the event chronology, failure chain, scientific or engineering "
"mechanisms, response, and human consequences with dense specific detail. Make all "
"three sections clearly unequal in length. Do not recap part 1 and do not insert a CTA."
),
},
{
"number": 3,
"minimum": 1000,
"maximum": 1100,
"target": 1050,
"purpose": (
"Write the final two titled sections and an ending of 120β180 words. "
"Cover the aftermath, accountability, rebuilding, lessons, unresolved risk, or "
"long-term human impact as appropriate. End with one restrained reflection that "
"echoes the documentary's central idea. Only after the story is fully resolved, "
"add a short natural outro that mentions The Saster once and contains one brief "
"subscribe request. Make the final two sections unequal in length."
),
},
]
# =========================================================
# LOGGING AND CORE UTILITIES
# =========================================================
def log(message: str) -> None:
timestamp = datetime.now().strftime("%H:%M:%S")
print(f"[{timestamp}] {message}", flush=True)
def get_client() -> Anthropic:
api_key = os.getenv("ANTHROPIC_API_KEY", "").strip()
if not api_key:
raise ValueError(
"ANTHROPIC_API_KEY is missing. Add it via "
"Hugging Face Space β Settings β Variables and secrets."
)
return Anthropic(
api_key=api_key,
timeout=API_TIMEOUT_SECONDS,
max_retries=0,
)
def count_words(text: str) -> int:
if not text:
return 0
return len(re.findall(r"\b[\wβ'-]+\b", text))
def format_elapsed(seconds: int, finished: bool = False) -> str:
seconds = max(0, int(seconds))
minutes, remaining_seconds = divmod(seconds, 60)
prefix = "β
Total generation time" if finished else "β±οΈ Elapsed time"
return (
f"{prefix}: {seconds} seconden "
f"({minutes:02d}:{remaining_seconds:02d})"
)
def extract_text(message) -> str:
text_parts = []
for block in message.content:
if getattr(block, "type", None) != "text":
continue
block_text = getattr(block, "text", "")
if block_text:
text_parts.append(block_text)
return "\n".join(text_parts).strip()
def joined_script(chunks: list[str]) -> str:
return "\n\n".join(
chunk.strip()
for chunk in chunks
if chunk.strip()
).strip()
def resolve_recency_days(option: str) -> int:
return RECENCY_OPTIONS.get(
option,
RECENCY_OPTIONS[DEFAULT_RECENCY_OPTION],
)
def resolve_news_balance(option: str) -> dict:
return NEWS_BALANCE_OPTIONS.get(
option,
NEWS_BALANCE_OPTIONS[DEFAULT_NEWS_BALANCE_OPTION],
)
def resolve_video_format(option: str) -> dict:
return VIDEO_FORMAT_OPTIONS.get(
option,
VIDEO_FORMAT_OPTIONS[DEFAULT_VIDEO_FORMAT_OPTION],
)
def get_chunk_specs(video_format_option: str) -> list[dict]:
format_config = resolve_video_format(video_format_option)
if not format_config["list_mode"]:
return CHUNK_SPECS
counts = format_config["chunk_sections"]
total = format_config["section_count"]
starts = [
1,
counts[0] + 1,
counts[0] + counts[1] + 1,
]
ends = [
counts[0],
counts[0] + counts[1],
total,
]
specs = []
for base, count, start, end in zip(
CHUNK_SPECS,
counts,
starts,
ends,
):
spec = dict(base)
spec["section_count"] = count
spec["section_start"] = start
spec["section_end"] = end
if base["number"] == 1:
spec["purpose"] = (
f"Write a cinematic cold-open introduction of 130β180 words and numbered "
f"subtopics {start} through {end}. Follow the selected hook strategy. "
f"Do not mention the channel in the introduction. Keep every "
f"subtopic distinct, factual, useful, visually editable, and naturally "
f"connected rather than padding the list."
)
elif base["number"] == 2:
spec["purpose"] = (
f"Write numbered subtopics {start} through {end}. Keep the "
f"list-documentary pace moving while still explaining mechanisms, "
f"geography, evidence, and consequences where useful. Keep sentence-to-"
f"sentence flow coherent and use editor-friendly topics. Keep the "
f"disaster narrative moving without inserting a mid-video CTA. "
f"Do not recap part 1."
)
else:
spec["purpose"] = (
f"Write numbered subtopics {start} through {end} and then a connected "
f"ending of 120β180 words. Keep every transition logically motivated. "
f"Resolve the final items into the larger meaning of the disaster. In the "
f"final 120 words, mention The Saster once and include one brief subscribe request."
)
specs.append(spec)
return specs
def get_chunk_structure_issue(
text: str,
spec: dict,
) -> Optional[str]:
if "section_start" not in spec:
return None
numbers = [
int(value)
for value in re.findall(
r"(?m)^##\s+(\d+)\.\s+.+$",
text or "",
)
]
expected = list(
range(
int(spec["section_start"]),
int(spec["section_end"]) + 1,
)
)
if numbers == expected:
return None
expected_text = (
f"{spec['section_start']}β"
f"{spec['section_end']}"
)
found_text = (
", ".join(str(number) for number in numbers)
if numbers
else "none"
)
return (
f"Expected numbered headings {expected_text} exactly once and in order; "
f"found: {found_text}."
)
def build_video_structure_requirements(
video_format_option: str,
) -> str:
config = resolve_video_format(video_format_option)
total = config["section_count"]
if not config["list_mode"]:
return f"""
VIDEO STRUCTURE β STANDARD DOCUMENTARY
- Build exactly {total} titled sections across the three chunks.
- The sections should feel like a connected documentary rather than a numbered list.
- Make section lengths deliberately unequal. Give the richest topics more room and use
shorter sections as bridges or reveals.
- The largest section should be at least 150 words longer than the shortest section.
""".strip()
return f"""
VIDEO STRUCTURE β LIST DOCUMENTARY ({total} SUBTOPICS)
- Build exactly {total} distinct, visible, numbered subtopics across the complete script.
- This is a Reasons-Why-style list documentary, but adapt the item type naturally to the
title: reasons, warning signs, places, facts, changes, risks, explanations, discoveries,
consequences, or another clearly fitting category.
- Every item must use the exact visible heading format: ## NUMBER. Short Title
- Number continuously from ## 1. through ## {total}. Never skip, duplicate, restart, merge,
or add an extra numbered item.
- Each numbered item must contribute a genuinely different idea. Do not split one fact into
several artificial items merely to reach the requested count.
- Keep the core The Saster writing voice: direct, documentary-like, evidence-dense, and
human. Do not turn it into a shallow countdown or repetitive listicle.
- Use tighter pacing as the item count rises. A 30-item script needs concise items; a 10-item
script can give each item substantially more explanation.
- Transitions should still connect neighboring items, but do not force a cliffhanger after
every single item. Use stronger open loops at natural intervals.
""".strip()
def build_hook_requirements(
hook_option: str,
) -> str:
if hook_option == "Cinematic date + place opening":
return """
HOOK STRATEGY β CINEMATIC DATE + PLACE
- Open with a precise date or time and a concrete location when the evidence supports it.
- Put the viewer inside the scene immediately: what the weather, landscape, city, facility,
aircraft, ship, crowd, or infrastructure is doing at that moment.
- Within the first four sentences, introduce the threat and one piece of information that the
people involved do not yet fully understand.
- Use chronology as tension. Do not dump the entire backstory in the first paragraph.
- After the cold open, briefly widen the frame so the audience understands why this place or
system was vulnerable before the event escalates.
""".strip()
if hook_option == "Immediate disaster scene":
return """
HOOK STRATEGY β IMMEDIATE DISASTER SCENE
- Start at or just before the most consequential moment, not with general background.
- Use concrete physical action: water rising, ground moving, alarms sounding, wind intensifying,
structures failing, communications going silent, people evacuating, or another verified event.
- Keep the first paragraph tightly focused on one scene and one time frame.
- Reveal only enough outcome to establish stakes, then rewind to explain how the situation reached
that point.
- Do not use invented sensory details or fictionalized dialogue.
""".strip()
if hook_option == "Warning / failure foreshadowing":
return """
HOOK STRATEGY β WARNING / FAILURE FORESHADOWING
- Open with the central vulnerability, warning, ignored finding, design weakness, operational
decision, or known hazard that later becomes crucial.
- Establish what experts, officials, operators, or residents knew before the disaster without
claiming they knew more than the evidence shows.
- Contrast the warning with the later event through chronology, not accusation or melodrama.
- Within the first paragraph, make clear what could happen if the vulnerable system failed.
""".strip()
if hook_option == "News clip continuation":
return """
HOOK STRATEGY β NEWS CLIP CONTINUATION
- Write the first line as a seamless continuation from a real news clip placed immediately before
the narration.
- Do not repeat the headline or summarize the clip.
- Use the clip as the visible surface of the event, then widen into the hidden chain of geography,
engineering, warnings, decisions, or physical mechanisms behind it.
- Never invent details about the unseen clip.
""".strip()
if hook_option == "Hard fact / consequence opening":
return """
HOOK STRATEGY β HARD FACT / CONSEQUENCE
- Open with one verified number or consequence that immediately establishes the scale of the event.
- In the next two or three sentences, connect that number to a specific place, moment, or failure.
- Do not stack statistics. One strong figure is enough before the narrative begins.
- Move from the consequence into the chain of events that produced it.
""".strip()
return """
HOOK STRATEGY β AUTO
- Choose the strongest opening for this specific disaster from:
CINEMATIC DATE + PLACE, IMMEDIATE DISASTER SCENE, WARNING / FAILURE FORESHADOWING,
or HARD FACT / CONSEQUENCE.
- Do not choose NEWS CLIP CONTINUATION automatically.
- Prefer a concrete scene over a general explanation.
- The opening should create a clear before-and-after tension: what was happening, what people
believed, and what was about to change.
- State the chosen hook mode in the INTERNAL plan and follow it consistently in chunk 1.
""".strip()
def get_news_window(
recency_days: int,
) -> tuple[date, date]:
current_date = date.today()
cutoff_date = (
current_date
- timedelta(days=recency_days)
)
return cutoff_date, current_date
def count_channel_mentions(
text: str,
) -> int:
return len(
re.findall(
re.escape(CHANNEL_NAME),
text or "",
flags=re.IGNORECASE,
)
)
def count_channel_questions(
text: str,
) -> int:
questions = re.findall(
r"[^?]*\?",
text or "",
flags=re.DOTALL,
)
return sum(
CHANNEL_NAME.lower()
in question.lower()
for question in questions
)
def count_subscribe_mentions(
text: str,
) -> int:
return len(
re.findall(
r"\bsubscribe\b",
text or "",
flags=re.IGNORECASE,
)
)
def extract_recency_verdict(
research: str,
) -> str:
match = re.search(
r"(?:EVIDENCE|RECENCY) VERDICT\s*:\s*(SUFFICIENT|INSUFFICIENT)",
research,
flags=re.IGNORECASE,
)
return (
match.group(1).upper()
if match
else "UNKNOWN"
)
def find_old_year_mentions(
text: str,
cutoff_date: date,
) -> list[int]:
years = [
int(value)
for value in re.findall(
r"\b(?:19|20)\d{2}\b",
text or "",
)
]
return [
year
for year in years
if year < cutoff_date.year
]
def story_requirement_warnings(
text: str,
cutoff_date: date,
current_date: date,
news_balance_option: str,
video_format_option: str,
) -> list[str]:
warnings = []
channel_mentions = count_channel_mentions(text)
subscribe_mentions = count_subscribe_mentions(text)
if channel_mentions != 1:
warnings.append(
f"{CHANNEL_NAME} appears {channel_mentions}x instead of 1x"
)
if subscribe_mentions != 1:
warnings.append(
f"subscribe appears {subscribe_mentions}x instead of 1x"
)
format_config = resolve_video_format(video_format_option)
if format_config["list_mode"]:
expected = format_config["section_count"]
numbered_headings = re.findall(
r"(?m)^##\s+(\d+)\.\s+.+$",
text or "",
)
numbers = [int(value) for value in numbered_headings]
expected_numbers = list(range(1, expected + 1))
if numbers != expected_numbers:
warnings.append(
f"numbered subtopics are not exactly 1β{expected} in continuous order "
f"({len(numbers)} matching headings found)"
)
if (
news_balance_option == "News-first β more current detail"
and re.search(rf"\b{current_date.year}\b", text or "") is None
):
warnings.append(
f"the current year {current_date.year} is not mentioned in news-first mode"
)
return warnings
# =========================================================
# GLOBAL WRITING RULES
# =========================================================
def build_global_writing_requirements(
cutoff_date: date,
current_date: date,
news_balance_option: str,
hook_option: str,
video_format_option: str,
) -> str:
balance = resolve_news_balance(news_balance_option)
hook_requirements = build_hook_requirements(hook_option)
format_config = resolve_video_format(video_format_option)
structure_requirements = build_video_structure_requirements(video_format_option)
topic_count = format_config["section_count"]
if format_config["list_mode"]:
ratio_min = balance["recent_anchor_min"] / 7
ratio_max = balance["recent_anchor_max"] / 7
recent_anchor_min = max(0, round(topic_count * ratio_min))
recent_anchor_max = max(recent_anchor_min, round(topic_count * ratio_max))
else:
recent_anchor_min = balance["recent_anchor_min"]
recent_anchor_max = balance["recent_anchor_max"]
return f"""
Write for The Saster: a high-retention documentary channel about natural disasters,
catastrophes, engineering failures, extreme events, accidents, evacuations, and the systems
that determine who survives and what fails.
The finished narration should feel cinematic without becoming fictional. It should combine the
clarity of a strong documentary with the momentum of a disaster reconstruction: concrete dates,
places, warnings, physical mechanisms, decisions, human consequences, response, aftermath, and
accountability.
Preserve the creator's own visible section structure. Do not imitate another channel's exact
sentences, recurring phrases, or unique wording.
{structure_requirements}
STORY DNA β THE SASTER
- Treat the disaster as a chain of events, not a pile of facts.
- Prefer chronological cause-and-effect whenever chronology is central to understanding what
happened.
- Build tension from information asymmetry: what was known, what was believed, what was missed,
and what changed next.
- Move repeatedly between MACRO and HUMAN scale:
city/region/system -> street/building/person -> back to the wider consequence.
- Use exact places and times when they matter.
- Introduce technical background at the moment the audience needs it. Do not front-load a lecture.
- When a levee, dam, fault, aircraft system, warning network, building, evacuation plan, or other
mechanism becomes important, explain it simply before showing how it performed under stress.
- Separate the hazard from the disaster. Ask what came from nature, what came from infrastructure,
decisions, exposure, communication, or preparedness.
- Do not invent scenes, thoughts, dialogue, motives, or sensory details.
- Human stories must come from verified evidence and should be used sparingly but specifically.
- Avoid exploitative language around deaths, injuries, or suffering.
- The emotional force should come from documented events and consequences.
NARRATIVE SHAPE
- Cold open: enter a specific moment, place, warning, or consequence.
- Widen the frame: explain why the location or system was vulnerable.
- Reconstruct the approach/escalation in a clean timeline.
- Slow down at the decisive failure or turning point.
- Show what the failure meant for real people and emergency response.
- Explain why the outcome became so severe.
- Cover aftermath, accountability, rebuilding, lessons, and present-day vulnerability when relevant.
- End by returning to the documentary's central idea, not by simply recapping the sections.
DOCUMENTARY TIMEFRAME β {news_balance_option}
- {balance['description']}
- Historical disasters do NOT need a recent-news hook.
- Current material, when the selected mode allows it, may anchor approximately
{recent_anchor_min}β{recent_anchor_max} of the {topic_count} main topics/subtopics.
- Required current material: {balance['recent_narration_share']} of the final narration.
- Historical EVENT dates are encouraged whenever they clarify the timeline.
- The target of {balance['date_mentions_min']}β{balance['date_mentions_max']} refers to useful
explicit date/time references in narration, not publication dates.
- Never mention a source publication date merely to make the script sound researched.
OPTIONAL PRESENT-DAY MATERIAL
- The core research may come from any year that is relevant to the disaster.
- Prioritize sources closest to the event and authoritative later investigations over recent
articles that merely retell old information.
- Anything explicitly described as current, new, recently announced, newly measured, newly rebuilt,
newly discovered, or newly warned must be supported by a source published between
{cutoff_date.isoformat()} and {current_date.isoformat()}.
- Never require a current source merely because the documentary is being produced today.
- Older authoritative sources are expected for the original event, official investigations,
engineering analysis, historical weather records, casualty figures, and durable background.
- Keep source publication date, event date, and later investigation date distinct internally.
INTRODUCTION β 130β180 WORDS
- Do not print the video title.
- Do not introduce The Saster or ask viewers to subscribe.
- Start immediately inside the story using the selected hook below.
- The first paragraph should normally contain a concrete date/time, place, physical event,
warning, decision, or consequence.
- Keep the first 3β5 sentences on one immediate scene or thread.
- Establish the central threat before giving broad background.
- Reveal one tension the documentary will resolve: a known vulnerability, a hidden failure,
a forecast, a decision, a system under stress, or a consequence that was not yet understood.
- The final sentence of the intro should pull the viewer forward into the explanation. It may
pose the central question or state the key unresolved problem, but do not use generic hype.
{hook_requirements}
SECTION WRITING
- Keep the creator's section headings and section count exactly as planned.
- Each section should still read like the next chapter of one continuous story.
- The first 2β4 sentences after a heading must continue the immediate thread from the previous
section or deliberately establish the next chronological step.
- Section headings must not make the narration feel like a list of disconnected mini-essays.
- Standard documentary sections should be deliberately unequal in length.
- In list mode, each numbered item must still have its own distinct claim or event.
DISASTER TIMELINE AND CAUSALITY
- Make event order unambiguous.
- Use temporal bridges when useful and vary the wording.
- Distinguish trigger, contributing factor, system failure, response failure, and consequence.
- Never imply causation when the evidence supports only correlation or contribution.
- If official investigations disagree, attribute the disagreement clearly.
- If later evidence changed the accepted explanation, show that change explicitly.
TECHNICAL EXPLANATION
- Explain technical systems in plain spoken English.
- Use measurements when they advance the story: wind, surge, depth, pressure, magnitude, speed,
rainfall, temperature, structural load, evacuation distance, population, cost, or response time.
- Connect every technical explanation to a concrete consequence.
- Avoid generic textbook paragraphs that could fit any disaster.
- Prefer named infrastructure, neighborhoods, agencies, facilities, geographic features, and
official investigations.
HUMAN SCALE
- Use verified individual or group experiences when they reveal something the macro statistics
cannot: inability to evacuate, rescue conditions, communications failure, shelter conditions,
survival decisions, displacement, or unequal exposure.
- Do not overuse names merely for emotion.
- Do not fictionalize what a person saw, thought, heard, or felt.
- Treat fatalities and victims with restraint.
RETENTION
- Put a strong verified development in the first 250 words.
- Build open loops from factual uncertainty, approaching danger, a system under stress, an
unanswered warning, or the next chronological turning point.
- Do not end every section with a question.
- Avoid fake mystery language. The viewer should continue because the causal chain is unfolding.
- Pay off earlier warnings and vulnerabilities when the failure occurs.
- Use short standalone sentences occasionally for emphasis, but not as a repetitive gimmick.
HUMAN WRITING
- Use mostly short and medium-length spoken sentences.
- Keep most paragraphs between one and four sentences.
- Prefer direct verbs and concrete nouns.
- Vary sentence rhythm naturally.
- Avoid academic framing, source-list phrasing, or AI-summary language.
- Avoid recurring stock phrases and obvious template language.
- Do not copy distinctive wording from the style sample or competitor reference.
COMPARISONS
- Use exactly three factual comparisons in the complete script.
- Each must clarify scale, speed, depth, distance, volume, time, or impact.
- Spread them across the documentary and verify the units.
- Do not use decorative analogies merely for drama.
THE SASTER BRANDING AND OUTRO
- Mention β{CHANNEL_NAME}β exactly once in the complete script.
- Do not mention the channel in the introduction or middle of the documentary.
- Do not use the word subscribe before the ending.
- The final 120β180 words should first resolve the story with one restrained closing insight.
- Only after that resolution, add a short human outro.
- In that outro, mention β{CHANNEL_NAME}β once and use the word subscribe exactly once.
- A brief thanks or invitation to comment is allowed, but do not let the CTA overpower the ending.
""".strip()
# =========================================================
# STYLE SAMPLE
# =========================================================
def load_style_file(
filepath: Optional[str],
) -> str:
default_style = """
Write cinematic but factual spoken English for a disaster documentary. Begin in a
specific moment, reconstruct events through clean cause-and-effect, introduce technical
background only when the viewer needs it, and move between system-level scale and verified
human consequences. Use short and medium-length sentences, brief paragraphs, concrete
places, times, measurements, warnings, decisions, failures, and aftermath. Sound like a
skilled human documentary writer, never an academic summary, sensational reenactment, or
AI narrator.
""".strip()
if not filepath:
return default_style
path = Path(filepath)
try:
if path.suffix.lower() == ".txt":
style_text = path.read_text(
encoding="utf-8",
errors="replace",
).strip()
elif path.suffix.lower() == ".docx":
document = Document(
str(path)
)
content = []
for paragraph in document.paragraphs:
paragraph_text = (
paragraph.text.strip()
)
if paragraph_text:
content.append(
paragraph_text
)
for table in document.tables:
for row in table.rows:
for cell in row.cells:
cell_text = (
cell.text.strip()
)
if cell_text:
content.append(
cell_text
)
style_text = "\n".join(
content
).strip()
else:
raise ValueError(
"Only .docx and .txt files are supported."
)
return (
style_text[:MAX_STYLE_CHARACTERS]
if style_text
else default_style
)
except Exception as exc:
raise ValueError(
f"The style document could not be read: {exc}"
) from exc
# =========================================================
# CLAUDE REQUESTS
# =========================================================
def validate_response(
response,
allow_partial_max_tokens: bool = False,
) -> None:
if response.stop_reason == "max_tokens":
if allow_partial_max_tokens:
return
raise RuntimeError(
"Claude reached the maximum output length."
)
if response.stop_reason == "refusal":
raise RuntimeError(
"Claude refused this request."
)
if response.stop_reason == "pause_turn":
raise RuntimeError(
"Claude did not complete the request."
)
def request_text(
client: Anthropic,
model: str,
system_prompt: str,
user_prompt: str,
max_tokens: int,
effort: str,
tools: Optional[list] = None,
allow_pause_turn: bool = False,
allow_partial_max_tokens: bool = False,
) -> tuple[str, object]:
messages = [
{
"role": "user",
"content": user_prompt,
}
]
attempts = (
2
if allow_pause_turn
else 1
)
for attempt in range(attempts):
request = {
"model": model,
"system": system_prompt,
"messages": messages,
"max_tokens": max_tokens,
"thinking": {
"type": "disabled",
},
"output_config": {
"effort": effort,
},
}
if tools:
request["tools"] = tools
with client.messages.stream(
**request
) as stream:
response = (
stream.get_final_message()
)
if (
response.stop_reason
== "pause_turn"
and allow_pause_turn
and attempt == 0
):
log(
"Web research returned pause_turn; "
"performing one continuation."
)
messages.append(
{
"role": "assistant",
"content": response.content,
}
)
continue
validate_response(
response,
allow_partial_max_tokens=(
allow_partial_max_tokens
),
)
text = extract_text(
response
)
if not text:
raise RuntimeError(
"Claude returned no usable text."
)
return text, response
raise RuntimeError(
"Claude could not complete the web research. "
"Try a more specific title."
)
def stream_text(
client: Anthropic,
model: str,
system_prompt: str,
user_prompt: str,
max_tokens: int,
effort: str,
) -> Generator[
tuple[str, Optional[object]],
None,
None,
]:
request = {
"model": model,
"system": system_prompt,
"messages": [
{
"role": "user",
"content": user_prompt,
}
],
"max_tokens": max_tokens,
"thinking": {
"type": "disabled",
},
"output_config": {
"effort": effort,
},
}
collected_text = ""
last_update = time.monotonic()
with client.messages.stream(
**request
) as stream:
for text_delta in stream.text_stream:
collected_text += text_delta
now = time.monotonic()
if (
now - last_update
>= STREAM_UPDATE_INTERVAL
):
yield (
collected_text,
None,
)
last_update = now
response = (
stream.get_final_message()
)
final_text = (
extract_text(response)
or collected_text.strip()
)
if response.stop_reason == "max_tokens":
log(
"A writing pass reached max_tokens; "
"the existing text is being kept."
)
yield (
final_text,
response,
)
return
validate_response(
response
)
yield (
final_text,
response,
)
# =========================================================
# PHASE 1 β DOCUMENTARY RESEARCH + CURRENT NEWS
# =========================================================
def research_topic(
client: Anthropic,
model: str,
title: str,
recency_days: int,
news_balance_option: str,
video_format_option: str,
) -> str:
cutoff_date, current_date = (
get_news_window(
recency_days
)
)
balance = resolve_news_balance(
news_balance_option
)
format_config = resolve_video_format(
video_format_option
)
topic_count = format_config[
"section_count"
]
list_mode = format_config[
"list_mode"
]
if list_mode:
ratio_min = (
balance["recent_anchor_min"]
/ 7
)
ratio_max = (
balance["recent_anchor_max"]
/ 7
)
research_anchor_min = max(
1,
round(
topic_count * ratio_min
),
)
research_anchor_max = max(
research_anchor_min,
round(
topic_count * ratio_max
),
)
else:
research_anchor_min = (
balance["recent_anchor_min"]
)
research_anchor_max = (
balance["recent_anchor_max"]
)
prompt = f"""
Today's date is {current_date.isoformat()}.
Research this proposed YouTube documentary title:
"{title}"
Create an INTERNAL evidence pack for a factual, high-retention disaster documentary of
approximately {TARGET_WORDS} words. Do not write the script. Build enough evidence to reconstruct
the event as a causal timeline, explain the physical or technical systems involved, show verified
human consequences, and cover aftermath/accountability without fictionalization.
SELECTED DOCUMENTARY TIMEFRAME
{news_balance_option}
{balance['description']}
The disaster itself is the narrative anchor. Do not require a modern news story to justify
covering a historical event.
Current material may be used in approximately {research_anchor_min}β{research_anchor_max} of
{topic_count} main topics/subtopics only when the selected mode allows it.
Required current-event narration: {balance['recent_narration_share']}.
HISTORICAL RESEARCH RULE
- Search across the full historical record needed to reconstruct the event accurately.
- Prefer contemporaneous official records, archived reporting, meteorological/seismological data,
government investigations, engineering reports, peer-reviewed studies, and credible eyewitness
documentation over modern retellings.
- Do NOT reject a topic because there is little or no recent news about it.
- Do NOT manufacture a present-day angle, anniversary hook, new warning, or "scientists now say"
framing when the historical story already stands on its own.
- If you use anything described as recent, new, current, newly measured, newly announced,
newly warned, newly rebuilt, or newly discovered, that specific claim must come from a source
published between {cutoff_date.isoformat()} and {current_date.isoformat()}.
- A recent article that repeats an old fact does not make that fact current news.
- Distinguish source publication date from event date and investigation date.
AUTHORITATIVE DOCUMENTARY BACKGROUND
- You MAY use older authoritative sources for stable topography, geology, hydrology,
engineering, historical context, long-running hazards, scientific mechanisms, and baseline
measurements when needed to explain the story.
- Prefer official agencies, universities, peer-reviewed research, recognized scientific
institutions, and high-quality datasets.
- Clearly label this material internally as BACKGROUND, not CURRENT.
- Do not use old background to manufacture a fake news angle.
- Avoid weak SEO explainers, copied summaries, and sensational unsupported claims.
EVIDENCE DECISION
Return exactly one of these near the beginning:
EVIDENCE VERDICT: SUFFICIENT
EVIDENCE VERDICT: INSUFFICIENT
Return SUFFICIENT when there is enough reliable historical and/or scientific evidence to build
{topic_count} connected main topics/subtopics. A historical disaster can be fully SUFFICIENT with
zero current-news sources.
A larger list format does NOT require a separate source or news story for every item.
If the verdict is INSUFFICIENT:
- Explain briefly which central claims or parts of the event cannot be verified well enough.
- Provide three alternative title angles that preserve the same broad event but are better
supported by the available evidence.
- Do not compensate for weak evidence with speculation, modern clickbait framing, or stale material
presented as news.
TITLE AUDIT
Also return:
TITLE VERDICT: SUPPORTED
TITLE VERDICT: PARTLY SUPPORTED
TITLE VERDICT: UNSUPPORTED
Continued activity is not acceleration, improved detection is not acceleration, and a new
publication about old data is not a new physical event.
Do not assume scientists are afraid, shocked, baffled, or issuing warnings unless reliable
evidence explicitly supports it.
SOURCE PRIORITY
Use no more than {MAX_WEB_SEARCHES} focused searches. Prioritize:
1. Official agency alerts, releases, datasets, maps, monitoring pages, and project updates.
2. University and scientific-institution research pages.
3. Peer-reviewed studies and recognized scientific journals.
4. Government decisions, infrastructure projects, legislation, funding, and operations.
5. Reputable news reporting for current human and regional context.
EDITORIAL VISUAL AVAILABILITY
- Use one or two of the available searches to check whether the strongest candidate story angles
have realistic visual support for a YouTube editor.
- Look for discoverable video or visual material on YouTube and/or official public websites:
news clips, agency videos, press briefings, interviews, fieldwork, maps, satellite imagery,
monitoring dashboards, animations, infrastructure footage, location footage, or other
concrete visuals.
- Do not select a weakly visual, text-only, or extremely obscure research detail as a major
standalone topic merely because it is scientifically interesting.
- If a scientifically important detail has poor visual support, mark it as SUPPORTING ONLY and
attach it to a stronger visually supported topic.
- Prefer candidate topics that can be illustrated with multiple independent visual options.
- Do not treat visual availability as evidence that a factual claim is true. Factual verification
and editability are separate checks.
BUILD THIS EVIDENCE PACK
1. EVIDENCE VERDICT.
2. TITLE VERDICT.
3. NEWS WINDOW:
{cutoff_date.isoformat()} to {current_date.isoformat()}.
4. THE CENTRAL DOCUMENTARY STORY in 120β180 words. Identify the trigger, the vulnerability,
the decisive turning point, the human consequence, and the deeper reason this disaster became
as severe as it did.
5. MASTER EVENT TIMELINE with the most important verified dates/times in chronological order.
Include forecasts, warnings, operational decisions, physical changes, failures, rescue/response,
and major aftermath milestones. Separate what was known AT THE TIME from what investigations
established later.
6. FAILURE / ESCALATION CHAIN:
map TRIGGER -> VULNERABILITY -> STRESS -> FAILURE/TURNING POINT -> CONSEQUENCE -> RESPONSE.
If the event does not involve an infrastructure failure, adapt this to the relevant physical
or organizational chain.
7. HUMAN EVIDENCE BANK:
verified experiences, evacuation constraints, rescue conditions, shelter conditions, injuries,
displacement, communications problems, or other human-scale evidence that can be narrated
without invention.
8. CURRENT NEWS LEDGER with roughly {balance['current_source_target']} strong sources when
available. For every source include publication date, event/research date, institution,
location, the genuinely new information, and certainty level.
6. DOCUMENTARY BACKGROUND LEDGER with 4β10 authoritative sources for durable topography,
mechanisms, baseline science, historical context, or regional consequences. Include dates
internally, but mark them BACKGROUND and do not imply recency.
7. FACT BANK with enough specific, non-duplicative evidence to support all {topic_count}
main topics/subtopics, normally at least {max(45, topic_count * 3)} useful facts.
Label every fact CURRENT or BACKGROUND.
Include location, source/institution, certainty, and why it matters.
8. SUBTOPIC BANK:
propose at least {topic_count + (5 if list_mode else 2)} distinct candidate topic angles so
the planner can select exactly {topic_count} without padding or duplication.
For list mode, each candidate must be meaningfully different and strong enough to support a
visible numbered item.
9. OPENING MATERIAL BANK with one strong evidence-based candidate for each opening mode:
- TOPOGRAPHY / GEOGRAPHY;
- DATE / CURRENT EVENT;
- NEWS CLIP CONTINUATION;
- HARD FACT / SCALE.
Also include two strong intro-ending candidates:
one central question and one verified hard fact/consequence.
10. RECENT DATA BLOCK containing the strongest current figures and measurements that are worth
mentioning in narration.
Do NOT include dates that add no storytelling value.
11. SCIENTIFIC EXPLANATIONS needed to understand the story:
mechanism, method, uncertainty, competing explanations, and limitations.
12. TOPOGRAPHY AND GEOGRAPHY details that can make the documentary visually specific.
13. HUMAN, environmental, economic, infrastructure, policy, or safety consequences.
14. At least six candidate factual comparisons with checked units.
The script will select exactly three.
15. ESSENTIAL HISTORICAL CONTEXT, limited to what genuinely improves understanding and short
enough to stay within {MAX_HISTORICAL_CONTEXT_PERCENT} percent of the final script.
16. EDITORIAL VISUAL SUPPORT BANK:
- For every strong candidate topic/subtopic, rate editability as HIGH, MEDIUM, or LOW.
- List 2β5 realistic visual avenues such as named locations, agency footage, maps,
satellite imagery, dashboards, interviews, fieldwork, public briefings, news clips,
infrastructure, or other searchable visuals.
- Mark LOW-visual topics as SUPPORTING ONLY unless they are absolutely essential.
- Prefer HIGH or MEDIUM topics for standalone sections/subtopics.
17. CONTINUITY LINKS:
- For every major candidate topic, state what fact or unresolved point naturally leads
INTO it.
- State what consequence, question, or mechanism naturally leads OUT of it.
- Flag any pair of candidate topics that would create an abrupt narrative jump.
18. CLAIMS TO AVOID.
19. EXTRA VERIFIED FACTS that can be used to reach the word target without repetitive dates,
stale filler, generic textbook language, or visually unworkable standalone topics.
Do not copy source sentences.
Do not write dramatic narration.
The evidence pack should be rich enough to support documentary depth, the selected amount of
current news, smooth narrative continuity, and realistic editing with discoverable visual
material.
""".strip()
web_search_tool = [
{
"type": "web_search_20260318",
"name": "web_search",
"max_uses": MAX_WEB_SEARCHES,
"allowed_callers": [
"direct",
],
"response_inclusion": "excluded",
}
]
log(
"Phase 1 started: documentary research with a current-news layer "
f"({cutoff_date.isoformat()} to {current_date.isoformat()}; "
f"{news_balance_option})."
)
research, response = request_text(
client=client,
model=model,
system_prompt=(
"You are a rigorous disaster-documentary researcher. Reconstruct event chronology, "
"distinguish what was known at the time from what later investigations found, and separate "
"the initiating hazard from infrastructure, operational, communication, preparedness, and "
"response factors. Build strong scientific, engineering, geographic, human, and aftermath "
"evidence without fictionalization. Current developments are optional unless the selected "
"news balance requires them. Also evaluate visual editability and natural continuity."
),
user_prompt=prompt,
max_tokens=RESEARCH_MAX_TOKENS,
effort="medium",
tools=web_search_tool,
allow_pause_turn=True,
allow_partial_max_tokens=True,
)
research_words = count_words(
research
)
recency_verdict = extract_recency_verdict(
research
)
if response.stop_reason == "max_tokens":
log(
"Research reached max_tokens; "
"the completed research is being used."
)
if recency_verdict == "INSUFFICIENT":
raise RuntimeError(
"There is not enough reliable evidence to support this documentary angle. "
"Try a more specific or better-documented event/title."
)
if recency_verdict != "SUFFICIENT":
raise RuntimeError(
"Claude could not confirm that there is enough reliable evidence for the documentary. "
"Try a more specific title or event."
)
if research_words < 800:
raise RuntimeError(
"Claude returned too little usable research. Make the event or title more specific."
)
log(
f"Phase 1 complete: "
f"{research_words} words of research."
)
return research
# =========================================================
# PHASE 2 β SCRIPT PLAN WITH FIXED WORD BUDGETS
# =========================================================
def create_script_plan(
client: Anthropic,
model: str,
title: str,
research: str,
cutoff_date: date,
current_date: date,
global_requirements: str,
news_balance_option: str,
hook_option: str,
video_format_option: str,
) -> str:
balance = resolve_news_balance(
news_balance_option
)
format_config = resolve_video_format(
video_format_option
)
topic_count = format_config[
"section_count"
]
list_mode = format_config[
"list_mode"
]
chunk_counts = format_config[
"chunk_sections"
]
if list_mode:
ratio_min = (
balance["recent_anchor_min"]
/ 7
)
ratio_max = (
balance["recent_anchor_max"]
/ 7
)
anchor_min = max(
1,
round(
topic_count * ratio_min
),
)
anchor_max = max(
anchor_min,
round(
topic_count * ratio_max
),
)
structure_plan = f"""
LIST-DOCUMENTARY STRUCTURE
- Plan exactly {topic_count} numbered subtopics.
- Chunk 1 contains subtopics 1β{chunk_counts[0]} after the introduction.
- Chunk 2 contains subtopics {chunk_counts[0] + 1}β{chunk_counts[0] + chunk_counts[1]}.
- Chunk 3 contains subtopics {chunk_counts[0] + chunk_counts[1] + 1}β{topic_count},
followed by the 100β160 word ending.
- Every planned heading must use: ## NUMBER. Short Title
- The item type must fit the title naturally. Use βreasonsβ only if the title truly asks why;
otherwise use facts, warning signs, locations, risks, mechanisms, changes, consequences,
or another fitting category.
- Give each item an exact word budget. Keep enough variation to avoid monotony, but do not use
the standard documentary rule requiring a 150-word gap between longest and shortest items.
- Prevent duplication aggressively: each numbered item must have its own core claim and evidence.
""".strip()
else:
anchor_min = (
balance["recent_anchor_min"]
)
anchor_max = (
balance["recent_anchor_max"]
)
structure_plan = """
STANDARD DOCUMENTARY STRUCTURE
- Plan exactly seven titled sections:
two in chunk 1,
three in chunk 2,
and two in chunk 3.
- Give every section an exact individual word budget.
- Do not give neighboring sections similar budgets unless necessary.
- Use the largest sections for the richest scientific or geographic material.
- Use at least two noticeably short bridge sections.
- The largest section must be at least 150 words longer than the shortest.
""".strip()
prompt = f"""
Create a concise but detailed INTERNAL writing plan for this proposed title:
"{title}"
<evidence_pack>
{research}
</evidence_pack>
SELECTED VIDEO FORMAT
{video_format_option}
The final spoken script must contain 2,900β3,200 words and exactly three writing chunks:
CHUNK 1 β 900β1,000 words
- A cinematic cold-open introduction of 130β180 words.
- Follow the selected hook: {hook_option}.
- Then cover the first {chunk_counts[0]} main topics/subtopics.
- Move into the strongest story material instead of automatically dumping dates or source
chronology.
CHUNK 2 β 1,000β1,100 words
- Cover the next {chunk_counts[1]} main topics/subtopics.
- Carry the densest scientific explanation, analysis, regional consequences, named research or
monitoring, and selected current developments.
CHUNK 3 β 1,000β1,100 words
- Cover the final {chunk_counts[2]} main topics/subtopics.
- Finish with a connected ending of 120β180 words that resolves the story before the brief outro.
That produces exactly {topic_count} main topics/subtopics in the full script.
{structure_plan}
{global_requirements}
NEWS / DOCUMENTARY ALLOCATION
- Mark every main topic/subtopic internally as either NEWS ANCHOR or DOCUMENTARY CORE.
- Use NEWS ANCHOR for approximately {anchor_min}β{anchor_max} items total.
Do not force news into every item.
- Use DOCUMENTARY CORE for topography, physical mechanisms, scientific explanation, regional
consequences, long-running systems, infrastructure, or other durable material.
- Recent-event narration across the whole script should be
{balance['recent_narration_share']}.
- Plan only {balance['date_mentions_min']}β{balance['date_mentions_max']} explicit calendar-date
references for the spoken narration.
- Publication dates can remain internal in the plan.
- Never create a standalone history lesson merely to fill an item.
- Never create a standalone latest-update item merely to satisfy recency.
Blend current developments into the central documentary story.
INTRO PLAN
- State the exact hook mode that chunk 1 will use.
- If the selected hook is AUTO, choose the strongest mode from the evidence pack and
record the choice.
- Plan the first 3β4 sentences by function only, not as sample narration.
- Do not include channel branding or a CTA in the introduction.
- Plan the intro as a cold open: one immediate scene/thread, one emerging threat, and one
unresolved vulnerability or consequence that pulls the viewer into section 1.
- Choose the intro's final sentence type:
CENTRAL QUESTION or HARD FACT / CONSEQUENCE.
- Do not automatically choose a question every time.
FOR EVERY MAIN TOPIC / SUBTOPIC PROVIDE
- its exact heading/title;
- ROLE: NEWS ANCHOR or DOCUMENTARY CORE;
- its central purpose;
- its exact word budget;
- the exact facts, measurements, people, locations, topography, and mechanisms it uses;
- the scientific explanation or analysis it contains;
- the human or practical consequence;
- if NEWS ANCHOR:
the current development, publication date, and event date;
- if DOCUMENTARY CORE:
the durable evidence it explains and how it connects to the story;
- whether an explicit date should actually be spoken aloud;
- MICRO-STORY:
the one person/place/event/measurement/mechanism the first 2β4 sentences follow;
- CONTINUITY IN:
the exact fact or unresolved point from the previous topic that leads here;
- CONTINUITY OUT:
the exact consequence, mechanism, or unresolved point that leads onward;
- VISUAL SUPPORT:
HIGH or MEDIUM;
- 2β4 INTERNAL VISUAL SEARCH ANCHORS for the editor;
- its transition to the next item or section;
- any essential historical context, limited to one or two brief points.
ALLOCATION RULES
- Assign every important fact to only one topic/subtopic.
- Put the strongest verified material in chunk 1, but that material does not have to be news.
- Reserve enough unused evidence for chunks 2 and 3.
- Select exactly three verified comparisons and assign each to a different part of the script.
- Assign named studies, projects, reports, alerts, datasets, or monitoring efforts where they
add substance. They do not all need to be recent.
- In list mode, audit the full list for overlap before finalizing the plan.
- If two items are substantially similar, merge the idea and replace one with a genuinely
different topic.
- Do not create a debunking video.
- Silently use the strongest accurate angle.
EDITORIAL EDITABILITY CHECK
- For every planned main topic/subtopic, include VISUAL SUPPORT: HIGH or MEDIUM.
- Do not use a LOW-visual candidate as a standalone item.
- Fold its useful science into the nearest HIGH/MEDIUM topic.
- For every planned topic, list 2β4 short visual search anchors for the editor:
named place, project, agency, event, map, satellite view, fieldwork, interview,
monitoring system, or infrastructure.
- These are INTERNAL planning notes only and must never appear in narration.
- Prefer topics with several realistic visual avenues rather than a single obscure paper or
text-only finding.
- If two candidate topics are equally strong factually, prefer the one with better editability.
CONTINUITY MAP
- Before finalizing the plan, audit every neighboring topic pair.
- For each transition write:
PREVIOUS THREAD β BRIDGE LOGIC β NEXT THREAD.
- The bridge logic must explain why the next topic follows naturally from the previous one.
- Reject or reorder any topic pair where one line would begin a story and the next line would
need to switch subject, location, time period, cause, or meaning without explanation.
- Within each topic, define a single MICRO-STORY for the opening 2β4 sentences.
- The opening 2β4 sentences of a topic must stay on that micro-story before widening into
background, science, or consequences.
- Mark any intentional change in interpretation as EXPLICIT CONTRAST so the writer must signal
it rather than abruptly reversing the previous sentence.
THE SASTER OUTRO PLAN
- No channel branding or CTA in chunks 1 or 2.
- No mid-video subscription interruption.
- In the final 120β180 words, resolve the documentary first.
- Then add a short human outro containing β{CHANNEL_NAME}β exactly once and the word
βsubscribeβ exactly once.
- A brief thanks or comment invitation is optional.
Keep the complete plan between 1,500 and 2,700 words.
Use compact bullet points.
Do not write sample narration and do not repeat the entire evidence pack.
This is a plan only.
""".strip()
log(
f"Phase 2 started: three-part plan for "
f"{video_format_option}."
)
plan, response = request_text(
client=client,
model=model,
system_prompt=(
"You are a senior disaster-documentary editor. Build a connected reconstruction with "
"a clear timeline, escalating cause-and-effect, technical explanation at the moment it "
"becomes relevant, verified human consequences, and a strong aftermath. Preserve the "
"creator's exact section format, prevent repetition, use current news only when warranted, "
"and give every neighboring topic a clear narrative bridge."
),
user_prompt=prompt,
max_tokens=PLAN_MAX_TOKENS,
effort="medium",
allow_partial_max_tokens=True,
)
if response.stop_reason == "max_tokens":
log(
"The script plan reached max_tokens; "
"the completed plan is being used."
)
if count_words(plan) < 400:
raise RuntimeError(
"Claude did not create a usable documentary plan."
)
log(
f"Phase 2 complete: "
f"{count_words(plan)} words in the plan."
)
return plan
# =========================================================
# PHASE 3 β THREE SCRIPT CHUNKS
# =========================================================
def channel_rules_for_chunk(
chunk_number: int,
) -> str:
if chunk_number in (1, 2):
return f"""
THE SASTER RULES FOR THIS CHUNK
- Do not mention β{CHANNEL_NAME}β in this chunk.
- Do not use the word subscribe.
- Do not interrupt the disaster narrative with a CTA, like request, or comment request.
""".strip()
return f"""
THE SASTER RULES FOR THIS CHUNK
- Do not mention β{CHANNEL_NAME}β until the final outro.
- Do not use the word subscribe before the final outro.
- First finish the documentary itself with a 120β180 word connected ending.
- After the story is resolved, add a short human outro.
- Mention β{CHANNEL_NAME}β exactly once in that outro.
- Use the word subscribe exactly once.
- A brief thank-you or invitation to comment is allowed.
- Keep the CTA restrained; the final documentary thought should remain the emotional endpoint.
""".strip()
def build_chunk_prompt(
title: str,
research: str,
plan: str,
style_text: str,
previous_script: str,
spec: dict,
cutoff_date: date,
current_date: date,
global_requirements: str,
) -> str:
chunk_number = spec["number"]
minimum = spec["minimum"]
maximum = spec["maximum"]
target = spec["target"]
if "section_start" in spec:
format_rule = (
f"This chunk must contain exactly the numbered headings "
f"## {spec['section_start']}. through ## {spec['section_end']}. "
f"Use every number once, in order, with no extra numbered subtopic."
)
else:
format_rule = (
"This chunk must contain exactly the standard documentary section headings "
"assigned to it in the plan."
)
if chunk_number == 1:
continuity_rule = (
"Do not print the video title. Write the 130β180 word introduction according "
"to the selected hook strategy in the global requirements and the exact hook "
"choice recorded in the plan. After the intro, move directly into the planned "
"story material without a source-list or date dump."
)
else:
continuity_rule = (
"Continue naturally from the previous script. Do not write a new introduction, "
"do not recap earlier sections, and do not repeat facts."
)
return f"""
Write ONLY CHUNK {chunk_number} of the final spoken YouTube documentary.
Proposed title:
"{title}"
<evidence_pack>
{research}
</evidence_pack>
<full_writing_plan>
{plan}
</full_writing_plan>
<style_sample>
{style_text}
</style_sample>
<previous_script>
{previous_script if previous_script else "No previous script yet."}
</previous_script>
CHUNK PURPOSE
{spec['purpose']}
EXACT STRUCTURE FOR THIS CHUNK
- {format_rule}
HARD LENGTH REQUIREMENT
- This chunk must contain between {minimum} and {maximum} words.
- Aim for {target} words.
- This is a hard production requirement, not a suggestion.
- Before answering, silently count the chunk and keep adding unused verified information,
explanation, consequences, topographic detail, or analysis until it reaches at least
{minimum} words.
- Do not add dates merely to fill space.
{global_requirements}
NEWS / DOCUMENTARY REQUIREMENTS FOR THIS CHUNK
- Follow the ROLE assignments in the plan:
NEWS ANCHOR versus DOCUMENTARY CORE.
- Only NEWS ANCHOR material may be narrated as a current development.
- Any claim described as recent or current must fall inside the news window
{cutoff_date.isoformat()} through {current_date.isoformat()}.
- DOCUMENTARY CORE material may use authoritative older evidence when the plan marks it as
durable background.
- Never make that material sound newly discovered.
- Follow the planned spoken-date budget.
- Do not mention publication dates unless the audience actually needs them.
- Do not turn every named study or agency update into a date sentence.
- Use exact dates sparingly.
- Use names, places, measurements, mechanisms, and consequences more often than chronology.
WRITING STANDARD
- {continuity_rule}
- Follow the exact topic/subtopic budgets assigned in the plan.
- Every paragraph must add a new fact, example, mechanism, measurement, consequence, event,
research result, analysis, topographic detail, or documented uncertainty.
- Write straight to the point and explain why the information matters.
- Use mostly short and medium-length sentences and paragraphs of one to four sentences.
- Translate technical language into natural spoken English.
- Use exact names, places, numbers, and measurements when useful.
- Explain the science deeply where the plan assigns it:
methods, causal mechanisms, uncertainty, limitations, competing explanations,
and practical implications.
- Follow the planned open loops and chronological turning points so each section connects directly
to the next. Prefer factual anticipation over rhetorical teasing.
- Follow the plan's MICRO-STORY, CONTINUITY IN, and CONTINUITY OUT instructions.
- Once a sentence introduces a person, place, event, measurement, mechanism, or claim,
keep the next sentence on that same thread unless an explicit bridge explains the change.
- Never let one sentence begin a story while the next sentence changes the subject,
location, time frame, cause, or interpretation without explaining the connection.
- Keep the first 2β4 sentences after each heading on the planned micro-story before widening
into background or analysis.
- When changing direction inside a paragraph, use one short causal, temporal, geographic,
or contrast bridge so the viewer understands why the new point follows.
- Do not let a pronoun or phrase such as βthis,β βit,β βthey,β or βthatβ silently change
referent from one sentence to the next.
- If the plan marks a point as EXPLICIT CONTRAST, signal the contrast clearly before changing
or qualifying the previous meaning.
- Keep standalone topics limited to material marked VISUAL SUPPORT: HIGH or MEDIUM in the plan.
- Technical LOW-visual details should appear only as supporting explanation inside a stronger
editable topic.
- Fully paraphrase the evidence and the style sample.
- Preserve uncertainty.
Do not turn possible, estimated, preliminary, or disputed information into certainty.
- Do not tell the audience that the proposed title was fact-checked or exaggerated.
- Use every heading exactly as planned for this chunk.
In list mode, preserve the exact continuous numbering.
- Use only the comparisons assigned to this chunk.
The complete script must contain exactly three factual comparisons in total.
- Do not include sources, URLs, citations, editor notes, camera directions, or B-roll.
DISASTER RECONSTRUCTION CHECK
- Keep the event order clear. If the narration jumps backward for context, signal the rewind.
- Separate what participants knew at the time from what later investigations established.
- When a system fails, explain what it was supposed to do before describing how it failed.
- Do not let technical explanation stall the timeline for too long; return to the unfolding event.
- Use verified human-scale evidence to show consequences, but never invent scenes or emotions.
- Treat casualty figures and suffering with restraint.
- If responsibility is disputed, attribute findings instead of declaring motive or blame.
- Let the most important causal insight emerge from the evidence rather than repeating the title.
SILENT CONTINUITY AUDIT BEFORE RETURNING
- Read every pair of neighboring sentences.
- If sentence B does not clearly continue, explain, qualify, contrast, or result from
sentence A, rewrite the pair or add a brief bridge.
- Check every paragraph boundary the same way.
- Remove abrupt pivots that change meaning or direction without setup.
- Check especially for:
sudden location changes;
sudden timeline changes;
sudden changes from one researcher to another;
sudden changes from a measurement to an unrelated mechanism;
sudden switches from confirmed fact to speculation;
and sentences that appear to contradict the line immediately before them.
- Preserve the same factual content.
Fix the flow rather than adding new material.
{channel_rules_for_chunk(chunk_number)}
Return only CHUNK {chunk_number} as finished spoken narration.
""".strip()
def build_chunk_revision_prompt(
research: str,
plan: str,
previous_script: str,
current_chunk: str,
chunk_number: int,
minimum: int,
maximum: int,
target: int,
cutoff_date: date,
current_date: date,
global_requirements: str,
structure_issue: Optional[str] = None,
) -> str:
current_words = count_words(
current_chunk
)
operations = []
if current_words < minimum:
operations.append(
f"The chunk is {minimum - current_words} words below the minimum. "
"Expand it with unused verified facts, topography, mechanisms, "
"scientific explanation, measurements, consequences, or planned "
"current developments assigned to this part. Respect the section "
"roles and spoken-date budget."
)
elif current_words > maximum:
operations.append(
f"The chunk is {current_words - maximum} words above the maximum. "
"Remove repetition, unnecessary chronology, source-date language, "
"and decorative phrasing while preserving important science, geography, "
"current anchors, open loops, comparisons, and CTA placement."
)
else:
operations.append(
"The chunk is already inside the required word range. "
"Preserve its overall length."
)
if structure_issue:
operations.append(
"Repair this exact structural problem: "
+ structure_issue
+ " Preserve every correct numbered heading, restore missing headings, "
"remove duplicates, and keep the planned evidence attached to the correct item."
)
operation = "\n".join(
operations
)
return f"""
Rewrite the COMPLETE chunk below.
It currently contains approximately {current_words} words.
It must contain between {minimum} and {maximum} words.
Aim for {target} words.
{operation}
<recent_evidence_pack>
{research}
</recent_evidence_pack>
<writing_plan>
{plan}
</writing_plan>
<previous_script>
{previous_script if previous_script else "No previous script."}
</previous_script>
<current_chunk>
{current_chunk}
</current_chunk>
{global_requirements}
NEWS / DOCUMENTARY BALANCE CHECK
- Preserve the NEWS ANCHOR and DOCUMENTARY CORE roles from the plan.
- Claims narrated as recent or current must be supported inside the window
{cutoff_date.isoformat()} through {current_date.isoformat()}.
- Durable older evidence may remain when it provides useful scientific, geographic,
or historical context and is not presented as recent.
- When expanding, prefer unused mechanisms, measurements, topography, consequences,
or verified facts over extra date references.
- When shortening, remove repetitive chronology and source-date language before
removing important science or geographic detail.
Keep the same topic purposes, exact headings, appropriate topic pacing,
scientific explanations, analysis, planned comparisons, and content-based cliffhangers.
If the chunk uses numbered ## headings, preserve the intended number range exactly:
do not skip, duplicate, merge, restart, or add a numbered item.
CONTINUITY REPAIR
- Preserve the plan's MICRO-STORY, CONTINUITY IN, and CONTINUITY OUT for each topic.
- Check each neighboring sentence pair.
- Sentence B must clearly continue, explain, qualify, contrast, or result from sentence A.
- Repair abrupt switches in:
subject;
location;
time frame;
causal explanation;
scientific interpretation;
or meaning.
- Keep the first 2β4 sentences under a heading on one immediate story before widening out.
- Add a short bridge when the narrative genuinely needs to pivot.
- Do not let pronouns silently change referent between sentences.
- Preserve intentional contrasts, but signpost them clearly.
- Do not promote a LOW-visual supporting detail into a standalone topic during revision.
- If a line begins a concrete event or story, do not abandon that event in the very next line.
Give it enough explanation or resolution before moving on.
- Check paragraph boundaries as carefully as sentence boundaries.
The first sentence of a new paragraph must clearly connect to what came immediately before it.
Keep the narration direct, human, and information-dense.
Do not add a new introduction, sources, citations, or production notes.
{channel_rules_for_chunk(chunk_number)}
Before returning:
1. Silently count the result.
2. Silently reread every neighboring sentence pair.
3. Fix any abrupt change of subject or meaning.
4. Confirm that standalone topics remain realistically editable.
Return only the complete revised chunk.
""".strip()
def revise_chunk(
client: Anthropic,
model: str,
research: str,
plan: str,
previous_script: str,
current_chunk: str,
chunk_number: int,
minimum: int,
maximum: int,
target: int,
cutoff_date: date,
current_date: date,
global_requirements: str,
structure_issue: Optional[str] = None,
) -> str:
prompt = build_chunk_revision_prompt(
research=research,
plan=plan,
previous_script=previous_script,
current_chunk=current_chunk,
chunk_number=chunk_number,
minimum=minimum,
maximum=maximum,
target=target,
cutoff_date=cutoff_date,
current_date=current_date,
global_requirements=global_requirements,
structure_issue=structure_issue,
)
revised, _ = request_text(
client=client,
model=model,
system_prompt=(
"You are a strict disaster-documentary editor. Meet the requested word range while "
"preserving timeline clarity, factual density, technical explanation, verified human "
"impact, natural spoken rhythm, causal escalation, aftermath, and exact brand placement. "
"Repair sentence-to-sentence continuity, preserve what was known at each point in time, "
"and never fictionalize scenes or motives."
),
user_prompt=prompt,
max_tokens=REVISION_MAX_TOKENS,
effort="medium",
allow_partial_max_tokens=True,
)
return revised
# =========================================================
# TOTAL LENGTH REBALANCING
# =========================================================
def rebalance_total(
client: Anthropic,
model: str,
research: str,
plan: str,
chunks: list[str],
cutoff_date: date,
current_date: date,
global_requirements: str,
) -> list[str]:
for _ in range(2):
total_words = count_words(
joined_script(chunks)
)
if MIN_WORDS <= total_words <= MAX_WORDS:
return chunks
if total_words < MIN_WORDS:
deficit = (
MIN_WORDS
- total_words
)
index = 1
current = count_words(
chunks[index]
)
minimum = (
current
+ deficit
+ 25
)
maximum = (
minimum
+ 70
)
target = (
minimum
+ 35
)
else:
excess = (
total_words
- MAX_WORDS
)
index = max(
range(
len(chunks)
),
key=lambda i: count_words(
chunks[i]
),
)
current = count_words(
chunks[index]
)
maximum = max(
650,
current - excess - 20,
)
minimum = max(
600,
maximum - 70,
)
target = (
minimum
+ 35
)
previous_script = joined_script(
chunks[:index]
)
chunks[index] = revise_chunk(
client=client,
model=model,
research=research,
plan=plan,
previous_script=previous_script,
current_chunk=chunks[index],
chunk_number=index + 1,
minimum=minimum,
maximum=maximum,
target=target,
cutoff_date=cutoff_date,
current_date=current_date,
global_requirements=global_requirements,
)
return chunks
# =========================================================
# MAIN WORKFLOW
# =========================================================
def generate_script(
title: str,
style_file: Optional[str],
model: str,
recency_option: str,
news_balance_option: str,
hook_option: str,
video_format_option: str,
):
current_script = ""
if not title or not title.strip():
yield (
"β Enter a video title first.",
"",
)
return
try:
client = get_client()
clean_title = (
title.strip()
)
style_text = load_style_file(
style_file
)
recency_days = resolve_recency_days(
recency_option
)
cutoff_date, current_date = (
get_news_window(
recency_days
)
)
global_requirements = (
build_global_writing_requirements(
cutoff_date=cutoff_date,
current_date=current_date,
news_balance_option=news_balance_option,
hook_option=hook_option,
video_format_option=video_format_option,
)
)
yield (
"π Phase 1/3 β gathering documentary research, "
"historical evidence, event chronology, and editor-friendly visual topics "
f"from {cutoff_date.isoformat()}β¦",
"",
)
research = research_topic(
client=client,
model=model,
title=clean_title,
recency_days=recency_days,
news_balance_option=news_balance_option,
video_format_option=video_format_option,
)
yield (
"π§ Phase 2/3 β distributing evidence, editability, "
"and narrative continuity across three partsβ¦",
"",
)
plan = create_script_plan(
client=client,
model=model,
title=clean_title,
research=research,
cutoff_date=cutoff_date,
current_date=current_date,
global_requirements=global_requirements,
news_balance_option=news_balance_option,
hook_option=hook_option,
video_format_option=video_format_option,
)
chunks: list[str] = []
active_chunk_specs = (
get_chunk_specs(
video_format_option
)
)
for spec in active_chunk_specs:
chunk_number = spec[
"number"
]
previous_script = (
joined_script(
chunks
)
)
yield (
f"βοΈ Phase 3/3 β writing part "
f"{chunk_number}/3 β total so far "
f"{count_words(previous_script)} wordsβ¦",
previous_script,
)
prompt = build_chunk_prompt(
title=clean_title,
research=research,
plan=plan,
style_text=style_text,
previous_script=previous_script,
spec=spec,
cutoff_date=cutoff_date,
current_date=current_date,
global_requirements=global_requirements,
)
chunk_text = ""
final_response = None
for (
partial_text,
response,
) in stream_text(
client=client,
model=model,
system_prompt=(
"You are an experienced human disaster-documentary writer. Write cinematic "
"but factual spoken English with a clear timeline, escalating cause-and-effect, "
"concrete places and times, plain-English technical explanation, verified human "
"consequences, and a strong aftermath. Use short and medium sentences with natural "
"rhythm. Build retention from what happens next and why, not generic hype. Never "
"invent scenes, motives, dialogue, or sensory details. Preserve the creator's "
"exact section format."
),
user_prompt=prompt,
max_tokens=CHUNK_MAX_TOKENS,
effort="medium",
):
chunk_text = (
partial_text
)
if response is not None:
final_response = (
response
)
current_script = (
joined_script(
chunks
+ [partial_text]
)
)
if response is None:
yield (
f"βοΈ Part {chunk_number}/3 β "
f"{count_words(partial_text)} words in this part β "
f"{count_words(current_script)} total",
current_script,
)
if not chunk_text.strip():
raise RuntimeError(
f"Claude did not write "
f"part {chunk_number}."
)
chunk_words = count_words(
chunk_text
)
log(
f"Part {chunk_number} "
f"first draft: "
f"{chunk_words} words."
)
structure_issue = (
get_chunk_structure_issue(
chunk_text,
spec,
)
)
for correction_attempt in range(3):
length_ok = (
spec["minimum"]
<= chunk_words
<= spec["maximum"]
)
if (
length_ok
and not structure_issue
):
break
issue_text = (
f" Structure check: "
f"{structure_issue}"
if structure_issue
else ""
)
yield (
f"π Part {chunk_number}/3 has "
f"{chunk_words} words; target is "
f"{spec['minimum']}β{spec['maximum']}."
f"{issue_text} Correction "
f"{correction_attempt + 1}/3β¦",
joined_script(
chunks
+ [chunk_text]
),
)
chunk_text = revise_chunk(
client=client,
model=model,
research=research,
plan=plan,
previous_script=previous_script,
current_chunk=chunk_text,
chunk_number=chunk_number,
minimum=spec["minimum"],
maximum=spec["maximum"],
target=spec["target"],
cutoff_date=cutoff_date,
current_date=current_date,
global_requirements=global_requirements,
structure_issue=structure_issue,
)
chunk_words = count_words(
chunk_text
)
structure_issue = (
get_chunk_structure_issue(
chunk_text,
spec,
)
)
log(
f"Part {chunk_number} after "
f"correction "
f"{correction_attempt + 1}: "
f"{chunk_words} words."
)
if (
final_response is not None
and final_response.stop_reason
== "max_tokens"
):
log(
f"Part {chunk_number} reached "
"max_tokens, but the existing "
"text is being kept."
)
chunks.append(
chunk_text.strip()
)
current_script = (
joined_script(
chunks
)
)
yield (
f"β
Part {chunk_number}/3 complete β "
f"{chunk_words} words β "
f"{count_words(current_script)} total",
current_script,
)
total_words = count_words(
current_script
)
if not (
MIN_WORDS
<= total_words
<= MAX_WORDS
):
yield (
f"π§ Total length is "
f"{total_words} words; "
"running final length correctionβ¦",
current_script,
)
chunks = rebalance_total(
client=client,
model=model,
research=research,
plan=plan,
chunks=chunks,
cutoff_date=cutoff_date,
current_date=current_date,
global_requirements=global_requirements,
)
current_script = (
joined_script(
chunks
)
)
total_words = count_words(
current_script
)
warnings = story_requirement_warnings(
text=current_script,
cutoff_date=cutoff_date,
current_date=current_date,
news_balance_option=news_balance_option,
video_format_option=video_format_option,
)
window_text = (
f"news window "
f"{cutoff_date.isoformat()} "
f"to "
f"{current_date.isoformat()}"
)
if (
MIN_WORDS
<= total_words
<= MAX_WORDS
and not warnings
):
status = (
f"β
Ready β "
f"{total_words} words β "
f"{window_text} β "
f"1x {CHANNEL_NAME} β "
"1x subscribe in outro"
)
elif (
MIN_WORDS
<= total_words
<= MAX_WORDS
):
status = (
f"β οΈ Ready β "
f"{total_words} words β "
f"{window_text}. Check: "
+ "; ".join(warnings)
)
else:
warning_text = (
f" Also check: "
f"{'; '.join(warnings)}"
if warnings
else ""
)
status = (
f"β οΈ Ready β "
f"{total_words} words. "
f"Target: "
f"{MIN_WORDS}β{MAX_WORDS}. "
f"{window_text}."
+ warning_text
)
yield (
status,
current_script,
)
except anthropic.AuthenticationError:
yield (
"β The Anthropic API key is invalid.",
current_script,
)
except anthropic.PermissionDeniedError:
yield (
"β Your Anthropic account does not have access "
"to this model or web search.",
current_script,
)
except anthropic.RateLimitError:
yield (
"β The Anthropic rate or usage limit has been reached. "
"Check your billing.",
current_script,
)
except anthropic.APITimeoutError:
yield (
f"β Claude did not respond within "
f"{API_TIMEOUT_SECONDS} seconden.",
current_script,
)
except anthropic.APIConnectionError:
yield (
"β Could not connect to Claude.",
current_script,
)
except anthropic.BadRequestError as exc:
error_text = str(
exc
)
lower_error = (
error_text.lower()
)
if (
"web search is not enabled"
in lower_error
):
message = (
"β Web search is not enabled for "
"your Anthropic organization."
)
elif (
"credit balance"
in lower_error
):
message = (
"β Your Anthropic API credit "
"balance is insufficient."
)
else:
message = (
f"β Anthropic rejected "
f"the request: "
f"{error_text}"
)
yield (
message,
current_script,
)
except anthropic.APIStatusError as exc:
yield (
f"β Anthropic API error "
f"{exc.status_code}: "
f"{exc.message}",
current_script,
)
except Exception as exc:
log(
f"Unexpected error: "
f"{exc}"
)
yield (
f"β Something went wrong: "
f"{exc}",
current_script,
)
# =========================================================
# TIMER AND INTERFACE
# =========================================================
def start_run():
start_time = time.time()
return (
start_time,
True,
format_elapsed(0),
"π Generation startedβ¦",
"",
gr.Button(
interactive=False,
),
)
def update_timer(
start_time: float,
is_running: bool,
):
if (
not is_running
or not start_time
):
return gr.skip()
elapsed_seconds = int(
time.time()
- float(start_time)
)
return format_elapsed(
elapsed_seconds
)
def finish_run(
start_time: float,
):
elapsed_seconds = (
int(
time.time()
- float(start_time)
)
if start_time
else 0
)
return (
False,
format_elapsed(
elapsed_seconds,
finished=True,
),
gr.Button(
interactive=True,
),
)
def clear_interface():
return (
"",
None,
DEFAULT_RECENCY_OPTION,
DEFAULT_NEWS_BALANCE_OPTION,
DEFAULT_HOOK_OPTION,
DEFAULT_VIDEO_FORMAT_OPTION,
"",
"",
0.0,
False,
format_elapsed(0),
gr.Button(
interactive=True,
),
)
with gr.Blocks() as demo:
gr.Markdown(
"""
# The Saster Documentary Script Writer
Creates a cinematic, factual disaster-documentary script of 2,900β3,200 words.
The Saster style prioritizes a strong cold open, clean event chronology, warnings,
failure chains, human consequences, technical explanation, aftermath, and accountability,
while preserving your own 7-section or 10/20/30-subtopic structure.
"""
)
start_time_state = gr.State(
0.0
)
running_state = gr.State(
False
)
elapsed_timer = gr.Timer(
value=1.0,
active=True,
)
with gr.Row():
title_input = gr.Textbox(
label="π― Video title",
placeholder=(
"The Storm That Emptied an Entire City β Houston 2005"
),
lines=2,
)
model_input = gr.Dropdown(
choices=MODEL_OPTIONS,
value="claude-sonnet-5",
label="π§ Claude model",
)
# Hidden internal state. Historical-disaster mode does not use a recency window.
# The fixed default is only consulted when a present-day-context mode is selected.
recency_input = gr.State(DEFAULT_RECENCY_OPTION)
with gr.Row():
news_balance_input = gr.Dropdown(
choices=list(
NEWS_BALANCE_OPTIONS.keys()
),
value=DEFAULT_NEWS_BALANCE_OPTION,
label="π°οΈ Documentary timeframe",
info=(
"Historical disaster mode requires no recent-news angle. "
"Use the other modes only when you intentionally want "
"present-day context or a current hook."
),
)
hook_input = gr.Dropdown(
choices=HOOK_OPTIONS,
value=DEFAULT_HOOK_OPTION,
label="π¬ Opening hook",
info=(
"Choose how the cold open starts. Auto selects "
"a date/place scene, an immediate disaster moment, "
"a warning/failure setup, or a hard consequence. "
"News clip continuation is used only when selected."
),
)
video_format_input = gr.Dropdown(
choices=list(
VIDEO_FORMAT_OPTIONS.keys()
),
value=DEFAULT_VIDEO_FORMAT_OPTION,
label="π§© Video format",
info=(
"Choose the normal 7-section documentary "
"or a Reasons-Why-style list documentary "
"with exactly 10, 20, or 30 visible "
"numbered subtopics."
),
)
style_file_input = gr.File(
label=(
"π Upload a handmade sample script "
"for style inspiration (.docx or .txt)"
),
file_types=[
".docx",
".txt",
],
type="filepath",
)
with gr.Row():
clear_button = gr.Button(
"Clear"
)
generate_button = gr.Button(
"π Generate",
variant="primary",
)
with gr.Row():
status_output = gr.Textbox(
label="Status",
interactive=False,
)
elapsed_output = gr.Textbox(
label="Elapsed time",
value=format_elapsed(0),
interactive=False,
)
script_output = gr.Textbox(
label="Final script",
lines=35,
interactive=False,
buttons=[
"copy",
],
)
elapsed_timer.tick(
fn=update_timer,
inputs=[
start_time_state,
running_state,
],
outputs=elapsed_output,
queue=False,
show_progress="hidden",
)
generation_event = (
generate_button.click(
fn=start_run,
inputs=None,
outputs=[
start_time_state,
running_state,
elapsed_output,
status_output,
script_output,
generate_button,
],
queue=False,
)
)
generation_event = (
generation_event.then(
fn=generate_script,
inputs=[
title_input,
style_file_input,
model_input,
recency_input,
news_balance_input,
hook_input,
video_format_input,
],
outputs=[
status_output,
script_output,
],
concurrency_limit=1,
show_progress="hidden",
)
)
generation_event.then(
fn=finish_run,
inputs=start_time_state,
outputs=[
running_state,
elapsed_output,
generate_button,
],
queue=False,
show_progress="hidden",
)
clear_button.click(
fn=clear_interface,
inputs=None,
outputs=[
title_input,
style_file_input,
recency_input,
news_balance_input,
hook_input,
video_format_input,
status_output,
script_output,
start_time_state,
running_state,
elapsed_output,
generate_button,
],
queue=False,
show_progress="hidden",
)
demo.queue(
default_concurrency_limit=1,
max_size=10,
)
if __name__ == "__main__":
demo.launch()
import os
import re
import time
from datetime import date, datetime, timedelta
from pathlib import Path
from typing import Generator, Optional
import anthropic
import gradio as gr
from anthropic import Anthropic
from docx import Document
# =========================================================
# SETTINGS
# =========================================================
MIN_WORDS = 2000
MAX_WORDS = 2400
TARGET_WORDS = 2300
CHANNEL_NAME = "The Saster"
API_TIMEOUT_SECONDS = 420
MAX_WEB_SEARCHES = 10
MAX_STYLE_CHARACTERS = 50_000
STREAM_UPDATE_INTERVAL = 0.8
RESEARCH_MAX_TOKENS = 12_000
PLAN_MAX_TOKENS = 12_000
CHUNK_MAX_TOKENS = 11_000
REVISION_MAX_TOKENS = 12_000
MAX_HISTORICAL_CONTEXT_PERCENT = 10
MAX_OLD_YEAR_MENTIONS = 2
MODEL_OPTIONS = [
"claude-sonnet-5",
"claude-opus-5",
]
RECENCY_OPTIONS = {
"Last 30 days": 30,
"Last 90 days": 90,
"Last 180 days": 180,
"Last 365 days": 365,
}
DEFAULT_RECENCY_OPTION = "Last 90 days"
NEWS_BALANCE_OPTIONS = {
"Historical disaster β no current-news requirement": {
"recent_anchor_min": 0,
"recent_anchor_max": 0,
"recent_narration_share": "0 percent required",
"date_mentions_min": 4,
"date_mentions_max": 18,
"current_source_target": "0",
"description": (
"Reconstruct the disaster itself using the strongest available historical evidence, "
"official reports, archives, scientific records, eyewitness material, and later "
"investigations. Do not search for or force a current-news angle. Present-day context "
"may appear only when it genuinely helps the ending."
),
},
"Historical + optional present-day context": {
"recent_anchor_min": 0,
"recent_anchor_max": 1,
"recent_narration_share": "roughly 0β10 percent",
"date_mentions_min": 4,
"date_mentions_max": 18,
"current_source_target": "0β3",
"description": (
"Tell the historical disaster as a complete reconstruction first. Optionally add a "
"brief present-day update about rebuilding, changed defenses, surviving risks, or new "
"research when it materially improves the ending."
),
},
"Balanced β documentary + recent updates": {
"recent_anchor_min": 1,
"recent_anchor_max": 3,
"recent_narration_share": "roughly 15β35 percent",
"date_mentions_min": 4,
"date_mentions_max": 16,
"current_source_target": "3β6",
"description": (
"Tell the disaster as a complete narrative first, then weave in a small number of "
"meaningful current developments, rebuilt systems, new findings, anniversaries, "
"or present-day risks."
),
},
"News-first β more current detail": {
"recent_anchor_min": 3,
"recent_anchor_max": 5,
"recent_narration_share": "roughly 35β55 percent",
"date_mentions_min": 5,
"date_mentions_max": 18,
"current_source_target": "5β9",
"description": (
"Use a current development as the reason to revisit the disaster, while still "
"telling the historical event as a coherent human and technical story."