Becio commited on
Commit
3bfcaf1
Β·
verified Β·
1 Parent(s): 62c6379

Update app.py

Browse files
Files changed (1) hide show
  1. app.py +1079 -340
app.py CHANGED
@@ -129,6 +129,7 @@ VIDEO_FORMAT_OPTIONS = {
129
 
130
  DEFAULT_VIDEO_FORMAT_OPTION = "Standard documentary β€” 7 sections"
131
 
 
132
  # The three minimum values add up to exactly 2,900 words.
133
  # The maximum values add up to exactly 3,200 words.
134
  CHUNK_SPECS = [
@@ -274,37 +275,59 @@ def get_chunk_specs(video_format_option: str) -> list[dict]:
274
 
275
  counts = format_config["chunk_sections"]
276
  total = format_config["section_count"]
277
- starts = [1, counts[0] + 1, counts[0] + counts[1] + 1]
278
- ends = [counts[0], counts[0] + counts[1], total]
 
 
 
 
 
 
 
 
 
 
279
 
280
  specs = []
281
- for base, count, start, end in zip(CHUNK_SPECS, counts, starts, ends):
 
 
 
 
 
 
282
  spec = dict(base)
 
283
  spec["section_count"] = count
284
  spec["section_start"] = start
285
  spec["section_end"] = end
286
 
287
  if base["number"] == 1:
288
  spec["purpose"] = (
289
- f"Write the direct introduction of 120–160 words and numbered subtopics "
290
- f"{start} through {end}. Follow the selected hook strategy. Mention "
291
- f"Discover Tube exactly once in the introduction. Keep every subtopic "
292
- f"distinct, factual, and useful rather than padding the list."
 
293
  )
 
294
  elif base["number"] == 2:
295
  spec["purpose"] = (
296
- f"Write numbered subtopics {start} through {end}. Keep the list-documentary "
297
- f"pace moving while still explaining mechanisms, geography, evidence, and "
298
- f"consequences where useful. Place the 40-percent Discover Tube subscribe "
299
- f"sentence inside this chunk. Do not recap part 1."
 
 
300
  )
 
301
  else:
302
  spec["purpose"] = (
303
- f"Write numbered subtopics {start} through {end} and then a connected ending "
304
- f"of 100–160 words. Place one Discover Tube audience question around 75 "
305
- f"percent of the full video. In the final 100 words, mention Discover Tube "
306
- f"once more, include a brief subscribe request, and ask one concrete comment "
307
- f"question."
308
  )
309
 
310
  specs.append(spec)
@@ -312,7 +335,10 @@ def get_chunk_specs(video_format_option: str) -> list[dict]:
312
  return specs
313
 
314
 
315
- def get_chunk_structure_issue(text: str, spec: dict) -> Optional[str]:
 
 
 
316
  if "section_start" not in spec:
317
  return None
318
 
@@ -323,6 +349,7 @@ def get_chunk_structure_issue(text: str, spec: dict) -> Optional[str]:
323
  text or "",
324
  )
325
  ]
 
