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 = 2700
MAX_WORDS = 3000
TARGET_WORDS = 2900
CHANNEL_NAME = "Discover Tube"
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 = {
"Documentary-first — fewer dates": {
"recent_anchor_min": 1,
"recent_anchor_max": 3,
"recent_narration_share": "roughly 20–35 percent",
"date_mentions_min": 1,
"date_mentions_max": 4,
"current_source_target": "3–6",
"description": (
"Use recent events as selective anchors, but let most of the script focus "
"on topography, mechanisms, regional consequences, scientific explanation, "
"and broader documentary context."
),
},
"Balanced — documentary + recent updates": {
"recent_anchor_min": 2,
"recent_anchor_max": 4,
"recent_narration_share": "roughly 35–50 percent",
"date_mentions_min": 2,
"date_mentions_max": 6,
"current_source_target": "5–8",
"description": (
"Blend a few strong current developments with broader documentary science. "
"Recent news should move the story forward without making every section "
"sound date-driven."
),
},
"News-first — more current detail": {
"recent_anchor_min": 4,
"recent_anchor_max": 6,
"recent_narration_share": "roughly 55–75 percent",
"date_mentions_min": 4,
"date_mentions_max": 9,
"current_source_target": "7–12",
"description": (
"Keep a strong current-news layer across most of the script while still "
"using documentary explanation and scientific context."
),
},
}
DEFAULT_NEWS_BALANCE_OPTION = "Balanced — documentary + recent updates"
HOOK_OPTIONS = [
"Auto — choose the strongest opening",
"Topography / geography opening",
"Date / current event opening",
"News clip continuation",
"Hard fact / scale opening",
]
DEFAULT_HOOK_OPTION = "Auto — choose the strongest 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 the direct introduction of 120–160 words and the first "
"two titled sections. Mention Discover Tube exactly once in the "
"introduction. Follow the selected hook strategy. After the introduction, "
"move into the strongest material for the story: this may be a recent "
"development, topography, a mechanism, a verified hard fact, or a combination. "
"Make the first two sections deliberately unequal in length."
),
},
{
"number": 2,
"minimum": 1000,
"maximum": 1100,
"target": 1050,
"purpose": (
"Write the next three titled sections. Deliver the densest scientific "
"explanations, analysis, named research or monitoring when useful, practical "
"consequences, and the planned amount of current-news material. Place the "
"40-percent Discover Tube subscribe sentence inside this chunk. Make all "
"three sections clearly unequal in length. Do not recap part 1."
),
},
{
"number": 3,
"minimum": 1000,
"maximum": 1100,
"target": 1050,
"purpose": (
"Write the final two titled sections and an ending of 100–160 words. "
"Resolve the central documentary question, explain the most important "
"implications, and include what happens next or what is being monitored "
"when the evidence supports it. Place one Discover Tube audience question "
"around 75 percent of the full video. In the final 100 words, mention "
"Discover Tube once more, include a brief subscribe request, and ask one "
"concrete question for viewers to answer in the comments. 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 the direct introduction of 120–160 words and numbered "
f"subtopics {start} through {end}. Follow the selected hook strategy. "
f"Mention Discover Tube exactly once 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. Place the "
f"40-percent Discover Tube subscribe sentence inside this chunk. "
f"Do not recap part 1."
)
else:
spec["purpose"] = (
f"Write numbered subtopics {start} through {end} and then a connected "
f"ending of 100–160 words. Keep every transition logically motivated. "
f"Place one Discover Tube audience question around 75 percent of the "
f"full video. In the final 100 words, mention Discover Tube once more, "
f"include a brief subscribe request, and ask one concrete comment question."
)
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 Discover Tube 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 == "Topography / geography opening":
return """
HOOK STRATEGY — TOPOGRAPHY / GEOGRAPHY
- Open by placing the viewer physically inside the landscape: terrain, coastline, basin,
mountain chain, fault zone, lake system, river corridor, or other defining geography.
- The first one or two sentences should be visual, concrete, and spatial rather than date-led.
- Do not put an exact calendar date in the first two sentences.
- By sentence three or four, connect that geography to the central danger, change, mystery,
or scientific question.
- Do not sound like a travel documentary; the geography must immediately serve the story.
""".strip()
if hook_option == "Date / current event opening":
return """
HOOK STRATEGY — DATE / CURRENT EVENT
- Start with one verified recent event, measurement, warning, decision, or discovery.
- Use an exact date in the opening sentence only when the evidence pack supports it and the
date genuinely makes the event more immediate.
- Do not continue stacking dates after the opening. Move quickly from the event into the
larger documentary question and physical mechanism.
""".strip()
if hook_option == "News clip continuation":
return """
HOOK STRATEGY — NEWS CLIP CONTINUATION
- Write the first line as a seamless continuation from a short news report that the viewer
has just watched immediately before the narration begins.
- Do not repeat a headline or re-summarize the whole report. Widen the frame immediately.
- You may use a bridge such as “What you just saw is only the visible part of a much larger
story,” but vary the wording naturally.
- Never invent details about the unseen clip. Connect only to verified material in the
evidence pack.
- Within the first three or four sentences, reveal the broader geographic or scientific
significance behind that news event.
""".strip()
if hook_option == "Hard fact / scale opening":
return """
HOOK STRATEGY — HARD FACT / SCALE
- Open with one surprising, verified measurement, physical fact, scale, consequence, or
contrast that immediately reframes the topic.
- The first line should stand on its own without hype or an unsupported superlative.
- Explain why the fact matters within the next two or three sentences, then move into the
central story.
- Do not force a date into the hook unless it is essential to the fact.
""".strip()
return """
HOOK STRATEGY — AUTO
- Choose the strongest opening for this specific topic from these three self-contained modes:
topography / geography, date / current event, or hard fact / scale.
- Do NOT choose news clip continuation automatically, because that mode assumes the editor
will place a real news clip immediately before the narration.
- Do not automatically choose a news-date opening. Prefer the mode that creates the clearest
immediate mental picture and strongest central tension from the evidence.
- State the chosen hook mode in the INTERNAL plan, then 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"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
)
branded_questions = count_channel_questions(
text
)
subscribe_mentions = count_subscribe_mentions(
text
)
old_years = find_old_year_mentions(
text,
cutoff_date,
)
current_year_mentions = len(
re.findall(
rf"\b{current_date.year}\b",
text or "",
)
)
if channel_mentions != 4:
warnings.append(
f"{CHANNEL_NAME} appears "
f"{channel_mentions}x instead of 4x"
)
if branded_questions != 2:
warnings.append(
f"questions containing {CHANNEL_NAME}: "
f"{branded_questions} instead of 2"
)
if subscribe_mentions != 2:
warnings.append(
f"subscribe appears "
f"{subscribe_mentions}x instead of 2x"
)
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 "
f"1–{expected} in continuous order "
f"({len(numbers)} matching headings found)"
)
if len(old_years) > MAX_OLD_YEAR_MENTIONS:
unique_old_years = sorted(
set(old_years)
)
warnings.append(
"too many older calendar years mentioned: "
+ ", ".join(
str(year)
for year in unique_old_years[:8]
)
)
if (
news_balance_option
== "News-first — more current detail"
and current_year_mentions == 0
):
warnings.append(
f"the current year "
f"{current_date.year} is not mentioned"
)
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(
1,
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 a high-retention science and geography documentary with a selective current-news
layer. The narration must feel human-written, purposeful, conversational, and factual.
Preserve the existing direct Discover Tube writing style; change the structure and balance of
material when requested, not the voice.
{structure_requirements}
NEWS BALANCE — {news_balance_option}
- {balance['description']}
- Use recent news as the true narrative anchor in approximately
{recent_anchor_min}–{recent_anchor_max} of the {topic_count} main topics/subtopics.
- Across the full narration, recent-event material should occupy
{balance['recent_narration_share']} of the script, not the entire script.
- Aim for only {balance['date_mentions_min']}–{balance['date_mentions_max']} explicit calendar-
date references in the spoken script. This is a narration target, not a research limit.
- Do not mention a publication date merely to prove that a source is recent.
- Dates belong in narration only when chronology, escalation, timing, or a specific event
genuinely depends on them.
- It is fine for several paragraphs or complete documentary topics to contain no dates.
RECENT NEWS WINDOW
- A claim described as recent, current, new, just announced, newly measured, newly warned,
or newly discovered must be supported by a source published between
{cutoff_date.isoformat()} and {current_date.isoformat()}.
- Never make an old event sound new because a recent article mentioned it.
- Publication date and event date are different; keep them distinct internally.
- Older authoritative research or official background may be used for durable scientific,
geographic, historical, or engineering context. Never label that material as recent.
- Historical context may use no more than {MAX_HISTORICAL_CONTEXT_PERCENT} percent of the
complete script and should avoid unnecessary calendar-year lists.
- Do not mention more than {MAX_OLD_YEAR_MENTIONS} calendar years from before
{cutoff_date.year} in the complete script unless the title absolutely requires a historical
chronology.
DOCUMENTARY DEPTH
- Build one coherent documentary even when the selected format contains many numbered items.
- The non-news portions should add real documentary value: topography, physical geography,
mechanisms, geology, hydrology, infrastructure, ecological consequences, regional scale,
scientific uncertainty, monitoring methods, or what the evidence means for people.
- Do not use generic textbook filler. Every paragraph or numbered item must add a specific fact,
mechanism, example, consequence, measurement, research result, or documented uncertainty.
- Use named locations, agencies, datasets, projects, researchers, and measurements when they
improve clarity, but do not turn the script into a list of source metadata.
- Explain why important facts matter and how the mechanism works.
- Preserve labels such as confirmed, preliminary, estimated, disputed, or unverified.
- Fully paraphrase the evidence pack and the style sample.
EDITOR-FRIENDLY TOPIC SELECTION
- Prefer story angles that an editor can realistically illustrate with readily discoverable
visual material on YouTube or official/public websites.
- Strong visual support includes: current or archival news footage, official agency video,
press briefings, fieldwork footage, interviews, satellite imagery, maps, monitoring dashboards,
public-domain imagery, animations, location footage, infrastructure footage, or clearly
searchable geographic visuals.
- Do not make a visually obscure, text-only, or highly technical detail into a standalone main
topic when there is little realistic footage or imagery available for it.
- If an important technical point has weak visual support, fold it into a better-supported topic
instead of giving it its own long section.
- Favor specific named places, visible physical features, real monitoring projects, documented
fieldwork, current incidents, and institutions with public visual material.
- The script itself must still contain narration only. Do not mention B-roll, YouTube search,
footage availability, or editing instructions to the viewer.
LINE-TO-LINE CONTINUITY
- Every paragraph should follow one clear micro-story or explanatory thread.
- Once a sentence introduces a person, place, event, measurement, mechanism, or claim, the next
sentence must normally develop, explain, qualify, or resolve that same thread before changing
direction.
- Do not start a story in one sentence and abruptly switch to a different subject, cause,
location, time period, or interpretation in the next sentence.
- When the direction genuinely needs to change, use a clear bridge that explains WHY the new
point follows from the previous one.
- Keep pronouns and references unambiguous. A new sentence should not make “it,” “they,” “this,”
or “that” suddenly refer to a different subject.
- Do not reverse or materially change the meaning of the previous sentence unless the contrast
is intentional, explicitly signposted, and supported by the evidence.
- Keep the first 2–4 sentences after a new topic or heading on the same immediate story before
widening into background or analysis.
- Paragraph endings should set up the next paragraph or section; paragraph openings should feel
like a continuation, consequence, explanation, or deliberate contrast rather than a reset.
INTRODUCTION — 120–160 WORDS
- Follow the selected hook strategy below.
- Mention “{CHANNEL_NAME}” exactly once in one short, natural sentence that is woven into the
story instead of sounding like a company mission statement.
- That sentence must smoothly communicate BOTH ideas: we make documentary-style videos that
dig deeper into major natural, geographic, and scientific stories, and we keep viewers
updated when important new developments change or advance those stories.
- Prefer conversational constructions such as: “Stories like this are what we dig into on
Discover Tube, where our documentaries go beyond the headline and keep you updated as new
developments unfold.” Do NOT copy this example mechanically; vary it naturally to fit the
topic and the sentence before it.
- Avoid stiff phrasing such as “Discover Tube makes documentary films...” or language that
sounds like an About Us page.
- This Discover Tube sentence is not a subscription request and not a question.
- Do not overload the intro with dates. One exact date is enough when the selected hook truly
needs it; otherwise use none.
- The FINAL sentence of the intro must land strongly in one of two ways:
(A) a specific central question the documentary will answer, OR
(B) a verified hard fact or consequence that raises the stakes.
- Choose A or B based on what is stronger for the topic. Do not default to the same ending
style every time.
{hook_requirements}
CENTRAL STORY AND RETENTION
- Every main topic or numbered subtopic must answer part of the central documentary question
and give the viewer a reason to continue.
- In standard documentary mode, end sections 1 through 6 with content-based open loops.
- In list-documentary mode, use open loops at natural intervals and especially at chunk
boundaries; do not make all 10/20/30 items end with the same rhetorical tease.
- Vary transitions through measurements, unresolved results, locations, consequences,
scientific limitations, official decisions, physical mechanisms, or competing explanations.
- Do not end every topic with a rhetorical question.
- Pay off earlier open loops later in the script so the story feels intentional.
- Put the strongest verified material in the first third, whether it is current news,
topography, a hard measurement, or an important scientific mechanism.
- Keep retention high through information, escalation, contrast, and consequence, not empty
mystery language.
HUMAN WRITING
- Use mostly short and medium-length sentences.
- Keep most paragraphs between one and four sentences.
- Use natural sentence variation and active language.
- Avoid sounding like a report, literature review, AI summary, or generic listicle.
- Introduce researchers through what they did, measured, found, announced, or questioned.
- Use concrete nouns instead of vague references when the evidence gives a name.
- Do not overuse em dashes, three-part dramatic lists, fragments, or rhetorical questions.
- Avoid formulaic phrases such as “let that sink in,” “here is where things get interesting,”
“the truth is,” “scientists are watching,” “more questions than answers,” or “only time
will tell.”
COMPARISONS
- Use exactly three factual comparisons in the complete script.
- Each comparison must clarify scale, speed, depth, distance, volume, time, or impact.
- Spread the comparisons across different parts of the script.
- Check all units and conversions mathematically.
- Do not use additional decorative comparisons beyond those three.
DISCOVER TUBE AND CTA PLACEMENT
- Use the exact phrase “{CHANNEL_NAME}” exactly four times in the complete script.
- Exactly two questions in the complete script may contain “{CHANNEL_NAME}”.
- Placement 1: once in the introduction, inside the natural one-sentence channel description.
This is not a question and contains no subscribe or comment request.
- Placement 2: around 40 percent of the video, as one brief subscribe sentence.
- Placement 3: around 75 percent of the video, inside one topic-specific audience question.
Do not ask for a subscription there.
- Placement 4: within the final 100 words. Include a brief subscribe request and ask one
concrete comment question. The question itself must contain “{CHANNEL_NAME}”.
- Do not mention “{CHANNEL_NAME}” anywhere else.
- Do not use the word subscribe outside placements 2 and 4.
""".strip()
# =========================================================
# STYLE SAMPLE
# =========================================================
def load_style_file(
filepath: Optional[str],
) -> str:
default_style = """
Write direct, information-dense spoken English for a high-retention YouTube
documentary with selective current-news elements. Use short and medium-length
sentences, brief paragraphs, concrete details, strong geographic or scientific
explanation, and connected transitions. Sound like a skilled human writer, not
an academic summary or an AI narrator. Build curiosity through evidence, scale,
mechanisms, consequences, and well-placed recent developments.
""".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 documentary of
approximately {TARGET_WORDS} words. Do not write the script.
SELECTED NEWS BALANCE
{news_balance_option}
{balance['description']}
The final script should use recent news as a genuine anchor in approximately
{research_anchor_min}–{research_anchor_max} of {topic_count} main topics/subtopics,
not in every topic.
Recent-event narration should occupy
{balance['recent_narration_share']} of the finished script.
The rest may use durable, authoritative documentary context.
CURRENT NEWS WINDOW
- Treat {cutoff_date.isoformat()} through {current_date.isoformat()} as the ONLY allowed
publication window for anything described as recent, new, current, newly measured,
newly announced, newly warned, or newly discovered.
- Current-news anchor sources must be dated and must contain genuinely new information.
- Distinguish source publication date from event or research date.
- A recent article that merely repeats an old fact does not make that old fact current news.
- Do not describe an old event as recent because it was republished or newly summarized.
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.
RECENCY DECISION
Return exactly one of these near the beginning:
RECENCY VERDICT: SUFFICIENT
RECENCY VERDICT: INSUFFICIENT
Return SUFFICIENT when there is enough reliable current material to support the selected news
balance plus enough authoritative documentary evidence to build {topic_count} connected
main topics/subtopics.
A larger list format does NOT require a separate news story for every item.
For lighter news modes, a smaller number of strong recent anchors can support several
documentary subtopics.
If the verdict is INSUFFICIENT:
- Explain briefly why the selected current-news layer cannot be supported.
- Provide three alternative title angles that preserve the same broad topic but are better
supported by the available current evidence.
- Do not fill the evidence pack with 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. RECENCY VERDICT.
2. TITLE VERDICT.
3. NEWS WINDOW:
{cutoff_date.isoformat()} to {current_date.isoformat()}.
4. THE CENTRAL DOCUMENTARY STORY in 120–180 words, showing how the current-news layer fits
into the larger geographic or scientific story.
5. 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(35, topic_count * 2)} 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 documentary researcher with strong current-news judgment. "
"Separate genuinely current developments from durable background. Build enough "
"topographic, scientific, human, and recent evidence for a compelling documentary "
"without forcing every section to be news-driven. Also evaluate whether proposed "
"main topics are realistically editable with discoverable YouTube or official visual "
"material, and map natural continuity between topics before they reach the planner."
),
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 current material for the selected news balance. "
"Choose a wider news window, a lighter news balance, or a better-supported title."
)
if recency_verdict != "SUFFICIENT":
raise RuntimeError(
"Claude could not confirm that there is enough reliable material. Try a broader "
"news window, a lighter news balance, or a more specific title."
)
if research_words < 800:
raise RuntimeError(
"Claude returned too little usable research. Make the title more specific or "
"choose a broader news window."
)
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}"
{research}
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 direct introduction of 120–160 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 100–160 words that resolves the story and explains what
matters next.
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.
- Reserve exactly one short bridge sentence for Discover Tube.
- It must feel conversational and connected to the story, not like a channel description
pasted into the intro.
- It should naturally communicate that Discover Tube goes deeper through documentary-style
videos and keeps viewers updated as important new developments unfold.
- 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.
DISCOVER TUBE PLACEMENT PLAN
1. Introduction:
one smooth non-question mention of “{CHANNEL_NAME}” inside the natural bridge sentence.
2. Around 40 percent:
one brief non-question subscribe sentence containing “{CHANNEL_NAME}”.
3. Around 75 percent:
one topic-specific audience question containing “{CHANNEL_NAME}”.
4. Final 100 words:
one brief subscribe request and one concrete comment question;
the question itself must contain “{CHANNEL_NAME}”.
Exactly four total mentions of “{CHANNEL_NAME}” and exactly two questions containing it.
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 documentary editor. Build a connected, high-retention plan that "
"preserves a strong human writing style, obeys the exact requested topic count, "
"uses only the selected amount of current news, prevents repetitive list items, "
"avoids visually unworkable standalone topics, and gives every neighboring topic "
"a clear narrative bridge so sentence-to-sentence meaning never jumps abruptly."
),
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 == 1:
return f"""
DISCOVER TUBE RULES FOR THIS CHUNK
- Use the exact phrase “{CHANNEL_NAME}” exactly once in this chunk.
- Place it naturally inside the introduction, preferably within the first 100 words.
- This mention must not be a question.
- Do not use the words subscribe, comment, or comments in this chunk.
""".strip()
if chunk_number == 2:
return f"""
DISCOVER TUBE RULES FOR THIS CHUNK
- Use the exact phrase “{CHANNEL_NAME}” exactly once in this chunk.
- Place it approximately 200–350 words into this chunk, corresponding to around
40 percent of the complete video.
- Write one brief, natural subscribe sentence containing “{CHANNEL_NAME}”.
- This sentence must not be a question and must not ask for comments.
- Do not mention “{CHANNEL_NAME}” anywhere else in this chunk.
""".strip()
return f"""
DISCOVER TUBE RULES FOR THIS CHUNK
- Use the exact phrase “{CHANNEL_NAME}” exactly twice in this chunk.
- First occurrence:
approximately 220–420 words into the chunk, corresponding to around
75 percent of the complete video.
- Put it inside one topic-specific audience question.
- Do not ask for a subscription there.
- Second occurrence:
within the final 100 words.
- Include a brief subscribe request.
- Invite viewers to leave a comment.
- Ask one concrete question.
- The question itself must contain “{CHANNEL_NAME}”.
- These must be the only two occurrences of “{CHANNEL_NAME}” in this chunk.
""".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 120–160 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}"
{research}
{plan}
{style_text}
{previous_script if previous_script else "No previous script yet."}
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 cliffhangers so each section connects directly to the next.
- 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.
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}
{research}
{plan}
{previous_script if previous_script else "No previous script."}
{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 documentary editor. Meet the requested word range while "
"preserving the selected news balance, factual density, scientific analysis, "
"topographic specificity, natural spoken rhythm, open-loop storytelling, and "
"exact brand placement. Repair sentence-to-sentence continuity so a line never "
"starts one story and the next line abruptly changes direction or meaning. Keep "
"standalone topics editor-friendly and visually supportable. Do not add unnecessary "
"dates as filler."
),
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, "
"current updates, 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 documentary writer. Write dense, "
"direct, natural spoken English with strong scientific and geographic "
"depth, selective current-news material, well-paced topic sizes, connected "
"cliffhangers, and high retention. Preserve the requested news balance "
"and do not overuse dates. Maintain strict line-to-line continuity: finish "
"or develop the current micro-story before changing direction, and use an "
"explicit bridge for every real pivot. Favor standalone topics with strong "
"editorial visual support and keep obscure text-only details subordinate."
),
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"4x {CHANNEL_NAME} — "
"2 vragen met Discover Tube"
)
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(
"""
# Discover Tube Documentary Script Writer
Creates a direct, information-dense, human-sounding YouTube documentary script of
2,900–3,200 words. Control the news balance, opening hook, and video structure:
either a standard documentary or a 10/20/30-subtopic list documentary, without
changing the core voice.
"""
)
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=(
"Scientists Are Monitoring "
"a Mysterious Change "
"Beneath the Great Lakes"
),
lines=2,
)
model_input = gr.Dropdown(
choices=MODEL_OPTIONS,
value="claude-sonnet-5",
label="🧠 Claude model",
)
recency_input = gr.Dropdown(
choices=list(
RECENCY_OPTIONS.keys()
),
value=DEFAULT_RECENCY_OPTION,
label="📰 Current-news search window",
)
with gr.Row():
news_balance_input = gr.Dropdown(
choices=list(
NEWS_BALANCE_OPTIONS.keys()
),
value=DEFAULT_NEWS_BALANCE_OPTION,
label="⚖️ News balance",
info=(
"Controls how much of the spoken script "
"is driven by current events. The research "
"can still use dates internally without "
"narrating all of them."
),
)
hook_input = gr.Dropdown(
choices=HOOK_OPTIONS,
value=DEFAULT_HOOK_OPTION,
label="🎬 Opening hook",
info=(
"Choose how the intro starts. Auto selects "
"topography, a recent event, or a hard fact. "
"News clip continuation is used only when "
"you select it."
),
)
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()