Becio commited on
Commit
44d3313
Β·
verified Β·
1 Parent(s): 0cef3d6

Upload 2 files

Browse files
Files changed (2) hide show
  1. app.py +158 -0
  2. requirements.txt +7 -0
app.py ADDED
@@ -0,0 +1,158 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ import gradio as gr
2
+ from openai import OpenAI
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
+ style_text = load_style_from_docx(style_file.name) if style_file else "YouTube stijl met drama en spanning."
43
+
44
+ prompt = f"""
45
+ You are a professional YouTube video text writer.
46
+ Below is an example YouTube video text that demonstrates the style, tone, pacing, and voice to follow:
47
+ --- STYLE INSPIRATION START ---
48
+ {style_text}
49
+ --- STYLE INSPIRATION END ---
50
+ Using this style as inspiration, write a full, complete, well-developed Youtube video text that contains between 2900 and 3200 words.
51
+ Expand on every key point, include vivid examples, and avoid summarizing too early.
52
+ Divide the text (except intro and ending) into 5-8 chapters.
53
+ The last chapter should not have a title like 'Outro' or 'Conclusion'β€”just close the script naturally.
54
+ Do not use brackets like [] in the chapter titles.
55
+ End the first chapter with a rhetorical question to intrigue the audience.
56
+ Keep the introduction (first chapter) under 350 words.
57
+ Do not show 'Chapter one' or something, show only the chapter title.
58
+ You are not allowed to generate any content that is not explicitly present in the provided context.
59
+ Do not infer, assume, or imagine any details.
60
+ You must reference the facts from the context directly, and nothing beyond that.
61
+ Do not include notes or comments for the editor. Do not reply with anything besides the text.
62
+ Write a script for the following title:
63
+ \"{title}\"
64
+ Use the following current information for context:
65
+ --- START OF FACTUAL CONTEXT ---
66
+ {context}
67
+ --- END OF FACTUAL CONTEXT ---
68
+ Maintain the same storytelling quality, sentence rhythm, and tone as the style sample.
69
+ Make the tone of the YouTube video dramatic and mysterious, using rhetorical questions.
70
+ Ensure the final script is between 2900 and 3200 words. Less than 2900 is NOT acceptable.
71
+ """
72
+
73
+ response = client.chat.completions.create(
74
+ model="gpt-4.1",
75
+ messages=[
76
+ {"role": "system", "content": "You're a professional scriptwriter."},
77
+ {"role": "user", "content": prompt}
78
+ ]
79
+ )
80
+
81
+ raw_script = response.choices[0].message.content
82
+
83
+ max_retries = 3
84
+ for attempt in range(max_retries):
85
+ word_count = len(raw_script.split())
86
+ if word_count >= 2900:
87
+ break
88
+
89
+ extra_prompt = f"""
90
+ The following script is currently {word_count} words long. Please expand it naturally to reach at least 2900 words.
91
+ Focus on adding details to chapters; keep the outro under 150 words.
92
+ Do NOT include editing notes, camera directions, or comments.
93
+ Script so far:
94
+ {raw_script}
95
+ """
96
+ extra_response = client.chat.completions.create(
97
+ model="gpt-4.1",
98
+ messages=[
99
+ {"role": "system", "content": "You're a professional scriptwriter."},
100
+ {"role": "user", "content": extra_prompt}
101
+ ]
102
+ )
103
+ raw_script = extra_response.choices[0].message.content
104
+
105
+ # Fact-check stap
106
+ final_script = factual_review(raw_script, context, client)
107
+ return final_script
108
+
109
+ except Exception as e:
110
+ return f"❌ Er ging iets fout: {str(e)}"
111
+
112
+ # πŸ”Ž Fact-check met soepele aanpak
113
+ def factual_review(script, context, client):
114
+ prompt = f"""
115
+ Below is a script and the factual context it was based on.
116
+ --- CONTEXT ---
117
+ {context}
118
+ --- SCRIPT ---
119
+ {script}
120
+ Please review the script for factual consistency:
121
+ - Minor elaborations are allowed if logically connected to the context.
122
+ - Remove clearly speculative or unverifiable claims.
123
+ - Keep dramatic tone and rhetorical questions if they don't create fake facts.
124
+ - Ensure the final script is at least 2900 and maximum 3200 words and keeps natural storytelling flow.
125
+ - Important: Do not add video editing instructions, title cards, camera directions, or editorial comments. Only return the final spoken script text.
126
+ - If the script is less than 2900 words, extend most chapters to reach 2900 words and do the factual review again.
127
+ Only rewrite or reword parts that really need it.
128
+ """
129
+ response = client.chat.completions.create(
130
+ model="gpt-4.1",
131
+ messages=[
132
+ {"role": "system", "content": "You are a careful but strict fact-checker and editor."},
133
+ {"role": "user", "content": prompt}
134
+ ]
135
+ )
136
+ return response.choices[0].message.content
137
+
138
+ # πŸŽ›οΈ Gradio interface
139
+ with gr.Blocks() as demo:
140
+ gr.Markdown("# 🎨 Script Writer 2.0 – Met woordtelling en Fact-Check")
141
+
142
+ with gr.Row():
143
+ api_key = gr.Textbox(label="πŸ”‘ OpenAI API Key", type="password")
144
+ title = gr.Textbox(label="🎯 Video Title (script topic)")
145
+
146
+ style_file = gr.File(label="πŸ“„ Upload script for style inspiration (.docx)", file_types=[".docx"], type="filepath")
147
+ output = gr.Textbox(label="βœ… Final Script (Fact-Checked)", lines=30, interactive=False)
148
+ with gr.Row():
149
+ clear_btn = gr.Button("πŸͺœ Clear")
150
+ submit_btn = gr.Button("πŸš€ Genereer")
151
+
152
+ submit_btn.click(fn=generate_script, inputs=[api_key, title, style_file], outputs=output)
153
+ clear_btn.click(fn=lambda: "", inputs=None, outputs=output)
154
+
155
+ # Run app
156
+ if __name__ == "__main__":
157
+ demo.launch()
158
+
requirements.txt ADDED
@@ -0,0 +1,7 @@
 
 
 
 
 
 
 
 
1
+ openai
2
+ gradio
3
+ requests
4
+ beautifulsoup4
5
+ python-docx
6
+ google-search-results
7
+