Becio commited on
Commit
58f62e8
Β·
verified Β·
1 Parent(s): dde5262

Update app.py

Browse files
Files changed (1) hide show
  1. app.py +148 -77
app.py CHANGED
@@ -3,89 +3,160 @@ from openai import OpenAI
3
  from docx import Document
4
  import os
5
  from serpapi import GoogleSearch
6
- import re
7
-
8
 
9
  # πŸ” Context ophalen via SerpAPI
10
  serpapi_key = "59ad264e7fef5ed3f7a534de3bca426000ee83730987ac2cf71e20eec95e85aa"
11
 
12
-
13
  def fetch_recent_info(topic):
14
- params = {
15
- "engine": "google",
16
- "q": f"{topic} news 2025",
17
- "api_key": serpapi_key,
18
- "num": 10,
19
- }
20
- search = GoogleSearch(params)
21
- results = search.get_dict()
22
- snippets = [result.get("snippet", "") for result in results.get("organic_results", [])]
23
- return "\n".join(snippets)
24
-
25
 
26
  # πŸ“„ Laad stijl uit .docx
27
  def load_style_from_docx(filepath):
28
- try:
29
- doc = Document(filepath)
30
- return "\n".join([para.text for para in doc.paragraphs])
31
- except Exception:
32
- return ""
33
-
34
-
35
- # 🧩 β€”β€”β€” CTA helpers β€”β€”β€”
36
-
37
-
38
- def _is_title_block(block: str) -> bool:
39
- """Heuristic: treat a block as a chapter title if it's a single shortish line
40
- that does NOT end with terminal punctuation and isn't empty."""
41
- line = block.strip()
42
- if not line:
43
- return False
44
- # single line
45
- if "\n" in line:
46
- return False
47
- # avoid typical sentence endings
48
- if line.endswith((".", "!", "?", ":")):
49
- return False
50
- # avoid markdown-style bullets
51
- if line.lstrip().startswith(("- ", "* ", "β€’ ", "β€” ")):
52
- return False
53
- # keep titles reasonably short
54
- return len(line) <= 120
55
-
56
-
57
- def _group_chapters(text: str):
58
- """Group text into chapters as (title, body) using a simple title heuristic.
59
- Returns a list of tuples. If no titles are found, returns a single chapter."""
60
- blocks = re.split(r"\n{2,}", text.strip())
61
- chapters = []
62
- i = 0
63
- while i < len(blocks):
64
- if _is_title_block(blocks[i]):
65
- title = blocks[i].strip()
66
- body_parts = []
67
- i += 1
68
- while i < len(blocks) and not _is_title_block(blocks[i]):
69
- body_parts.append(blocks[i])
70
- i += 1
71
- chapters.append((title, "\n\n".join(bp.strip() for bp in body_parts).strip()))
72
- else:
73
- # No clear title β€” merge consecutive non-title blocks as a single "chapter"
74
- body_parts = [blocks[i]]
75
- i += 1
76
- while i < len(blocks) and not _is_title_block(blocks[i]):
77
- body_parts.append(blocks[i])
78
- i += 1
79
- chapters.append(("", "\n\n".join(bp.strip() for bp in body_parts).strip()))
80
- return chapters
81
-
82
-
83
- def _assemble_chapters(chapters):
84
- parts = []
85
- for title, body in chapters:
86
- if title:
87
- parts.append(title.strip())
88
- if body:
89
- parts.append(body.strip())
90
- return "\n\n".join(p for p in parts if p)
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
91
 
 
 
 
 
3
  from docx import Document
4
  import os
5
  from serpapi import GoogleSearch
 
 
6
 
7
  # πŸ” Context ophalen via SerpAPI
8
  serpapi_key = "59ad264e7fef5ed3f7a534de3bca426000ee83730987ac2cf71e20eec95e85aa"
9
 
 
10
  def fetch_recent_info(topic):
