File size: 4,749 Bytes
1e6d966
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
import os
import requests
import gradio as gr
import re

# === API SETUP ===
GROQ_API_KEY = "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"
GROQ_API_URL = "https://api.groq.com/openai/v1/chat/completions"

HEADERS = {
    "Authorization": f"Bearer {GROQ_API_KEY}",
    "Content-Type": "application/json"
}

# === BLOCK INAPPROPRIATE CONTENT ===
BLOCKED_KEYWORDS = [
    "sex", "drugs", "violence", "suicide", "death", "kill", "murder", "gun",
    "abuse", "politics", "terror", "crime", "war", "religion", "racism",
    "nude", "adult", "nsfw"
]

def is_safe_topic(topic: str) -> bool:
    topic_lower = topic.lower()
    return not any(bad_word in topic_lower for bad_word in BLOCKED_KEYWORDS)

# === PODCAST GENERATION ===
def generate_educational_podcast(topic: str, model: str = "llama3-70b-8192") -> str:
    prompt = f"""
You are a scriptwriter for an educational podcast aimed at school students in grades 8 to 12.

Create a short and engaging podcast script on the topic: "{topic}".

The two hosts are named Ali and Talha. Ali starts the conversation. 
They should have a back-and-forth conversation about the topic. 
The tone should be friendly, easy to understand, and informative. 

Avoid music or sound effects. Keep the total length under 800 words.
Only write their dialogue and a few narration lines if needed. Do NOT use Host 1/2 or any generic names.
"""

    data = {
        "model": model,
        "messages": [
            {"role": "system", "content": "You are a creative and age-appropriate educational podcast writer."},
            {"role": "user", "content": prompt.strip()}
        ],
        "temperature": 0.75,
        "max_tokens": 1024
    }

    response = requests.post(GROQ_API_URL, headers=HEADERS, json=data)

    if response.status_code == 200:
        return response.json()["choices"][0]["message"]["content"].strip()
    else:
        return f"<b>Error {response.status_code}</b>: {response.text}"

# === FORMAT SCRIPT CLEANLY FOR DISPLAY ===
def format_script(script: str) -> str:
    # Remove markdown bolding like **text**
    script = re.sub(r'\*\*(.*?)\*\*', r'\1', script)

    # Remove music and direction lines
    script = re.sub(r'(?i)^.*(music|sound effect).*$','', script, flags=re.MULTILINE)

    # Normalize host names to Ali and Talha
    script = script.replace("Host 1:", "Ali:")
    script = script.replace("Host 2:", "Talha:")
    script = re.sub(r'\b[Aa]lex:', 'Ali:', script)
    script = re.sub(r'\b[Mm]aya:', 'Talha:', script)

    lines = script.strip().split("\n")
    formatted = ""

    for line in lines:
        line = line.strip()
        if not line:
            continue
        # Only keep lines that are spoken by Ali or Talha
        if line.startswith("Ali:"):
            content = line.replace("Ali:", "").strip()
            formatted += f"<div class='host1'>🎙️ <b>Ali:</b> {content}</div>\n"
        elif line.startswith("Talha:"):
            content = line.replace("Talha:", "").strip()
            formatted += f"<div class='host2'>🎧 <b>Talha:</b> {content}</div>\n"

    return formatted

# === FINAL FUNCTION ===
def generate(topic):
    if not is_safe_topic(topic):
        return "<b style='color:red;'>⚠️ Restricted content. Please enter an appropriate educational topic.</b>"
    raw_script = generate_educational_podcast(topic)
    return format_script(raw_script)

# === DARK GLOSSY CSS ===
custom_css = """
# body {
#     background-color: darkslateblue !important;
#     color: #ffffff;
# }

# .gradio-container {
#     background-color: darkslateblue !important;
# }

# textarea, input, .gr-button {
#     background-color: darkslategray !important;
#     color: #ffffff !important;
#     border: 1px solid #aaa !important;
# }

.host1, .host2 {
    border-radius: 16px;
    padding: 14px;
    margin: 16px 0;
    box-shadow: 0 4px 10px rgba(255,255,255,0.2);
    font-size: 16px;
    line-height: 1.6;
    color: #ffffff;
}

.host1 {
    background: linear-gradient(135deg, #4b6cb7, #182848);  /* Dark blue gradient */
}

.host2 {
    background: linear-gradient(135deg, #2c3e50, #4ca1af);  /* Slate gray gradient */
}

.narration {
    font-style: italic;
    color: #cccccc;
    margin: 10px 0;
    font-size: 15px;
}
"""

# === GRADIO INTERFACE ===
with gr.Blocks(css=custom_css) as demo:
    gr.Markdown("## 🎙️ Educational Podcast Generator for Students", elem_id="title")
    gr.Markdown("Enter an educational topic, and enjoy a friendly podcast conversation between Ali and Talha.")

    topic_input = gr.Textbox(label="Enter educational topic")
    generate_btn = gr.Button("🎧 Generate Podcast")
    output_box = gr.HTML()

    generate_btn.click(fn=generate, inputs=topic_input, outputs=output_box)

demo.launch()