Luongsosad commited on
Commit
135bbcb
·
verified ·
1 Parent(s): 1bb999a

Update app.py

Browse files
Files changed (1) hide show
  1. app.py +35 -49
app.py CHANGED
@@ -4,7 +4,7 @@ import gradio as gr
4
  import re
5
 
6
  # === API SETUP ===
7
- GROQ_API_KEY = "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" # Bạn nên dùng biến môi trường
8
  GROQ_API_URL = "https://api.groq.com/openai/v1/chat/completions"
9
 
10
  HEADERS = {
@@ -23,28 +23,30 @@ def is_safe_topic(topic: str) -> bool:
23
  topic_lower = topic.lower()
24
  return not any(bad_word in topic_lower for bad_word in BLOCKED_KEYWORDS)
25
 
26
- # === PODCAST GENERATION ===
27
- def generate_educational_podcast(topic: str, language: str, model: str = "llama3-70b-8192") -> str:
28
  prompt = f"""
29
- You are a scriptwriter for an educational podcast for students in grades 8 to 12.
30
 
31
- Create a short and engaging podcast script in **{language}** on the topic: "{topic}".
32
 
33
- The two hosts are named Ali and Talha. Ali starts the conversation.
34
- They should have a back-and-forth conversation about the topic.
35
- The tone should be friendly, easy to understand, and informative.
36
- Avoid music or sound effects. Keep the total length under 800 words.
37
 
38
- Only write their dialogue and a few narration lines if needed. Do NOT use Host 1/2 or generic names.
 
 
 
39
  """
40
 
41
  data = {
42
  "model": model,
43
  "messages": [
44
- {"role": "system", "content": "You are a creative and age-appropriate educational podcast writer."},
45
  {"role": "user", "content": prompt.strip()}
46
  ],
47
- "temperature": 0.75,
48
  "max_tokens": 1024
49
  }
50
 
@@ -56,62 +58,46 @@ Only write their dialogue and a few narration lines if needed. Do NOT use Host 1
56
 
57
  # === SCRIPT FORMATTING ===
58
  def format_script(script: str) -> str:
59
- script = re.sub(r'\*\*(.*?)\*\*', r'\1', script)
60
- script = re.sub(r'(?i)^.*(music|sound effect).*$','', script, flags=re.MULTILINE)
61
- script = script.replace("Host 1:", "Ali:").replace("Host 2:", "Talha:")
62
- script = re.sub(r'\b[Aa]lex:', 'Ali:', script)
63
- script = re.sub(r'\b[Mm]aya:', 'Talha:', script)
64
-
65
- lines = script.strip().split("\n")
66
  formatted = ""
67
- for line in lines:
68
- line = line.strip()
69
- if not line:
70
- continue
71
- if line.startswith("Ali:"):
72
- content = line.replace("Ali:", "").strip()
73
- formatted += f"<div class='host1'>🎙️ <b>Ali:</b> {content}</div>\n"
74
- elif line.startswith("Talha:"):
75
- content = line.replace("Talha:", "").strip()
76
- formatted += f"<div class='host2'>🎧 <b>Talha:</b> {content}</div>\n"
77
  return formatted
78
 
79
  # === GRADIO UI ===
80
  custom_css = """
81
- .host1, .host2 {
82
- border-radius: 16px;
83
- padding: 14px;
84
- margin: 16px 0;
85
- box-shadow: 0 4px 10px rgba(255,255,255,0.2);
86
- font-size: 16px;
87
- line-height: 1.6;
88
- color: #ffffff;
89
- }
90
- .host1 {
91
- background: linear-gradient(135deg, #4b6cb7, #182848);
92
- }
93
- .host2 {
94
- background: linear-gradient(135deg, #2c3e50, #4ca1af);
95
  }
96
  """
97
 
98
  def generate(topic, language):
99
  if not is_safe_topic(topic):
100
- return "<b style='color:red;'>⚠️ Restricted content. Please enter an appropriate educational topic.</b>"
101
- raw_script = generate_educational_podcast(topic, language)
102
  return format_script(raw_script)
103
 
104
  with gr.Blocks(css=custom_css) as demo:
105
- gr.Markdown("## 🎙️ Educational Podcast Generator for Students")
106
- gr.Markdown("Enter a topic and choose your language to generate a friendly podcast between Ali and Talha.")
107
 
108
- topic_input = gr.Textbox(label="Enter educational topic")
109
  lang_input = gr.Dropdown(
110
  choices=["English", "Vietnamese", "Spanish", "French", "Japanese"],
111
  value="English",
112
  label="Select output language"
113
  )
114
- generate_btn = gr.Button("🎧 Generate Podcast")
115
  output_box = gr.HTML()
116
 
117
  generate_btn.click(fn=generate, inputs=[topic_input, lang_input], outputs=output_box)
 
4
  import re
5
 
6
  # === API SETUP ===
7
+ GROQ_API_KEY = "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" # Nên dùng biến môi trường trong thực tế
8
  GROQ_API_URL = "https://api.groq.com/openai/v1/chat/completions"
9
 
10
  HEADERS = {
 
23
  topic_lower = topic.lower()
24
  return not any(bad_word in topic_lower for bad_word in BLOCKED_KEYWORDS)
25
 
26
+ # === REFLECTIVE SCRIPT GENERATION ===
27
+ def generate_reflective_script(topic: str, language: str, model: str = "llama3-70b-8192") -> str:
28
  prompt = f"""
29
+ You are a reflective and thoughtful writer.
30
 
31
+ Write a short, emotional, and thought-provoking script in **{language}** about the topic: "{topic}".
32
 
33
+ The tone should be reflective, poetic, and emotional suitable for a short narration video.
34
+ Avoid giving facts or academic details. Instead, focus on emotions, metaphors, inner voice, and human feelings.
35
+ Use beautiful language, natural rhythm, and pauses.
 
36
 
37
+ The output should be between 200 to 400 words, formatted as a poetic monologue or a subtle inner conversation.
38
+
39
+ Do NOT include sound effects, scene descriptions, or storytelling instructions.
40
+ Just output the reflective script.
41
  """
42
 
43
  data = {
44
  "model": model,
45
  "messages": [
46
+ {"role": "system", "content": "You are a poetic, emotional writer that creates powerful scripts for videos."},
47
  {"role": "user", "content": prompt.strip()}
48
  ],
49
+ "temperature": 0.8,
50
  "max_tokens": 1024
51
  }
52
 
 
58
 
59
  # === SCRIPT FORMATTING ===
60
  def format_script(script: str) -> str:
61
+ paragraphs = script.strip().split("\n")
 
 
 
 
 
 
62
  formatted = ""
63
+ for para in paragraphs:
64
+ para = para.strip()
65
+ if para:
66
+ formatted += f"<div class='narration'>{para}</div>\n"
 
 
 
 
 
 
67
  return formatted
68
 
69
  # === GRADIO UI ===
70
  custom_css = """
71
+ .narration {
72
+ background: linear-gradient(to right, #434343, #000000);
73
+ color: #f5f5f5;
74
+ padding: 20px;
75
+ margin: 18px 0;
76
+ border-radius: 12px;
77
+ font-size: 18px;
78
+ line-height: 1.8;
79
+ box-shadow: 0 4px 12px rgba(0,0,0,0.5);
80
+ font-family: 'Georgia', serif;
 
 
 
 
81
  }
82
  """
83
 
84
  def generate(topic, language):
85
  if not is_safe_topic(topic):
86
+ return "<b style='color:red;'>⚠️ Restricted content. Please enter a safe, inspirational topic.</b>"
87
+ raw_script = generate_reflective_script(topic, language)
88
  return format_script(raw_script)
89
 
90
  with gr.Blocks(css=custom_css) as demo:
91
+ gr.Markdown("## 🌌 Reflective Video Script Generator")
92
+ gr.Markdown("Enter a thoughtful topic and choose your language to generate a poetic and emotional script for video narration.")
93
 
94
+ topic_input = gr.Textbox(label="Enter a reflective topic (e.g., loneliness, hope, youth...)")
95
  lang_input = gr.Dropdown(
96
  choices=["English", "Vietnamese", "Spanish", "French", "Japanese"],
97
  value="English",
98
  label="Select output language"
99
  )
100
+ generate_btn = gr.Button("📝 Generate Script")
101
  output_box = gr.HTML()
102
 
103
  generate_btn.click(fn=generate, inputs=[topic_input, lang_input], outputs=output_box)