11
+ params = {
12
+ "engine": "google",
13
+ "q": f"{topic} news 2025",
14
+ "api_key": serpapi_key,
15
+ "num": 10,
16
+ }
17
+ search = GoogleSearch(params)
18
+ results = search.get_dict()
19
+ snippets = [result.get("snippet", "") for result in results.get("organic_results", [])]
20
+ return "\n".join(snippets)
 
21
 
22
  # πŸ“„ Laad stijl uit .docx
23
  def load_style_from_docx(filepath):
24
+ try:
25
+ doc = Document(filepath)
26
+ return "\n".join([para.text for para in doc.paragraphs])
27
+ except Exception:
28
+ return ""
29
+
30
+ # 🧠 Script generatie met context en stijl
31
+ def generate_script(api_key, title, style_file):
32
+ if not api_key or not title:
33
+ return "❌ Vul alle verplichte velden in."
34
+
35
+ try:
36
+ client = OpenAI(api_key=api_key)
37
+ context = fetch_recent_info(title)
38
+
39
+ if not context or len(context.strip()) < 100:
40
+ return "⚠️ Geen context gevonden. Geef een concreter onderwerp of controleer SerpAPI key."
41
+
42
+ # Space-niche default: mysterieus maar feitelijk, met nadruk op bewijs uit de context
43
+ style_text = load_style_from_docx(style_file.name) if style_file else "YouTube ruimte/astronomie-stijl: mysterieus maar feitelijk, met duidelijke uitleg van wetenschap, rehooks, en nadruk op bewijs uit de context."
44
+
45
+ prompt = f"""
46
+ You are a professional YouTube video text writer for the space/astronomy niche.
47
+ Below is an example YouTube video text that demonstrates the style, tone, pacing, and voice to follow:
48
+ --- STYLE INSPIRATION START ---
49
+ {style_text}
50
+ --- STYLE INSPIRATION END ---
51
+ Using this style as inspiration, write a full, complete, well-developed Youtube video text that contains between 2900 and 3200 words.
52
+ Expand on every key point, include vivid examples, and avoid summarizing too early.
53
+ Divide the text (except intro and ending) into 5-8 chapters.
54
+ The last chapter should not have a title like 'Outro' or 'Conclusion'β€”just close the script naturally.
55
+ Do not use brackets like [] in the chapter titles.
56
+ End the first chapter with a rhetorical question to intrigue the audience.
57
+ Keep the introduction (first chapter) under 350 words.
58
+ Do not show 'Chapter one' or something, show only the chapter title.
59
+ You are not allowed to generate any content that is not explicitly present in the provided context.
60
+ Do not infer, assume, or imagine any details.
61
+ You must reference the facts from the context directly, and nothing beyond that.
62
+ Favor a 'Mystery Setup' hook, add rehooks with surprising but factual turns, build to a clear climax revealing the key discovery, and finish with a reflective resolution on implications for space exploration.
63
+ Align the content precisely with the title and avoid clickbait exaggerations.
64
+ Insert a short call-to-action encouraging viewers to subscribe around 30% of the way through the script, placed naturally at the end of a chapter.
65
+ Do not include notes or comments for the editor. Do not reply with anything besides the text.
66
+ Write a script for the following title:
67
+ \"{title}\"
68
+ Use the following current information for context:
69
+ --- START OF FACTUAL CONTEXT ---
70
+ {context}
71
+ --- END OF FACTUAL CONTEXT ---
72
+ Maintain the same storytelling quality, sentence rhythm, and tone as the style sample.
73
+ Make the tone of the YouTube video dramatic and mysterious while remaining scientifically grounded; use rhetorical questions without suggesting unsupported claims.
74
+ Ensure the final script is between 2900 and 3200 words. Less than 2900 is NOT acceptable.
75
+ """
76
+
77
+ response = client.chat.completions.create(
78
+ model="gpt-4.1",
79
+ messages=[
80
+ {"role": "system", "content": "You're a professional scriptwriter."},
81
+ {"role": "user", "content": prompt}
82
+ ]
83
+ )
84
+
85
+ raw_script = response.choices[0].message.content
86
+
87
+ max_retries = 3
88
+ for attempt in range(max_retries):
89
+ word_count = len(raw_script.split())
90
+ if word_count >= 2900:
91
+ break
92
+
93
+ extra_prompt = f"""
94
+ The following script is currently {word_count} words long. Please expand it naturally to reach at least 2900 words.
95
+ Focus on adding details to chapters; keep the outro under 150 words.
96
+ Do NOT include editing notes, camera directions, or comments.
97
+ Script so far:
98
+ {raw_script}
99
+ """
100
+ extra_response = client.chat.completions.create(
101
+ model="gpt-4.1",
102
+ messages=[
103
+ {"role": "system", "content": "You're a professional scriptwriter."},
104
+ {"role": "user", "content": extra_prompt}
105
+ ]
106
+ )
107
+ raw_script = extra_response.choices[0].message.content
108
+
109
+ # Fact-check stap
110
+ final_script = factual_review(raw_script, context, client)
111
+ return final_script
112
+
113
+ except Exception as e:
114
+ return f"❌ Er ging iets fout: {str(e)}"
115
+
116
+ # πŸ”Ž Fact-check met soepele aanpak
117
+ def factual_review(script, context, client):
118
+ prompt = f"""
119
+ Below is a script and the factual context it was based on.
120
+ --- CONTEXT ---
121
+ {context}
122
+ --- SCRIPT ---
123
+ {script}
124
+ Please review the script for factual consistency:
125
+ - Minor elaborations are allowed if logically connected to the context.
126
+ - Remove clearly speculative or unverifiable claims, sensational framings, and any mismatch between title and content.
127
+ - Keep dramatic, mysterious tone only when supported by evidence from the context; prioritize scientific clarity and plain-language explanations of complex ideas.
128
+ - Ensure the final script is at least 2900 and maximum 3200 words and keeps natural storytelling flow with a clear resolution (no abrupt ending).
129
+ - Important: Do not add video editing instructions, title cards, camera directions, or editorial comments. Only return the final spoken script text.
130
+ - If the script is less than 2900 words, extend most chapters to reach 2900 words and do the factual review again.
131
+ Only rewrite or reword parts that really need it.
132
+ """
133
+ response = client.chat.completions.create(
134
+ model="gpt-4.1",
135
+ messages=[
136
+ {"role": "system", "content": "You are a careful but strict fact-checker and editor."},
137
+ {"role": "user", "content": prompt}
138
+ ]
139
+ )
140
+ return response.choices[0].message.content
141
+
142
+ # πŸŽ›οΈ Gradio interface
143
+ with gr.Blocks() as demo:
144
+ gr.Markdown("# 🎨 Script Writer 2.0 – Met woordtelling en Fact-Check")
145
+
146
+ with gr.Row():
147
+ api_key = gr.Textbox(label="πŸ”‘ OpenAI API Key", type="password")
148
+ title = gr.Textbox(label="🎯 Video Title (script topic)")
149
+
150
+ style_file = gr.File(label="πŸ“„ Upload script for style inspiration (.docx)", file_types=[".docx"], type="filepath")
151
+ output = gr.Textbox(label="βœ… Final Script (Fact-Checked)", lines=30, interactive=False)
152
+
153
+ with gr.Row():
154
+ clear_btn = gr.Button("πŸͺœ Clear")
155
+ submit_btn = gr.Button("πŸš€ Genereer")
156
+
157
+ submit_btn.click(fn=generate_script, inputs=[api_key, title, style_file], outputs=output)
158
+ clear_btn.click(fn=lambda: "", inputs=None, outputs=output)
159
 
160
+ # Run app
161
+ if __name__ == "__main__":
162
+ demo.launch()