Becio commited on
Commit
7daada3
Β·
verified Β·
1 Parent(s): fc3ce64

Update app.py

Browse files
Files changed (1) hide show
  1. app.py +600 -391
app.py CHANGED
@@ -12,7 +12,7 @@ from docx import Document
12
 
13
 
14
  # =========================================================
15
- # INSTELLINGEN
16
  # =========================================================
17
 
18
  MIN_WORDS = 2900
@@ -39,16 +39,69 @@ MODEL_OPTIONS = [
39
  ]
40
 
41
  RECENCY_OPTIONS = {
42
- "Laatste 30 dagen": 30,
43
- "Laatste 90 dagen": 90,
44
- "Laatste 180 dagen": 180,
45
- "Laatste 365 dagen": 365,
46
  }
47
 
48
- DEFAULT_RECENCY_OPTION = "Laatste 90 dagen"
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
49
 
50
- # De drie minimumwaarden tellen exact op tot 2.900 woorden.
51
- # De maxima tellen exact op tot 3.200 woorden.
 
 
 
 
 
 
 
 
 
 
52
  CHUNK_SPECS = [
53
  {
54
  "number": 1,
@@ -58,10 +111,10 @@ CHUNK_SPECS = [
58
  "purpose": (
59
  "Write the direct introduction of 120–160 words and the first "
60
  "two titled sections. Mention Discover Tube exactly once in the "
61
- "introduction. Open with the strongest current news development. "
62
- "Immediately after the introduction, deliver recent verified figures, "
63
- "dates, measurements, and data from the selected news window. Make the "
64
- "first two sections deliberately unequal in length."
65
  ),
66
  },
67
  {
@@ -70,11 +123,11 @@ CHUNK_SPECS = [
70
  "maximum": 1100,
71
  "target": 1050,
72
  "purpose": (
73
- "Write the next three titled sections. Deliver the densest recent "
74
- "scientific explanations, analysis, named current research, policy or "
75
- "project developments, and human consequences. Place the 40-percent "
76
- "Discover Tube subscribe sentence inside this chunk. Make all three "
77
- "sections clearly unequal in length. Do not recap part 1."
78
  ),
79
  },
80
  {
@@ -84,19 +137,20 @@ CHUNK_SPECS = [
84
  "target": 1050,
85
  "purpose": (
86
  "Write the final two titled sections and an ending of 100–160 words. "
87
- "Keep the focus on the newest developments, what happens next, and what "
88
- "researchers or authorities are currently monitoring. Place one Discover "
89
- "Tube audience question around 75 percent of the full video. In the final "
90
- "100 words, mention Discover Tube once more, include a brief subscribe "
91
- "request, and ask one concrete question for viewers to answer in the "
92
- "comments. Make the final two sections unequal in length."
 
93
  ),
94
  },
95
  ]
96
 
97
 
98
  # =========================================================
99
- # LOGGING EN BASISFUNCTIES
100
  # =========================================================
101
 
102
 
@@ -110,7 +164,7 @@ def get_client() -> Anthropic:
110
 
111
  if not api_key:
112
  raise ValueError(
113
- "ANTHROPIC_API_KEY ontbreekt. Voeg deze toe via "
114
  "Hugging Face Space β†’ Settings β†’ Variables and secrets."
115
  )
116
 
@@ -131,7 +185,7 @@ def count_words(text: str) -> int:
131
  def format_elapsed(seconds: int, finished: bool = False) -> str:
132
  seconds = max(0, int(seconds))
133
  minutes, remaining_seconds = divmod(seconds, 60)
134
- prefix = "βœ… Totale generatietijd" if finished else "⏱️ Verstreken tijd"
135
 
136
  return (
137
  f"{prefix}: {seconds} seconden "
@@ -169,6 +223,78 @@ def resolve_recency_days(option: str) -> int:
169
  )
170
 
171
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
172
  def get_news_window(recency_days: int) -> tuple[date, date]:
173
  current_date = date.today()
174
  cutoff_date = current_date - timedelta(days=recency_days)
@@ -242,6 +368,7 @@ def story_requirement_warnings(
242
  text: str,
243
  cutoff_date: date,
244
  current_date: date,
 
245
  ) -> list[str]:
246
  warnings = []
247
 
@@ -262,114 +389,144 @@ def story_requirement_warnings(
262
 
263
  if channel_mentions != 4:
264
  warnings.append(
265
- f"{CHANNEL_NAME} staat {channel_mentions}x in plaats van 4x"
266
  )
267
 
268
  if branded_questions != 2:
269
  warnings.append(
270
- f"vragen met {CHANNEL_NAME}: "
271
- f"{branded_questions} in plaats van 2"
272
  )
273
 
274
  if subscribe_mentions != 2:
275
  warnings.append(
276
- f"subscribe staat {subscribe_mentions}x in plaats van 2x"
277
  )
278
 
279
  if len(old_years) > MAX_OLD_YEAR_MENTIONS:
280
  unique_old_years = sorted(set(old_years))
281
 
282
  warnings.append(
283
- "te veel oude kalenderjaren genoemd: "
284
  + ", ".join(
285
  str(year)
286
  for year in unique_old_years[:8]
287
  )
288
  )
289
 
290
- if current_year_mentions == 0:
 
 
 
 
 
291
  warnings.append(
292
- f"het actuele jaar {current_date.year} wordt niet genoemd"
293
  )
294
 
295
  return warnings
296
 
297
 
298
  # =========================================================
299
- # ACTUELE SCHRIJFREGELS
300
  # =========================================================
301
 
302
 
303
  def build_global_writing_requirements(
304
  cutoff_date: date,
305
  current_date: date,
 
 
306
  ) -> str:
 
 
 
307
  return f"""
308
- Write for a high-retention current-news science documentary. The narration must
309
- feel human-written, purposeful, and conversational while remaining factual.
310
-
311
- STRICT NEWS WINDOW
312
-
313
- - The permitted source publication window is {cutoff_date.isoformat()} through
314
- {current_date.isoformat()}.
315
- - The central story, every major section, and at least 90 percent of concrete
316
- factual claims must concern developments, announcements, findings, measurements,
317
- warnings, legislation, funding, projects, incidents, or reporting from this window.
318
- - Do not build a section around an old study, old event, historical mystery, or
319
- long-known process merely because a recent article mentioned it.
320
- - A newly published article that only repeats an old fact does not make that fact
321
- current news.
322
- - New analysis, a new measurement, an official update, a newly published study,
323
- a current field campaign, a new warning, a funding decision, a policy action,
324
- or a recently reported incident does count as current news.
325
- - Older context may use no more than {MAX_HISTORICAL_CONTEXT_PERCENT} percent of
326
- the complete script. Use it only when it is essential to understand a recent
327
- development, and return to the current story immediately.
 
 
 
 
 
 
 
 
 
 
328
  - Do not mention more than {MAX_OLD_YEAR_MENTIONS} calendar years from before
329
- {cutoff_date.year} in the complete script.
330
- - Do not use any factual claim that is supported only by a source published before
331
- {cutoff_date.isoformat()}.
332
- - When a recent source discusses older history, treat that history as brief context,
333
- not as a main topic.
334
- - Use publication dates and event dates carefully. Do not present an old event as
335
- if it happened recently because a new article reported it.
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
336
 
337
  CENTRAL STORY AND RETENTION
338
 
339
- - Build one continuous current-news story instead of seven isolated mini-essays.
340
- - Every section must answer part of the central current question and create a reason
341
- to hear the next section.
342
- - End sections 1 through 6 with a content-based open loop or cliffhanger that leads
343
- directly into the next topic.
344
- - Vary the transition method. Use a new measurement, unresolved result, location,
345
- consequence, scientific limitation, official decision, or competing explanation.
346
  - Do not end every section with a rhetorical question.
347
  - Pay off earlier open loops later in the script so the story feels intentional.
348
- - Put the newest and strongest verified material in the first third of the video.
349
- - Keep retention high through information, escalation, contrast, and consequence,
350
- not through empty mystery language.
351
-
352
- FACTS, DATA, AND SCIENTIFIC DEPTH
353
-
354
- - Immediately after the introduction, provide substantial verified figures, dates,
355
- measurements, named places, and recent data from the permitted news window.
356
- - Every paragraph must add at least one new current fact, number, mechanism, example,
357
- consequence, research result, official update, or documented uncertainty.
358
- - Do not merely list facts. Explain why they matter and how the mechanism works.
359
- - Go deeper into the science when useful: explain methods, causal mechanisms,
360
- uncertainty, alternative explanations, limitations, and what the latest evidence
361
- does or does not prove.
362
- - Include analysis that connects recent facts without inventing certainty.
363
- - Use real named current research, institutions, datasets, projects, agencies,
364
- reports, or studies from the permitted window when the evidence supports them.
365
- - Preserve labels such as confirmed, preliminary, estimated, disputed, or unverified.
366
- - Fully paraphrase the evidence pack and the style sample.
367
 
368
  UNEQUAL TOPIC LENGTHS
369
 
370
  - The seven titled sections must not be equal in size.
371
- - Give the most important or scientifically rich current topics substantially more
372
- space.
373
  - Use shorter sections as bridges, reveals, or transitions.
374
  - The writing plan must assign a distinct word budget to every section.
375
  - The largest section should be at least 150 words longer than the shortest section.
@@ -380,14 +537,12 @@ HUMAN WRITING
380
  - Keep most paragraphs between one and four sentences.
381
  - Use natural sentence variation and active language.
382
  - Avoid sounding like a report, literature review, or AI summary.
383
- - Introduce researchers through what they recently did, measured, found, announced,
384
- or questioned.
385
  - Use concrete nouns instead of vague references when the evidence gives a name.
386
- - Do not overuse em dashes, three-part dramatic lists, fragments, or rhetorical
387
- questions.
388
- - Avoid formulaic phrases such as β€œlet that sink in,” β€œhere is where things get
389
- interesting,” β€œthe truth is,” β€œscientists are watching,” β€œmore questions than
390
- answers,” or β€œonly time will tell.”
391
 
392
  COMPARISONS
393
 
@@ -401,32 +556,32 @@ DISCOVER TUBE AND CTA PLACEMENT
401
 
402
  - Use the exact phrase β€œ{CHANNEL_NAME}” exactly four times in the complete script.
403
  - Exactly two questions in the complete script may contain β€œ{CHANNEL_NAME}”.
404
- - Placement 1: once in the introduction, as a natural non-question mention. Do not
405
  ask for a subscription or comment there.
406
  - Placement 2: around 40 percent of the video, as one brief subscribe sentence.
407
  This occurrence is not a question and does not ask for comments.
408
- - Placement 3: around 75 percent of the video, inside one topic-specific audience
409
- question. Do not ask for a subscription in that occurrence.
410
- - Placement 4: within the final 100 words. Include a brief subscribe request and ask
411
- one concrete comment question. The question itself must contain β€œ{CHANNEL_NAME}”.
412
  - Do not mention β€œ{CHANNEL_NAME}” anywhere else.
413
  - Do not use the word subscribe outside placements 2 and 4.
414
  """.strip()
415
 
416
 
417
  # =========================================================
418
- # STIJLVOORBEELD
419
  # =========================================================
420
 
421
 
422
  def load_style_file(filepath: Optional[str]) -> str:
423
  default_style = """
424
- Write direct, information-dense spoken English for a current-news YouTube
425
- documentary. Open with a specific recent event, announcement, discovery,
426
- measurement, warning, or consequence. Use short and medium-length sentences,
427
- brief paragraphs, concrete details, scientific explanation, and connected
428
- transitions. Sound like a skilled human writer, not an academic summary or an
429
- AI narrator. Build curiosity through recent evidence and consequences.
430
  """.strip()
431
 
432
  if not filepath:
@@ -463,7 +618,7 @@ AI narrator. Build curiosity through recent evidence and consequences.
463
 
464
  else:
465
  raise ValueError(
466
- "Alleen .docx- en .txt-bestanden worden ondersteund."
467
  )
468
 
469
  return (
@@ -474,12 +629,12 @@ AI narrator. Build curiosity through recent evidence and consequences.
474
 
475
  except Exception as exc:
476
  raise ValueError(
477
- f"Het stijldocument kon niet worden gelezen: {exc}"
478
  ) from exc
479
 
480
 
481
  # =========================================================
482
- # CLAUDE-AANROEPEN
483
  # =========================================================
484
 
485
 
@@ -492,17 +647,17 @@ def validate_response(
492
  return
493
 
494
  raise RuntimeError(
495
- "Claude bereikte de maximale outputlengte."
496
  )
497
 
498
  if response.stop_reason == "refusal":
499
  raise RuntimeError(
500
- "Claude heeft deze opdracht geweigerd."
501
  )
502
 
503
  if response.stop_reason == "pause_turn":
504
  raise RuntimeError(
505
- "Claude heeft de opdracht niet volledig afgerond."
506
  )
507
 
508
 
@@ -552,8 +707,8 @@ def request_text(
552
  and attempt == 0
553
  ):
554
  log(
555
- "Webonderzoek gaf pause_turn; "
556
- "één hervatting wordt uitgevoerd."
557
  )
558
 
559
  messages.append(
@@ -574,14 +729,14 @@ def request_text(
574
 
575
  if not text:
576
  raise RuntimeError(
577
- "Claude heeft geen bruikbare tekst teruggegeven."
578
  )
579
 
580
  return text, response
581
 
582
  raise RuntimeError(
583
- "Claude kon het webonderzoek niet afronden. "
584
- "Probeer een concretere titel."
585
  )
586
 
587
 
@@ -629,8 +784,8 @@ def stream_text(
629
 
630
  if response.stop_reason == "max_tokens":
631
  log(
632
- "Een schrijfronde bereikte max_tokens; "
633
- "de bestaande tekst blijft behouden."
634
  )
635
 
636
  yield final_text, response
@@ -641,7 +796,7 @@ def stream_text(
641
 
642
 
643
  # =========================================================
644
- # FASE 1 β€” STRIKT RECENT NIEUWSONDERZOEK
645
  # =========================================================
646
 
647
 
@@ -650,10 +805,12 @@ def research_topic(
650
  model: str,
651
  title: str,
652
  recency_days: int,
 
653
  ) -> str:
654
  cutoff_date, current_date = get_news_window(
655
  recency_days
656
  )
 
657
 
658
  prompt = f"""
659
  Today's date is {current_date.isoformat()}.
@@ -662,24 +819,39 @@ Research this proposed YouTube documentary title:
662
 
663
  "{title}"
664
 
665
- Create an INTERNAL evidence pack for a factual, current-news script of
666
  approximately {TARGET_WORDS} words. Do not write the script.
667
 
668
- STRICT PUBLICATION WINDOW
669
-
670
- - Use only sources published from {cutoff_date.isoformat()} through
671
- {current_date.isoformat()}.
672
- - Exclude undated sources.
673
- - Exclude every source published before {cutoff_date.isoformat()}.
674
- - Search publication dates explicitly before using a source.
675
- - Do not use an old study merely because a recent webpage mentions it.
676
- - A recent article that simply repeats old facts does not qualify as a recent
677
- development.
678
- - A recent update qualifies only when it contains a new measurement, finding,
679
- announcement, official decision, field campaign, incident, warning, funding
680
- development, policy change, or genuinely new analysis.
681
- - Distinguish the source publication date from the date the event actually happened.
682
- - Do not describe an old event as current news because it was republished recently.
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
683
 
684
  RECENCY DECISION
685
 
@@ -688,16 +860,17 @@ Return exactly one of these near the beginning:
688
  RECENCY VERDICT: SUFFICIENT
689
  RECENCY VERDICT: INSUFFICIENT
690
 
691
- Return SUFFICIENT only when there is enough reliable news within the strict window
692
- to support seven connected sections and a 2,900–3,200 word script without using old
693
- material as filler.
 
694
 
695
  If the verdict is INSUFFICIENT:
696
 
697
- - Explain briefly why.
698
- - Provide three alternative current-news title angles that are genuinely supported
699
- inside the selected window.
700
- - Do not fill the evidence pack with older research.
701
 
702
  TITLE AUDIT
703
 
@@ -707,61 +880,58 @@ TITLE VERDICT: SUPPORTED
707
  TITLE VERDICT: PARTLY SUPPORTED
708
  TITLE VERDICT: UNSUPPORTED
709
 
710
- Continued activity is not acceleration, improved detection is not acceleration,
711
- and a new publication about old data is not a new physical event. Do not assume
712
- scientists are afraid, shocked, baffled, or issuing warnings unless recent reliable
713
- evidence explicitly supports that description.
714
 
715
  SOURCE PRIORITY
716
 
717
  Use no more than {MAX_WEB_SEARCHES} focused searches. Prioritize:
718
 
719
- 1. Official agency alerts, releases, datasets, and project updates.
720
- 2. University and scientific-institution newsrooms describing current work.
721
- 3. Peer-reviewed studies published inside the strict window.
722
- 4. Government decisions, legislation, funding, and operational updates.
723
  5. Reputable news reporting for current human and regional context.
724
 
725
- Do not rely on encyclopedias, undated explainers, SEO summaries, copied articles,
726
- or general background pages.
727
-
728
  BUILD THIS EVIDENCE PACK
729
 
730
  1. RECENCY VERDICT.
731
  2. TITLE VERDICT.
732
  3. NEWS WINDOW: {cutoff_date.isoformat()} to {current_date.isoformat()}.
733
- 4. THE STRONGEST CURRENT STORY in 120–180 words.
734
- 5. RECENT SOURCE LEDGER with 8–15 sources. For every source include:
735
- - title;
736
- - publisher or institution;
737
- - publication date;
738
- - event or research date;
739
- - why it contains genuinely new information.
740
- 6. A RECENT FACT BANK of 35–50 specific, non-duplicative facts. Every fact must show:
741
- - publication date;
742
- - event date;
743
- - location;
744
- - named institution, researcher, project, report, or authority;
745
- - certainty level;
746
- - why it matters now.
747
- 7. An EARLY DATA BLOCK containing the strongest current figures and measurements to
748
- use immediately after the introduction.
749
- 8. CURRENT NAMED RESEARCH, projects, official reports, alerts, or datasets published
750
- or materially updated within the strict window. Explain who conducted the work,
751
- what was measured, the method, the result, and the limitation.
752
- 9. SCIENTIFIC EXPLANATIONS needed to understand the recent news.
753
- 10. HUMAN, environmental, economic, infrastructure, policy, or safety consequences.
754
- 11. At least six candidate factual comparisons with checked units. The script will
755
- select exactly three.
756
- 12. ESSENTIAL HISTORICAL CONTEXT, limited to material needed to explain the recent
757
- news. This must be short enough to occupy no more than
758
- {MAX_HISTORICAL_CONTEXT_PERCENT} percent of the final script and must be supported
759
- by recent sources from the strict window.
760
- 13. CLAIMS TO AVOID.
761
- 14. EXTRA RECENT FACTS that can be used to reach the word target without old filler.
762
-
763
- Do not copy source sentences. Do not write dramatic narration. The evidence pack
764
- must be dominated by new information from the selected window.
 
765
  """.strip()
766
 
767
  web_search_tool = [
@@ -777,20 +947,19 @@ must be dominated by new information from the selected window.
777
  ]
778
 
779
  log(
780
- "Fase 1 gestart: strikt recent nieuwsonderzoek "
781
- f"({cutoff_date.isoformat()} t/m "
782
- f"{current_date.isoformat()})."
783
  )
784
 
785
  research, response = request_text(
786
  client=client,
787
  model=model,
788
  system_prompt=(
789
- "You are a rigorous current-news documentary researcher. "
790
- "Enforce the publication cutoff strictly. Reject stale material "
791
- "rather than filling the evidence pack with old studies or "
792
- "historical facts. Accuracy, freshness, source dates, and "
793
- "genuinely new information matter most."
794
  ),
795
  user_prompt=prompt,
796
  max_tokens=RESEARCH_MAX_TOKENS,
@@ -807,40 +976,36 @@ must be dominated by new information from the selected window.
807
 
808
  if response.stop_reason == "max_tokens":
809
  log(
810
- "Research bereikte max_tokens; "
811
- "de voltooide research wordt gebruikt."
812
  )
813
 
814
  if recency_verdict == "INSUFFICIENT":
815
  raise RuntimeError(
816
- "Er is onvoldoende betrouwbaar nieuws gevonden binnen "
817
- f"de gekozen periode van {recency_days} dagen. Kies een "
818
- "bredere nieuwsperiode of gebruik een actuelere videotitel."
819
  )
820
 
821
  if recency_verdict != "SUFFICIENT":
822
  raise RuntimeError(
823
- "Claude kon niet bevestigen dat er genoeg recente "
824
- "informatie is. Probeer een actuelere titel of kies "
825
- "een bredere nieuwsperiode."
826
  )
827
 
828
  if research_words < 800:
829
  raise RuntimeError(
830
- "Claude vond onvoldoende recente research. "
831
- "Maak de videotitel specifieker of kies een bredere periode."
832
  )
833
 
834
  log(
835
- f"Fase 1 afgerond: "
836
- f"{research_words} woorden recente research."
837
  )
838
 
839
  return research
840
 
841
 
842
  # =========================================================
843
- # FASE 2 β€” ACTUEEL PLAN MET VASTE WOORDBUDGETTEN
844
  # =========================================================
845
 
846
 
@@ -852,96 +1017,112 @@ def create_script_plan(
852
  cutoff_date: date,
853
  current_date: date,
854
  global_requirements: str,
 
 
855
  ) -> str:
 
 
856
  prompt = f"""
857
  Create a concise but detailed INTERNAL writing plan for this proposed title:
858
 
859
  "{title}"
860
 
861
- <recent_evidence_pack>
862
  {research}
863
- </recent_evidence_pack>
864
 
865
- The final spoken script must contain 2,900–3,200 words. Build exactly three
866
- writing chunks with these budgets:
867
 
868
  CHUNK 1 β€” 900–1,000 words
869
  - A direct introduction of 120–160 words.
870
  - Two titled sections.
871
- - Immediately after the introduction, deliver the strongest recent data,
872
- measurements, dates, and figures.
 
873
 
874
  CHUNK 2 β€” 1,000–1,100 words
875
  - Three titled sections.
876
- - The densest current scientific explanation, named recent research, analysis,
877
- and consequences.
878
 
879
  CHUNK 3 β€” 1,000–1,100 words
880
  - Two titled sections.
881
- - A connected ending of 100–160 words focused on what happens next.
882
 
883
  That produces exactly seven titled sections in the full script.
884
 
885
  {global_requirements}
886
 
887
- CURRENT-NEWS PLAN RULES
888
-
889
- - Every one of the seven sections must be anchored to at least one genuinely new
890
- development reported or published between {cutoff_date.isoformat()} and
891
- {current_date.isoformat()}.
892
- - No section may be centered on a source, study, event, or discovery from before the
893
- cutoff date.
894
- - Historical background may appear only as short context inside a current section.
895
- - Allocate at least five different recent publication dates across the script.
896
- - Allocate recent developments from multiple reliable institutions or publishers.
897
- - Do not create an old geological-history section, old shipwreck section, or old
898
- research-history section unless a new development inside the news window is the
899
- real reason that topic is being discussed.
900
- - The conclusion must explain the next current milestone, expected update, active
901
- investigation, pending decision, field campaign, or monitoring step.
 
 
 
 
 
 
 
 
 
902
 
903
  PLAN THE SEVEN SECTIONS AS UNEQUAL TOPICS
904
 
905
  - Give every section an exact individual word budget.
906
  - Do not give neighboring sections similar budgets unless necessary.
907
- - Use the largest sections for the most important current scientific material.
908
  - Use at least two noticeably short bridge sections.
909
  - The largest section must be at least 150 words longer than the shortest.
910
 
911
  FOR EVERY SECTION PROVIDE
912
 
913
  - a short, specific title;
914
- - the recent news development that anchors the section;
915
- - the publication date and event date;
916
  - its central purpose;
917
  - its exact word budget;
918
- - the exact recent facts, measurements, people, locations, and mechanisms it uses;
919
  - the scientific explanation or analysis it contains;
920
  - the human or practical consequence;
921
- - the specific open loop or cliffhanger that leads into the next section;
 
 
 
 
922
  - any essential historical context, limited to one or two brief points.
923
 
924
  ALLOCATION RULES
925
 
926
  - Assign every important fact to only one section.
927
- - Put the newest and strongest verified information in chunk 1.
928
- - Reserve enough unused recent facts for chunks 2 and 3.
929
  - Select exactly three verified comparisons and assign each to a different section.
930
- - Assign at least two named recent studies, projects, reports, alerts, or datasets.
931
- - Do not create a debunking video. Silently use the strongest accurate current angle.
 
932
 
933
  DISCOVER TUBE PLACEMENT PLAN
934
 
935
- 1. Introduction: one natural non-question mention of β€œ{CHANNEL_NAME}”.
936
- 2. Around 40 percent: one brief non-question subscribe sentence containing
937
- β€œ{CHANNEL_NAME}”.
938
- 3. Around 75 percent: one topic-specific audience question containing
939
- β€œ{CHANNEL_NAME}”.
940
- 4. Final 100 words: one brief subscribe request and one concrete comment question;
941
- the question itself must contain β€œ{CHANNEL_NAME}”.
942
 
943
- Exactly four total mentions of β€œ{CHANNEL_NAME}” and exactly two questions
944
- containing it.
945
 
946
  Keep the complete plan between 1,500 and 2,500 words. Use compact bullet points.
947
  Do not write sample narration and do not repeat the entire evidence pack.
@@ -949,17 +1130,16 @@ This is a plan only.
949
  """.strip()
950
 
951
  log(
952
- "Fase 2 gestart: recent driedelig scriptplan."
953
  )
954
 
955
  plan, response = request_text(
956
  client=client,
957
  model=model,
958
  system_prompt=(
959
- "You are a senior current-news documentary editor. "
960
- "Allocate only fresh evidence across three writing chunks "
961
- "so the final script is recent, scientific, human, "
962
- "high-retention, connected, and free of stale filler."
963
  ),
964
  user_prompt=prompt,
965
  max_tokens=PLAN_MAX_TOKENS,
@@ -969,25 +1149,23 @@ This is a plan only.
969
 
970
  if response.stop_reason == "max_tokens":
971
  log(
972
- "Het scriptplan bereikte max_tokens; "
973
- "het reeds gemaakte plan wordt gebruikt."
974
  )
975
 
976
  if count_words(plan) < 400:
977
  raise RuntimeError(
978
- "Claude heeft geen bruikbaar recent scriptplan gemaakt."
979
  )
980
 
981
  log(
982
- f"Fase 2 afgerond: "
983
- f"{count_words(plan)} woorden plan."
984
  )
985
 
986
  return plan
987
 
988
 
989
  # =========================================================
990
- # FASE 3 β€” DRIE ACTUELE SCRIPTDELEN
991
  # =========================================================
992
 
993
 
@@ -1048,28 +1226,26 @@ def build_chunk_prompt(
1048
 
1049
  if chunk_number == 1:
1050
  continuity_rule = (
1051
- f"Start with a concrete development reported between "
1052
- f"{cutoff_date.isoformat()} and {current_date.isoformat()}. "
1053
- "Do not print the video title. After the 120–160 word "
1054
- "introduction, move directly into dense recent figures, "
1055
- "dates, and measurements."
1056
  )
1057
  else:
1058
  continuity_rule = (
1059
- "Continue naturally from the previous script. Do not write "
1060
- "a new introduction, do not recap earlier sections, and do "
1061
- "not repeat facts."
1062
  )
1063
 
1064
  return f"""
1065
- Write ONLY CHUNK {chunk_number} of the final spoken current-news YouTube documentary.
1066
 
1067
  Proposed title:
1068
  "{title}"
1069
 
1070
- <recent_evidence_pack>
1071
  {research}
1072
- </recent_evidence_pack>
1073
 
1074
  <full_writing_plan>
1075
  {plan}
@@ -1092,49 +1268,46 @@ HARD LENGTH REQUIREMENT
1092
  - This chunk must contain between {minimum} and {maximum} words.
1093
  - Aim for {target} words.
1094
  - This is a hard production requirement, not a suggestion.
1095
- - Before answering, silently count the chunk and keep adding unused recent verified
1096
- information until it reaches at least {minimum} words.
 
1097
 
1098
  {global_requirements}
1099
 
1100
- CURRENT-NEWS REQUIREMENTS FOR THIS CHUNK
1101
 
1102
- - Use only facts allocated to this chunk in the recent writing plan.
1103
- - Every main topic must be anchored to a development inside the news window
 
1104
  {cutoff_date.isoformat()} through {current_date.isoformat()}.
1105
- - At least 90 percent of concrete claims in this chunk must concern developments
1106
- inside that window.
1107
- - Do not center a paragraph on an old study or old event.
1108
- - Do not cite a study published before the cutoff date.
1109
- - Do not mention a pre-cutoff calendar year unless the plan explicitly identifies it
1110
- as essential context.
1111
- - Keep essential historical context brief and immediately reconnect it to the recent
1112
- development.
1113
- - Use publication dates and event dates accurately.
1114
- - A new article about an old fact is not itself a new scientific development.
1115
 
1116
  WRITING STANDARD
1117
 
1118
  - {continuity_rule}
1119
  - Use the exact unequal section budgets assigned in the plan.
1120
- - Every paragraph must add a new current fact, example, mechanism, measurement,
1121
- consequence, event, research result, analysis, or documented uncertainty.
1122
- - Write straight to the point. Give the latest information first and explain it.
1123
  - Use mostly short and medium-length sentences and paragraphs of one to four sentences.
1124
  - Translate technical language into natural spoken English.
1125
- - Use exact recent dates, names, places, and numbers when useful.
1126
- - Explain why each important current fact matters and how the science works.
1127
- - Go deeper where the plan assigns scientific analysis, including methods,
1128
  uncertainty, limitations, competing explanations, and practical implications.
1129
- - Follow the planned open loops and cliffhangers so each section connects directly
1130
- to the next one.
1131
  - Fully paraphrase the evidence and the style sample.
1132
- - Preserve uncertainty. Do not turn possible, estimated, preliminary, or disputed
1133
- information into certainty.
1134
  - Do not tell the audience that the proposed title was fact-checked or exaggerated.
1135
  - Use section headings exactly as planned for this chunk.
1136
- - Use only the comparisons assigned to this chunk. The complete script must contain
1137
- exactly three factual comparisons in total.
1138
  - Do not include sources, URLs, citations, editor notes, camera directions, or B-roll.
1139
 
1140
  {channel_rules_for_chunk(chunk_number)}
@@ -1163,17 +1336,16 @@ def build_chunk_revision_prompt(
1163
  if current_words < minimum:
1164
  operation = (
1165
  f"The chunk is {minimum - current_words} words below the minimum. "
1166
- "Expand it only with unused recent facts, current research, "
1167
- "new measurements, current scientific analysis, consequences, "
1168
- "and active developments assigned to this part. Do not use "
1169
- "old material as filler."
1170
  )
1171
  else:
1172
  operation = (
1173
  f"The chunk is {current_words - maximum} words above the maximum. "
1174
- "Remove repetition, stale background, and decorative phrasing "
1175
- "while preserving recent facts, scientific depth, open loops, "
1176
- "comparisons, and CTA placement."
1177
  )
1178
 
1179
  return f"""
@@ -1203,13 +1375,17 @@ Aim for {target} words.
1203
 
1204
  {global_requirements}
1205
 
1206
- STRICT FRESHNESS CHECK
1207
 
1208
- - Keep the chunk centered on news published from {cutoff_date.isoformat()} through
1209
- {current_date.isoformat()}.
1210
- - Remove any section or paragraph whose main value comes from an older event or study.
1211
- - Use no more than brief essential background.
1212
- - Add only verified, non-repeated, current information.
 
 
 
 
1213
 
1214
  Keep the same section purpose, exact headings, unequal topic sizes, scientific
1215
  explanations, analysis, planned comparisons, and content-based cliffhangers.
@@ -1255,11 +1431,10 @@ def revise_chunk(
1255
  client=client,
1256
  model=model,
1257
  system_prompt=(
1258
- "You are a strict current-news documentary editor. "
1259
- "Meet the requested word range while preserving freshness, "
1260
- "factual density, scientific analysis, natural spoken rhythm, "
1261
- "open-loop storytelling, and exact brand placement. "
1262
- "Remove stale background rather than expanding it."
1263
  ),
1264
  user_prompt=prompt,
1265
  max_tokens=REVISION_MAX_TOKENS,
@@ -1271,7 +1446,7 @@ def revise_chunk(
1271
 
1272
 
1273
  # =========================================================
1274
- # TOTAALLENGTE BALANCEREN
1275
  # =========================================================
1276
 
1277
 
@@ -1353,7 +1528,7 @@ def rebalance_total(
1353
 
1354
 
1355
  # =========================================================
1356
- # HOOFDWORKFLOW
1357
  # =========================================================
1358
 
1359
 
@@ -1362,11 +1537,13 @@ def generate_script(
1362
  style_file: Optional[str],
1363
  model: str,
1364
  recency_option: str,
 
 
1365
  ):
1366
  current_script = ""
1367
 
1368
  if not title or not title.strip():
1369
- yield "❌ Vul eerst een videotitel in.", ""
1370
  return
1371
 
1372
  try:
@@ -1387,11 +1564,13 @@ def generate_script(
1387
  global_requirements = build_global_writing_requirements(
1388
  cutoff_date=cutoff_date,
1389
  current_date=current_date,
 
 
1390
  )
1391
 
1392
  yield (
1393
- "πŸ”Ž Fase 1/3 β€” recent nieuws verzamelen "
1394
- f"vanaf {cutoff_date.isoformat()}…",
1395
  "",
1396
  )
1397
 
@@ -1400,11 +1579,12 @@ def generate_script(
1400
  model=model,
1401
  title=clean_title,
1402
  recency_days=recency_days,
 
1403
  )
1404
 
1405
  yield (
1406
- "🧭 Fase 2/3 β€” recente informatie en storytelling "
1407
- "over drie delen verdelen…",
1408
  "",
1409
  )
1410
 
@@ -1416,6 +1596,8 @@ def generate_script(
1416
  cutoff_date=cutoff_date,
1417
  current_date=current_date,
1418
  global_requirements=global_requirements,
 
 
1419
  )
1420
 
1421
  chunks: list[str] = []
@@ -1427,9 +1609,9 @@ def generate_script(
1427
  )
1428
 
1429
  yield (
1430
- f"✍️ Fase 3/3 β€” actueel deel {chunk_number}/3 "
1431
- f"wordt geschreven β€” totaal "
1432
- f"{count_words(previous_script)} woorden…",
1433
  previous_script,
1434
  )
1435
 
@@ -1452,12 +1634,11 @@ def generate_script(
1452
  client=client,
1453
  model=model,
1454
  system_prompt=(
1455
- "You are an experienced human current-news "
1456
- "documentary writer. Write dense, direct, natural "
1457
- "spoken English with fresh data, current scientific "
1458
- "depth, unequal topic sizes, connected cliffhangers, "
1459
- "and high retention. Do not use stale studies or "
1460
- "historical material as the main story."
1461
  ),
1462
  user_prompt=prompt,
1463
  max_tokens=CHUNK_MAX_TOKENS,
@@ -1474,15 +1655,15 @@ def generate_script(
1474
 
1475
  if response is None:
1476
  yield (
1477
- f"✍️ Actueel deel {chunk_number}/3 β€” "
1478
- f"{count_words(partial_text)} woorden in dit deel β€” "
1479
- f"{count_words(current_script)} totaal",
1480
  current_script,
1481
  )
1482
 
1483
  if not chunk_text.strip():
1484
  raise RuntimeError(
1485
- f"Claude heeft deel {chunk_number} niet geschreven."
1486
  )
1487
 
1488
  chunk_words = count_words(
@@ -1490,11 +1671,11 @@ def generate_script(
1490
  )
1491
 
1492
  log(
1493
- f"Deel {chunk_number} eerste versie: "
1494
- f"{chunk_words} woorden."
1495
  )
1496
 
1497
- # Maximaal drie gerichte correctierondes per deel.
1498
  for correction_attempt in range(3):
1499
  if (
1500
  spec["minimum"]
@@ -1504,10 +1685,10 @@ def generate_script(
1504
  break
1505
 
1506
  yield (
1507
- f"πŸ“ Deel {chunk_number}/3 heeft "
1508
- f"{chunk_words} woorden; doel is "
1509
  f"{spec['minimum']}–{spec['maximum']}. "
1510
- f"Correctie {correction_attempt + 1}/3…",
1511
  joined_script(
1512
  chunks + [chunk_text]
1513
  ),
@@ -1534,9 +1715,9 @@ def generate_script(
1534
  )
1535
 
1536
  log(
1537
- f"Deel {chunk_number} na correctie "
1538
  f"{correction_attempt + 1}: "
1539
- f"{chunk_words} woorden."
1540
  )
1541
 
1542
  if (
@@ -1544,8 +1725,8 @@ def generate_script(
1544
  and final_response.stop_reason == "max_tokens"
1545
  ):
1546
  log(
1547
- f"Deel {chunk_number} bereikte "
1548
- "max_tokens, maar is behouden."
1549
  )
1550
 
1551
  chunks.append(
@@ -1557,9 +1738,9 @@ def generate_script(
1557
  )
1558
 
1559
  yield (
1560
- f"βœ… Deel {chunk_number}/3 afgerond β€” "
1561
- f"{chunk_words} woorden β€” "
1562
- f"{count_words(current_script)} totaal",
1563
  current_script,
1564
  )
1565
 
@@ -1569,8 +1750,8 @@ def generate_script(
1569
 
1570
  if not MIN_WORDS <= total_words <= MAX_WORDS:
1571
  yield (
1572
- f"πŸ”§ Totale lengte is {total_words} woorden; "
1573
- "laatste actuele lengtecorrectie wordt uitgevoerd…",
1574
  current_script,
1575
  )
1576
 
@@ -1597,11 +1778,12 @@ def generate_script(
1597
  text=current_script,
1598
  cutoff_date=cutoff_date,
1599
  current_date=current_date,
 
1600
  )
1601
 
1602
  window_text = (
1603
- f"nieuwsperiode {cutoff_date.isoformat()} "
1604
- f"t/m {current_date.isoformat()}"
1605
  )
1606
 
1607
  if (
@@ -1609,28 +1791,28 @@ def generate_script(
1609
  and not warnings
1610
  ):
1611
  status = (
1612
- f"βœ… Gereed β€” {total_words} woorden β€” "
1613
  f"{window_text} β€” 4x {CHANNEL_NAME} β€” "
1614
  "2 vragen met Discover Tube"
1615
  )
1616
 
1617
  elif MIN_WORDS <= total_words <= MAX_WORDS:
1618
  status = (
1619
- f"⚠️ Gereed β€” {total_words} woorden β€” "
1620
- f"{window_text}. Controleer: "
1621
  + "; ".join(warnings)
1622
  )
1623
 
1624
  else:
1625
  warning_text = (
1626
- f" Controleer ook: {'; '.join(warnings)}"
1627
  if warnings
1628
  else ""
1629
  )
1630
 
1631
  status = (
1632
- f"⚠️ Gereed β€” {total_words} woorden. "
1633
- f"Gewenst: {MIN_WORDS}–{MAX_WORDS}. "
1634
  f"{window_text}."
1635
  + warning_text
1636
  )
@@ -1639,34 +1821,34 @@ def generate_script(
1639
 
1640
  except anthropic.AuthenticationError:
1641
  yield (
1642
- "❌ De Anthropic API-key is ongeldig.",
1643
  current_script,
1644
  )
1645
 
1646
  except anthropic.PermissionDeniedError:
1647
  yield (
1648
- "❌ Je Anthropic-account heeft geen toegang "
1649
- "tot dit model of websearch.",
1650
  current_script,
1651
  )
1652
 
1653
  except anthropic.RateLimitError:
1654
  yield (
1655
- "❌ De Anthropic rate- of usage-limiet is bereikt. "
1656
- "Controleer je billing.",
1657
  current_script,
1658
  )
1659
 
1660
  except anthropic.APITimeoutError:
1661
  yield (
1662
- f"❌ Claude reageerde niet binnen "
1663
  f"{API_TIMEOUT_SECONDS} seconden.",
1664
  current_script,
1665
  )
1666
 
1667
  except anthropic.APIConnectionError:
1668
  yield (
1669
- "❌ Er kon geen verbinding worden gemaakt met Claude.",
1670
  current_script,
1671
  )
1672
 
@@ -1676,43 +1858,43 @@ def generate_script(
1676
 
1677
  if "web search is not enabled" in lower_error:
1678
  message = (
1679
- "❌ Websearch staat niet aan voor "
1680
- "je Anthropic-organisatie."
1681
  )
1682
 
1683
  elif "credit balance" in lower_error:
1684
  message = (
1685
- "❌ Je Anthropic API-tegoed is onvoldoende."
1686
  )
1687
 
1688
  else:
1689
  message = (
1690
- f"❌ Anthropic heeft het verzoek "
1691
- f"afgewezen: {error_text}"
1692
  )
1693
 
1694
  yield message, current_script
1695
 
1696
  except anthropic.APIStatusError as exc:
1697
  yield (
1698
- f"❌ Anthropic API-fout "
1699
  f"{exc.status_code}: {exc.message}",
1700
  current_script,
1701
  )
1702
 
1703
  except Exception as exc:
1704
  log(
1705
- f"Onverwachte fout: {exc}"
1706
  )
1707
 
1708
  yield (
1709
- f"❌ Er ging iets fout: {exc}",
1710
  current_script,
1711
  )
1712
 
1713
 
1714
  # =========================================================
1715
- # TIMER EN INTERFACE
1716
  # =========================================================
1717
 
1718
 
@@ -1723,7 +1905,7 @@ def start_run():
1723
  start_time,
1724
  True,
1725
  format_elapsed(0),
1726
- "πŸš€ Opdracht wordt gestart…",
1727
  "",
1728
  gr.Button(
1729
  interactive=False,
@@ -1771,6 +1953,8 @@ def clear_interface():
1771
  "",
1772
  None,
1773
  DEFAULT_RECENCY_OPTION,
 
 
1774
  "",
1775
  "",
1776
  0.0,
@@ -1785,11 +1969,11 @@ def clear_interface():
1785
  with gr.Blocks() as demo:
1786
  gr.Markdown(
1787
  """
1788
- # Claude Current News Script Writer
1789
 
1790
- Onderzoekt uitsluitend recente bronnen en schrijft een direct,
1791
- informatierijk, menselijk en high-retention YouTube-script van
1792
- 2.900–3.200 woorden.
1793
  """
1794
  )
1795
 
@@ -1803,7 +1987,7 @@ informatierijk, menselijk en high-retention YouTube-script van
1803
 
1804
  with gr.Row():
1805
  title_input = gr.Textbox(
1806
- label="🎯 Videotitel",
1807
  placeholder=(
1808
  "Scientists Are Monitoring a Mysterious Change "
1809
  "Beneath the Great Lakes"
@@ -1814,19 +1998,40 @@ informatierijk, menselijk en high-retention YouTube-script van
1814
  model_input = gr.Dropdown(
1815
  choices=MODEL_OPTIONS,
1816
  value="claude-sonnet-5",
1817
- label="🧠 Claude-model",
1818
  )
1819
 
1820
  recency_input = gr.Dropdown(
1821
  choices=list(RECENCY_OPTIONS.keys()),
1822
  value=DEFAULT_RECENCY_OPTION,
1823
- label="πŸ“° Nieuwsperiode",
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1824
  )
1825
 
1826
  style_file_input = gr.File(
1827
  label=(
1828
- "πŸ“„ Upload een handgemaakt voorbeeldscript "
1829
- "voor stijlinspiratie (.docx of .txt)"
1830
  ),
1831
  file_types=[
1832
  ".docx",
@@ -1837,11 +2042,11 @@ informatierijk, menselijk en high-retention YouTube-script van
1837
 
1838
  with gr.Row():
1839
  clear_button = gr.Button(
1840
- "Wissen"
1841
  )
1842
 
1843
  generate_button = gr.Button(
1844
- "πŸš€ Genereer",
1845
  variant="primary",
1846
  )
1847
 
@@ -1852,13 +2057,13 @@ informatierijk, menselijk en high-retention YouTube-script van
1852
  )
1853
 
1854
  elapsed_output = gr.Textbox(
1855
- label="Verstreken tijd",
1856
  value=format_elapsed(0),
1857
  interactive=False,
1858
  )
1859
 
1860
  script_output = gr.Textbox(
1861
- label="Definitief script",
1862
  lines=35,
1863
  interactive=False,
1864
  buttons=[
@@ -1898,6 +2103,8 @@ informatierijk, menselijk en high-retention YouTube-script van
1898
  style_file_input,
1899
  model_input,
1900
  recency_input,
 
 
1901
  ],
1902
  outputs=[
1903
  status_output,
@@ -1926,6 +2133,8 @@ informatierijk, menselijk en high-retention YouTube-script van
1926
  title_input,
1927
  style_file_input,
1928
  recency_input,
 
 
1929
  status_output,
1930
  script_output,
1931
  start_time_state,
 
12
 
13
 
14
  # =========================================================
15
+ # SETTINGS
16
  # =========================================================
17
 
18
  MIN_WORDS = 2900
 
39
  ]
40
 
41
  RECENCY_OPTIONS = {
42
+ "Last 30 days": 30,
43
+ "Last 90 days": 90,
44
+ "Last 180 days": 180,
45
+ "Last 365 days": 365,
46
  }
47
 
48
+ DEFAULT_RECENCY_OPTION = "Last 90 days"
49
+
50
+ NEWS_BALANCE_OPTIONS = {
51
+ "Documentary-first β€” fewer dates": {
52
+ "recent_anchor_min": 1,
53
+ "recent_anchor_max": 3,
54
+ "recent_narration_share": "roughly 20–35 percent",
55
+ "date_mentions_min": 1,
56
+ "date_mentions_max": 4,
57
+ "current_source_target": "3–6",
58
+ "description": (
59
+ "Use recent events as selective anchors, but let most of the script focus "
60
+ "on topography, mechanisms, regional consequences, scientific explanation, "
61
+ "and broader documentary context."
62
+ ),
63
+ },
64
+ "Balanced β€” documentary + recent updates": {
65
+ "recent_anchor_min": 2,
66
+ "recent_anchor_max": 4,
67
+ "recent_narration_share": "roughly 35–50 percent",
68
+ "date_mentions_min": 2,
69
+ "date_mentions_max": 6,
70
+ "current_source_target": "5–8",
71
+ "description": (
72
+ "Blend a few strong current developments with broader documentary science. "
73
+ "Recent news should move the story forward without making every section "
74
+ "sound date-driven."
75
+ ),
76
+ },
77
+ "News-first β€” more current detail": {
78
+ "recent_anchor_min": 4,
79
+ "recent_anchor_max": 6,
80
+ "recent_narration_share": "roughly 55–75 percent",
81
+ "date_mentions_min": 4,
82
+ "date_mentions_max": 9,
83
+ "current_source_target": "7–12",
84
+ "description": (
85
+ "Keep a strong current-news layer across most of the script while still "
86
+ "using documentary explanation and scientific context."
87
+ ),
88
+ },
89
+ }
90
+
91
+ DEFAULT_NEWS_BALANCE_OPTION = "Balanced β€” documentary + recent updates"
92
 
93
+ HOOK_OPTIONS = [
94
+ "Auto β€” choose the strongest opening",
95
+ "Topography / geography opening",
96
+ "Date / current event opening",
97
+ "News clip continuation",
98
+ "Hard fact / scale opening",
99
+ ]
100
+
101
+ DEFAULT_HOOK_OPTION = "Auto β€” choose the strongest opening"
102
+
103
+ # The three minimum values add up to exactly 2,900 words.
104
+ # The maximum values add up to exactly 3,200 words.
105
  CHUNK_SPECS = [
106
  {
107
  "number": 1,
 
111
  "purpose": (
112
  "Write the direct introduction of 120–160 words and the first "
113
  "two titled sections. Mention Discover Tube exactly once in the "
114
+ "introduction. Follow the selected hook strategy. After the introduction, "
115
+ "move into the strongest material for the story: this may be a recent "
116
+ "development, topography, a mechanism, a verified hard fact, or a combination. "
117
+ "Make the first two sections deliberately unequal in length."
118
  ),
119
  },
120
  {
 
123
  "maximum": 1100,
124
  "target": 1050,
125
  "purpose": (
126
+ "Write the next three titled sections. Deliver the densest scientific "
127
+ "explanations, analysis, named research or monitoring when useful, practical "
128
+ "consequences, and the planned amount of current-news material. Place the "
129
+ "40-percent Discover Tube subscribe sentence inside this chunk. Make all "
130
+ "three sections clearly unequal in length. Do not recap part 1."
131
  ),
132
  },
133
  {
 
137
  "target": 1050,
138
  "purpose": (
139
  "Write the final two titled sections and an ending of 100–160 words. "
140
+ "Resolve the central documentary question, explain the most important "
141
+ "implications, and include what happens next or what is being monitored "
142
+ "when the evidence supports it. Place one Discover Tube audience question "
143
+ "around 75 percent of the full video. In the final 100 words, mention "
144
+ "Discover Tube once more, include a brief subscribe request, and ask one "
145
+ "concrete question for viewers to answer in the comments. Make the final "
146
+ "two sections unequal in length."
147
  ),
148
  },
149
  ]
150
 
151
 
152
  # =========================================================
153
+ # LOGGING AND CORE UTILITIES
154
  # =========================================================
155
 
156
 
 
164
 
165
  if not api_key:
166
  raise ValueError(
167
+ "ANTHROPIC_API_KEY is missing. Add it via "
168
  "Hugging Face Space β†’ Settings β†’ Variables and secrets."
169
  )
170
 
 
185
  def format_elapsed(seconds: int, finished: bool = False) -> str:
186
  seconds = max(0, int(seconds))
187
  minutes, remaining_seconds = divmod(seconds, 60)
188
+ prefix = "βœ… Total generation time" if finished else "⏱️ Elapsed time"
189
 
190
  return (
191
  f"{prefix}: {seconds} seconden "
 
223
  )
224
 
225
 
226
+ def resolve_news_balance(option: str) -> dict:
227
+ return NEWS_BALANCE_OPTIONS.get(
228
+ option,
229
+ NEWS_BALANCE_OPTIONS[DEFAULT_NEWS_BALANCE_OPTION],
230
+ )
231
+
232
+
233
+ def build_hook_requirements(hook_option: str) -> str:
234
+ if hook_option == "Topography / geography opening":
235
+ return """
236
+ HOOK STRATEGY β€” TOPOGRAPHY / GEOGRAPHY
237
+
238
+ - Open by placing the viewer physically inside the landscape: terrain, coastline, basin,
239
+ mountain chain, fault zone, lake system, river corridor, or other defining geography.
240
+ - The first one or two sentences should be visual, concrete, and spatial rather than date-led.
241
+ - Do not put an exact calendar date in the first two sentences.
242
+ - By sentence three or four, connect that geography to the central danger, change, mystery,
243
+ or scientific question.
244
+ - Do not sound like a travel documentary; the geography must immediately serve the story.
245
+ """.strip()
246
+
247
+ if hook_option == "Date / current event opening":
248
+ return """
249
+ HOOK STRATEGY β€” DATE / CURRENT EVENT
250
+
251
+ - Start with one verified recent event, measurement, warning, decision, or discovery.
252
+ - Use an exact date in the opening sentence only when the evidence pack supports it and the
253
+ date genuinely makes the event more immediate.
254
+ - Do not continue stacking dates after the opening. Move quickly from the event into the
255
+ larger documentary question and physical mechanism.
256
+ """.strip()
257
+
258
+ if hook_option == "News clip continuation":
259
+ return """
260
+ HOOK STRATEGY β€” NEWS CLIP CONTINUATION
261
+
262
+ - Write the first line as a seamless continuation from a short news report that the viewer
263
+ has just watched immediately before the narration begins.
264
+ - Do not repeat a headline or re-summarize the whole report. Widen the frame immediately.
265
+ - You may use a bridge such as β€œWhat you just saw is only the visible part of a much larger
266
+ story,” but vary the wording naturally.
267
+ - Never invent details about the unseen clip. Connect only to verified material in the
268
+ evidence pack.
269
+ - Within the first three or four sentences, reveal the broader geographic or scientific
270
+ significance behind that news event.
271
+ """.strip()
272
+
273
+ if hook_option == "Hard fact / scale opening":
274
+ return """
275
+ HOOK STRATEGY β€” HARD FACT / SCALE
276
+
277
+ - Open with one surprising, verified measurement, physical fact, scale, consequence, or
278
+ contrast that immediately reframes the topic.
279
+ - The first line should stand on its own without hype or an unsupported superlative.
280
+ - Explain why the fact matters within the next two or three sentences, then move into the
281
+ central story.
282
+ - Do not force a date into the hook unless it is essential to the fact.
283
+ """.strip()
284
+
285
+ return """
286
+ HOOK STRATEGY β€” AUTO
287
+
288
+ - Choose the strongest opening for this specific topic from these three self-contained modes:
289
+ topography / geography, date / current event, or hard fact / scale.
290
+ - Do NOT choose news clip continuation automatically, because that mode assumes the editor
291
+ will place a real news clip immediately before the narration.
292
+ - Do not automatically choose a news-date opening. Prefer the mode that creates the clearest
293
+ immediate mental picture and strongest central tension from the evidence.
294
+ - State the chosen hook mode in the INTERNAL plan, then follow it consistently in chunk 1.
295
+ """.strip()
296
+
297
+
298
  def get_news_window(recency_days: int) -> tuple[date, date]:
299
  current_date = date.today()
300
  cutoff_date = current_date - timedelta(days=recency_days)
 
368
  text: str,
369
  cutoff_date: date,
370
  current_date: date,
371
+ news_balance_option: str,
372
  ) -> list[str]:
373
  warnings = []
374
 
 
389
 
390
  if channel_mentions != 4:
391
  warnings.append(
392
+ f"{CHANNEL_NAME} appears {channel_mentions}x instead of 4x"
393
  )
394
 
395
  if branded_questions != 2:
396
  warnings.append(
397
+ f"questions containing {CHANNEL_NAME}: "
398
+ f"{branded_questions} instead of 2"
399
  )
400
 
401
  if subscribe_mentions != 2:
402
  warnings.append(
403
+ f"subscribe appears {subscribe_mentions}x instead of 2x"
404
  )
405
 
406
  if len(old_years) > MAX_OLD_YEAR_MENTIONS:
407
  unique_old_years = sorted(set(old_years))
408
 
409
  warnings.append(
410
+ "too many older calendar years mentioned: "
411
  + ", ".join(
412
  str(year)
413
  for year in unique_old_years[:8]
414
  )
415
  )
416
 
417
+ # Only the news-first mode requires an explicit current-year mention.
418
+ # The lighter modes are intentionally allowed to sound less date-driven.
419
+ if (
420
+ news_balance_option == "News-first β€” more current detail"
421
+ and current_year_mentions == 0
422
+ ):
423
  warnings.append(
424
+ f"the current year {current_date.year} is not mentioned"
425
  )
426
 
427
  return warnings
428
 
429
 
430
  # =========================================================
431
+ # GLOBAL WRITING RULES
432
  # =========================================================
433
 
434
 
435
  def build_global_writing_requirements(
436
  cutoff_date: date,
437
  current_date: date,
438
+ news_balance_option: str,
439
+ hook_option: str,
440
  ) -> str:
441
+ balance = resolve_news_balance(news_balance_option)
442
+ hook_requirements = build_hook_requirements(hook_option)
443
+
444
  return f"""
445
+ Write for a high-retention science and geography documentary with a selective current-news
446
+ layer. The narration must feel human-written, purposeful, conversational, and factual.
447
+ Preserve the existing direct Discover Tube writing style; change the balance of material,
448
+ not the voice.
449
+
450
+ NEWS BALANCE β€” {news_balance_option}
451
+
452
+ - {balance['description']}
453
+ - Use recent news as the true narrative anchor in approximately
454
+ {balance['recent_anchor_min']}–{balance['recent_anchor_max']} of the seven titled sections.
455
+ - Across the full narration, recent-event material should occupy
456
+ {balance['recent_narration_share']} of the script, not the entire script.
457
+ - Aim for only {balance['date_mentions_min']}–{balance['date_mentions_max']} explicit calendar-
458
+ date references in the spoken script. This is a narration target, not a research limit.
459
+ - Do not mention a publication date merely to prove that a source is recent.
460
+ - Dates belong in narration only when chronology, escalation, timing, or a specific event
461
+ genuinely depends on them.
462
+ - It is fine for several paragraphs or complete documentary sections to contain no dates.
463
+
464
+ RECENT NEWS WINDOW
465
+
466
+ - A claim described as recent, current, new, just announced, newly measured, newly warned,
467
+ or newly discovered must be supported by a source published between
468
+ {cutoff_date.isoformat()} and {current_date.isoformat()}.
469
+ - Never make an old event sound new because a recent article mentioned it.
470
+ - Publication date and event date are different; keep them distinct internally.
471
+ - Older authoritative research or official background may be used for durable scientific,
472
+ geographic, historical, or engineering context. Never label that material as recent.
473
+ - Historical context may use no more than {MAX_HISTORICAL_CONTEXT_PERCENT} percent of the
474
+ complete script and should avoid unnecessary calendar-year lists.
475
  - Do not mention more than {MAX_OLD_YEAR_MENTIONS} calendar years from before
476
+ {cutoff_date.year} in the complete script unless the title absolutely requires a historical
477
+ chronology.
478
+
479
+ DOCUMENTARY DEPTH
480
+
481
+ - Build one continuous story instead of seven isolated mini-essays.
482
+ - The non-news portions should add real documentary value: topography, physical geography,
483
+ mechanisms, geology, hydrology, infrastructure, ecological consequences, regional scale,
484
+ scientific uncertainty, monitoring methods, or what the evidence means for people.
485
+ - Do not use generic textbook filler. Every paragraph must add a specific fact, mechanism,
486
+ example, consequence, measurement, research result, or documented uncertainty.
487
+ - Use named locations, agencies, datasets, projects, researchers, and measurements when they
488
+ improve clarity, but do not turn the script into a list of source metadata.
489
+ - Explain why important facts matter and how the mechanism works.
490
+ - Preserve labels such as confirmed, preliminary, estimated, disputed, or unverified.
491
+ - Fully paraphrase the evidence pack and the style sample.
492
+
493
+ INTRODUCTION β€” 120–160 WORDS
494
+
495
+ - Follow the selected hook strategy below.
496
+ - The intro must contain exactly one natural sentence explaining what Discover Tube does:
497
+ it makes documentary videos that explain major natural, geographic, or scientific stories
498
+ while keeping viewers up to date on important recent developments. The wording may vary,
499
+ but that purpose must be clear in ONE sentence.
500
+ - That Discover Tube sentence is not a subscription request and not a question.
501
+ - Do not overload the intro with dates. One exact date is enough when the selected hook truly
502
+ needs it; otherwise use none.
503
+ - The FINAL sentence of the intro must land strongly in one of two ways:
504
+ (A) a specific central question the documentary will answer, OR
505
+ (B) a verified hard fact or consequence that raises the stakes.
506
+ - Choose A or B based on what is stronger for the topic. Do not default to the same ending
507
+ style every time.
508
+
509
+ {hook_requirements}
510
 
511
  CENTRAL STORY AND RETENTION
512
 
513
+ - Every section must answer part of the central documentary question and create a reason to
514
+ hear the next section.
515
+ - End sections 1 through 6 with a content-based open loop or cliffhanger that leads directly
516
+ into the next topic.
517
+ - Vary the transition method. Use a new measurement, unresolved result, location, consequence,
518
+ scientific limitation, official decision, physical mechanism, or competing explanation.
 
519
  - Do not end every section with a rhetorical question.
520
  - Pay off earlier open loops later in the script so the story feels intentional.
521
+ - Put the strongest verified material in the first third, whether it is current news,
522
+ topography, a hard measurement, or an important scientific mechanism.
523
+ - Keep retention high through information, escalation, contrast, and consequence, not empty
524
+ mystery language.
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
525
 
526
  UNEQUAL TOPIC LENGTHS
527
 
528
  - The seven titled sections must not be equal in size.
529
+ - Give the most important or scientifically rich topics substantially more space.
 
530
  - Use shorter sections as bridges, reveals, or transitions.
531
  - The writing plan must assign a distinct word budget to every section.
532
  - The largest section should be at least 150 words longer than the shortest section.
 
537
  - Keep most paragraphs between one and four sentences.
538
  - Use natural sentence variation and active language.
539
  - Avoid sounding like a report, literature review, or AI summary.
540
+ - Introduce researchers through what they did, measured, found, announced, or questioned.
 
541
  - Use concrete nouns instead of vague references when the evidence gives a name.
542
+ - Do not overuse em dashes, three-part dramatic lists, fragments, or rhetorical questions.
543
+ - Avoid formulaic phrases such as β€œlet that sink in,” β€œhere is where things get interesting,”
544
+ β€œthe truth is,” β€œscientists are watching,” β€œmore questions than answers,” or β€œonly time
545
+ will tell.”
 
546
 
547
  COMPARISONS
548
 
 
556
 
557
  - Use the exact phrase β€œ{CHANNEL_NAME}” exactly four times in the complete script.
558
  - Exactly two questions in the complete script may contain β€œ{CHANNEL_NAME}”.
559
+ - Placement 1: once in the introduction, inside the one-sentence channel explanation. Do not
560
  ask for a subscription or comment there.
561
  - Placement 2: around 40 percent of the video, as one brief subscribe sentence.
562
  This occurrence is not a question and does not ask for comments.
563
+ - Placement 3: around 75 percent of the video, inside one topic-specific audience question.
564
+ Do not ask for a subscription in that occurrence.
565
+ - Placement 4: within the final 100 words. Include a brief subscribe request and ask one
566
+ concrete comment question. The question itself must contain β€œ{CHANNEL_NAME}”.
567
  - Do not mention β€œ{CHANNEL_NAME}” anywhere else.
568
  - Do not use the word subscribe outside placements 2 and 4.
569
  """.strip()
570
 
571
 
572
  # =========================================================
573
+ # STYLE SAMPLE
574
  # =========================================================
575
 
576
 
577
  def load_style_file(filepath: Optional[str]) -> str:
578
  default_style = """
579
+ Write direct, information-dense spoken English for a high-retention YouTube
580
+ documentary with selective current-news elements. Use short and medium-length
581
+ sentences, brief paragraphs, concrete details, strong geographic or scientific
582
+ explanation, and connected transitions. Sound like a skilled human writer, not
583
+ an academic summary or an AI narrator. Build curiosity through evidence, scale,
584
+ mechanisms, consequences, and well-placed recent developments.
585
  """.strip()
586
 
587
  if not filepath:
 
618
 
619
  else:
620
  raise ValueError(
621
+ "Only .docx and .txt files are supported."
622
  )
623
 
624
  return (
 
629
 
630
  except Exception as exc:
631
  raise ValueError(
632
+ f"The style document could not be read: {exc}"
633
  ) from exc
634
 
635
 
636
  # =========================================================
637
+ # CLAUDE REQUESTS
638
  # =========================================================
639
 
640
 
 
647
  return
648
 
649
  raise RuntimeError(
650
+ "Claude reached the maximum output length."
651
  )
652
 
653
  if response.stop_reason == "refusal":
654
  raise RuntimeError(
655
+ "Claude refused this request."
656
  )
657
 
658
  if response.stop_reason == "pause_turn":
659
  raise RuntimeError(
660
+ "Claude did not complete the request."
661
  )
662
 
663
 
 
707
  and attempt == 0
708
  ):
709
  log(
710
+ "Web research returned pause_turn; "
711
+ "performing one continuation."
712
  )
713
 
714
  messages.append(
 
729
 
730
  if not text:
731
  raise RuntimeError(
732
+ "Claude returned no usable text."
733
  )
734
 
735
  return text, response
736
 
737
  raise RuntimeError(
738
+ "Claude could not complete the web research. "
739
+ "Try a more specific title."
740
  )
741
 
742
 
 
784
 
785
  if response.stop_reason == "max_tokens":
786
  log(
787
+ "A writing pass reached max_tokens; "
788
+ "the existing text is being kept."
789
  )
790
 
791
  yield final_text, response
 
796
 
797
 
798
  # =========================================================
799
+ # PHASE 1 β€” DOCUMENTARY RESEARCH + CURRENT NEWS
800
  # =========================================================
801
 
802
 
 
805
  model: str,
806
  title: str,
807
  recency_days: int,
808
+ news_balance_option: str,
809
  ) -> str:
810
  cutoff_date, current_date = get_news_window(
811
  recency_days
812
  )
813
+ balance = resolve_news_balance(news_balance_option)
814
 
815
  prompt = f"""
816
  Today's date is {current_date.isoformat()}.
 
819
 
820
  "{title}"
821
 
822
+ Create an INTERNAL evidence pack for a factual, high-retention documentary of
823
  approximately {TARGET_WORDS} words. Do not write the script.
824
 
825
+ SELECTED NEWS BALANCE
826
+
827
+ {news_balance_option}
828
+ {balance['description']}
829
+
830
+ The final script should use recent news as a genuine anchor in approximately
831
+ {balance['recent_anchor_min']}–{balance['recent_anchor_max']} of seven sections, not in every
832
+ section. Recent-event narration should occupy {balance['recent_narration_share']} of the
833
+ finished script. The rest may use durable, authoritative documentary context.
834
+
835
+ CURRENT NEWS WINDOW
836
+
837
+ - Treat {cutoff_date.isoformat()} through {current_date.isoformat()} as the ONLY allowed
838
+ publication window for anything described as recent, new, current, newly measured, newly
839
+ announced, newly warned, or newly discovered.
840
+ - Current-news anchor sources must be dated and must contain genuinely new information.
841
+ - Distinguish source publication date from event or research date.
842
+ - A recent article that merely repeats an old fact does not make that old fact current news.
843
+ - Do not describe an old event as recent because it was republished or newly summarized.
844
+
845
+ AUTHORITATIVE DOCUMENTARY BACKGROUND
846
+
847
+ - You MAY use older authoritative sources for stable topography, geology, hydrology,
848
+ engineering, historical context, long-running hazards, scientific mechanisms, and baseline
849
+ measurements when needed to explain the story.
850
+ - Prefer official agencies, universities, peer-reviewed research, recognized scientific
851
+ institutions, and high-quality datasets.
852
+ - Clearly label this material internally as BACKGROUND, not CURRENT.
853
+ - Do not use old background to manufacture a fake news angle.
854
+ - Avoid weak SEO explainers, copied summaries, and sensational unsupported claims.
855
 
856
  RECENCY DECISION
857
 
 
860
  RECENCY VERDICT: SUFFICIENT
861
  RECENCY VERDICT: INSUFFICIENT
862
 
863
+ Return SUFFICIENT when there is enough reliable current material to support the selected news
864
+ balance plus enough authoritative documentary evidence to build seven connected sections.
865
+ For the lighter modes, one or two strong recent anchors can be enough; do NOT require seven
866
+ separate recent stories.
867
 
868
  If the verdict is INSUFFICIENT:
869
 
870
+ - Explain briefly why the selected current-news layer cannot be supported.
871
+ - Provide three alternative title angles that preserve the same broad topic but are better
872
+ supported by the available current evidence.
873
+ - Do not fill the evidence pack with stale material presented as news.
874
 
875
  TITLE AUDIT
876
 
 
880
  TITLE VERDICT: PARTLY SUPPORTED
881
  TITLE VERDICT: UNSUPPORTED
882
 
883
+ Continued activity is not acceleration, improved detection is not acceleration, and a new
884
+ publication about old data is not a new physical event. Do not assume scientists are afraid,
885
+ shocked, baffled, or issuing warnings unless reliable evidence explicitly supports it.
 
886
 
887
  SOURCE PRIORITY
888
 
889
  Use no more than {MAX_WEB_SEARCHES} focused searches. Prioritize:
890
 
891
+ 1. Official agency alerts, releases, datasets, maps, monitoring pages, and project updates.
892
+ 2. University and scientific-institution research pages.
893
+ 3. Peer-reviewed studies and recognized scientific journals.
894
+ 4. Government decisions, infrastructure projects, legislation, funding, and operations.
895
  5. Reputable news reporting for current human and regional context.
896
 
 
 
 
897
  BUILD THIS EVIDENCE PACK
898
 
899
  1. RECENCY VERDICT.
900
  2. TITLE VERDICT.
901
  3. NEWS WINDOW: {cutoff_date.isoformat()} to {current_date.isoformat()}.
902
+ 4. THE CENTRAL DOCUMENTARY STORY in 120–180 words, showing how the current-news layer fits
903
+ into the larger geographic or scientific story.
904
+ 5. CURRENT NEWS LEDGER with roughly {balance['current_source_target']} strong sources when
905
+ available. For every source include publication date, event/research date, institution,
906
+ location, the genuinely new information, and certainty level.
907
+ 6. DOCUMENTARY BACKGROUND LEDGER with 4–10 authoritative sources for durable topography,
908
+ mechanisms, baseline science, historical context, or regional consequences. Include dates
909
+ internally, but mark them BACKGROUND and do not imply recency.
910
+ 7. FACT BANK of 35–50 specific, non-duplicative facts. Label every fact CURRENT or
911
+ BACKGROUND. Include location, source/institution, certainty, and why it matters.
912
+ 8. OPENING MATERIAL BANK with one strong evidence-based candidate for each opening mode:
913
+ - TOPOGRAPHY / GEOGRAPHY;
914
+ - DATE / CURRENT EVENT;
915
+ - NEWS CLIP CONTINUATION;
916
+ - HARD FACT / SCALE.
917
+ Also include two strong intro-ending candidates: one central question and one verified hard
918
+ fact/consequence.
919
+ 9. RECENT DATA BLOCK containing the strongest current figures and measurements that are worth
920
+ mentioning in narration. Do NOT include dates that add no storytelling value.
921
+ 10. SCIENTIFIC EXPLANATIONS needed to understand the story: mechanism, method, uncertainty,
922
+ competing explanations, and limitations.
923
+ 11. TOPOGRAPHY AND GEOGRAPHY details that can make the documentary visually specific.
924
+ 12. HUMAN, environmental, economic, infrastructure, policy, or safety consequences.
925
+ 13. At least six candidate factual comparisons with checked units. The script will select
926
+ exactly three.
927
+ 14. ESSENTIAL HISTORICAL CONTEXT, limited to what genuinely improves understanding and short
928
+ enough to stay within {MAX_HISTORICAL_CONTEXT_PERCENT} percent of the final script.
929
+ 15. CLAIMS TO AVOID.
930
+ 16. EXTRA VERIFIED FACTS that can be used to reach the word target without repetitive dates,
931
+ stale filler, or generic textbook language.
932
+
933
+ Do not copy source sentences. Do not write dramatic narration. The evidence pack should be
934
+ rich enough to support both documentary depth and the selected amount of current news.
935
  """.strip()
936
 
937
  web_search_tool = [
 
947
  ]
948
 
949
  log(
950
+ "Phase 1 started: documentary research with a current-news layer "
951
+ f"({cutoff_date.isoformat()} to {current_date.isoformat()}; "
952
+ f"{news_balance_option})."
953
  )
954
 
955
  research, response = request_text(
956
  client=client,
957
  model=model,
958
  system_prompt=(
959
+ "You are a rigorous documentary researcher with strong current-news judgment. "
960
+ "Separate genuinely current developments from durable background. Build enough "
961
+ "topographic, scientific, human, and recent evidence for a compelling documentary "
962
+ "without forcing every section to be news-driven."
 
963
  ),
964
  user_prompt=prompt,
965
  max_tokens=RESEARCH_MAX_TOKENS,
 
976
 
977
  if response.stop_reason == "max_tokens":
978
  log(
979
+ "Research reached max_tokens; the completed research is being used."
 
980
  )
981
 
982
  if recency_verdict == "INSUFFICIENT":
983
  raise RuntimeError(
984
+ "There is not enough reliable current material for the selected news balance. "
985
+ "Choose a wider news window, a lighter news balance, or a better-supported title."
 
986
  )
987
 
988
  if recency_verdict != "SUFFICIENT":
989
  raise RuntimeError(
990
+ "Claude could not confirm that there is enough reliable material. Try a broader "
991
+ "news window, a lighter news balance, or a more specific title."
 
992
  )
993
 
994
  if research_words < 800:
995
  raise RuntimeError(
996
+ "Claude returned too little usable research. Make the title more specific or "
997
+ "choose a broader news window."
998
  )
999
 
1000
  log(
1001
+ f"Phase 1 complete: {research_words} words of research."
 
1002
  )
1003
 
1004
  return research
1005
 
1006
 
1007
  # =========================================================
1008
+ # PHASE 2 β€” SCRIPT PLAN WITH FIXED WORD BUDGETS
1009
  # =========================================================
1010
 
1011
 
 
1017
  cutoff_date: date,
1018
  current_date: date,
1019
  global_requirements: str,
1020
+ news_balance_option: str,
1021
+ hook_option: str,
1022
  ) -> str:
1023
+ balance = resolve_news_balance(news_balance_option)
1024
+
1025
  prompt = f"""
1026
  Create a concise but detailed INTERNAL writing plan for this proposed title:
1027
 
1028
  "{title}"
1029
 
1030
+ <evidence_pack>
1031
  {research}
1032
+ </evidence_pack>
1033
 
1034
+ The final spoken script must contain 2,900–3,200 words. Build exactly three writing chunks
1035
+ with these budgets:
1036
 
1037
  CHUNK 1 β€” 900–1,000 words
1038
  - A direct introduction of 120–160 words.
1039
  - Two titled sections.
1040
+ - Follow the selected hook: {hook_option}.
1041
+ - After the introduction, move into the strongest material for the story instead of
1042
+ automatically dumping dates or source chronology.
1043
 
1044
  CHUNK 2 β€” 1,000–1,100 words
1045
  - Three titled sections.
1046
+ - The densest scientific explanation, analysis, regional consequences, named research or
1047
+ monitoring, and selected current developments.
1048
 
1049
  CHUNK 3 β€” 1,000–1,100 words
1050
  - Two titled sections.
1051
+ - A connected ending of 100–160 words that resolves the story and explains what matters next.
1052
 
1053
  That produces exactly seven titled sections in the full script.
1054
 
1055
  {global_requirements}
1056
 
1057
+ NEWS / DOCUMENTARY ALLOCATION
1058
+
1059
+ - Mark every section internally as either NEWS ANCHOR or DOCUMENTARY CORE.
1060
+ - Use NEWS ANCHOR for approximately {balance['recent_anchor_min']}–
1061
+ {balance['recent_anchor_max']} sections total. Do not force news into all seven sections.
1062
+ - Use DOCUMENTARY CORE sections for topography, physical mechanisms, scientific explanation,
1063
+ regional consequences, long-running systems, infrastructure, or other durable material.
1064
+ - Recent-event narration across the whole script should be {balance['recent_narration_share']}.
1065
+ - Plan only {balance['date_mentions_min']}–{balance['date_mentions_max']} explicit calendar-date
1066
+ references for the spoken narration. Publication dates can remain internal in the plan.
1067
+ - Never create a standalone β€œhistory lesson” section unless history is essential to the title.
1068
+ - Never create a standalone β€œlatest updates” section just to satisfy recency. Blend current
1069
+ developments into the central documentary story.
1070
+
1071
+ INTRO PLAN
1072
+
1073
+ - State the exact hook mode that chunk 1 will use. If the selected hook is AUTO, choose the
1074
+ strongest mode from the evidence pack and record the choice.
1075
+ - Plan the first 3–4 sentences of the intro by function only, not as sample narration.
1076
+ - Reserve exactly one sentence for explaining that Discover Tube makes documentary videos
1077
+ about major natural, geographic, or scientific stories while keeping viewers up to date on
1078
+ important recent developments.
1079
+ - Choose the intro's final sentence type: CENTRAL QUESTION or HARD FACT / CONSEQUENCE.
1080
+ - Do not automatically choose a question every time.
1081
 
1082
  PLAN THE SEVEN SECTIONS AS UNEQUAL TOPICS
1083
 
1084
  - Give every section an exact individual word budget.
1085
  - Do not give neighboring sections similar budgets unless necessary.
1086
+ - Use the largest sections for the most important scientific or geographic material.
1087
  - Use at least two noticeably short bridge sections.
1088
  - The largest section must be at least 150 words longer than the shortest.
1089
 
1090
  FOR EVERY SECTION PROVIDE
1091
 
1092
  - a short, specific title;
1093
+ - ROLE: NEWS ANCHOR or DOCUMENTARY CORE;
 
1094
  - its central purpose;
1095
  - its exact word budget;
1096
+ - the exact facts, measurements, people, locations, topography, and mechanisms it uses;
1097
  - the scientific explanation or analysis it contains;
1098
  - the human or practical consequence;
1099
+ - if it is a NEWS ANCHOR: the current development, publication date, and event date;
1100
+ - if it is DOCUMENTARY CORE: the durable evidence it explains and how it connects to the
1101
+ central story;
1102
+ - whether an explicit date should actually be spoken aloud;
1103
+ - the specific open loop or cliffhanger leading into the next section;
1104
  - any essential historical context, limited to one or two brief points.
1105
 
1106
  ALLOCATION RULES
1107
 
1108
  - Assign every important fact to only one section.
1109
+ - Put the strongest verified material in chunk 1, but that material does not have to be news.
1110
+ - Reserve enough unused evidence for chunks 2 and 3.
1111
  - Select exactly three verified comparisons and assign each to a different section.
1112
+ - Assign at least two named studies, projects, reports, alerts, datasets, or monitoring efforts
1113
+ across the complete plan when evidence supports them. They do not all need to be recent.
1114
+ - Do not create a debunking video. Silently use the strongest accurate angle.
1115
 
1116
  DISCOVER TUBE PLACEMENT PLAN
1117
 
1118
+ 1. Introduction: one natural non-question mention of β€œ{CHANNEL_NAME}” inside the one-sentence
1119
+ explanation of what the channel does.
1120
+ 2. Around 40 percent: one brief non-question subscribe sentence containing β€œ{CHANNEL_NAME}”.
1121
+ 3. Around 75 percent: one topic-specific audience question containing β€œ{CHANNEL_NAME}”.
1122
+ 4. Final 100 words: one brief subscribe request and one concrete comment question; the question
1123
+ itself must contain β€œ{CHANNEL_NAME}”.
 
1124
 
1125
+ Exactly four total mentions of β€œ{CHANNEL_NAME}” and exactly two questions containing it.
 
1126
 
1127
  Keep the complete plan between 1,500 and 2,500 words. Use compact bullet points.
1128
  Do not write sample narration and do not repeat the entire evidence pack.
 
1130
  """.strip()
1131
 
1132
  log(
1133
+ "Phase 2 started: three-part documentary plan with flexible news balance."
1134
  )
1135
 
1136
  plan, response = request_text(
1137
  client=client,
1138
  model=model,
1139
  system_prompt=(
1140
+ "You are a senior documentary editor. Build a connected, high-retention plan that "
1141
+ "preserves a strong human writing style while using only the selected amount of "
1142
+ "current news. Give topography, mechanisms, consequences, and science enough room."
 
1143
  ),
1144
  user_prompt=prompt,
1145
  max_tokens=PLAN_MAX_TOKENS,
 
1149
 
1150
  if response.stop_reason == "max_tokens":
1151
  log(
1152
+ "The script plan reached max_tokens; the completed plan is being used."
 
1153
  )
1154
 
1155
  if count_words(plan) < 400:
1156
  raise RuntimeError(
1157
+ "Claude did not create a usable documentary plan."
1158
  )
1159
 
1160
  log(
1161
+ f"Phase 2 complete: {count_words(plan)} words in the plan."
 
1162
  )
1163
 
1164
  return plan
1165
 
1166
 
1167
  # =========================================================
1168
+ # PHASE 3 β€” THREE SCRIPT CHUNKS
1169
  # =========================================================
1170
 
1171
 
 
1226
 
1227
  if chunk_number == 1:
1228
  continuity_rule = (
1229
+ "Do not print the video title. Write the 120–160 word introduction according "
1230
+ "to the selected hook strategy in the global requirements and the exact hook "
1231
+ "choice recorded in the plan. After the intro, move directly into the planned "
1232
+ "story material without a source-list or date dump."
 
1233
  )
1234
  else:
1235
  continuity_rule = (
1236
+ "Continue naturally from the previous script. Do not write a new introduction, "
1237
+ "do not recap earlier sections, and do not repeat facts."
 
1238
  )
1239
 
1240
  return f"""
1241
+ Write ONLY CHUNK {chunk_number} of the final spoken YouTube documentary.
1242
 
1243
  Proposed title:
1244
  "{title}"
1245
 
1246
+ <evidence_pack>
1247
  {research}
1248
+ </evidence_pack>
1249
 
1250
  <full_writing_plan>
1251
  {plan}
 
1268
  - This chunk must contain between {minimum} and {maximum} words.
1269
  - Aim for {target} words.
1270
  - This is a hard production requirement, not a suggestion.
1271
+ - Before answering, silently count the chunk and keep adding unused verified information,
1272
+ explanation, consequences, topographic detail, or analysis until it reaches at least
1273
+ {minimum} words. Do not add dates merely to fill space.
1274
 
1275
  {global_requirements}
1276
 
1277
+ NEWS / DOCUMENTARY REQUIREMENTS FOR THIS CHUNK
1278
 
1279
+ - Follow the ROLE assignments in the plan: NEWS ANCHOR versus DOCUMENTARY CORE.
1280
+ - Only NEWS ANCHOR material may be narrated as a current development.
1281
+ - Any claim described as recent or current must fall inside the news window
1282
  {cutoff_date.isoformat()} through {current_date.isoformat()}.
1283
+ - DOCUMENTARY CORE material may use authoritative older evidence when the plan marks it as
1284
+ durable background. Never make that material sound newly discovered.
1285
+ - Follow the planned spoken-date budget. Do not mention publication dates unless the audience
1286
+ actually needs them.
1287
+ - Do not turn every named study or agency update into a date sentence.
1288
+ - Use exact dates sparingly; use names, places, measurements, mechanisms, and consequences more
1289
+ often than chronology.
 
 
 
1290
 
1291
  WRITING STANDARD
1292
 
1293
  - {continuity_rule}
1294
  - Use the exact unequal section budgets assigned in the plan.
1295
+ - Every paragraph must add a new fact, example, mechanism, measurement, consequence, event,
1296
+ research result, analysis, topographic detail, or documented uncertainty.
1297
+ - Write straight to the point and explain why the information matters.
1298
  - Use mostly short and medium-length sentences and paragraphs of one to four sentences.
1299
  - Translate technical language into natural spoken English.
1300
+ - Use exact names, places, numbers, and measurements when useful.
1301
+ - Explain the science deeply where the plan assigns it: methods, causal mechanisms,
 
1302
  uncertainty, limitations, competing explanations, and practical implications.
1303
+ - Follow the planned open loops and cliffhangers so each section connects directly to the next.
 
1304
  - Fully paraphrase the evidence and the style sample.
1305
+ - Preserve uncertainty. Do not turn possible, estimated, preliminary, or disputed information
1306
+ into certainty.
1307
  - Do not tell the audience that the proposed title was fact-checked or exaggerated.
1308
  - Use section headings exactly as planned for this chunk.
1309
+ - Use only the comparisons assigned to this chunk. The complete script must contain exactly
1310
+ three factual comparisons in total.
1311
  - Do not include sources, URLs, citations, editor notes, camera directions, or B-roll.
1312
 
1313
  {channel_rules_for_chunk(chunk_number)}
 
1336
  if current_words < minimum:
1337
  operation = (
1338
  f"The chunk is {minimum - current_words} words below the minimum. "
1339
+ "Expand it with unused verified facts, topography, mechanisms, scientific "
1340
+ "explanation, measurements, consequences, or planned current developments "
1341
+ "assigned to this part. Respect the section roles and spoken-date budget."
 
1342
  )
1343
  else:
1344
  operation = (
1345
  f"The chunk is {current_words - maximum} words above the maximum. "
1346
+ "Remove repetition, unnecessary chronology, source-date language, and decorative "
1347
+ "phrasing while preserving important science, geography, current anchors, open "
1348
+ "loops, comparisons, and CTA placement."
1349
  )
1350
 
1351
  return f"""
 
1375
 
1376
  {global_requirements}
1377
 
1378
+ NEWS / DOCUMENTARY BALANCE CHECK
1379
 
1380
+ - Preserve the NEWS ANCHOR and DOCUMENTARY CORE roles from the plan.
1381
+ - Claims narrated as recent or current must be supported inside the window
1382
+ {cutoff_date.isoformat()} through {current_date.isoformat()}.
1383
+ - Durable older evidence may remain when it provides useful scientific, geographic, or
1384
+ historical context and is not presented as recent.
1385
+ - When expanding, prefer unused mechanisms, measurements, topography, consequences, or
1386
+ verified facts over extra date references.
1387
+ - When shortening, remove repetitive chronology and source-date language before removing
1388
+ important science or geographic detail.
1389
 
1390
  Keep the same section purpose, exact headings, unequal topic sizes, scientific
1391
  explanations, analysis, planned comparisons, and content-based cliffhangers.
 
1431
  client=client,
1432
  model=model,
1433
  system_prompt=(
1434
+ "You are a strict documentary editor. Meet the requested word range while "
1435
+ "preserving the selected news balance, factual density, scientific analysis, "
1436
+ "topographic specificity, natural spoken rhythm, open-loop storytelling, and "
1437
+ "exact brand placement. Do not add unnecessary dates as filler."
 
1438
  ),
1439
  user_prompt=prompt,
1440
  max_tokens=REVISION_MAX_TOKENS,
 
1446
 
1447
 
1448
  # =========================================================
1449
+ # TOTAL LENGTH REBALANCING
1450
  # =========================================================
1451
 
1452
 
 
1528
 
1529
 
1530
  # =========================================================
1531
+ # MAIN WORKFLOW
1532
  # =========================================================
1533
 
1534
 
 
1537
  style_file: Optional[str],
1538
  model: str,
1539
  recency_option: str,
1540
+ news_balance_option: str,
1541
+ hook_option: str,
1542
  ):
1543
  current_script = ""
1544
 
1545
  if not title or not title.strip():
1546
+ yield "❌ Enter a video title first.", ""
1547
  return
1548
 
1549
  try:
 
1564
  global_requirements = build_global_writing_requirements(
1565
  cutoff_date=cutoff_date,
1566
  current_date=current_date,
1567
+ news_balance_option=news_balance_option,
1568
+ hook_option=hook_option,
1569
  )
1570
 
1571
  yield (
1572
+ "πŸ”Ž Phase 1/3 β€” gathering documentary research and current updates "
1573
+ f"from {cutoff_date.isoformat()}…",
1574
  "",
1575
  )
1576
 
 
1579
  model=model,
1580
  title=clean_title,
1581
  recency_days=recency_days,
1582
+ news_balance_option=news_balance_option,
1583
  )
1584
 
1585
  yield (
1586
+ "🧭 Phase 2/3 β€” distributing evidence and storytelling "
1587
+ "across three parts…",
1588
  "",
1589
  )
1590
 
 
1596
  cutoff_date=cutoff_date,
1597
  current_date=current_date,
1598
  global_requirements=global_requirements,
1599
+ news_balance_option=news_balance_option,
1600
+ hook_option=hook_option,
1601
  )
1602
 
1603
  chunks: list[str] = []
 
1609
  )
1610
 
1611
  yield (
1612
+ f"✍️ Phase 3/3 β€” writing part {chunk_number}/3 "
1613
+ f"β€” total so far "
1614
+ f"{count_words(previous_script)} words…",
1615
  previous_script,
1616
  )
1617
 
 
1634
  client=client,
1635
  model=model,
1636
  system_prompt=(
1637
+ "You are an experienced human documentary writer. Write dense, "
1638
+ "direct, natural spoken English with strong scientific and geographic "
1639
+ "depth, selective current-news material, unequal topic sizes, connected "
1640
+ "cliffhangers, and high retention. Preserve the requested news balance "
1641
+ "and do not overuse dates."
 
1642
  ),
1643
  user_prompt=prompt,
1644
  max_tokens=CHUNK_MAX_TOKENS,
 
1655
 
1656
  if response is None:
1657
  yield (
1658
+ f"✍️ Part {chunk_number}/3 β€” "
1659
+ f"{count_words(partial_text)} words in this part β€” "
1660
+ f"{count_words(current_script)} total",
1661
  current_script,
1662
  )
1663
 
1664
  if not chunk_text.strip():
1665
  raise RuntimeError(
1666
+ f"Claude did not write part {chunk_number}."
1667
  )
1668
 
1669
  chunk_words = count_words(
 
1671
  )
1672
 
1673
  log(
1674
+ f"Part {chunk_number} first draft: "
1675
+ f"{chunk_words} words."
1676
  )
1677
 
1678
+ # Maximum of three targeted correction rounds per chunk.
1679
  for correction_attempt in range(3):
1680
  if (
1681
  spec["minimum"]
 
1685
  break
1686
 
1687
  yield (
1688
+ f"πŸ“ Part {chunk_number}/3 has "
1689
+ f"{chunk_words} words; target is "
1690
  f"{spec['minimum']}–{spec['maximum']}. "
1691
+ f"Correction {correction_attempt + 1}/3…",
1692
  joined_script(
1693
  chunks + [chunk_text]
1694
  ),
 
1715
  )
1716
 
1717
  log(
1718
+ f"Part {chunk_number} after correction "
1719
  f"{correction_attempt + 1}: "
1720
+ f"{chunk_words} words."
1721
  )
1722
 
1723
  if (
 
1725
  and final_response.stop_reason == "max_tokens"
1726
  ):
1727
  log(
1728
+ f"Part {chunk_number} reached "
1729
+ "max_tokens, but the existing text is being kept."
1730
  )
1731
 
1732
  chunks.append(
 
1738
  )
1739
 
1740
  yield (
1741
+ f"βœ… Part {chunk_number}/3 complete β€” "
1742
+ f"{chunk_words} words β€” "
1743
+ f"{count_words(current_script)} total",
1744
  current_script,
1745
  )
1746
 
 
1750
 
1751
  if not MIN_WORDS <= total_words <= MAX_WORDS:
1752
  yield (
1753
+ f"πŸ”§ Total length is {total_words} words; "
1754
+ "running final length correction…",
1755
  current_script,
1756
  )
1757
 
 
1778
  text=current_script,
1779
  cutoff_date=cutoff_date,
1780
  current_date=current_date,
1781
+ news_balance_option=news_balance_option,
1782
  )
1783
 
1784
  window_text = (
1785
+ f"news window {cutoff_date.isoformat()} "
1786
+ f"to {current_date.isoformat()}"
1787
  )
1788
 
1789
  if (
 
1791
  and not warnings
1792
  ):
1793
  status = (
1794
+ f"βœ… Ready β€” {total_words} words β€” "
1795
  f"{window_text} β€” 4x {CHANNEL_NAME} β€” "
1796
  "2 vragen met Discover Tube"
1797
  )
1798
 
1799
  elif MIN_WORDS <= total_words <= MAX_WORDS:
1800
  status = (
1801
+ f"⚠️ Ready β€” {total_words} words β€” "
1802
+ f"{window_text}. Check: "
1803
  + "; ".join(warnings)
1804
  )
1805
 
1806
  else:
1807
  warning_text = (
1808
+ f" Also check: {'; '.join(warnings)}"
1809
  if warnings
1810
  else ""
1811
  )
1812
 
1813
  status = (
1814
+ f"⚠️ Ready β€” {total_words} words. "
1815
+ f"Target: {MIN_WORDS}–{MAX_WORDS}. "
1816
  f"{window_text}."
1817
  + warning_text
1818
  )
 
1821
 
1822
  except anthropic.AuthenticationError:
1823
  yield (
1824
+ "❌ The Anthropic API key is invalid.",
1825
  current_script,
1826
  )
1827
 
1828
  except anthropic.PermissionDeniedError:
1829
  yield (
1830
+ "❌ Your Anthropic account does not have access "
1831
+ "to this model or web search.",
1832
  current_script,
1833
  )
1834
 
1835
  except anthropic.RateLimitError:
1836
  yield (
1837
+ "❌ The Anthropic rate or usage limit has been reached. "
1838
+ "Check your billing.",
1839
  current_script,
1840
  )
1841
 
1842
  except anthropic.APITimeoutError:
1843
  yield (
1844
+ f"❌ Claude did not respond within "
1845
  f"{API_TIMEOUT_SECONDS} seconden.",
1846
  current_script,
1847
  )
1848
 
1849
  except anthropic.APIConnectionError:
1850
  yield (
1851
+ "❌ Could not connect to Claude.",
1852
  current_script,
1853
  )
1854
 
 
1858
 
1859
  if "web search is not enabled" in lower_error:
1860
  message = (
1861
+ "❌ Web search is not enabled for "
1862
+ "your Anthropic organization."
1863
  )
1864
 
1865
  elif "credit balance" in lower_error:
1866
  message = (
1867
+ "❌ Your Anthropic API credit balance is insufficient."
1868
  )
1869
 
1870
  else:
1871
  message = (
1872
+ f"❌ Anthropic rejected the request "
1873
+ f": {error_text}"
1874
  )
1875
 
1876
  yield message, current_script
1877
 
1878
  except anthropic.APIStatusError as exc:
1879
  yield (
1880
+ f"❌ Anthropic API error "
1881
  f"{exc.status_code}: {exc.message}",
1882
  current_script,
1883
  )
1884
 
1885
  except Exception as exc:
1886
  log(
1887
+ f"Unexpected error: {exc}"
1888
  )
1889
 
1890
  yield (
1891
+ f"❌ Something went wrong: {exc}",
1892
  current_script,
1893
  )
1894
 
1895
 
1896
  # =========================================================
1897
+ # TIMER AND INTERFACE
1898
  # =========================================================
1899
 
1900
 
 
1905
  start_time,
1906
  True,
1907
  format_elapsed(0),
1908
+ "πŸš€ Generation started…",
1909
  "",
1910
  gr.Button(
1911
  interactive=False,
 
1953
  "",
1954
  None,
1955
  DEFAULT_RECENCY_OPTION,
1956
+ DEFAULT_NEWS_BALANCE_OPTION,
1957
+ DEFAULT_HOOK_OPTION,
1958
  "",
1959
  "",
1960
  0.0,
 
1969
  with gr.Blocks() as demo:
1970
  gr.Markdown(
1971
  """
1972
+ # Discover Tube Documentary Script Writer
1973
 
1974
+ Creates a direct, information-dense, human-sounding YouTube documentary script of
1975
+ 2,900–3,200 words. You can control how news-heavy the narration feels and choose the
1976
+ opening hook style without changing the core writing voice.
1977
  """
1978
  )
1979
 
 
1987
 
1988
  with gr.Row():
1989
  title_input = gr.Textbox(
1990
+ label="🎯 Video title",
1991
  placeholder=(
1992
  "Scientists Are Monitoring a Mysterious Change "
1993
  "Beneath the Great Lakes"
 
1998
  model_input = gr.Dropdown(
1999
  choices=MODEL_OPTIONS,
2000
  value="claude-sonnet-5",
2001
+ label="🧠 Claude model",
2002
  )
2003
 
2004
  recency_input = gr.Dropdown(
2005
  choices=list(RECENCY_OPTIONS.keys()),
2006
  value=DEFAULT_RECENCY_OPTION,
2007
+ label="πŸ“° Current-news search window",
2008
+ )
2009
+
2010
+ with gr.Row():
2011
+ news_balance_input = gr.Dropdown(
2012
+ choices=list(NEWS_BALANCE_OPTIONS.keys()),
2013
+ value=DEFAULT_NEWS_BALANCE_OPTION,
2014
+ label="βš–οΈ News balance",
2015
+ info=(
2016
+ "Controls how much of the spoken script is driven by current events. "
2017
+ "The research can still use dates internally without narrating all of them."
2018
+ ),
2019
+ )
2020
+
2021
+ hook_input = gr.Dropdown(
2022
+ choices=HOOK_OPTIONS,
2023
+ value=DEFAULT_HOOK_OPTION,
2024
+ label="🎬 Opening hook",
2025
+ info=(
2026
+ "Choose how the intro starts. Auto selects topography, a recent event, "
2027
+ "or a hard fact. News clip continuation is used only when you select it."
2028
+ ),
2029
  )
2030
 
2031
  style_file_input = gr.File(
2032
  label=(
2033
+ "πŸ“„ Upload a handmade sample script for style inspiration "
2034
+ "(.docx or .txt)"
2035
  ),
2036
  file_types=[
2037
  ".docx",
 
2042
 
2043
  with gr.Row():
2044
  clear_button = gr.Button(
2045
+ "Clear"
2046
  )
2047
 
2048
  generate_button = gr.Button(
2049
+ "πŸš€ Generate",
2050
  variant="primary",
2051
  )
2052
 
 
2057
  )
2058
 
2059
  elapsed_output = gr.Textbox(
2060
+ label="Elapsed time",
2061
  value=format_elapsed(0),
2062
  interactive=False,
2063
  )
2064
 
2065
  script_output = gr.Textbox(
2066
+ label="Final script",
2067
  lines=35,
2068
  interactive=False,
2069
  buttons=[
 
2103
  style_file_input,
2104
  model_input,
2105
  recency_input,
2106
+ news_balance_input,
2107
+ hook_input,
2108
  ],
2109
  outputs=[
2110
  status_output,
 
2133
  title_input,
2134
  style_file_input,
2135
  recency_input,
2136
+ news_balance_input,
2137
+ hook_input,
2138
  status_output,
2139
  script_output,
2140
  start_time_state,