Becio commited on
Commit
00cce90
·
verified ·
1 Parent(s): 6056e28

Update app.py

Browse files
Files changed (1) hide show
  1. app.py +23 -35
app.py CHANGED
@@ -1,12 +1,11 @@
1
  import gradio as gr
2
  from openai import OpenAI
3
- import requests
4
  from docx import Document
5
  import os
 
6
 
7
- # 🔍 Context ophalen via SerpAPI (werkt altijd)
8
  serpapi_key = "59ad264e7fef5ed3f7a534de3bca426000ee83730987ac2cf71e20eec95e85aa"
9
- from serpapi import GoogleSearch
10
 
11
  def fetch_recent_info(topic):
12
  params = {
@@ -20,9 +19,7 @@ def fetch_recent_info(topic):
20
  snippets = [result.get("snippet", "") for result in results.get("organic_results", [])]
21
  return "\n".join(snippets)
22
 
23
-
24
  # 📄 Laad stijl uit .docx
25
-
26
  def load_style_from_docx(filepath):
27
  try:
28
  doc = Document(filepath)
@@ -30,15 +27,13 @@ def load_style_from_docx(filepath):
30
  except Exception:
31
  return ""
32
 
33
- openai_api_key = "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"
34
  # 🧠 Script generatie met context en stijl
35
- def generate_script(title, style_file):
36
- if not title:
37
  return "❌ Vul alle verplichte velden in."
38
 
39
-
40
  try:
41
- client = OpenAI(api_key=openai_api_key)
42
  context = fetch_recent_info(title)
43
 
44
  if not context or len(context.strip()) < 100:
@@ -65,7 +60,7 @@ Do not infer, assume, or imagine any details.
65
  You must reference the facts from the context directly, and nothing beyond that.
66
  Do not include notes or comments for the editor. Do not reply with anything besides the text.
67
  Write a script for the following title:
68
- "{title}"
69
  Use the following current information for context:
70
  --- START OF FACTUAL CONTEXT ---
71
  {context}
@@ -75,9 +70,8 @@ Make the tone of the YouTube video dramatic and mysterious, using rhetorical que
75
  Ensure the final script is between 2700 and 2800 words. Less than 2700 is NOT acceptable.
76
  """
77
 
78
-
79
  response = client.chat.completions.create(
80
- model="gpt-4.1", # ✅ GPT-4.1 zoals je wilde
81
  messages=[
82
  {"role": "system", "content": "You're a professional scriptwriter."},
83
  {"role": "user", "content": prompt}
@@ -90,53 +84,46 @@ Ensure the final script is between 2700 and 2800 words. Less than 2700 is NOT ac
90
  for attempt in range(max_retries):
91
  word_count = len(raw_script.split())
92
  if word_count >= 2700:
93
- break # ✅ voldoende woorden → klaar
94
 
95
- extra_prompt = f"""
96
  The following script is currently {word_count} words long. Please expand it naturally to reach at least 2700 words.
97
  Focus on adding details to chapters; keep the outro under 150 words.
98
  Do NOT include editing notes, camera directions, or comments.
99
-
100
  Script so far:
101
  {raw_script}
102
  """
103
- extra_response = client.chat.completions.create(
104
- model="gpt-4.1",
105
- messages=[
106
- {"role": "system", "content": "You're a professional scriptwriter."},
107
- {"role": "user", "content": extra_prompt}
108
- ]
109
- )
110
- raw_script = extra_response.choices[0].message.content
111
-
112
- # Stap 6: Fact-check het script (versoepeld)
113
  final_script = factual_review(raw_script, context, client)
114
  return final_script
115
 
116
  except Exception as e:
117
  return f"❌ Er ging iets fout: {str(e)}"
118
 
119
-
120
  # 🔎 Fact-check met soepele aanpak
121
  def factual_review(script, context, client):
122
  prompt = f"""
123
  Below is a script and the factual context it was based on.
124
-
125
  --- CONTEXT ---
126
  {context}
127
-
128
  --- SCRIPT ---
129
  {script}
130
-
131
  Please review the script for factual consistency:
132
-
133
  - Minor elaborations are allowed if logically connected to the context.
134
  - Remove clearly speculative or unverifiable claims.
135
  - Keep dramatic tone and rhetorical questions if they don't create fake facts.
136
  - Ensure the final script is at least 2700 and maximum 2800 words and keeps natural storytelling flow.
137
  - Important: Do not add video editing instructions, title cards, camera directions, or editorial comments. Only return the final spoken script text.
138
- - If the script is less than 2700 words, extend most chapters to reach 2700 words and to the factual review again.
139
-
140
  Only rewrite or reword parts that really need it.
141
  """
142
  response = client.chat.completions.create(
@@ -153,6 +140,7 @@ with gr.Blocks() as demo:
153
  gr.Markdown("# 🎨 Script Writer 2.0 – Met woordtelling en Fact-Check")
154
 
155
  with gr.Row():
 
156
  title = gr.Textbox(label="🎯 Video Title (script topic)")
157
 
158
  style_file = gr.File(label="📄 Upload script for style inspiration (.docx)", file_types=[".docx"], type="filepath")
@@ -162,9 +150,9 @@ with gr.Blocks() as demo:
162
  clear_btn = gr.Button("🪜 Clear")
163
  submit_btn = gr.Button("🚀 Genereer")
164
 
165
- submit_btn.click(fn=generate_script, inputs=[title, style_file], outputs=output)
166
  clear_btn.click(fn=lambda: "", inputs=None, outputs=output)
167
 
168
  # Run app
169
  if __name__ == "__main__":
170
- demo.launch()
 
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 = {
 
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)
 
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:
 
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}
 
70
  Ensure the final script is between 2700 and 2800 words. Less than 2700 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}
 
84
  for attempt in range(max_retries):
85
  word_count = len(raw_script.split())
86
  if word_count >= 2700:
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 2700 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 2700 and maximum 2800 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 2700 words, extend most chapters to reach 2700 words and do the factual review again.
 
127
  Only rewrite or reword parts that really need it.
128
  """
129
  response = client.chat.completions.create(
 
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")
 
150
  clear_btn = gr.Button("🪜 Clear")
151
  submit_btn = gr.Button("🚀 Genereer")
152
 
153
+ submit_btn.click(fn=generate_script, inputs=[api_key, title, style_file], outputs=output)
154
  clear_btn.click(fn=lambda: "", inputs=None, outputs=output)
155
 
156
  # Run app
157
  if __name__ == "__main__":
158
+ demo.launch()