326
  expected = list(
327
  range(
328
  int(spec["section_start"]),
@@ -333,15 +360,26 @@ def get_chunk_structure_issue(text: str, spec: dict) -> Optional[str]:
333
  if numbers == expected:
334
  return None
335
 
336
- expected_text = f"{spec['section_start']}–{spec['section_end']}"
337
- found_text = ", ".join(str(number) for number in numbers) if numbers else "none"
 
 
 
 
 
 
 
 
 
338
  return (
339
  f"Expected numbered headings {expected_text} exactly once and in order; "
340
  f"found: {found_text}."
341
  )
342
 
343
 
344
- def build_video_structure_requirements(video_format_option: str) -> str:
 
 
345
  config = resolve_video_format(video_format_option)
346
  total = config["section_count"]
347
 
@@ -377,7 +415,9 @@ VIDEO STRUCTURE β€” LIST DOCUMENTARY ({total} SUBTOPICS)
377
  """.strip()
378
 
379
 
380
- def build_hook_requirements(hook_option: str) -> str:
 
 
381
  if hook_option == "Topography / geography opening":
382
  return """
383
  HOOK STRATEGY β€” TOPOGRAPHY / GEOGRAPHY
@@ -442,14 +482,21 @@ HOOK STRATEGY β€” AUTO
442
  """.strip()
443
 
444
 
445
- def get_news_window(recency_days: int) -> tuple[date, date]:
 
 
446
  current_date = date.today()
447
- cutoff_date = current_date - timedelta(days=recency_days)
 
 
 
448
 
449
  return cutoff_date, current_date
450
 
451
 
452
- def count_channel_mentions(text: str) -> int:
 
 
453
  return len(
454
  re.findall(
455
  re.escape(CHANNEL_NAME),
@@ -459,7 +506,9 @@ def count_channel_mentions(text: str) -> int:
459
  )
460
 
461
 
462
- def count_channel_questions(text: str) -> int:
 
 
463
  questions = re.findall(
464
  r"[^?]*\?",
465
  text or "",
@@ -467,12 +516,15 @@ def count_channel_questions(text: str) -> int:
467
  )
468
 
469
  return sum(
470
- CHANNEL_NAME.lower() in question.lower()
 
471
  for question in questions
472
  )
473
 
474
 
475
- def count_subscribe_mentions(text: str) -> int:
 
 
476
  return len(
477
  re.findall(
478
  r"\bsubscribe\b",
@@ -482,14 +534,20 @@ def count_subscribe_mentions(text: str) -> int:
482
  )
483
 
484
 
485
- def extract_recency_verdict(research: str) -> str:
 
 
486
  match = re.search(
487
  r"RECENCY VERDICT\s*:\s*(SUFFICIENT|INSUFFICIENT)",
488
  research,
489
  flags=re.IGNORECASE,
490
  )
491
 
492
- return match.group(1).upper() if match else "UNKNOWN"
 
 
 
 
493
 
494
 
495
  def find_old_year_mentions(
@@ -520,9 +578,18 @@ def story_requirement_warnings(
520
  ) -> list[str]:
521
  warnings = []
522
 
523
- channel_mentions = count_channel_mentions(text)
524
- branded_questions = count_channel_questions(text)
525
- subscribe_mentions = count_subscribe_mentions(text)
 
 
 
 
 
 
 
 
 
526
  old_years = find_old_year_mentions(
527
  text,
528
  cutoff_date,
@@ -537,7 +604,8 @@ def story_requirement_warnings(
537
 
538
  if channel_mentions != 4:
539
  warnings.append(
540
- f"{CHANNEL_NAME} appears {channel_mentions}x instead of 4x"
 
541
  )
542
 
543
  if branded_questions != 2:
@@ -548,27 +616,44 @@ def story_requirement_warnings(
548
 
549
  if subscribe_mentions != 2:
550
  warnings.append(
551
- f"subscribe appears {subscribe_mentions}x instead of 2x"
 
552
  )
553
 
554
- format_config = resolve_video_format(video_format_option)
 
 
 
555
  if format_config["list_mode"]:
556
- expected = format_config["section_count"]
 
 
 
557
  numbered_headings = re.findall(
558
  r"(?m)^##\s+(\d+)\.\s+.+$",
559
  text or "",
560
  )
561
- numbers = [int(value) for value in numbered_headings]
562
- expected_numbers = list(range(1, expected + 1))
 
 
 
 
 
 
 
563
 
564
  if numbers != expected_numbers:
565
  warnings.append(
566
- f"numbered subtopics are not exactly 1–{expected} in continuous order "
 
567
  f"({len(numbers)} matching headings found)"
568
  )
569
 
570
  if len(old_years) > MAX_OLD_YEAR_MENTIONS:
571
- unique_old_years = sorted(set(old_years))
 
 
572
 
573
  warnings.append(
574
  "too many older calendar years mentioned: "
@@ -578,14 +663,14 @@ def story_requirement_warnings(
578
  )
579
  )
580
 
581
- # Only the news-first mode requires an explicit current-year mention.
582
- # The lighter modes are intentionally allowed to sound less date-driven.
583
  if (
584
- news_balance_option == "News-first β€” more current detail"
 
585
  and current_year_mentions == 0
586
  ):
587
  warnings.append(
588
- f"the current year {current_date.year} is not mentioned"
 
589
  )
590
 
591
  return warnings
@@ -603,22 +688,61 @@ def build_global_writing_requirements(
603
  hook_option: str,
604
  video_format_option: str,
605
  ) -> str:
606
- balance = resolve_news_balance(news_balance_option)
607
- hook_requirements = build_hook_requirements(hook_option)
608
- format_config = resolve_video_format(video_format_option)
609
- structure_requirements = build_video_structure_requirements(video_format_option)
610
- topic_count = format_config["section_count"]
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
611
 
612
- # Scale the number of explicit news anchors with the chosen list size without making
613
- # the narration date-heavy. Standard mode keeps the original ranges.
614
  if format_config["list_mode"]:
615
- ratio_min = balance["recent_anchor_min"] / 7
616
- ratio_max = balance["recent_anchor_max"] / 7
617
- recent_anchor_min = max(1, round(topic_count * ratio_min))
618
- recent_anchor_max = max(recent_anchor_min, round(topic_count * ratio_max))
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
619
  else:
620
- recent_anchor_min = balance["recent_anchor_min"]
621
- recent_anchor_max = balance["recent_anchor_max"]
 
 
 
 
 
622
 
623
  return f"""
624
  Write for a high-retention science and geography documentary with a selective current-news
@@ -671,6 +795,42 @@ DOCUMENTARY DEPTH
671
  - Preserve labels such as confirmed, preliminary, estimated, disputed, or unverified.
672
  - Fully paraphrase the evidence pack and the style sample.
673
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
674
  INTRODUCTION β€” 120–160 WORDS
675
 
676
  - Follow the selected hook strategy below.
@@ -748,12 +908,15 @@ DISCOVER TUBE AND CTA PLACEMENT
748
  - Do not use the word subscribe outside placements 2 and 4.
749
  """.strip()
750
 
 
751
  # =========================================================
752
  # STYLE SAMPLE
753
  # =========================================================
754
 
755
 
756
- def load_style_file(filepath: Optional[str]) -> str:
 
 
757
  default_style = """
758
  Write direct, information-dense spoken English for a high-retention YouTube
759
  documentary with selective current-news elements. Use short and medium-length
@@ -776,24 +939,37 @@ mechanisms, consequences, and well-placed recent developments.
776
  ).strip()
777
 
778
  elif path.suffix.lower() == ".docx":
779
- document = Document(str(path))
 
 
 
780
  content = []
781
 
782
  for paragraph in document.paragraphs:
783
- paragraph_text = paragraph.text.strip()
 
 
784
 
785
  if paragraph_text:
786
- content.append(paragraph_text)
 
 
787
 
788
  for table in document.tables:
789
  for row in table.rows:
790
  for cell in row.cells:
791
- cell_text = cell.text.strip()
 
 
792
 
793
  if cell_text:
794
- content.append(cell_text)
 
 
795
 
796
- style_text = "\n".join(content).strip()
 
 
797
 
798
  else:
799
  raise ValueError(
@@ -851,6 +1027,7 @@ def request_text(
851
  allow_pause_turn: bool = False,
852
  allow_partial_max_tokens: bool = False,
853
  ) -> tuple[str, object]:
 
854
  messages = [
855
  {
856
  "role": "user",
@@ -858,7 +1035,11 @@ def request_text(
858
  }
859
  ]
860
 
861
- attempts = 2 if allow_pause_turn else 1
 
 
 
 
862
 
863
  for attempt in range(attempts):
864
  request = {
@@ -877,11 +1058,16 @@ def request_text(
877
  if tools:
878
  request["tools"] = tools
879
 
880
- with client.messages.stream(**request) as stream:
881
- response = stream.get_final_message()
 
 
 
 
882
 
883
  if (
884
- response.stop_reason == "pause_turn"
 
885
  and allow_pause_turn
886
  and attempt == 0
887
  ):
@@ -901,10 +1087,14 @@ def request_text(
901
 
902
  validate_response(
903
  response,
904
- allow_partial_max_tokens=allow_partial_max_tokens,
 
 
905
  )
906
 
907
- text = extract_text(response)
 
 
908
 
909
  if not text:
910
  raise RuntimeError(
@@ -926,7 +1116,11 @@ def stream_text(
926
  user_prompt: str,
927
  max_tokens: int,
928
  effort: str,
929
- ) -> Generator[tuple[str, Optional[object]], None, None]:
 
 
 
 
930
  request = {
931
  "model": model,
932
  "system": system_prompt,
@@ -948,18 +1142,32 @@ def stream_text(
948
  collected_text = ""
949
  last_update = time.monotonic()
950
 
951
- with client.messages.stream(**request) as stream:
 
 
952
  for text_delta in stream.text_stream:
953
  collected_text += text_delta
954
  now = time.monotonic()
955
 
956
- if now - last_update >= STREAM_UPDATE_INTERVAL:
957
- yield collected_text, None
 
 
 
 
 
 
 
958
  last_update = now
959
 
960
- response = stream.get_final_message()
 
 
961
 
962
- final_text = extract_text(response) or collected_text.strip()
 
 
 
963
 
964
  if response.stop_reason == "max_tokens":
965
  log(
@@ -967,11 +1175,21 @@ def stream_text(
967
  "the existing text is being kept."
968
  )
969
 
970
- yield final_text, response
 
 
 
 
971
  return
972
 
973
- validate_response(response)
974
- yield final_text, response
 
 
 
 
 
 
975
 
976
 
977
  # =========================================================
@@ -987,22 +1205,62 @@ def research_topic(
987
  news_balance_option: str,
988
  video_format_option: str,
989
  ) -> str:
990
- cutoff_date, current_date = get_news_window(
991
- recency_days
 
 
 
992
  )
993
- balance = resolve_news_balance(news_balance_option)
994
- format_config = resolve_video_format(video_format_option)
995
- topic_count = format_config["section_count"]
996
- list_mode = format_config["list_mode"]
 
 
 
 
 
 
 
 
 
 
 
 
997
 
998
  if list_mode:
999
- ratio_min = balance["recent_anchor_min"] / 7
1000
- ratio_max = balance["recent_anchor_max"] / 7
1001
- research_anchor_min = max(1, round(topic_count * ratio_min))
1002
- research_anchor_max = max(research_anchor_min, round(topic_count * ratio_max))
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1003
  else:
1004
- research_anchor_min = balance["recent_anchor_min"]
1005
- research_anchor_max = balance["recent_anchor_max"]
 
 
 
 
 
1006
 
1007
  prompt = f"""
1008
  Today's date is {current_date.isoformat()}.
@@ -1020,15 +1278,19 @@ SELECTED NEWS BALANCE
1020
  {balance['description']}
1021
 
1022
  The final script should use recent news as a genuine anchor in approximately
1023
- {research_anchor_min}–{research_anchor_max} of {topic_count} main topics/subtopics, not in every
1024
- topic. Recent-event narration should occupy {balance['recent_narration_share']} of the
1025
- finished script. The rest may use durable, authoritative documentary context.
 
 
 
 
1026
 
1027
  CURRENT NEWS WINDOW
1028
 
1029
  - Treat {cutoff_date.isoformat()} through {current_date.isoformat()} as the ONLY allowed
1030
- publication window for anything described as recent, new, current, newly measured, newly
1031
- announced, newly warned, or newly discovered.
1032
  - Current-news anchor sources must be dated and must contain genuinely new information.
1033
  - Distinguish source publication date from event or research date.
1034
  - A recent article that merely repeats an old fact does not make that old fact current news.
@@ -1054,8 +1316,11 @@ RECENCY VERDICT: INSUFFICIENT
1054
 
1055
  Return SUFFICIENT when there is enough reliable current material to support the selected news
1056
  balance plus enough authoritative documentary evidence to build {topic_count} connected
1057
- main topics/subtopics. A larger list format does NOT require a separate news story for every
1058
- item. For lighter news modes, a smaller number of strong recent anchors can support several
 
 
 
1059
  documentary subtopics.
1060
 
1061
  If the verdict is INSUFFICIENT:
@@ -1074,8 +1339,10 @@ TITLE VERDICT: PARTLY SUPPORTED
1074
  TITLE VERDICT: UNSUPPORTED
1075
 
1076
  Continued activity is not acceleration, improved detection is not acceleration, and a new
1077
- publication about old data is not a new physical event. Do not assume scientists are afraid,
1078
- shocked, baffled, or issuing warnings unless reliable evidence explicitly supports it.
 
 
1079
 
1080
  SOURCE PRIORITY
1081
 
@@ -1087,49 +1354,110 @@ Use no more than {MAX_WEB_SEARCHES} focused searches. Prioritize:
1087
  4. Government decisions, infrastructure projects, legislation, funding, and operations.
1088
  5. Reputable news reporting for current human and regional context.
1089
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1090
  BUILD THIS EVIDENCE PACK
1091
 
1092
  1. RECENCY VERDICT.
 
1093
  2. TITLE VERDICT.
1094
- 3. NEWS WINDOW: {cutoff_date.isoformat()} to {current_date.isoformat()}.
 
 
 
1095
  4. THE CENTRAL DOCUMENTARY STORY in 120–180 words, showing how the current-news layer fits
1096
  into the larger geographic or scientific story.
 
1097
  5. CURRENT NEWS LEDGER with roughly {balance['current_source_target']} strong sources when
1098
  available. For every source include publication date, event/research date, institution,
1099
  location, the genuinely new information, and certainty level.
 
1100
  6. DOCUMENTARY BACKGROUND LEDGER with 4–10 authoritative sources for durable topography,
1101
  mechanisms, baseline science, historical context, or regional consequences. Include dates
1102
  internally, but mark them BACKGROUND and do not imply recency.
 
1103
  7. FACT BANK with enough specific, non-duplicative evidence to support all {topic_count}
1104
- main topics/subtopics (normally at least {max(35, topic_count * 2)} useful facts). Label every fact CURRENT or
1105
- BACKGROUND. Include location, source/institution, certainty, and why it matters.
1106
- 8. SUBTOPIC BANK: propose at least {topic_count + (5 if list_mode else 2)} distinct candidate
1107
- topic angles so the planner can select exactly {topic_count} without padding or duplication.
 
 
 
 
1108
  For list mode, each candidate must be meaningfully different and strong enough to support a
1109
  visible numbered item.
 
1110
  9. OPENING MATERIAL BANK with one strong evidence-based candidate for each opening mode:
 
1111
  - TOPOGRAPHY / GEOGRAPHY;
1112
  - DATE / CURRENT EVENT;
1113
  - NEWS CLIP CONTINUATION;
1114
  - HARD FACT / SCALE.
1115
- Also include two strong intro-ending candidates: one central question and one verified hard
1116
- fact/consequence.
 
 
1117
  10. RECENT DATA BLOCK containing the strongest current figures and measurements that are worth
1118
- mentioning in narration. Do NOT include dates that add no storytelling value.
1119
- 11. SCIENTIFIC EXPLANATIONS needed to understand the story: mechanism, method, uncertainty,
1120
- competing explanations, and limitations.
 
 
 
 
1121
  12. TOPOGRAPHY AND GEOGRAPHY details that can make the documentary visually specific.
 
1122
  13. HUMAN, environmental, economic, infrastructure, policy, or safety consequences.
1123
- 14. At least six candidate factual comparisons with checked units. The script will select
1124
- exactly three.
 
 
1125
  15. ESSENTIAL HISTORICAL CONTEXT, limited to what genuinely improves understanding and short
1126
  enough to stay within {MAX_HISTORICAL_CONTEXT_PERCENT} percent of the final script.
1127
- 16. CLAIMS TO AVOID.
1128
- 17. EXTRA VERIFIED FACTS that can be used to reach the word target without repetitive dates,
1129
- stale filler, or generic textbook language.
1130
 
1131
- Do not copy source sentences. Do not write dramatic narration. The evidence pack should be
1132
- rich enough to support both documentary depth and the selected amount of current news.
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1133
  """.strip()
1134
 
1135
  web_search_tool = [
@@ -1157,7 +1485,9 @@ rich enough to support both documentary depth and the selected amount of current
1157
  "You are a rigorous documentary researcher with strong current-news judgment. "
1158
  "Separate genuinely current developments from durable background. Build enough "
1159
  "topographic, scientific, human, and recent evidence for a compelling documentary "
1160
- "without forcing every section to be news-driven."
 
 
1161
  ),
1162
  user_prompt=prompt,
1163
  max_tokens=RESEARCH_MAX_TOKENS,
@@ -1167,14 +1497,18 @@ rich enough to support both documentary depth and the selected amount of current
1167
  allow_partial_max_tokens=True,
1168
  )
1169
 
1170
- research_words = count_words(research)
 
 
 
1171
  recency_verdict = extract_recency_verdict(
1172
  research
1173
  )
1174
 
1175
  if response.stop_reason == "max_tokens":
1176
  log(
1177
- "Research reached max_tokens; the completed research is being used."
 
1178
  )
1179
 
1180
  if recency_verdict == "INSUFFICIENT":
@@ -1196,7 +1530,8 @@ rich enough to support both documentary depth and the selected amount of current
1196
  )
1197
 
1198
  log(
1199
- f"Phase 1 complete: {research_words} words of research."
 
1200
  )
1201
 
1202
  return research
@@ -1219,40 +1554,85 @@ def create_script_plan(
1219
  hook_option: str,
1220
  video_format_option: str,
1221
  ) -> str:
1222
- balance = resolve_news_balance(news_balance_option)
1223
- format_config = resolve_video_format(video_format_option)
1224
- topic_count = format_config["section_count"]
1225
- list_mode = format_config["list_mode"]
1226
- chunk_counts = format_config["chunk_sections"]
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1227
 
1228
  if list_mode:
1229
- ratio_min = balance["recent_anchor_min"] / 7
1230
- ratio_max = balance["recent_anchor_max"] / 7
1231
- anchor_min = max(1, round(topic_count * ratio_min))
1232
- anchor_max = max(anchor_min, round(topic_count * ratio_max))
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1233
  structure_plan = f"""
1234
  LIST-DOCUMENTARY STRUCTURE
1235
 
1236
  - Plan exactly {topic_count} numbered subtopics.
1237
  - Chunk 1 contains subtopics 1–{chunk_counts[0]} after the introduction.
1238
  - Chunk 2 contains subtopics {chunk_counts[0] + 1}–{chunk_counts[0] + chunk_counts[1]}.
1239
- - Chunk 3 contains subtopics {chunk_counts[0] + chunk_counts[1] + 1}–{topic_count}, followed by
1240
- the 100–160 word ending.
1241
  - Every planned heading must use: ## NUMBER. Short Title
1242
  - The item type must fit the title naturally. Use β€œreasons” only if the title truly asks why;
1243
- otherwise use facts, warning signs, locations, risks, mechanisms, changes, consequences, or
1244
- another fitting category.
1245
  - Give each item an exact word budget. Keep enough variation to avoid monotony, but do not use
1246
  the standard documentary rule requiring a 150-word gap between longest and shortest items.
1247
  - Prevent duplication aggressively: each numbered item must have its own core claim and evidence.
1248
  """.strip()
 
1249
  else:
1250
- anchor_min = balance["recent_anchor_min"]
1251
- anchor_max = balance["recent_anchor_max"]
 
 
 
 
 
 
1252
  structure_plan = """
1253
  STANDARD DOCUMENTARY STRUCTURE
1254
 
1255
- - Plan exactly seven titled sections: two in chunk 1, three in chunk 2, and two in chunk 3.
 
 
 
1256
  - Give every section an exact individual word budget.
1257
  - Do not give neighboring sections similar budgets unless necessary.
1258
  - Use the largest sections for the richest scientific or geographic material.
@@ -1276,6 +1656,7 @@ SELECTED VIDEO FORMAT
1276
  The final spoken script must contain 2,900–3,200 words and exactly three writing chunks:
1277
 
1278
  CHUNK 1 β€” 900–1,000 words
 
1279
  - A direct introduction of 120–160 words.
1280
  - Follow the selected hook: {hook_option}.
1281
  - Then cover the first {chunk_counts[0]} main topics/subtopics.
@@ -1283,11 +1664,13 @@ CHUNK 1 β€” 900–1,000 words
1283
  chronology.
1284
 
1285
  CHUNK 2 β€” 1,000–1,100 words
 
1286
  - Cover the next {chunk_counts[1]} main topics/subtopics.
1287
  - Carry the densest scientific explanation, analysis, regional consequences, named research or
1288
  monitoring, and selected current developments.
1289
 
1290
  CHUNK 3 β€” 1,000–1,100 words
 
1291
  - Cover the final {chunk_counts[2]} main topics/subtopics.
1292
  - Finish with a connected ending of 100–160 words that resolves the story and explains what
1293
  matters next.
@@ -1301,27 +1684,32 @@ That produces exactly {topic_count} main topics/subtopics in the full script.
1301
  NEWS / DOCUMENTARY ALLOCATION
1302
 
1303
  - Mark every main topic/subtopic internally as either NEWS ANCHOR or DOCUMENTARY CORE.
1304
- - Use NEWS ANCHOR for approximately {anchor_min}–{anchor_max} items total. Do not force news
1305
- into every item.
1306
  - Use DOCUMENTARY CORE for topography, physical mechanisms, scientific explanation, regional
1307
  consequences, long-running systems, infrastructure, or other durable material.
1308
- - Recent-event narration across the whole script should be {balance['recent_narration_share']}.
 
1309
  - Plan only {balance['date_mentions_min']}–{balance['date_mentions_max']} explicit calendar-date
1310
- references for the spoken narration. Publication dates can remain internal in the plan.
 
1311
  - Never create a standalone history lesson merely to fill an item.
1312
- - Never create a standalone latest-update item merely to satisfy recency. Blend current
1313
- developments into the central documentary story.
1314
 
1315
  INTRO PLAN
1316
 
1317
- - State the exact hook mode that chunk 1 will use. If the selected hook is AUTO, choose the
1318
- strongest mode from the evidence pack and record the choice.
 
1319
  - Plan the first 3–4 sentences by function only, not as sample narration.
1320
- - Reserve exactly one short bridge sentence for Discover Tube. It must feel conversational and
1321
- connected to the story, not like a channel description pasted into the intro. It should
1322
- naturally communicate that Discover Tube goes deeper through documentary-style videos and
1323
- keeps viewers updated as important new developments unfold.
1324
- - Choose the intro's final sentence type: CENTRAL QUESTION or HARD FACT / CONSEQUENCE.
 
 
1325
  - Do not automatically choose a question every time.
1326
 
1327
  FOR EVERY MAIN TOPIC / SUBTOPIC PROVIDE
@@ -1333,9 +1721,20 @@ FOR EVERY MAIN TOPIC / SUBTOPIC PROVIDE
1333
  - the exact facts, measurements, people, locations, topography, and mechanisms it uses;
1334
  - the scientific explanation or analysis it contains;
1335
  - the human or practical consequence;
1336
- - if NEWS ANCHOR: the current development, publication date, and event date;
1337
- - if DOCUMENTARY CORE: the durable evidence it explains and how it connects to the story;
 
 
1338
  - whether an explicit date should actually be spoken aloud;
 
 
 
 
 
 
 
 
 
1339
  - its transition to the next item or section;
1340
  - any essential historical context, limited to one or two brief points.
1341
 
@@ -1347,28 +1746,67 @@ ALLOCATION RULES
1347
  - Select exactly three verified comparisons and assign each to a different part of the script.
1348
  - Assign named studies, projects, reports, alerts, datasets, or monitoring efforts where they
1349
  add substance. They do not all need to be recent.
1350
- - In list mode, audit the full list for overlap before finalizing the plan. If two items are
1351
- substantially similar, merge the idea and replace one with a genuinely different topic.
1352
- - Do not create a debunking video. Silently use the strongest accurate angle.
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1353
 
1354
  DISCOVER TUBE PLACEMENT PLAN
1355
 
1356
- 1. Introduction: one smooth non-question mention of β€œ{CHANNEL_NAME}” inside the natural bridge
1357
- sentence described above.
1358
- 2. Around 40 percent: one brief non-question subscribe sentence containing β€œ{CHANNEL_NAME}”.
1359
- 3. Around 75 percent: one topic-specific audience question containing β€œ{CHANNEL_NAME}”.
1360
- 4. Final 100 words: one brief subscribe request and one concrete comment question; the question
1361
- itself must contain β€œ{CHANNEL_NAME}”.
 
 
 
 
 
 
1362
 
1363
  Exactly four total mentions of β€œ{CHANNEL_NAME}” and exactly two questions containing it.
1364
 
1365
- Keep the complete plan between 1,500 and 2,700 words. Use compact bullet points.
 
1366
  Do not write sample narration and do not repeat the entire evidence pack.
1367
  This is a plan only.
1368
  """.strip()
1369
 
1370
  log(
1371
- f"Phase 2 started: three-part plan for {video_format_option}."
 
1372
  )
1373
 
1374
  plan, response = request_text(
@@ -1377,7 +1815,9 @@ This is a plan only.
1377
  system_prompt=(
1378
  "You are a senior documentary editor. Build a connected, high-retention plan that "
1379
  "preserves a strong human writing style, obeys the exact requested topic count, "
1380
- "uses only the selected amount of current news, and prevents repetitive list items."
 
 
1381
  ),
1382
  user_prompt=prompt,
1383
  max_tokens=PLAN_MAX_TOKENS,
@@ -1387,7 +1827,8 @@ This is a plan only.
1387
 
1388
  if response.stop_reason == "max_tokens":
1389
  log(
1390
- "The script plan reached max_tokens; the completed plan is being used."
 
1391
  )
1392
 
1393
  if count_words(plan) < 400:
@@ -1396,11 +1837,13 @@ This is a plan only.
1396
  )
1397
 
1398
  log(
1399
- f"Phase 2 complete: {count_words(plan)} words in the plan."
 
1400
  )
1401
 
1402
  return plan
1403
 
 
1404
  # =========================================================
1405
  # PHASE 3 β€” THREE SCRIPT CHUNKS
1406
  # =========================================================
@@ -1435,12 +1878,19 @@ DISCOVER TUBE RULES FOR THIS CHUNK
1435
  DISCOVER TUBE RULES FOR THIS CHUNK
1436
 
1437
  - Use the exact phrase β€œ{CHANNEL_NAME}” exactly twice in this chunk.
1438
- - First occurrence: approximately 220–420 words into the chunk, corresponding to
1439
- around 75 percent of the complete video. Put it inside one topic-specific audience
1440
- question. Do not ask for a subscription there.
1441
- - Second occurrence: within the final 100 words. Include a brief subscribe request,
1442
- invite viewers to leave a comment, and ask one concrete question. The question
1443
- itself must contain β€œ{CHANNEL_NAME}”.
 
 
 
 
 
 
 
1444
  - These must be the only two occurrences of β€œ{CHANNEL_NAME}” in this chunk.
1445
  """.strip()
1446
 
@@ -1456,6 +1906,7 @@ def build_chunk_prompt(
1456
  current_date: date,
1457
  global_requirements: str,
1458
  ) -> str:
 
1459
  chunk_number = spec["number"]
1460
  minimum = spec["minimum"]
1461
  maximum = spec["maximum"]
@@ -1463,10 +1914,11 @@ def build_chunk_prompt(
1463
 
1464
  if "section_start" in spec:
1465
  format_rule = (
1466
- f"This chunk must contain exactly the numbered headings ## {spec['section_start']}. "
1467
- f"through ## {spec['section_end']}. Use every number once, in order, with no "
1468
- f"extra numbered subtopic."
1469
  )
 
1470
  else:
1471
  format_rule = (
1472
  "This chunk must contain exactly the standard documentary section headings "
@@ -1480,6 +1932,7 @@ def build_chunk_prompt(
1480
  "choice recorded in the plan. After the intro, move directly into the planned "
1481
  "story material without a source-list or date dump."
1482
  )
 
1483
  else:
1484
  continuity_rule = (
1485
  "Continue naturally from the previous script. Do not write a new introduction, "
@@ -1490,6 +1943,7 @@ def build_chunk_prompt(
1490
  Write ONLY CHUNK {chunk_number} of the final spoken YouTube documentary.
1491
 
1492
  Proposed title:
 
1493
  "{title}"
1494
 
1495
  <evidence_pack>
@@ -1523,47 +1977,112 @@ HARD LENGTH REQUIREMENT
1523
  - This is a hard production requirement, not a suggestion.
1524
  - Before answering, silently count the chunk and keep adding unused verified information,
1525
  explanation, consequences, topographic detail, or analysis until it reaches at least
1526
- {minimum} words. Do not add dates merely to fill space.
 
1527
 
1528
  {global_requirements}
1529
 
1530
  NEWS / DOCUMENTARY REQUIREMENTS FOR THIS CHUNK
1531
 
1532
- - Follow the ROLE assignments in the plan: NEWS ANCHOR versus DOCUMENTARY CORE.
 
1533
  - Only NEWS ANCHOR material may be narrated as a current development.
1534
  - Any claim described as recent or current must fall inside the news window
1535
  {cutoff_date.isoformat()} through {current_date.isoformat()}.
1536
  - DOCUMENTARY CORE material may use authoritative older evidence when the plan marks it as
1537
- durable background. Never make that material sound newly discovered.
1538
- - Follow the planned spoken-date budget. Do not mention publication dates unless the audience
1539
- actually needs them.
 
1540
  - Do not turn every named study or agency update into a date sentence.
1541
- - Use exact dates sparingly; use names, places, measurements, mechanisms, and consequences more
1542
- often than chronology.
1543
 
1544
  WRITING STANDARD
1545
 
1546
  - {continuity_rule}
 
1547
  - Follow the exact topic/subtopic budgets assigned in the plan.
 
1548
  - Every paragraph must add a new fact, example, mechanism, measurement, consequence, event,
1549
  research result, analysis, topographic detail, or documented uncertainty.
 
1550
  - Write straight to the point and explain why the information matters.
 
1551
  - Use mostly short and medium-length sentences and paragraphs of one to four sentences.
 
1552
  - Translate technical language into natural spoken English.
 
1553
  - Use exact names, places, numbers, and measurements when useful.
1554
- - Explain the science deeply where the plan assigns it: methods, causal mechanisms,
1555
- uncertainty, limitations, competing explanations, and practical implications.
 
 
 
1556
  - Follow the planned open loops and cliffhangers so each section connects directly to the next.
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1557
  - Fully paraphrase the evidence and the style sample.
1558
- - Preserve uncertainty. Do not turn possible, estimated, preliminary, or disputed information
1559
- into certainty.
 
 
1560
  - Do not tell the audience that the proposed title was fact-checked or exaggerated.
1561
- - Use every heading exactly as planned for this chunk. In list mode, preserve the exact
1562
- continuous numbering.
1563
- - Use only the comparisons assigned to this chunk. The complete script must contain exactly
1564
- three factual comparisons in total.
 
 
 
1565
  - Do not include sources, URLs, citations, editor notes, camera directions, or B-roll.
1566
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1567
  {channel_rules_for_chunk(chunk_number)}
1568
 
1569
  Return only CHUNK {chunk_number} as finished spoken narration.
@@ -1584,6 +2103,7 @@ def build_chunk_revision_prompt(
1584
  global_requirements: str,
1585
  structure_issue: Optional[str] = None,
1586
  ) -> str:
 
1587
  current_words = count_words(
1588
  current_chunk
1589
  )
@@ -1592,37 +2112,46 @@ def build_chunk_revision_prompt(
1592
 
1593
  if current_words < minimum:
1594
  operations.append(
1595
- f"The chunk is {minimum - current_words} words below the minimum. Expand it with "
1596
- "unused verified facts, topography, mechanisms, scientific explanation, "
1597
- "measurements, consequences, or planned current developments assigned to this "
1598
- "part. Respect the section roles and spoken-date budget."
 
1599
  )
 
1600
  elif current_words > maximum:
1601
  operations.append(
1602
- f"The chunk is {current_words - maximum} words above the maximum. Remove "
1603
- "repetition, unnecessary chronology, source-date language, and decorative "
1604
- "phrasing while preserving important science, geography, current anchors, open "
1605
- "loops, comparisons, and CTA placement."
1606
  )
 
1607
  else:
1608
  operations.append(
1609
- "The chunk is already inside the required word range. Preserve its overall length."
 
1610
  )
1611
 
1612
  if structure_issue:
1613
  operations.append(
1614
- "Repair this exact structural problem: " + structure_issue + " Preserve every "
1615
- "correct numbered heading, restore missing headings, remove duplicates, and keep "
1616
- "the planned evidence attached to the correct item."
 
1617
  )
1618
 
1619
- operation = "\n".join(operations)
 
 
1620
 
1621
  return f"""
1622
  Rewrite the COMPLETE chunk below.
1623
 
1624
  It currently contains approximately {current_words} words.
 
1625
  It must contain between {minimum} and {maximum} words.
 
1626
  Aim for {target} words.
1627
 
1628
  {operation}
@@ -1648,25 +2177,71 @@ Aim for {target} words.
1648
  NEWS / DOCUMENTARY BALANCE CHECK
1649
 
1650
  - Preserve the NEWS ANCHOR and DOCUMENTARY CORE roles from the plan.
 
1651
  - Claims narrated as recent or current must be supported inside the window
1652
  {cutoff_date.isoformat()} through {current_date.isoformat()}.
1653
- - Durable older evidence may remain when it provides useful scientific, geographic, or
1654
- historical context and is not presented as recent.
1655
- - When expanding, prefer unused mechanisms, measurements, topography, consequences, or
1656
- verified facts over extra date references.
1657
- - When shortening, remove repetitive chronology and source-date language before removing
1658
- important science or geographic detail.
1659
-
1660
- Keep the same topic purposes, exact headings, appropriate topic pacing, scientific
1661
- explanations, analysis, planned comparisons, and content-based cliffhangers. If the chunk uses
1662
- numbered ## headings, preserve the intended number range exactly: do not skip, duplicate, merge,
1663
- restart, or add a numbered item.
1664
- Keep the narration direct, human, and information-dense. Do not add a new
1665
- introduction, sources, citations, or production notes.
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1666
 
1667
  {channel_rules_for_chunk(chunk_number)}
1668
 
1669
- Before returning, silently count the result. Return only the complete revised chunk.
 
 
 
 
 
 
 
1670
  """.strip()
1671
 
1672
 
@@ -1686,6 +2261,7 @@ def revise_chunk(
1686
  global_requirements: str,
1687
  structure_issue: Optional[str] = None,
1688
  ) -> str:
 
1689
  prompt = build_chunk_revision_prompt(
1690
  research=research,
1691
  plan=plan,
@@ -1708,7 +2284,10 @@ def revise_chunk(
1708
  "You are a strict documentary editor. Meet the requested word range while "
1709
  "preserving the selected news balance, factual density, scientific analysis, "
1710
  "topographic specificity, natural spoken rhythm, open-loop storytelling, and "
1711
- "exact brand placement. Do not add unnecessary dates as filler."
 
 
 
1712
  ),
1713
  user_prompt=prompt,
1714
  max_tokens=REVISION_MAX_TOKENS,
@@ -1734,6 +2313,7 @@ def rebalance_total(
1734
  current_date: date,
1735
  global_requirements: str,
1736
  ) -> list[str]:
 
1737
  for _ in range(2):
1738
  total_words = count_words(
1739
  joined_script(chunks)
@@ -1743,23 +2323,46 @@ def rebalance_total(
1743
  return chunks
1744
 
1745
  if total_words < MIN_WORDS:
1746
- deficit = MIN_WORDS - total_words
 
 
 
 
1747
  index = 1
1748
 
1749
  current = count_words(
1750
  chunks[index]
1751
  )
1752
 
1753
- minimum = current + deficit + 25
1754
- maximum = minimum + 70
1755
- target = minimum + 35
 
 
 
 
 
 
 
 
 
 
 
 
1756
 
1757
  else:
1758
- excess = total_words - MAX_WORDS
 
 
 
1759
 
1760
  index = max(
1761
- range(len(chunks)),
1762
- key=lambda i: count_words(chunks[i]),
 
 
 
 
1763
  )
1764
 
1765
  current = count_words(
@@ -1776,7 +2379,10 @@ def rebalance_total(
1776
  maximum - 70,
1777
  )
1778
 
1779
- target = minimum + 35
 
 
 
1780
 
1781
  previous_script = joined_script(
1782
  chunks[:index]
@@ -1818,12 +2424,19 @@ def generate_script(
1818
  current_script = ""
1819
 
1820
  if not title or not title.strip():
1821
- yield "❌ Enter a video title first.", ""
 
 
 
1822
  return
1823
 
1824
  try:
1825
  client = get_client()
1826
- clean_title = title.strip()
 
 
 
 
1827
  style_text = load_style_file(
1828
  style_file
1829
  )
@@ -1832,20 +2445,25 @@ def generate_script(
1832
  recency_option
1833
  )
1834
 
1835
- cutoff_date, current_date = get_news_window(
1836
- recency_days
 
 
1837
  )
1838
 
1839
- global_requirements = build_global_writing_requirements(
1840
- cutoff_date=cutoff_date,
1841
- current_date=current_date,
1842
- news_balance_option=news_balance_option,
1843
- hook_option=hook_option,
1844
- video_format_option=video_format_option,
 
 
1845
  )
1846
 
1847
  yield (
1848
- "πŸ”Ž Phase 1/3 β€” gathering documentary research and current updates "
 
1849
  f"from {cutoff_date.isoformat()}…",
1850
  "",
1851
  )
@@ -1860,8 +2478,8 @@ def generate_script(
1860
  )
1861
 
1862
  yield (
1863
- "🧭 Phase 2/3 β€” distributing evidence and storytelling "
1864
- "across three parts…",
1865
  "",
1866
  )
1867
 
@@ -1879,17 +2497,27 @@ def generate_script(
1879
  )
1880
 
1881
  chunks: list[str] = []
1882
- active_chunk_specs = get_chunk_specs(video_format_option)
 
 
 
 
 
1883
 
1884
  for spec in active_chunk_specs:
1885
- chunk_number = spec["number"]
1886
- previous_script = joined_script(
1887
- chunks
 
 
 
 
 
1888
  )
1889
 
1890
  yield (
1891
- f"✍️ Phase 3/3 β€” writing part {chunk_number}/3 "
1892
- f"β€” total so far "
1893
  f"{count_words(previous_script)} words…",
1894
  previous_script,
1895
  )
@@ -1909,7 +2537,10 @@ def generate_script(
1909
  chunk_text = ""
1910
  final_response = None
1911
 
1912
- for partial_text, response in stream_text(
 
 
 
1913
  client=client,
1914
  model=model,
1915
  system_prompt=(
@@ -1917,19 +2548,29 @@ def generate_script(
1917
  "direct, natural spoken English with strong scientific and geographic "
1918
  "depth, selective current-news material, well-paced topic sizes, connected "
1919
  "cliffhangers, and high retention. Preserve the requested news balance "
1920
- "and do not overuse dates."
 
 
 
1921
  ),
1922
  user_prompt=prompt,
1923
  max_tokens=CHUNK_MAX_TOKENS,
1924
  effort="medium",
1925
  ):
1926
- chunk_text = partial_text
 
 
1927
 
1928
  if response is not None:
1929
- final_response = response
 
 
1930
 
1931
- current_script = joined_script(
1932
- chunks + [partial_text]
 
 
 
1933
  )
1934
 
1935
  if response is None:
@@ -1942,7 +2583,8 @@ def generate_script(
1942
 
1943
  if not chunk_text.strip():
1944
  raise RuntimeError(
1945
- f"Claude did not write part {chunk_number}."
 
1946
  )
1947
 
1948
  chunk_words = count_words(
@@ -1950,12 +2592,17 @@ def generate_script(
1950
  )
1951
 
1952
  log(
1953
- f"Part {chunk_number} first draft: "
 
1954
  f"{chunk_words} words."
1955
  )
1956
 
1957
- # Maximum of three targeted correction rounds per chunk.
1958
- structure_issue = get_chunk_structure_issue(chunk_text, spec)
 
 
 
 
1959
 
1960
  for correction_attempt in range(3):
1961
  length_ok = (
@@ -1964,11 +2611,15 @@ def generate_script(
1964
  <= spec["maximum"]
1965
  )
1966
 
1967
- if length_ok and not structure_issue:
 
 
 
1968
  break
1969
 
1970
  issue_text = (
1971
- f" Structure check: {structure_issue}"
 
1972
  if structure_issue
1973
  else ""
1974
  )
@@ -1977,9 +2628,11 @@ def generate_script(
1977
  f"πŸ“ Part {chunk_number}/3 has "
1978
  f"{chunk_words} words; target is "
1979
  f"{spec['minimum']}–{spec['maximum']}."
1980
- f"{issue_text} Correction {correction_attempt + 1}/3…",
 
1981
  joined_script(
1982
- chunks + [chunk_text]
 
1983
  ),
1984
  )
1985
 
@@ -2003,29 +2656,40 @@ def generate_script(
2003
  chunk_words = count_words(
2004
  chunk_text
2005
  )
2006
- structure_issue = get_chunk_structure_issue(chunk_text, spec)
 
 
 
 
 
 
2007
 
2008
  log(
2009
- f"Part {chunk_number} after correction "
 
2010
  f"{correction_attempt + 1}: "
2011
  f"{chunk_words} words."
2012
  )
2013
 
2014
  if (
2015
  final_response is not None
2016
- and final_response.stop_reason == "max_tokens"
 
2017
  ):
2018
  log(
2019
  f"Part {chunk_number} reached "
2020
- "max_tokens, but the existing text is being kept."
 
2021
  )
2022
 
2023
  chunks.append(
2024
  chunk_text.strip()
2025
  )
2026
 
2027
- current_script = joined_script(
2028
- chunks
 
 
2029
  )
2030
 
2031
  yield (
@@ -2039,9 +2703,14 @@ def generate_script(
2039
  current_script
2040
  )
2041
 
2042
- if not MIN_WORDS <= total_words <= MAX_WORDS:
 
 
 
 
2043
  yield (
2044
- f"πŸ”§ Total length is {total_words} words; "
 
2045
  "running final length correction…",
2046
  current_script,
2047
  )
@@ -2057,8 +2726,10 @@ def generate_script(
2057
  global_requirements=global_requirements,
2058
  )
2059
 
2060
- current_script = joined_script(
2061
- chunks
 
 
2062
  )
2063
 
2064
  total_words = count_words(
@@ -2074,42 +2745,59 @@ def generate_script(
2074
  )
2075
 
2076
  window_text = (
2077
- f"news window {cutoff_date.isoformat()} "
2078
- f"to {current_date.isoformat()}"
 
 
2079
  )
2080
 
2081
  if (
2082
- MIN_WORDS <= total_words <= MAX_WORDS
 
 
2083
  and not warnings
2084
  ):
2085
  status = (
2086
- f"βœ… Ready β€” {total_words} words β€” "
2087
- f"{window_text} β€” 4x {CHANNEL_NAME} β€” "
 
 
2088
  "2 vragen met Discover Tube"
2089
  )
2090
 
2091
- elif MIN_WORDS <= total_words <= MAX_WORDS:
 
 
 
 
2092
  status = (
2093
- f"⚠️ Ready β€” {total_words} words β€” "
 
2094
  f"{window_text}. Check: "
2095
  + "; ".join(warnings)
2096
  )
2097
 
2098
  else:
2099
  warning_text = (
2100
- f" Also check: {'; '.join(warnings)}"
 
2101
  if warnings
2102
  else ""
2103
  )
2104
 
2105
  status = (
2106
- f"⚠️ Ready β€” {total_words} words. "
2107
- f"Target: {MIN_WORDS}–{MAX_WORDS}. "
 
 
2108
  f"{window_text}."
2109
  + warning_text
2110
  )
2111
 
2112
- yield status, current_script
 
 
 
2113
 
2114
  except anthropic.AuthenticationError:
2115
  yield (
@@ -2145,42 +2833,61 @@ def generate_script(
2145
  )
2146
 
2147
  except anthropic.BadRequestError as exc:
2148
- error_text = str(exc)
2149
- lower_error = error_text.lower()
 
 
 
 
 
2150
 
2151
- if "web search is not enabled" in lower_error:
 
 
 
2152
  message = (
2153
  "❌ Web search is not enabled for "
2154
  "your Anthropic organization."
2155
  )
2156
 
2157
- elif "credit balance" in lower_error:
 
 
 
2158
  message = (
2159
- "❌ Your Anthropic API credit balance is insufficient."
 
2160
  )
2161
 
2162
  else:
2163
  message = (
2164
- f"❌ Anthropic rejected the request "
2165
- f": {error_text}"
 
2166
  )
2167
 
2168
- yield message, current_script
 
 
 
2169
 
2170
  except anthropic.APIStatusError as exc:
2171
  yield (
2172
  f"❌ Anthropic API error "
2173
- f"{exc.status_code}: {exc.message}",
 
2174
  current_script,
2175
  )
2176
 
2177
  except Exception as exc:
2178
  log(
2179
- f"Unexpected error: {exc}"
 
2180
  )
2181
 
2182
  yield (
2183
- f"❌ Something went wrong: {exc}",
 
2184
  current_script,
2185
  )
2186
 
@@ -2209,11 +2916,15 @@ def update_timer(
2209
  start_time: float,
2210
  is_running: bool,
2211
  ):
2212
- if not is_running or not start_time:
 
 
 
2213
  return gr.skip()
2214
 
2215
  elapsed_seconds = int(
2216
- time.time() - float(start_time)
 
2217
  )
2218
 
2219
  return format_elapsed(
@@ -2221,9 +2932,14 @@ def update_timer(
2221
  )
2222
 
2223
 
2224
- def finish_run(start_time: float):
 
 
2225
  elapsed_seconds = (
2226
- int(time.time() - float(start_time))
 
 
 
2227
  if start_time
2228
  else 0
2229
  )
@@ -2265,13 +2981,19 @@ with gr.Blocks() as demo:
2265
  # Discover Tube Documentary Script Writer
2266
 
2267
  Creates a direct, information-dense, human-sounding YouTube documentary script of
2268
- 2,900–3,200 words. Control the news balance, opening hook, and video structure: either a
2269
- standard documentary or a 10/20/30-subtopic list documentary, without changing the core voice.
 
2270
  """
2271
  )
2272
 
2273
- start_time_state = gr.State(0.0)
2274
- running_state = gr.State(False)
 
 
 
 
 
2275
 
2276
  elapsed_timer = gr.Timer(
2277
  value=1.0,
@@ -2282,7 +3004,8 @@ standard documentary or a 10/20/30-subtopic list documentary, without changing t
2282
  title_input = gr.Textbox(
2283
  label="🎯 Video title",
2284
  placeholder=(
2285
- "Scientists Are Monitoring a Mysterious Change "
 
2286
  "Beneath the Great Lakes"
2287
  ),
2288
  lines=2,
@@ -2295,19 +3018,25 @@ standard documentary or a 10/20/30-subtopic list documentary, without changing t
2295
  )
2296
 
2297
  recency_input = gr.Dropdown(
2298
- choices=list(RECENCY_OPTIONS.keys()),
 
 
2299
  value=DEFAULT_RECENCY_OPTION,
2300
  label="πŸ“° Current-news search window",
2301
  )
2302
 
2303
  with gr.Row():
2304
  news_balance_input = gr.Dropdown(
2305
- choices=list(NEWS_BALANCE_OPTIONS.keys()),
 
 
2306
  value=DEFAULT_NEWS_BALANCE_OPTION,
2307
  label="βš–οΈ News balance",
2308
  info=(
2309
- "Controls how much of the spoken script is driven by current events. "
2310
- "The research can still use dates internally without narrating all of them."
 
 
2311
  ),
2312
  )
2313
 
@@ -2316,25 +3045,31 @@ standard documentary or a 10/20/30-subtopic list documentary, without changing t
2316
  value=DEFAULT_HOOK_OPTION,
2317
  label="🎬 Opening hook",
2318
  info=(
2319
- "Choose how the intro starts. Auto selects topography, a recent event, "
2320
- "or a hard fact. News clip continuation is used only when you select it."
 
 
2321
  ),
2322
  )
2323
 
2324
  video_format_input = gr.Dropdown(
2325
- choices=list(VIDEO_FORMAT_OPTIONS.keys()),
 
 
2326
  value=DEFAULT_VIDEO_FORMAT_OPTION,
2327
  label="🧩 Video format",
2328
  info=(
2329
- "Choose the normal 7-section documentary or a Reasons-Why-style list "
2330
- "documentary with exactly 10, 20, or 30 visible numbered subtopics."
 
 
2331
  ),
2332
  )
2333
 
2334
  style_file_input = gr.File(
2335
  label=(
2336
- "πŸ“„ Upload a handmade sample script for style inspiration "
2337
- "(.docx or .txt)"
2338
  ),
2339
  file_types=[
2340
  ".docx",
@@ -2385,37 +3120,41 @@ standard documentary or a 10/20/30-subtopic list documentary, without changing t
2385
  show_progress="hidden",
2386
  )
2387
 
2388
- generation_event = generate_button.click(
2389
- fn=start_run,
2390
- inputs=None,
2391
- outputs=[
2392
- start_time_state,
2393
- running_state,
2394
- elapsed_output,
2395
- status_output,
2396
- script_output,
2397
- generate_button,
2398
- ],
2399
- queue=False,
 
 
2400
  )
2401
 
2402
- generation_event = generation_event.then(
2403
- fn=generate_script,
2404
- inputs=[
2405
- title_input,
2406
- style_file_input,
2407
- model_input,
2408
- recency_input,
2409
- news_balance_input,
2410
- hook_input,
2411
- video_format_input,
2412
- ],
2413
- outputs=[
2414
- status_output,
2415
- script_output,
2416
- ],
2417
- concurrency_limit=1,
2418
- show_progress="hidden",
 
 
2419
  )
2420
 
2421
  generation_event.then(
 
129
 
130
  DEFAULT_VIDEO_FORMAT_OPTION = "Standard documentary β€” 7 sections"
131
 
132
+
133
  # The three minimum values add up to exactly 2,900 words.
134
  # The maximum values add up to exactly 3,200 words.
135
  CHUNK_SPECS = [
 
275
 
276
  counts = format_config["chunk_sections"]
277
  total = format_config["section_count"]
278
+
279
+ starts = [
280
+ 1,
281
+ counts[0] + 1,
282
+ counts[0] + counts[1] + 1,
283
+ ]
284
+
285
+ ends = [
286
+ counts[0],
287
+ counts[0] + counts[1],
288
+ total,
289
+ ]
290
 
291
  specs = []
292
+
293
+ for base, count, start, end in zip(
294
+ CHUNK_SPECS,
295
+ counts,
296
+ starts,
297
+ ends,
298
+ ):
299
  spec = dict(base)
300
+
301
  spec["section_count"] = count
302
  spec["section_start"] = start
303
  spec["section_end"] = end
304
 
305
  if base["number"] == 1:
306
  spec["purpose"] = (
307
+ f"Write the direct introduction of 120–160 words and numbered "
308
+ f"subtopics {start} through {end}. Follow the selected hook strategy. "
309
+ f"Mention Discover Tube exactly once in the introduction. Keep every "
310
+ f"subtopic distinct, factual, useful, visually editable, and naturally "
311
+ f"connected rather than padding the list."
312
  )
313
+
314
  elif base["number"] == 2:
315
  spec["purpose"] = (
316
+ f"Write numbered subtopics {start} through {end}. Keep the "
317
+ f"list-documentary pace moving while still explaining mechanisms, "
318
+ f"geography, evidence, and consequences where useful. Keep sentence-to-"
319
+ f"sentence flow coherent and use editor-friendly topics. Place the "
320
+ f"40-percent Discover Tube subscribe sentence inside this chunk. "
321
+ f"Do not recap part 1."
322
  )
323
+
324
  else:
325
  spec["purpose"] = (
326
+ f"Write numbered subtopics {start} through {end} and then a connected "
327
+ f"ending of 100–160 words. Keep every transition logically motivated. "
328
+ f"Place one Discover Tube audience question around 75 percent of the "
329
+ f"full video. In the final 100 words, mention Discover Tube once more, "
330
+ f"include a brief subscribe request, and ask one concrete comment question."
331
  )
332
 
333
  specs.append(spec)
 
335
  return specs
336
 
337
 
338
+ def get_chunk_structure_issue(
339
+ text: str,
340
+ spec: dict,
341
+ ) -> Optional[str]:
342
  if "section_start" not in spec:
343
  return None
344
 
 
349
  text or "",
350
  )
351
  ]
352
+
353
  expected = list(
354
  range(
355
  int(spec["section_start"]),
 
360
  if numbers == expected:
361
  return None
362
 
363
+ expected_text = (
364
+ f"{spec['section_start']}–"
365
+ f"{spec['section_end']}"
366
+ )
367
+
368
+ found_text = (
369
+ ", ".join(str(number) for number in numbers)
370
+ if numbers
371
+ else "none"
372
+ )
373
+
374
  return (
375
  f"Expected numbered headings {expected_text} exactly once and in order; "
376
  f"found: {found_text}."
377
  )
378
 
379
 
380
+ def build_video_structure_requirements(
381
+ video_format_option: str,
382
+ ) -> str:
383
  config = resolve_video_format(video_format_option)
384
  total = config["section_count"]
385
 
 
415
  """.strip()
416
 
417
 
418
+ def build_hook_requirements(
419
+ hook_option: str,
420
+ ) -> str:
421
  if hook_option == "Topography / geography opening":
422
  return """
423
  HOOK STRATEGY β€” TOPOGRAPHY / GEOGRAPHY
 
482
  """.strip()
483
 
484
 
485
+ def get_news_window(
486
+ recency_days: int,
487
+ ) -> tuple[date, date]:
488
  current_date = date.today()
489
+ cutoff_date = (
490
+ current_date
491
+ - timedelta(days=recency_days)
492
+ )
493
 
494
  return cutoff_date, current_date
495
 
496
 
497
+ def count_channel_mentions(
498
+ text: str,
499
+ ) -> int:
500
  return len(
501
  re.findall(
502
  re.escape(CHANNEL_NAME),
 
506
  )
507
 
508
 
509
+ def count_channel_questions(
510
+ text: str,
511
+ ) -> int:
512
  questions = re.findall(
513
  r"[^?]*\?",
514
  text or "",
 
516
  )
517
 
518
  return sum(
519
+ CHANNEL_NAME.lower()
520
+ in question.lower()
521
  for question in questions
522
  )
523
 
524
 
525
+ def count_subscribe_mentions(
526
+ text: str,
527
+ ) -> int:
528
  return len(
529
  re.findall(
530
  r"\bsubscribe\b",
 
534
  )
535
 
536
 
537
+ def extract_recency_verdict(
538
+ research: str,
539
+ ) -> str:
540
  match = re.search(
541
  r"RECENCY VERDICT\s*:\s*(SUFFICIENT|INSUFFICIENT)",
542
  research,
543
  flags=re.IGNORECASE,
544
  )
545
 
546
+ return (
547
+ match.group(1).upper()
548
+ if match
549
+ else "UNKNOWN"
550
+ )
551
 
552
 
553
  def find_old_year_mentions(
 
578
  ) -> list[str]:
579
  warnings = []
580
 
581
+ channel_mentions = count_channel_mentions(
582
+ text
583
+ )
584
+
585
+ branded_questions = count_channel_questions(
586
+ text
587
+ )
588
+
589
+ subscribe_mentions = count_subscribe_mentions(
590
+ text
591
+ )
592
+
593
  old_years = find_old_year_mentions(
594
  text,
595
  cutoff_date,
 
604
 
605
  if channel_mentions != 4:
606
  warnings.append(
607
+ f"{CHANNEL_NAME} appears "
608
+ f"{channel_mentions}x instead of 4x"
609
  )
610
 
611
  if branded_questions != 2:
 
616
 
617
  if subscribe_mentions != 2:
618
  warnings.append(
619
+ f"subscribe appears "
620
+ f"{subscribe_mentions}x instead of 2x"
621
  )
622
 
623
+ format_config = resolve_video_format(
624
+ video_format_option
625
+ )
626
+
627
  if format_config["list_mode"]:
628
+ expected = format_config[
629
+ "section_count"
630
+ ]
631
+
632
  numbered_headings = re.findall(
633
  r"(?m)^##\s+(\d+)\.\s+.+$",
634
  text or "",
635
  )
636
+
637
+ numbers = [
638
+ int(value)
639
+ for value in numbered_headings
640
+ ]
641
+
642
+ expected_numbers = list(
643
+ range(1, expected + 1)
644
+ )
645
 
646
  if numbers != expected_numbers:
647
  warnings.append(
648
+ f"numbered subtopics are not exactly "
649
+ f"1–{expected} in continuous order "
650
  f"({len(numbers)} matching headings found)"
651
  )
652
 
653
  if len(old_years) > MAX_OLD_YEAR_MENTIONS:
654
+ unique_old_years = sorted(
655
+ set(old_years)
656
+ )
657
 
658
  warnings.append(
659
  "too many older calendar years mentioned: "
 
663
  )
664
  )
665
 
 
 
666
  if (
667
+ news_balance_option
668
+ == "News-first β€” more current detail"
669
  and current_year_mentions == 0
670
  ):
671
  warnings.append(
672
+ f"the current year "
673
+ f"{current_date.year} is not mentioned"
674
  )
675
 
676
  return warnings
 
688
  hook_option: str,
689
  video_format_option: str,
690
  ) -> str:
691
+ balance = resolve_news_balance(
692
+ news_balance_option
693
+ )
694
+
695
+ hook_requirements = build_hook_requirements(
696
+ hook_option
697
+ )
698
+
699
+ format_config = resolve_video_format(
700
+ video_format_option
701
+ )
702
+
703
+ structure_requirements = (
704
+ build_video_structure_requirements(
705
+ video_format_option
706
+ )
707
+ )
708
+
709
+ topic_count = format_config[
710
+ "section_count"
711
+ ]
712
 
 
 
713
  if format_config["list_mode"]:
714
+ ratio_min = (
715
+ balance["recent_anchor_min"]
716
+ / 7
717
+ )
718
+
719
+ ratio_max = (
720
+ balance["recent_anchor_max"]
721
+ / 7
722
+ )
723
+
724
+ recent_anchor_min = max(
725
+ 1,
726
+ round(
727
+ topic_count * ratio_min
728
+ ),
729
+ )
730
+
731
+ recent_anchor_max = max(
732
+ recent_anchor_min,
733
+ round(
734
+ topic_count * ratio_max
735
+ ),
736
+ )
737
+
738
  else:
739
+ recent_anchor_min = (
740
+ balance["recent_anchor_min"]
741
+ )
742
+
743
+ recent_anchor_max = (
744
+ balance["recent_anchor_max"]
745
+ )
746
 
747
  return f"""
748
  Write for a high-retention science and geography documentary with a selective current-news
 
795
  - Preserve labels such as confirmed, preliminary, estimated, disputed, or unverified.
796
  - Fully paraphrase the evidence pack and the style sample.
797
 
798
+ EDITOR-FRIENDLY TOPIC SELECTION
799
+
800
+ - Prefer story angles that an editor can realistically illustrate with readily discoverable
801
+ visual material on YouTube or official/public websites.
802
+ - Strong visual support includes: current or archival news footage, official agency video,
803
+ press briefings, fieldwork footage, interviews, satellite imagery, maps, monitoring dashboards,
804
+ public-domain imagery, animations, location footage, infrastructure footage, or clearly
805
+ searchable geographic visuals.
806
+ - Do not make a visually obscure, text-only, or highly technical detail into a standalone main
807
+ topic when there is little realistic footage or imagery available for it.
808
+ - If an important technical point has weak visual support, fold it into a better-supported topic
809
+ instead of giving it its own long section.
810
+ - Favor specific named places, visible physical features, real monitoring projects, documented
811
+ fieldwork, current incidents, and institutions with public visual material.
812
+ - The script itself must still contain narration only. Do not mention B-roll, YouTube search,
813
+ footage availability, or editing instructions to the viewer.
814
+
815
+ LINE-TO-LINE CONTINUITY
816
+
817
+ - Every paragraph should follow one clear micro-story or explanatory thread.
818
+ - Once a sentence introduces a person, place, event, measurement, mechanism, or claim, the next
819
+ sentence must normally develop, explain, qualify, or resolve that same thread before changing
820
+ direction.
821
+ - Do not start a story in one sentence and abruptly switch to a different subject, cause,
822
+ location, time period, or interpretation in the next sentence.
823
+ - When the direction genuinely needs to change, use a clear bridge that explains WHY the new
824
+ point follows from the previous one.
825
+ - Keep pronouns and references unambiguous. A new sentence should not make β€œit,” β€œthey,” β€œthis,”
826
+ or β€œthat” suddenly refer to a different subject.
827
+ - Do not reverse or materially change the meaning of the previous sentence unless the contrast
828
+ is intentional, explicitly signposted, and supported by the evidence.
829
+ - Keep the first 2–4 sentences after a new topic or heading on the same immediate story before
830
+ widening into background or analysis.
831
+ - Paragraph endings should set up the next paragraph or section; paragraph openings should feel
832
+ like a continuation, consequence, explanation, or deliberate contrast rather than a reset.
833
+
834
  INTRODUCTION β€” 120–160 WORDS
835
 
836
  - Follow the selected hook strategy below.
 
908
  - Do not use the word subscribe outside placements 2 and 4.
909
  """.strip()
910
 
911
+
912
  # =========================================================
913
  # STYLE SAMPLE
914
  # =========================================================
915
 
916
 
917
+ def load_style_file(
918
+ filepath: Optional[str],
919
+ ) -> str:
920
  default_style = """
921
  Write direct, information-dense spoken English for a high-retention YouTube
922
  documentary with selective current-news elements. Use short and medium-length
 
939
  ).strip()
940
 
941
  elif path.suffix.lower() == ".docx":
942
+ document = Document(
943
+ str(path)
944
+ )
945
+
946
  content = []
947
 
948
  for paragraph in document.paragraphs:
949
+ paragraph_text = (
950
+ paragraph.text.strip()
951
+ )
952
 
953
  if paragraph_text:
954
+ content.append(
955
+ paragraph_text
956
+ )
957
 
958
  for table in document.tables:
959
  for row in table.rows:
960
  for cell in row.cells:
961
+ cell_text = (
962
+ cell.text.strip()
963
+ )
964
 
965
  if cell_text:
966
+ content.append(
967
+ cell_text
968
+ )
969
 
970
+ style_text = "\n".join(
971
+ content
972
+ ).strip()
973
 
974
  else:
975
  raise ValueError(
 
1027
  allow_pause_turn: bool = False,
1028
  allow_partial_max_tokens: bool = False,
1029
  ) -> tuple[str, object]:
1030
+
1031
  messages = [
1032
  {
1033
  "role": "user",
 
1035
  }
1036
  ]
1037
 
1038
+ attempts = (
1039
+ 2
1040
+ if allow_pause_turn
1041
+ else 1
1042
+ )
1043
 
1044
  for attempt in range(attempts):
1045
  request = {
 
1058
  if tools:
1059
  request["tools"] = tools
1060
 
1061
+ with client.messages.stream(
1062
+ **request
1063
+ ) as stream:
1064
+ response = (
1065
+ stream.get_final_message()
1066
+ )
1067
 
1068
  if (
1069
+ response.stop_reason
1070
+ == "pause_turn"
1071
  and allow_pause_turn
1072
  and attempt == 0
1073
  ):
 
1087
 
1088
  validate_response(
1089
  response,
1090
+ allow_partial_max_tokens=(
1091
+ allow_partial_max_tokens
1092
+ ),
1093
  )
1094
 
1095
+ text = extract_text(
1096
+ response
1097
+ )
1098
 
1099
  if not text:
1100
  raise RuntimeError(
 
1116
  user_prompt: str,
1117
  max_tokens: int,
1118
  effort: str,
1119
+ ) -> Generator[
1120
+ tuple[str, Optional[object]],
1121
+ None,
1122
+ None,
1123
+ ]:
1124
  request = {
1125
  "model": model,
1126
  "system": system_prompt,
 
1142
  collected_text = ""
1143
  last_update = time.monotonic()
1144
 
1145
+ with client.messages.stream(
1146
+ **request
1147
+ ) as stream:
1148
  for text_delta in stream.text_stream:
1149
  collected_text += text_delta
1150
  now = time.monotonic()
1151
 
1152
+ if (
1153
+ now - last_update
1154
+ >= STREAM_UPDATE_INTERVAL
1155
+ ):
1156
+ yield (
1157
+ collected_text,
1158
+ None,
1159
+ )
1160
+
1161
  last_update = now
1162
 
1163
+ response = (
1164
+ stream.get_final_message()
1165
+ )
1166
 
1167
+ final_text = (
1168
+ extract_text(response)
1169
+ or collected_text.strip()
1170
+ )
1171
 
1172
  if response.stop_reason == "max_tokens":
1173
  log(
 
1175
  "the existing text is being kept."
1176
  )
1177
 
1178
+ yield (
1179
+ final_text,
1180
+ response,
1181
+ )
1182
+
1183
  return
1184
 
1185
+ validate_response(
1186
+ response
1187
+ )
1188
+
1189
+ yield (
1190
+ final_text,
1191
+ response,
1192
+ )
1193
 
1194
 
1195
  # =========================================================
 
1205
  news_balance_option: str,
1206
  video_format_option: str,
1207
  ) -> str:
1208
+
1209
+ cutoff_date, current_date = (
1210
+ get_news_window(
1211
+ recency_days
1212
+ )
1213
  )
1214
+
1215
+ balance = resolve_news_balance(
1216
+ news_balance_option
1217
+ )
1218
+
1219
+ format_config = resolve_video_format(
1220
+ video_format_option
1221
+ )
1222
+
1223
+ topic_count = format_config[
1224
+ "section_count"
1225
+ ]
1226
+
1227
+ list_mode = format_config[
1228
+ "list_mode"
1229
+ ]
1230
 
1231
  if list_mode:
1232
+ ratio_min = (
1233
+ balance["recent_anchor_min"]
1234
+ / 7
1235
+ )
1236
+
1237
+ ratio_max = (
1238
+ balance["recent_anchor_max"]
1239
+ / 7
1240
+ )
1241
+
1242
+ research_anchor_min = max(
1243
+ 1,
1244
+ round(
1245
+ topic_count * ratio_min
1246
+ ),
1247
+ )
1248
+
1249
+ research_anchor_max = max(
1250
+ research_anchor_min,
1251
+ round(
1252
+ topic_count * ratio_max
1253
+ ),
1254
+ )
1255
+
1256
  else:
1257
+ research_anchor_min = (
1258
+ balance["recent_anchor_min"]
1259
+ )
1260
+
1261
+ research_anchor_max = (
1262
+ balance["recent_anchor_max"]
1263
+ )
1264
 
1265
  prompt = f"""
1266
  Today's date is {current_date.isoformat()}.
 
1278
  {balance['description']}
1279
 
1280
  The final script should use recent news as a genuine anchor in approximately
1281
+ {research_anchor_min}–{research_anchor_max} of {topic_count} main topics/subtopics,
1282
+ not in every topic.
1283
+
1284
+ Recent-event narration should occupy
1285
+ {balance['recent_narration_share']} of the finished script.
1286
+
1287
+ The rest may use durable, authoritative documentary context.
1288
 
1289
  CURRENT NEWS WINDOW
1290
 
1291
  - Treat {cutoff_date.isoformat()} through {current_date.isoformat()} as the ONLY allowed
1292
+ publication window for anything described as recent, new, current, newly measured,
1293
+ newly announced, newly warned, or newly discovered.
1294
  - Current-news anchor sources must be dated and must contain genuinely new information.
1295
  - Distinguish source publication date from event or research date.
1296
  - A recent article that merely repeats an old fact does not make that old fact current news.
 
1316
 
1317
  Return SUFFICIENT when there is enough reliable current material to support the selected news
1318
  balance plus enough authoritative documentary evidence to build {topic_count} connected
1319
+ main topics/subtopics.
1320
+
1321
+ A larger list format does NOT require a separate news story for every item.
1322
+
1323
+ For lighter news modes, a smaller number of strong recent anchors can support several
1324
  documentary subtopics.
1325
 
1326
  If the verdict is INSUFFICIENT:
 
1339
  TITLE VERDICT: UNSUPPORTED
1340
 
1341
  Continued activity is not acceleration, improved detection is not acceleration, and a new
1342
+ publication about old data is not a new physical event.
1343
+
1344
+ Do not assume scientists are afraid, shocked, baffled, or issuing warnings unless reliable
1345
+ evidence explicitly supports it.
1346
 
1347
  SOURCE PRIORITY
1348
 
 
1354
  4. Government decisions, infrastructure projects, legislation, funding, and operations.
1355
  5. Reputable news reporting for current human and regional context.
1356
 
1357
+ EDITORIAL VISUAL AVAILABILITY
1358
+
1359
+ - Use one or two of the available searches to check whether the strongest candidate story angles
1360
+ have realistic visual support for a YouTube editor.
1361
+ - Look for discoverable video or visual material on YouTube and/or official public websites:
1362
+ news clips, agency videos, press briefings, interviews, fieldwork, maps, satellite imagery,
1363
+ monitoring dashboards, animations, infrastructure footage, location footage, or other
1364
+ concrete visuals.
1365
+ - Do not select a weakly visual, text-only, or extremely obscure research detail as a major
1366
+ standalone topic merely because it is scientifically interesting.
1367
+ - If a scientifically important detail has poor visual support, mark it as SUPPORTING ONLY and
1368
+ attach it to a stronger visually supported topic.
1369
+ - Prefer candidate topics that can be illustrated with multiple independent visual options.
1370
+ - Do not treat visual availability as evidence that a factual claim is true. Factual verification
1371
+ and editability are separate checks.
1372
+
1373
  BUILD THIS EVIDENCE PACK
1374
 
1375
  1. RECENCY VERDICT.
1376
+
1377
  2. TITLE VERDICT.
1378
+
1379
+ 3. NEWS WINDOW:
1380
+ {cutoff_date.isoformat()} to {current_date.isoformat()}.
1381
+
1382
  4. THE CENTRAL DOCUMENTARY STORY in 120–180 words, showing how the current-news layer fits
1383
  into the larger geographic or scientific story.
1384
+
1385
  5. CURRENT NEWS LEDGER with roughly {balance['current_source_target']} strong sources when
1386
  available. For every source include publication date, event/research date, institution,
1387
  location, the genuinely new information, and certainty level.
1388
+
1389
  6. DOCUMENTARY BACKGROUND LEDGER with 4–10 authoritative sources for durable topography,
1390
  mechanisms, baseline science, historical context, or regional consequences. Include dates
1391
  internally, but mark them BACKGROUND and do not imply recency.
1392
+
1393
  7. FACT BANK with enough specific, non-duplicative evidence to support all {topic_count}
1394
+ main topics/subtopics, normally at least {max(35, topic_count * 2)} useful facts.
1395
+ Label every fact CURRENT or BACKGROUND.
1396
+ Include location, source/institution, certainty, and why it matters.
1397
+
1398
+ 8. SUBTOPIC BANK:
1399
+ propose at least {topic_count + (5 if list_mode else 2)} distinct candidate topic angles so
1400
+ the planner can select exactly {topic_count} without padding or duplication.
1401
+
1402
  For list mode, each candidate must be meaningfully different and strong enough to support a
1403
  visible numbered item.
1404
+
1405
  9. OPENING MATERIAL BANK with one strong evidence-based candidate for each opening mode:
1406
+
1407
  - TOPOGRAPHY / GEOGRAPHY;
1408
  - DATE / CURRENT EVENT;
1409
  - NEWS CLIP CONTINUATION;
1410
  - HARD FACT / SCALE.
1411
+
1412
+ Also include two strong intro-ending candidates:
1413
+ one central question and one verified hard fact/consequence.
1414
+
1415
  10. RECENT DATA BLOCK containing the strongest current figures and measurements that are worth
1416
+ mentioning in narration.
1417
+
1418
+ Do NOT include dates that add no storytelling value.
1419
+
1420
+ 11. SCIENTIFIC EXPLANATIONS needed to understand the story:
1421
+ mechanism, method, uncertainty, competing explanations, and limitations.
1422
+
1423
  12. TOPOGRAPHY AND GEOGRAPHY details that can make the documentary visually specific.
1424
+
1425
  13. HUMAN, environmental, economic, infrastructure, policy, or safety consequences.
1426
+
1427
+ 14. At least six candidate factual comparisons with checked units.
1428
+ The script will select exactly three.
1429
+
1430
  15. ESSENTIAL HISTORICAL CONTEXT, limited to what genuinely improves understanding and short
1431
  enough to stay within {MAX_HISTORICAL_CONTEXT_PERCENT} percent of the final script.
 
 
 
1432
 
1433
+ 16. EDITORIAL VISUAL SUPPORT BANK:
1434
+
1435
+ - For every strong candidate topic/subtopic, rate editability as HIGH, MEDIUM, or LOW.
1436
+ - List 2–5 realistic visual avenues such as named locations, agency footage, maps,
1437
+ satellite imagery, dashboards, interviews, fieldwork, public briefings, news clips,
1438
+ infrastructure, or other searchable visuals.
1439
+ - Mark LOW-visual topics as SUPPORTING ONLY unless they are absolutely essential.
1440
+ - Prefer HIGH or MEDIUM topics for standalone sections/subtopics.
1441
+
1442
+ 17. CONTINUITY LINKS:
1443
+
1444
+ - For every major candidate topic, state what fact or unresolved point naturally leads
1445
+ INTO it.
1446
+ - State what consequence, question, or mechanism naturally leads OUT of it.
1447
+ - Flag any pair of candidate topics that would create an abrupt narrative jump.
1448
+
1449
+ 18. CLAIMS TO AVOID.
1450
+
1451
+ 19. EXTRA VERIFIED FACTS that can be used to reach the word target without repetitive dates,
1452
+ stale filler, generic textbook language, or visually unworkable standalone topics.
1453
+
1454
+ Do not copy source sentences.
1455
+
1456
+ Do not write dramatic narration.
1457
+
1458
+ The evidence pack should be rich enough to support documentary depth, the selected amount of
1459
+ current news, smooth narrative continuity, and realistic editing with discoverable visual
1460
+ material.
1461
  """.strip()
1462
 
1463
  web_search_tool = [
 
1485
  "You are a rigorous documentary researcher with strong current-news judgment. "
1486
  "Separate genuinely current developments from durable background. Build enough "
1487
  "topographic, scientific, human, and recent evidence for a compelling documentary "
1488
+ "without forcing every section to be news-driven. Also evaluate whether proposed "
1489
+ "main topics are realistically editable with discoverable YouTube or official visual "
1490
+ "material, and map natural continuity between topics before they reach the planner."
1491
  ),
1492
  user_prompt=prompt,
1493
  max_tokens=RESEARCH_MAX_TOKENS,
 
1497
  allow_partial_max_tokens=True,
1498
  )
1499
 
1500
+ research_words = count_words(
1501
+ research
1502
+ )
1503
+
1504
  recency_verdict = extract_recency_verdict(
1505
  research
1506
  )
1507
 
1508
  if response.stop_reason == "max_tokens":
1509
  log(
1510
+ "Research reached max_tokens; "
1511
+ "the completed research is being used."
1512
  )
1513
 
1514
  if recency_verdict == "INSUFFICIENT":
 
1530
  )
1531
 
1532
  log(
1533
+ f"Phase 1 complete: "
1534
+ f"{research_words} words of research."
1535
  )
1536
 
1537
  return research
 
1554
  hook_option: str,
1555
  video_format_option: str,
1556
  ) -> str:
1557
+
1558
+ balance = resolve_news_balance(
1559
+ news_balance_option
1560
+ )
1561
+
1562
+ format_config = resolve_video_format(
1563
+ video_format_option
1564
+ )
1565
+
1566
+ topic_count = format_config[
1567
+ "section_count"
1568
+ ]
1569
+
1570
+ list_mode = format_config[
1571
+ "list_mode"
1572
+ ]
1573
+
1574
+ chunk_counts = format_config[
1575
+ "chunk_sections"
1576
+ ]
1577
 
1578
  if list_mode:
1579
+ ratio_min = (
1580
+ balance["recent_anchor_min"]
1581
+ / 7
1582
+ )
1583
+
1584
+ ratio_max = (
1585
+ balance["recent_anchor_max"]
1586
+ / 7
1587
+ )
1588
+
1589
+ anchor_min = max(
1590
+ 1,
1591
+ round(
1592
+ topic_count * ratio_min
1593
+ ),
1594
+ )
1595
+
1596
+ anchor_max = max(
1597
+ anchor_min,
1598
+ round(
1599
+ topic_count * ratio_max
1600
+ ),
1601
+ )
1602
+
1603
  structure_plan = f"""
1604
  LIST-DOCUMENTARY STRUCTURE
1605
 
1606
  - Plan exactly {topic_count} numbered subtopics.
1607
  - Chunk 1 contains subtopics 1–{chunk_counts[0]} after the introduction.
1608
  - Chunk 2 contains subtopics {chunk_counts[0] + 1}–{chunk_counts[0] + chunk_counts[1]}.
1609
+ - Chunk 3 contains subtopics {chunk_counts[0] + chunk_counts[1] + 1}–{topic_count},
1610
+ followed by the 100–160 word ending.
1611
  - Every planned heading must use: ## NUMBER. Short Title
1612
  - The item type must fit the title naturally. Use β€œreasons” only if the title truly asks why;
1613
+ otherwise use facts, warning signs, locations, risks, mechanisms, changes, consequences,
1614
+ or another fitting category.
1615
  - Give each item an exact word budget. Keep enough variation to avoid monotony, but do not use
1616
  the standard documentary rule requiring a 150-word gap between longest and shortest items.
1617
  - Prevent duplication aggressively: each numbered item must have its own core claim and evidence.
1618
  """.strip()
1619
+
1620
  else:
1621
+ anchor_min = (
1622
+ balance["recent_anchor_min"]
1623
+ )
1624
+
1625
+ anchor_max = (
1626
+ balance["recent_anchor_max"]
1627
+ )
1628
+
1629
  structure_plan = """
1630
  STANDARD DOCUMENTARY STRUCTURE
1631
 
1632
+ - Plan exactly seven titled sections:
1633
+ two in chunk 1,
1634
+ three in chunk 2,
1635
+ and two in chunk 3.
1636
  - Give every section an exact individual word budget.
1637
  - Do not give neighboring sections similar budgets unless necessary.
1638
  - Use the largest sections for the richest scientific or geographic material.
 
1656
  The final spoken script must contain 2,900–3,200 words and exactly three writing chunks:
1657
 
1658
  CHUNK 1 β€” 900–1,000 words
1659
+
1660
  - A direct introduction of 120–160 words.
1661
  - Follow the selected hook: {hook_option}.
1662
  - Then cover the first {chunk_counts[0]} main topics/subtopics.
 
1664
  chronology.
1665
 
1666
  CHUNK 2 β€” 1,000–1,100 words
1667
+
1668
  - Cover the next {chunk_counts[1]} main topics/subtopics.
1669
  - Carry the densest scientific explanation, analysis, regional consequences, named research or
1670
  monitoring, and selected current developments.
1671
 
1672
  CHUNK 3 β€” 1,000–1,100 words
1673
+
1674
  - Cover the final {chunk_counts[2]} main topics/subtopics.
1675
  - Finish with a connected ending of 100–160 words that resolves the story and explains what
1676
  matters next.
 
1684
  NEWS / DOCUMENTARY ALLOCATION
1685
 
1686
  - Mark every main topic/subtopic internally as either NEWS ANCHOR or DOCUMENTARY CORE.
1687
+ - Use NEWS ANCHOR for approximately {anchor_min}–{anchor_max} items total.
1688
+ Do not force news into every item.
1689
  - Use DOCUMENTARY CORE for topography, physical mechanisms, scientific explanation, regional
1690
  consequences, long-running systems, infrastructure, or other durable material.
1691
+ - Recent-event narration across the whole script should be
1692
+ {balance['recent_narration_share']}.
1693
  - Plan only {balance['date_mentions_min']}–{balance['date_mentions_max']} explicit calendar-date
1694
+ references for the spoken narration.
1695
+ - Publication dates can remain internal in the plan.
1696
  - Never create a standalone history lesson merely to fill an item.
1697
+ - Never create a standalone latest-update item merely to satisfy recency.
1698
+ Blend current developments into the central documentary story.
1699
 
1700
  INTRO PLAN
1701
 
1702
+ - State the exact hook mode that chunk 1 will use.
1703
+ - If the selected hook is AUTO, choose the strongest mode from the evidence pack and
1704
+ record the choice.
1705
  - Plan the first 3–4 sentences by function only, not as sample narration.
1706
+ - Reserve exactly one short bridge sentence for Discover Tube.
1707
+ - It must feel conversational and connected to the story, not like a channel description
1708
+ pasted into the intro.
1709
+ - It should naturally communicate that Discover Tube goes deeper through documentary-style
1710
+ videos and keeps viewers updated as important new developments unfold.
1711
+ - Choose the intro's final sentence type:
1712
+ CENTRAL QUESTION or HARD FACT / CONSEQUENCE.
1713
  - Do not automatically choose a question every time.
1714
 
1715
  FOR EVERY MAIN TOPIC / SUBTOPIC PROVIDE
 
1721
  - the exact facts, measurements, people, locations, topography, and mechanisms it uses;
1722
  - the scientific explanation or analysis it contains;
1723
  - the human or practical consequence;
1724
+ - if NEWS ANCHOR:
1725
+ the current development, publication date, and event date;
1726
+ - if DOCUMENTARY CORE:
1727
+ the durable evidence it explains and how it connects to the story;
1728
  - whether an explicit date should actually be spoken aloud;
1729
+ - MICRO-STORY:
1730
+ the one person/place/event/measurement/mechanism the first 2–4 sentences follow;
1731
+ - CONTINUITY IN:
1732
+ the exact fact or unresolved point from the previous topic that leads here;
1733
+ - CONTINUITY OUT:
1734
+ the exact consequence, mechanism, or unresolved point that leads onward;
1735
+ - VISUAL SUPPORT:
1736
+ HIGH or MEDIUM;
1737
+ - 2–4 INTERNAL VISUAL SEARCH ANCHORS for the editor;
1738
  - its transition to the next item or section;
1739
  - any essential historical context, limited to one or two brief points.
1740
 
 
1746
  - Select exactly three verified comparisons and assign each to a different part of the script.
1747
  - Assign named studies, projects, reports, alerts, datasets, or monitoring efforts where they
1748
  add substance. They do not all need to be recent.
1749
+ - In list mode, audit the full list for overlap before finalizing the plan.
1750
+ - If two items are substantially similar, merge the idea and replace one with a genuinely
1751
+ different topic.
1752
+ - Do not create a debunking video.
1753
+ - Silently use the strongest accurate angle.
1754
+
1755
+ EDITORIAL EDITABILITY CHECK
1756
+
1757
+ - For every planned main topic/subtopic, include VISUAL SUPPORT: HIGH or MEDIUM.
1758
+ - Do not use a LOW-visual candidate as a standalone item.
1759
+ - Fold its useful science into the nearest HIGH/MEDIUM topic.
1760
+ - For every planned topic, list 2–4 short visual search anchors for the editor:
1761
+ named place, project, agency, event, map, satellite view, fieldwork, interview,
1762
+ monitoring system, or infrastructure.
1763
+ - These are INTERNAL planning notes only and must never appear in narration.
1764
+ - Prefer topics with several realistic visual avenues rather than a single obscure paper or
1765
+ text-only finding.
1766
+ - If two candidate topics are equally strong factually, prefer the one with better editability.
1767
+
1768
+ CONTINUITY MAP
1769
+
1770
+ - Before finalizing the plan, audit every neighboring topic pair.
1771
+ - For each transition write:
1772
+
1773
+ PREVIOUS THREAD β†’ BRIDGE LOGIC β†’ NEXT THREAD.
1774
+
1775
+ - The bridge logic must explain why the next topic follows naturally from the previous one.
1776
+ - Reject or reorder any topic pair where one line would begin a story and the next line would
1777
+ need to switch subject, location, time period, cause, or meaning without explanation.
1778
+ - Within each topic, define a single MICRO-STORY for the opening 2–4 sentences.
1779
+ - The opening 2–4 sentences of a topic must stay on that micro-story before widening into
1780
+ background, science, or consequences.
1781
+ - Mark any intentional change in interpretation as EXPLICIT CONTRAST so the writer must signal
1782
+ it rather than abruptly reversing the previous sentence.
1783
 
1784
  DISCOVER TUBE PLACEMENT PLAN
1785
 
1786
+ 1. Introduction:
1787
+ one smooth non-question mention of β€œ{CHANNEL_NAME}” inside the natural bridge sentence.
1788
+
1789
+ 2. Around 40 percent:
1790
+ one brief non-question subscribe sentence containing β€œ{CHANNEL_NAME}”.
1791
+
1792
+ 3. Around 75 percent:
1793
+ one topic-specific audience question containing β€œ{CHANNEL_NAME}”.
1794
+
1795
+ 4. Final 100 words:
1796
+ one brief subscribe request and one concrete comment question;
1797
+ the question itself must contain β€œ{CHANNEL_NAME}”.
1798
 
1799
  Exactly four total mentions of β€œ{CHANNEL_NAME}” and exactly two questions containing it.
1800
 
1801
+ Keep the complete plan between 1,500 and 2,700 words.
1802
+ Use compact bullet points.
1803
  Do not write sample narration and do not repeat the entire evidence pack.
1804
  This is a plan only.
1805
  """.strip()
1806
 
1807
  log(
1808
+ f"Phase 2 started: three-part plan for "
1809
+ f"{video_format_option}."
1810
  )
1811
 
1812
  plan, response = request_text(
 
1815
  system_prompt=(
1816
  "You are a senior documentary editor. Build a connected, high-retention plan that "
1817
  "preserves a strong human writing style, obeys the exact requested topic count, "
1818
+ "uses only the selected amount of current news, prevents repetitive list items, "
1819
+ "avoids visually unworkable standalone topics, and gives every neighboring topic "
1820
+ "a clear narrative bridge so sentence-to-sentence meaning never jumps abruptly."
1821
  ),
1822
  user_prompt=prompt,
1823
  max_tokens=PLAN_MAX_TOKENS,
 
1827
 
1828
  if response.stop_reason == "max_tokens":
1829
  log(
1830
+ "The script plan reached max_tokens; "
1831
+ "the completed plan is being used."
1832
  )
1833
 
1834
  if count_words(plan) < 400:
 
1837
  )
1838
 
1839
  log(
1840
+ f"Phase 2 complete: "
1841
+ f"{count_words(plan)} words in the plan."
1842
  )
1843
 
1844
  return plan
1845
 
1846
+
1847
  # =========================================================
1848
  # PHASE 3 β€” THREE SCRIPT CHUNKS
1849
  # =========================================================
 
1878
  DISCOVER TUBE RULES FOR THIS CHUNK
1879
 
1880
  - Use the exact phrase β€œ{CHANNEL_NAME}” exactly twice in this chunk.
1881
+ - First occurrence:
1882
+ approximately 220–420 words into the chunk, corresponding to around
1883
+ 75 percent of the complete video.
1884
+ - Put it inside one topic-specific audience question.
1885
+ - Do not ask for a subscription there.
1886
+
1887
+ - Second occurrence:
1888
+ within the final 100 words.
1889
+ - Include a brief subscribe request.
1890
+ - Invite viewers to leave a comment.
1891
+ - Ask one concrete question.
1892
+ - The question itself must contain β€œ{CHANNEL_NAME}”.
1893
+
1894
  - These must be the only two occurrences of β€œ{CHANNEL_NAME}” in this chunk.
1895
  """.strip()
1896
 
 
1906
  current_date: date,
1907
  global_requirements: str,
1908
  ) -> str:
1909
+
1910
  chunk_number = spec["number"]
1911
  minimum = spec["minimum"]
1912
  maximum = spec["maximum"]
 
1914
 
1915
  if "section_start" in spec:
1916
  format_rule = (
1917
+ f"This chunk must contain exactly the numbered headings "
1918
+ f"## {spec['section_start']}. through ## {spec['section_end']}. "
1919
+ f"Use every number once, in order, with no extra numbered subtopic."
1920
  )
1921
+
1922
  else:
1923
  format_rule = (
1924
  "This chunk must contain exactly the standard documentary section headings "
 
1932
  "choice recorded in the plan. After the intro, move directly into the planned "
1933
  "story material without a source-list or date dump."
1934
  )
1935
+
1936
  else:
1937
  continuity_rule = (
1938
  "Continue naturally from the previous script. Do not write a new introduction, "
 
1943
  Write ONLY CHUNK {chunk_number} of the final spoken YouTube documentary.
1944
 
1945
  Proposed title:
1946
+
1947
  "{title}"
1948
 
1949
  <evidence_pack>
 
1977
  - This is a hard production requirement, not a suggestion.
1978
  - Before answering, silently count the chunk and keep adding unused verified information,
1979
  explanation, consequences, topographic detail, or analysis until it reaches at least
1980
+ {minimum} words.
1981
+ - Do not add dates merely to fill space.
1982
 
1983
  {global_requirements}
1984
 
1985
  NEWS / DOCUMENTARY REQUIREMENTS FOR THIS CHUNK
1986
 
1987
+ - Follow the ROLE assignments in the plan:
1988
+ NEWS ANCHOR versus DOCUMENTARY CORE.
1989
  - Only NEWS ANCHOR material may be narrated as a current development.
1990
  - Any claim described as recent or current must fall inside the news window
1991
  {cutoff_date.isoformat()} through {current_date.isoformat()}.
1992
  - DOCUMENTARY CORE material may use authoritative older evidence when the plan marks it as
1993
+ durable background.
1994
+ - Never make that material sound newly discovered.
1995
+ - Follow the planned spoken-date budget.
1996
+ - Do not mention publication dates unless the audience actually needs them.
1997
  - Do not turn every named study or agency update into a date sentence.
1998
+ - Use exact dates sparingly.
1999
+ - Use names, places, measurements, mechanisms, and consequences more often than chronology.
2000
 
2001
  WRITING STANDARD
2002
 
2003
  - {continuity_rule}
2004
+
2005
  - Follow the exact topic/subtopic budgets assigned in the plan.
2006
+
2007
  - Every paragraph must add a new fact, example, mechanism, measurement, consequence, event,
2008
  research result, analysis, topographic detail, or documented uncertainty.
2009
+
2010
  - Write straight to the point and explain why the information matters.
2011
+
2012
  - Use mostly short and medium-length sentences and paragraphs of one to four sentences.
2013
+
2014
  - Translate technical language into natural spoken English.
2015
+
2016
  - Use exact names, places, numbers, and measurements when useful.
2017
+
2018
+ - Explain the science deeply where the plan assigns it:
2019
+ methods, causal mechanisms, uncertainty, limitations, competing explanations,
2020
+ and practical implications.
2021
+
2022
  - Follow the planned open loops and cliffhangers so each section connects directly to the next.
2023
+
2024
+ - Follow the plan's MICRO-STORY, CONTINUITY IN, and CONTINUITY OUT instructions.
2025
+
2026
+ - Once a sentence introduces a person, place, event, measurement, mechanism, or claim,
2027
+ keep the next sentence on that same thread unless an explicit bridge explains the change.
2028
+
2029
+ - Never let one sentence begin a story while the next sentence changes the subject,
2030
+ location, time frame, cause, or interpretation without explaining the connection.
2031
+
2032
+ - Keep the first 2–4 sentences after each heading on the planned micro-story before widening
2033
+ into background or analysis.
2034
+
2035
+ - When changing direction inside a paragraph, use one short causal, temporal, geographic,
2036
+ or contrast bridge so the viewer understands why the new point follows.
2037
+
2038
+ - Do not let a pronoun or phrase such as β€œthis,” β€œit,” β€œthey,” or β€œthat” silently change
2039
+ referent from one sentence to the next.
2040
+
2041
+ - If the plan marks a point as EXPLICIT CONTRAST, signal the contrast clearly before changing
2042
+ or qualifying the previous meaning.
2043
+
2044
+ - Keep standalone topics limited to material marked VISUAL SUPPORT: HIGH or MEDIUM in the plan.
2045
+
2046
+ - Technical LOW-visual details should appear only as supporting explanation inside a stronger
2047
+ editable topic.
2048
+
2049
  - Fully paraphrase the evidence and the style sample.
2050
+
2051
+ - Preserve uncertainty.
2052
+ Do not turn possible, estimated, preliminary, or disputed information into certainty.
2053
+
2054
  - Do not tell the audience that the proposed title was fact-checked or exaggerated.
2055
+
2056
+ - Use every heading exactly as planned for this chunk.
2057
+ In list mode, preserve the exact continuous numbering.
2058
+
2059
+ - Use only the comparisons assigned to this chunk.
2060
+ The complete script must contain exactly three factual comparisons in total.
2061
+
2062
  - Do not include sources, URLs, citations, editor notes, camera directions, or B-roll.
2063
 
2064
+ SILENT CONTINUITY AUDIT BEFORE RETURNING
2065
+
2066
+ - Read every pair of neighboring sentences.
2067
+
2068
+ - If sentence B does not clearly continue, explain, qualify, contrast, or result from
2069
+ sentence A, rewrite the pair or add a brief bridge.
2070
+
2071
+ - Check every paragraph boundary the same way.
2072
+
2073
+ - Remove abrupt pivots that change meaning or direction without setup.
2074
+
2075
+ - Check especially for:
2076
+ sudden location changes;
2077
+ sudden timeline changes;
2078
+ sudden changes from one researcher to another;
2079
+ sudden changes from a measurement to an unrelated mechanism;
2080
+ sudden switches from confirmed fact to speculation;
2081
+ and sentences that appear to contradict the line immediately before them.
2082
+
2083
+ - Preserve the same factual content.
2084
+ Fix the flow rather than adding new material.
2085
+
2086
  {channel_rules_for_chunk(chunk_number)}
2087
 
2088
  Return only CHUNK {chunk_number} as finished spoken narration.
 
2103
  global_requirements: str,
2104
  structure_issue: Optional[str] = None,
2105
  ) -> str:
2106
+
2107
  current_words = count_words(
2108
  current_chunk
2109
  )
 
2112
 
2113
  if current_words < minimum:
2114
  operations.append(
2115
+ f"The chunk is {minimum - current_words} words below the minimum. "
2116
+ "Expand it with unused verified facts, topography, mechanisms, "
2117
+ "scientific explanation, measurements, consequences, or planned "
2118
+ "current developments assigned to this part. Respect the section "
2119
+ "roles and spoken-date budget."
2120
  )
2121
+
2122
  elif current_words > maximum:
2123
  operations.append(
2124
+ f"The chunk is {current_words - maximum} words above the maximum. "
2125
+ "Remove repetition, unnecessary chronology, source-date language, "
2126
+ "and decorative phrasing while preserving important science, geography, "
2127
+ "current anchors, open loops, comparisons, and CTA placement."
2128
  )
2129
+
2130
  else:
2131
  operations.append(
2132
+ "The chunk is already inside the required word range. "
2133
+ "Preserve its overall length."
2134
  )
2135
 
2136
  if structure_issue:
2137
  operations.append(
2138
+ "Repair this exact structural problem: "
2139
+ + structure_issue
2140
+ + " Preserve every correct numbered heading, restore missing headings, "
2141
+ "remove duplicates, and keep the planned evidence attached to the correct item."
2142
  )
2143
 
2144
+ operation = "\n".join(
2145
+ operations
2146
+ )
2147
 
2148
  return f"""
2149
  Rewrite the COMPLETE chunk below.
2150
 
2151
  It currently contains approximately {current_words} words.
2152
+
2153
  It must contain between {minimum} and {maximum} words.
2154
+
2155
  Aim for {target} words.
2156
 
2157
  {operation}
 
2177
  NEWS / DOCUMENTARY BALANCE CHECK
2178
 
2179
  - Preserve the NEWS ANCHOR and DOCUMENTARY CORE roles from the plan.
2180
+
2181
  - Claims narrated as recent or current must be supported inside the window
2182
  {cutoff_date.isoformat()} through {current_date.isoformat()}.
2183
+
2184
+ - Durable older evidence may remain when it provides useful scientific, geographic,
2185
+ or historical context and is not presented as recent.
2186
+
2187
+ - When expanding, prefer unused mechanisms, measurements, topography, consequences,
2188
+ or verified facts over extra date references.
2189
+
2190
+ - When shortening, remove repetitive chronology and source-date language before
2191
+ removing important science or geographic detail.
2192
+
2193
+ Keep the same topic purposes, exact headings, appropriate topic pacing,
2194
+ scientific explanations, analysis, planned comparisons, and content-based cliffhangers.
2195
+
2196
+ If the chunk uses numbered ## headings, preserve the intended number range exactly:
2197
+ do not skip, duplicate, merge, restart, or add a numbered item.
2198
+
2199
+ CONTINUITY REPAIR
2200
+
2201
+ - Preserve the plan's MICRO-STORY, CONTINUITY IN, and CONTINUITY OUT for each topic.
2202
+
2203
+ - Check each neighboring sentence pair.
2204
+
2205
+ - Sentence B must clearly continue, explain, qualify, contrast, or result from sentence A.
2206
+
2207
+ - Repair abrupt switches in:
2208
+ subject;
2209
+ location;
2210
+ time frame;
2211
+ causal explanation;
2212
+ scientific interpretation;
2213
+ or meaning.
2214
+
2215
+ - Keep the first 2–4 sentences under a heading on one immediate story before widening out.
2216
+
2217
+ - Add a short bridge when the narrative genuinely needs to pivot.
2218
+
2219
+ - Do not let pronouns silently change referent between sentences.
2220
+
2221
+ - Preserve intentional contrasts, but signpost them clearly.
2222
+
2223
+ - Do not promote a LOW-visual supporting detail into a standalone topic during revision.
2224
+
2225
+ - If a line begins a concrete event or story, do not abandon that event in the very next line.
2226
+ Give it enough explanation or resolution before moving on.
2227
+
2228
+ - Check paragraph boundaries as carefully as sentence boundaries.
2229
+ The first sentence of a new paragraph must clearly connect to what came immediately before it.
2230
+
2231
+ Keep the narration direct, human, and information-dense.
2232
+
2233
+ Do not add a new introduction, sources, citations, or production notes.
2234
 
2235
  {channel_rules_for_chunk(chunk_number)}
2236
 
2237
+ Before returning:
2238
+
2239
+ 1. Silently count the result.
2240
+ 2. Silently reread every neighboring sentence pair.
2241
+ 3. Fix any abrupt change of subject or meaning.
2242
+ 4. Confirm that standalone topics remain realistically editable.
2243
+
2244
+ Return only the complete revised chunk.
2245
  """.strip()
2246
 
2247
 
 
2261
  global_requirements: str,
2262
  structure_issue: Optional[str] = None,
2263
  ) -> str:
2264
+
2265
  prompt = build_chunk_revision_prompt(
2266
  research=research,
2267
  plan=plan,
 
2284
  "You are a strict documentary editor. Meet the requested word range while "
2285
  "preserving the selected news balance, factual density, scientific analysis, "
2286
  "topographic specificity, natural spoken rhythm, open-loop storytelling, and "
2287
+ "exact brand placement. Repair sentence-to-sentence continuity so a line never "
2288
+ "starts one story and the next line abruptly changes direction or meaning. Keep "
2289
+ "standalone topics editor-friendly and visually supportable. Do not add unnecessary "
2290
+ "dates as filler."
2291
  ),
2292
  user_prompt=prompt,
2293
  max_tokens=REVISION_MAX_TOKENS,
 
2313
  current_date: date,
2314
  global_requirements: str,
2315
  ) -> list[str]:
2316
+
2317
  for _ in range(2):
2318
  total_words = count_words(
2319
  joined_script(chunks)
 
2323
  return chunks
2324
 
2325
  if total_words < MIN_WORDS:
2326
+ deficit = (
2327
+ MIN_WORDS
2328
+ - total_words
2329
+ )
2330
+
2331
  index = 1
2332
 
2333
  current = count_words(
2334
  chunks[index]
2335
  )
2336
 
2337
+ minimum = (
2338
+ current
2339
+ + deficit
2340
+ + 25
2341
+ )
2342
+
2343
+ maximum = (
2344
+ minimum
2345
+ + 70
2346
+ )
2347
+
2348
+ target = (
2349
+ minimum
2350
+ + 35
2351
+ )
2352
 
2353
  else:
2354
+ excess = (
2355
+ total_words
2356
+ - MAX_WORDS
2357
+ )
2358
 
2359
  index = max(
2360
+ range(
2361
+ len(chunks)
2362
+ ),
2363
+ key=lambda i: count_words(
2364
+ chunks[i]
2365
+ ),
2366
  )
2367
 
2368
  current = count_words(
 
2379
  maximum - 70,
2380
  )
2381
 
2382
+ target = (
2383
+ minimum
2384
+ + 35
2385
+ )
2386
 
2387
  previous_script = joined_script(
2388
  chunks[:index]
 
2424
  current_script = ""
2425
 
2426
  if not title or not title.strip():
2427
+ yield (
2428
+ "❌ Enter a video title first.",
2429
+ "",
2430
+ )
2431
  return
2432
 
2433
  try:
2434
  client = get_client()
2435
+
2436
+ clean_title = (
2437
+ title.strip()
2438
+ )
2439
+
2440
  style_text = load_style_file(
2441
  style_file
2442
  )
 
2445
  recency_option
2446
  )
2447
 
2448
+ cutoff_date, current_date = (
2449
+ get_news_window(
2450
+ recency_days
2451
+ )
2452
  )
2453
 
2454
+ global_requirements = (
2455
+ build_global_writing_requirements(
2456
+ cutoff_date=cutoff_date,
2457
+ current_date=current_date,
2458
+ news_balance_option=news_balance_option,
2459
+ hook_option=hook_option,
2460
+ video_format_option=video_format_option,
2461
+ )
2462
  )
2463
 
2464
  yield (
2465
+ "πŸ”Ž Phase 1/3 β€” gathering documentary research, "
2466
+ "current updates, and editor-friendly visual topics "
2467
  f"from {cutoff_date.isoformat()}…",
2468
  "",
2469
  )
 
2478
  )
2479
 
2480
  yield (
2481
+ "🧭 Phase 2/3 β€” distributing evidence, editability, "
2482
+ "and narrative continuity across three parts…",
2483
  "",
2484
  )
2485
 
 
2497
  )
2498
 
2499
  chunks: list[str] = []
2500
+
2501
+ active_chunk_specs = (
2502
+ get_chunk_specs(
2503
+ video_format_option
2504
+ )
2505
+ )
2506
 
2507
  for spec in active_chunk_specs:
2508
+ chunk_number = spec[
2509
+ "number"
2510
+ ]
2511
+
2512
+ previous_script = (
2513
+ joined_script(
2514
+ chunks
2515
+ )
2516
  )
2517
 
2518
  yield (
2519
+ f"✍️ Phase 3/3 β€” writing part "
2520
+ f"{chunk_number}/3 β€” total so far "
2521
  f"{count_words(previous_script)} words…",
2522
  previous_script,
2523
  )
 
2537
  chunk_text = ""
2538
  final_response = None
2539
 
2540
+ for (
2541
+ partial_text,
2542
+ response,
2543
+ ) in stream_text(
2544
  client=client,
2545
  model=model,
2546
  system_prompt=(
 
2548
  "direct, natural spoken English with strong scientific and geographic "
2549
  "depth, selective current-news material, well-paced topic sizes, connected "
2550
  "cliffhangers, and high retention. Preserve the requested news balance "
2551
+ "and do not overuse dates. Maintain strict line-to-line continuity: finish "
2552
+ "or develop the current micro-story before changing direction, and use an "
2553
+ "explicit bridge for every real pivot. Favor standalone topics with strong "
2554
+ "editorial visual support and keep obscure text-only details subordinate."
2555
  ),
2556
  user_prompt=prompt,
2557
  max_tokens=CHUNK_MAX_TOKENS,
2558
  effort="medium",
2559
  ):
2560
+ chunk_text = (
2561
+ partial_text
2562
+ )
2563
 
2564
  if response is not None:
2565
+ final_response = (
2566
+ response
2567
+ )
2568
 
2569
+ current_script = (
2570
+ joined_script(
2571
+ chunks
2572
+ + [partial_text]
2573
+ )
2574
  )
2575
 
2576
  if response is None:
 
2583
 
2584
  if not chunk_text.strip():
2585
  raise RuntimeError(
2586
+ f"Claude did not write "
2587
+ f"part {chunk_number}."
2588
  )
2589
 
2590
  chunk_words = count_words(
 
2592
  )
2593
 
2594
  log(
2595
+ f"Part {chunk_number} "
2596
+ f"first draft: "
2597
  f"{chunk_words} words."
2598
  )
2599
 
2600
+ structure_issue = (
2601
+ get_chunk_structure_issue(
2602
+ chunk_text,
2603
+ spec,
2604
+ )
2605
+ )
2606
 
2607
  for correction_attempt in range(3):
2608
  length_ok = (
 
2611
  <= spec["maximum"]
2612
  )
2613
 
2614
+ if (
2615
+ length_ok
2616
+ and not structure_issue
2617
+ ):
2618
  break
2619
 
2620
  issue_text = (
2621
+ f" Structure check: "
2622
+ f"{structure_issue}"
2623
  if structure_issue
2624
  else ""
2625
  )
 
2628
  f"πŸ“ Part {chunk_number}/3 has "
2629
  f"{chunk_words} words; target is "
2630
  f"{spec['minimum']}–{spec['maximum']}."
2631
+ f"{issue_text} Correction "
2632
+ f"{correction_attempt + 1}/3…",
2633
  joined_script(
2634
+ chunks
2635
+ + [chunk_text]
2636
  ),
2637
  )
2638
 
 
2656
  chunk_words = count_words(
2657
  chunk_text
2658
  )
2659
+
2660
+ structure_issue = (
2661
+ get_chunk_structure_issue(
2662
+ chunk_text,
2663
+ spec,
2664
+ )
2665
+ )
2666
 
2667
  log(
2668
+ f"Part {chunk_number} after "
2669
+ f"correction "
2670
  f"{correction_attempt + 1}: "
2671
  f"{chunk_words} words."
2672
  )
2673
 
2674
  if (
2675
  final_response is not None
2676
+ and final_response.stop_reason
2677
+ == "max_tokens"
2678
  ):
2679
  log(
2680
  f"Part {chunk_number} reached "
2681
+ "max_tokens, but the existing "
2682
+ "text is being kept."
2683
  )
2684
 
2685
  chunks.append(
2686
  chunk_text.strip()
2687
  )
2688
 
2689
+ current_script = (
2690
+ joined_script(
2691
+ chunks
2692
+ )
2693
  )
2694
 
2695
  yield (
 
2703
  current_script
2704
  )
2705
 
2706
+ if not (
2707
+ MIN_WORDS
2708
+ <= total_words
2709
+ <= MAX_WORDS
2710
+ ):
2711
  yield (
2712
+ f"πŸ”§ Total length is "
2713
+ f"{total_words} words; "
2714
  "running final length correction…",
2715
  current_script,
2716
  )
 
2726
  global_requirements=global_requirements,
2727
  )
2728
 
2729
+ current_script = (
2730
+ joined_script(
2731
+ chunks
2732
+ )
2733
  )
2734
 
2735
  total_words = count_words(
 
2745
  )
2746
 
2747
  window_text = (
2748
+ f"news window "
2749
+ f"{cutoff_date.isoformat()} "
2750
+ f"to "
2751
+ f"{current_date.isoformat()}"
2752
  )
2753
 
2754
  if (
2755
+ MIN_WORDS
2756
+ <= total_words
2757
+ <= MAX_WORDS
2758
  and not warnings
2759
  ):
2760
  status = (
2761
+ f"βœ… Ready β€” "
2762
+ f"{total_words} words β€” "
2763
+ f"{window_text} β€” "
2764
+ f"4x {CHANNEL_NAME} β€” "
2765
  "2 vragen met Discover Tube"
2766
  )
2767
 
2768
+ elif (
2769
+ MIN_WORDS
2770
+ <= total_words
2771
+ <= MAX_WORDS
2772
+ ):
2773
  status = (
2774
+ f"⚠️ Ready β€” "
2775
+ f"{total_words} words β€” "
2776
  f"{window_text}. Check: "
2777
  + "; ".join(warnings)
2778
  )
2779
 
2780
  else:
2781
  warning_text = (
2782
+ f" Also check: "
2783
+ f"{'; '.join(warnings)}"
2784
  if warnings
2785
  else ""
2786
  )
2787
 
2788
  status = (
2789
+ f"⚠️ Ready β€” "
2790
+ f"{total_words} words. "
2791
+ f"Target: "
2792
+ f"{MIN_WORDS}–{MAX_WORDS}. "
2793
  f"{window_text}."
2794
  + warning_text
2795
  )
2796
 
2797
+ yield (
2798
+ status,
2799
+ current_script,
2800
+ )
2801
 
2802
  except anthropic.AuthenticationError:
2803
  yield (
 
2833
  )
2834
 
2835
  except anthropic.BadRequestError as exc:
2836
+ error_text = str(
2837
+ exc
2838
+ )
2839
+
2840
+ lower_error = (
2841
+ error_text.lower()
2842
+ )
2843
 
2844
+ if (
2845
+ "web search is not enabled"
2846
+ in lower_error
2847
+ ):
2848
  message = (
2849
  "❌ Web search is not enabled for "
2850
  "your Anthropic organization."
2851
  )
2852
 
2853
+ elif (
2854
+ "credit balance"
2855
+ in lower_error
2856
+ ):
2857
  message = (
2858
+ "❌ Your Anthropic API credit "
2859
+ "balance is insufficient."
2860
  )
2861
 
2862
  else:
2863
  message = (
2864
+ f"❌ Anthropic rejected "
2865
+ f"the request: "
2866
+ f"{error_text}"
2867
  )
2868
 
2869
+ yield (
2870
+ message,
2871
+ current_script,
2872
+ )
2873
 
2874
  except anthropic.APIStatusError as exc:
2875
  yield (
2876
  f"❌ Anthropic API error "
2877
+ f"{exc.status_code}: "
2878
+ f"{exc.message}",
2879
  current_script,
2880
  )
2881
 
2882
  except Exception as exc:
2883
  log(
2884
+ f"Unexpected error: "
2885
+ f"{exc}"
2886
  )
2887
 
2888
  yield (
2889
+ f"❌ Something went wrong: "
2890
+ f"{exc}",
2891
  current_script,
2892
  )
2893
 
 
2916
  start_time: float,
2917
  is_running: bool,
2918
  ):
2919
+ if (
2920
+ not is_running
2921
+ or not start_time
2922
+ ):
2923
  return gr.skip()
2924
 
2925
  elapsed_seconds = int(
2926
+ time.time()
2927
+ - float(start_time)
2928
  )
2929
 
2930
  return format_elapsed(
 
2932
  )
2933
 
2934
 
2935
+ def finish_run(
2936
+ start_time: float,
2937
+ ):
2938
  elapsed_seconds = (
2939
+ int(
2940
+ time.time()
2941
+ - float(start_time)
2942
+ )
2943
  if start_time
2944
  else 0
2945
  )
 
2981
  # Discover Tube Documentary Script Writer
2982
 
2983
  Creates a direct, information-dense, human-sounding YouTube documentary script of
2984
+ 2,900–3,200 words. Control the news balance, opening hook, and video structure:
2985
+ either a standard documentary or a 10/20/30-subtopic list documentary, without
2986
+ changing the core voice.
2987
  """
2988
  )
2989
 
2990
+ start_time_state = gr.State(
2991
+ 0.0
2992
+ )
2993
+
2994
+ running_state = gr.State(
2995
+ False
2996
+ )
2997
 
2998
  elapsed_timer = gr.Timer(
2999
  value=1.0,
 
3004
  title_input = gr.Textbox(
3005
  label="🎯 Video title",
3006
  placeholder=(
3007
+ "Scientists Are Monitoring "
3008
+ "a Mysterious Change "
3009
  "Beneath the Great Lakes"
3010
  ),
3011
  lines=2,
 
3018
  )
3019
 
3020
  recency_input = gr.Dropdown(
3021
+ choices=list(
3022
+ RECENCY_OPTIONS.keys()
3023
+ ),
3024
  value=DEFAULT_RECENCY_OPTION,
3025
  label="πŸ“° Current-news search window",
3026
  )
3027
 
3028
  with gr.Row():
3029
  news_balance_input = gr.Dropdown(
3030
+ choices=list(
3031
+ NEWS_BALANCE_OPTIONS.keys()
3032
+ ),
3033
  value=DEFAULT_NEWS_BALANCE_OPTION,
3034
  label="βš–οΈ News balance",
3035
  info=(
3036
+ "Controls how much of the spoken script "
3037
+ "is driven by current events. The research "
3038
+ "can still use dates internally without "
3039
+ "narrating all of them."
3040
  ),
3041
  )
3042
 
 
3045
  value=DEFAULT_HOOK_OPTION,
3046
  label="🎬 Opening hook",
3047
  info=(
3048
+ "Choose how the intro starts. Auto selects "
3049
+ "topography, a recent event, or a hard fact. "
3050
+ "News clip continuation is used only when "
3051
+ "you select it."
3052
  ),
3053
  )
3054
 
3055
  video_format_input = gr.Dropdown(
3056
+ choices=list(
3057
+ VIDEO_FORMAT_OPTIONS.keys()
3058
+ ),
3059
  value=DEFAULT_VIDEO_FORMAT_OPTION,
3060
  label="🧩 Video format",
3061
  info=(
3062
+ "Choose the normal 7-section documentary "
3063
+ "or a Reasons-Why-style list documentary "
3064
+ "with exactly 10, 20, or 30 visible "
3065
+ "numbered subtopics."
3066
  ),
3067
  )
3068
 
3069
  style_file_input = gr.File(
3070
  label=(
3071
+ "πŸ“„ Upload a handmade sample script "
3072
+ "for style inspiration (.docx or .txt)"
3073
  ),
3074
  file_types=[
3075
  ".docx",
 
3120
  show_progress="hidden",
3121
  )
3122
 
3123
+ generation_event = (
3124
+ generate_button.click(
3125
+ fn=start_run,
3126
+ inputs=None,
3127
+ outputs=[
3128
+ start_time_state,
3129
+ running_state,
3130
+ elapsed_output,
3131
+ status_output,
3132
+ script_output,
3133
+ generate_button,
3134
+ ],
3135
+ queue=False,
3136
+ )
3137
  )
3138
 
3139
+ generation_event = (
3140
+ generation_event.then(
3141
+ fn=generate_script,
3142
+ inputs=[
3143
+ title_input,
3144
+ style_file_input,
3145
+ model_input,
3146
+ recency_input,
3147
+ news_balance_input,
3148
+ hook_input,
3149
+ video_format_input,
3150
+ ],
3151
+ outputs=[
3152
+ status_output,
3153
+ script_output,
3154
+ ],
3155
+ concurrency_limit=1,
3156
+ show_progress="hidden",
3157
+ )
3158
  )
3159
 
3160
  generation_event.then(