Becio commited on
Commit
08a8b10
·
1 Parent(s): 87c300d

Rename Script_Writer_v3.py to app.py for Hugging Face Space

Browse files
Files changed (1) hide show
  1. app.py +163 -0
app.py ADDED
@@ -0,0 +1,163 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ import gradio as gr
2
+ from openai import OpenAI
3
+ import requests
4
+ from bs4 import BeautifulSoup
5
+ from docx import Document
6
+
7
+ # 🌐 Webscraper om context te verzamelen
8
+ def fetch_recent_info(topic):
9
+ try:
10
+ url = f"https://www.google.com/search?q={topic}+news+2025"
11
+ headers = {"User-Agent": "Mozilla/5.0"}
12
+ response = requests.get(url, headers=headers)
13
+ soup = BeautifulSoup(response.text, "html.parser")
14
+ snippets = [p.text for p in soup.find_all("p")][:10]
15
+ return "\n".join(snippets)
16
+ except Exception:
17
+ return ""
18
+
19
+ # 📄 Laadt stijlinspiratie vanuit een docx bestand
20
+ def load_style_from_docx(filepath):
21
+ try:
22
+ doc = Document(filepath)
23
+ return "\n".join([para.text for para in doc.paragraphs])
24
+ except Exception:
25
+ return ""
26
+
27
+ # 🧠 Script generator met gecontroleerde lengte
28
+ def generate_script(api_key, title, style_file):
29
+ if not api_key or not title:
30
+ return "❌ Vul alle verplichte velden in."
31
+
32
+ try:
33
+ client = OpenAI(api_key=api_key)
34
+
35
+ # Stap 1: Verzamel context
36
+ context = fetch_recent_info(title)
37
+ if not context or len(context.strip()) < 100:
38
+ return "⚠️ Geen context gevonden op het internet. Geef een concreter onderwerp of controleer je verbinding."
39
+
40
+ # Stap 2: Laad stijl of gebruik fallback
41
+ style_text = load_style_from_docx(style_file.name) if style_file else "YouTube stijl met drama en spanning."
42
+
43
+ # Stap 3: Maak prompt voor het script
44
+ prompt = f"""
45
+ You are a professional YouTube video text writer.
46
+
47
+ Below is an example YouTube video text that demonstrates the style, tone, pacing, and voice to follow:
48
+
49
+ --- STYLE INSPIRATION START ---
50
+ {style_text}
51
+ --- STYLE INSPIRATION END ---
52
+
53
+ Using this style as inspiration, write a full, complete, well-developed Youtube video text that contains between 2700 and 2800 words.
54
+ Expand every point with vivid examples and avoid summarizing too early.
55
+ Try to cut the text (besides intro and outro) into 5-8 chapters.
56
+ Tell realistic information each chapter.
57
+
58
+ Important rules:
59
+ - Only use facts from the context.
60
+ - No invented, speculative or imaginary details.
61
+ - Focus on flow, rhythm, suspense, and drama.
62
+ - IF the generated text is not 2700 words yet, automatically continue writing until 2700 words is reached.
63
+ - Important: Do not include video editing instructions, title cards, camera directions, or comments intended for editors. Only provide the clean script text that would be spoken aloud.
64
+
65
+ Title:
66
+ "{title}"
67
+
68
+ Use this factual context:
69
+ --- CONTEXT ---
70
+ {context}
71
+ --- END CONTEXT ---
72
+ """
73
+
74
+ # Stap 4: Vraag het script op bij OpenAI
75
+ response = client.chat.completions.create(
76
+ model="gpt-4.1", # ✅ GPT-4.1 zoals je wilde
77
+ messages=[
78
+ {"role": "system", "content": "You're a professional scriptwriter."},
79
+ {"role": "user", "content": prompt}
80
+ ]
81
+ )
82
+
83
+ raw_script = response.choices[0].message.content
84
+
85
+ # Stap 5: Controleer woordenaantal
86
+ word_count = len(raw_script.split())
87
+ if word_count < 2700:
88
+ extra_prompt = f"""
89
+ The following script is only {word_count} words long. Please continue writing naturally until it reaches at least 2700 words.
90
+ Maintain the same tone, structure, and factual accuracy.
91
+ Do NOT add editing notes, camera directions, or video comments.
92
+
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 += "\n" + extra_response.choices[0].message.content
104
+
105
+ # Stap 6: Fact-check het script (versoepeld)
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
+
113
+ # 🔎 Fact-check met soepele aanpak
114
+ def factual_review(script, context, client):
115
+ prompt = f"""
116
+ Below is a script and the factual context it was based on.
117
+
118
+ --- CONTEXT ---
119
+ {context}
120
+
121
+ --- SCRIPT ---
122
+ {script}
123
+
124
+ Please review the script for factual consistency:
125
+
126
+ - Minor elaborations are allowed if logically connected to the context.
127
+ - Remove clearly speculative or unverifiable claims.
128
+ - Keep dramatic tone and rhetorical questions if they don't create fake facts.
129
+ - Ensure the final script is at least 2700 and maximum 2800 words and keeps natural storytelling flow.
130
+ - Important: Do not add video editing instructions, title cards, camera directions, or editorial comments. Only return the final spoken script text.
131
+
132
+ Only rewrite or reword parts that really need it.
133
+ """
134
+ response = client.chat.completions.create(
135
+ model="gpt-4.1",
136
+ messages=[
137
+ {"role": "system", "content": "You are a careful but strict fact-checker and editor."},
138
+ {"role": "user", "content": prompt}
139
+ ]
140
+ )
141
+ return response.choices[0].message.content
142
+
143
+
144
+ # 🎛️ Gradio Interface
145
+ with gr.Blocks() as demo:
146
+ gr.Markdown("🎬 **Script Writer 2.0 – Met woordtelling en Fact-Check**")
147
+
148
+ with gr.Row():
149
+ api_key = gr.Textbox(label="🔑 OpenAI API Key", type="password")
150
+ title = gr.Textbox(label="🎯 Video Title (script topic)")
151
+
152
+ style_file = gr.File(label="📄 Upload script for style inspiration (.docx)", file_types=[".docx"], type="filepath")
153
+ output = gr.Textbox(label="✅ Final Script (Fact-Checked)", lines=30, interactive=False)
154
+
155
+ with gr.Row():
156
+ clear_btn = gr.Button("🧹 Clear")
157
+ submit_btn = gr.Button("🚀 Generate Script")
158
+
159
+ submit_btn.click(fn=generate_script, inputs=[api_key, title, style_file], outputs=output)
160
+ clear_btn.click(fn=lambda: "", inputs=None, outputs=output)
161
+
162
+ if __name__ == "__main__":
163
+ demo.launch()