Ansa12 commited on
Commit
95d8968
Β·
verified Β·
1 Parent(s): e687be2

Update app.py

Browse files
Files changed (1) hide show
  1. app.py +118 -56
app.py CHANGED
@@ -1,18 +1,17 @@
1
- import os
2
- from groq import Groq
3
  import gradio as gr
 
4
  from gtts import gTTS
5
  import re
6
 
7
- # Get API key from HuggingFace Secrets
8
- client = Groq(api_key=os.environ["GROQ_API_KEY"])
9
 
10
  def generate_story(age, theme, language):
11
  system_msg = {
12
  "role": "system",
13
  "content": "You write age-appropriate stories with complete endings and a moral."
14
  }
15
-
16
  age_i = int(age)
17
  if age_i <= 6:
18
  length = "300 words"
@@ -20,7 +19,7 @@ def generate_story(age, theme, language):
20
  length = "600 words"
21
  else:
22
  length = "1000 words"
23
-
24
  user_msg = {
25
  "role": "user",
26
  "content": (
@@ -29,36 +28,41 @@ def generate_story(age, theme, language):
29
  "End with a clear moral of the story."
30
  )
31
  }
32
-
33
- response = client.chat.completions.create(
34
- messages=[system_msg, user_msg],
35
- model="openai/gpt-oss-20b",
36
- max_tokens=2000,
37
- temperature=0.8
38
- )
39
-
40
- story = response.choices[0].message.content.strip()
41
- return story
42
-
43
 
44
  def story_to_speech(story, language_code='en'):
45
- filename = "story.mp3"
46
- tts = gTTS(text=story, lang=language_code)
47
- tts.save(filename)
48
- return filename
49
-
 
 
 
50
 
51
  def create_story_interface(age, theme, language, tts_option):
52
  story = generate_story(age, theme, language)
53
-
54
- story = re.sub(r'[*_#`~]', '', story)
55
-
 
 
56
  lines = story.split("\n", 1)
57
  if len(lines) > 1:
58
  title, rest_of_story = lines[0], lines[1]
59
  else:
60
  title, rest_of_story = lines[0], ""
61
-
62
  if language.lower().startswith("u"): # Urdu
63
  story_html = (
64
  f'<div style="text-align:center; font-size:1.3em; direction:rtl; margin-bottom:5px;">{title}</div>'
@@ -71,30 +75,33 @@ def create_story_interface(age, theme, language, tts_option):
71
  f'<div style="font-size:1.2em; direction:ltr; text-align:left;">{rest_of_story}</div>'
72
  )
73
  lang_code = "en"
74
-
 
75
  audio_file = story_to_speech(story, lang_code) if tts_option else None
76
-
77
  return story_html, audio_file
78
 
79
-
80
  age_options = [str(i) for i in range(3, 13)]
 
 
81
  theme_options = [
82
- "Adventure", "Animals", "Fantasy", "Educational",
83
- "Friendship", "Magic", "Science", "Mystery",
84
- "Space", "Nature", "Kindness", "Courage"
85
  ]
 
 
86
  language_options = ["English", "Urdu"]
87
 
 
88
  custom_css = """
89
  @import url('https://fonts.googleapis.com/css2?family=Comic+Neue:wght@400;700&display=swap');
90
-
91
  .gradio-container {
92
  font-family: 'Comic Neue', cursive !important;
93
  background: linear-gradient(135deg, #ffafbd, #ffc3a0) !important;
94
  padding-top: 10px !important;
95
  margin-top: -70px !important;
96
  }
97
-
98
  .main-header {
99
  text-align: center;
100
  font-weight: bold !important;
@@ -104,7 +111,6 @@ custom_css = """
104
  text-shadow: 2px 2px 4px rgba(0,0,0,0.1);
105
  color: #12979B;
106
  }
107
-
108
  .story-container {
109
  background:#fff5ee;
110
  border-radius: 20px;
@@ -114,7 +120,6 @@ custom_css = """
114
  min-height: 400px;
115
  margin-top: -20px !important;
116
  }
117
-
118
  .control-panel {
119
  background: #fff5ee;
120
  border-radius: 15px;
@@ -124,7 +129,6 @@ custom_css = """
124
  font-weight: 600;
125
  margin-top: -20px !important;
126
  }
127
-
128
  .generate-btn {
129
  background: linear-gradient(45deg, #FF6B6B, #FF9E7D) !important;
130
  border: none !important;
@@ -135,52 +139,110 @@ custom_css = """
135
  color: white !important;
136
  margin-top: 20px !important;
137
  }
138
-
139
  .generate-btn:hover {
140
  transform: scale(1.05);
141
  box-shadow: 0 5px 15px rgba(255, 107, 107, 0.4);
142
  }
143
-
 
 
 
 
144
  .audio-player {
145
  border-radius: 15px !important;
146
  margin-top: 20px;
147
  }
148
-
149
  .subtitle {
 
150
  font-size: 1.5em !important;
151
  font-weight: 600;
152
  color: white;
 
153
  margin-bottom: 20px;
154
  text-shadow: 1px 1px 2px rgba(0,0,0,0.1);
155
  }
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
156
  """
157
 
 
158
  with gr.Blocks(css=custom_css, theme=gr.themes.Soft()) as iface:
159
- gr.HTML("<div class='main-header'>🌈 StoryTime AI πŸŽͺ</div>")
160
- gr.HTML("<div class='subtitle'>🎯 Create amazing stories that spark imagination and teach valuable lessons!</div>")
161
-
 
 
 
 
 
 
 
 
 
162
  with gr.Row():
163
  with gr.Column(scale=1, min_width=300):
164
  with gr.Group(elem_classes="control-panel"):
165
  gr.Markdown("### 🎨 Story Settings")
166
-
167
- age_input = gr.Dropdown(age_options, label="", value="5")
168
- theme_input = gr.Dropdown(theme_options, label="", value="Adventure")
169
- language_input = gr.Dropdown(language_options, label="", value="English")
170
- tts_input = gr.Checkbox(label="🎡 Include Audio Story", value=True)
171
-
172
- generate_btn = gr.Button("✨ Create Magical Story! ✨", elem_classes="generate-btn")
173
-
 
 
 
 
 
 
 
 
 
 
 
174
  with gr.Column(scale=2):
175
  with gr.Group(elem_classes="story-container"):
176
- story_output = gr.HTML("Your story will appear here! πŸŽ‡")
177
-
178
- audio_output = gr.Audio(label="Audio Story", elem_classes="audio-player")
179
-
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
180
  generate_btn.click(
181
  create_story_interface,
182
  [age_input, theme_input, language_input, tts_input],
183
  [story_output, audio_output]
184
  )
185
 
186
- iface.launch()
 
 
 
 
1
  import gradio as gr
2
+ from groq import Groq
3
  from gtts import gTTS
4
  import re
5
 
6
+ # Initialize Groq client
7
+ client = Groq()
8
 
9
  def generate_story(age, theme, language):
10
  system_msg = {
11
  "role": "system",
12
  "content": "You write age-appropriate stories with complete endings and a moral."
13
  }
14
+
15
  age_i = int(age)
16
  if age_i <= 6:
17
  length = "300 words"
 
19
  length = "600 words"
20
  else:
21
  length = "1000 words"
22
+
23
  user_msg = {
24
  "role": "user",
25
  "content": (
 
28
  "End with a clear moral of the story."
29
  )
30
  }
31
+
32
+ try:
33
+ response = client.chat.completions.create(
34
+ messages=[system_msg, user_msg],
35
+ model="openai/gpt-oss-20b",
36
+ max_tokens=2000,
37
+ temperature=0.8
38
+ )
39
+ return response.choices[0].message.content.strip()
40
+ except Exception as e:
41
+ return f"Error generating story: {str(e)}"
42
 
43
  def story_to_speech(story, language_code='en'):
44
+ try:
45
+ tts = gTTS(text=story, lang=language_code)
46
+ filename = "story.mp3"
47
+ tts.save(filename)
48
+ return filename
49
+ except Exception as e:
50
+ print(f"TTS Error: {e}")
51
+ return None
52
 
53
  def create_story_interface(age, theme, language, tts_option):
54
  story = generate_story(age, theme, language)
55
+
56
+ # Remove Markdown symbols (*, #, _, etc.) to prevent asterisks showing up
57
+ story = re.sub(r'[*_#~]', '', story)
58
+
59
+ # Split first line as title
60
  lines = story.split("\n", 1)
61
  if len(lines) > 1:
62
  title, rest_of_story = lines[0], lines[1]
63
  else:
64
  title, rest_of_story = lines[0], ""
65
+
66
  if language.lower().startswith("u"): # Urdu
67
  story_html = (
68
  f'<div style="text-align:center; font-size:1.3em; direction:rtl; margin-bottom:5px;">{title}</div>'
 
75
  f'<div style="font-size:1.2em; direction:ltr; text-align:left;">{rest_of_story}</div>'
76
  )
77
  lang_code = "en"
78
+
79
+ # Generate audio if TTS is enabled
80
  audio_file = story_to_speech(story, lang_code) if tts_option else None
81
+
82
  return story_html, audio_file
83
 
84
+ # Age options
85
  age_options = [str(i) for i in range(3, 13)]
86
+
87
+ # Theme options
88
  theme_options = [
89
+ "Adventure", "Animals", "Fantasy", "Educational", "Friendship",
90
+ "Magic", "Science", "Mystery", "Space", "Nature", "Kindness", "Courage"
 
91
  ]
92
+
93
+ # Language options
94
  language_options = ["English", "Urdu"]
95
 
96
+ # Custom CSS for child-friendly interface
97
  custom_css = """
98
  @import url('https://fonts.googleapis.com/css2?family=Comic+Neue:wght@400;700&display=swap');
 
99
  .gradio-container {
100
  font-family: 'Comic Neue', cursive !important;
101
  background: linear-gradient(135deg, #ffafbd, #ffc3a0) !important;
102
  padding-top: 10px !important;
103
  margin-top: -70px !important;
104
  }
 
105
  .main-header {
106
  text-align: center;
107
  font-weight: bold !important;
 
111
  text-shadow: 2px 2px 4px rgba(0,0,0,0.1);
112
  color: #12979B;
113
  }
 
114
  .story-container {
115
  background:#fff5ee;
116
  border-radius: 20px;
 
120
  min-height: 400px;
121
  margin-top: -20px !important;
122
  }
 
123
  .control-panel {
124
  background: #fff5ee;
125
  border-radius: 15px;
 
129
  font-weight: 600;
130
  margin-top: -20px !important;
131
  }
 
132
  .generate-btn {
133
  background: linear-gradient(45deg, #FF6B6B, #FF9E7D) !important;
134
  border: none !important;
 
139
  color: white !important;
140
  margin-top: 20px !important;
141
  }
 
142
  .generate-btn:hover {
143
  transform: scale(1.05);
144
  box-shadow: 0 5px 15px rgba(255, 107, 107, 0.4);
145
  }
146
+ .dropdown, .checkbox {
147
+ background: white !important;
148
+ border-radius: 10px !important;
149
+ border: 2px solid #96CEB4 !important;
150
+ }
151
  .audio-player {
152
  border-radius: 15px !important;
153
  margin-top: 20px;
154
  }
 
155
  .subtitle {
156
+ text-align: left;
157
  font-size: 1.5em !important;
158
  font-weight: 600;
159
  color: white;
160
+ margin-top: -10px !important;
161
  margin-bottom: 20px;
162
  text-shadow: 1px 1px 2px rgba(0,0,0,0.1);
163
  }
164
+ .control-panel .gr-Markdown {
165
+ font-size: 1.5em !important;
166
+ }
167
+ .story-container .gr-Markdown {
168
+ font-size: 1.5em !important;
169
+ }
170
+ .footer {
171
+ text-align: center;
172
+ margin-top: 20px;
173
+ color: #666;
174
+ font-style: italic;
175
+ font-size: 1.5em !important;
176
+ }
177
+ .main-header + div {
178
+ margin-top: -145px !important;
179
+ }
180
  """
181
 
182
+ # Create the interface
183
  with gr.Blocks(css=custom_css, theme=gr.themes.Soft()) as iface:
184
+ gr.HTML("""
185
+ <div class="main-header">
186
+ 🌈 StoryTime AIπŸŽͺ
187
+ </div>
188
+ """)
189
+
190
+ gr.HTML("""
191
+ <div class="subtitle">
192
+ 🎯 Create amazing stories that spark imagination and teach valuable lessons!
193
+ </div>
194
+ """)
195
+
196
  with gr.Row():
197
  with gr.Column(scale=1, min_width=300):
198
  with gr.Group(elem_classes="control-panel"):
199
  gr.Markdown("### 🎨 Story Settings")
200
+
201
+ with gr.Group():
202
+ gr.Markdown("πŸ‘Ά **Child's Age**")
203
+ age_input = gr.Dropdown(age_options, label="", value="5", show_label=False)
204
+
205
+ with gr.Group():
206
+ gr.Markdown("🎭 **Story Theme**")
207
+ theme_input = gr.Dropdown(theme_options, label="", value="Adventure", show_label=False)
208
+
209
+ with gr.Group():
210
+ gr.Markdown("🌍 **Language**")
211
+ language_input = gr.Dropdown(language_options, label="", value="English", show_label=False)
212
+
213
+ with gr.Group():
214
+ gr.Markdown("πŸ”Š **Audio Options**")
215
+ tts_input = gr.Checkbox(label="🎡 Include Audio Story", value=True)
216
+
217
+ generate_btn = gr.Button("✨ Create Magical Story! ✨", elem_classes="generate-btn", size="lg")
218
+
219
  with gr.Column(scale=2):
220
  with gr.Group(elem_classes="story-container"):
221
+ gr.Markdown("### πŸ“– Your Magical Story")
222
+ story_output = gr.Markdown(
223
+ "Your story will appear here! Choose settings and click the magic button! πŸŽ‡",
224
+ show_label=False
225
+ )
226
+
227
+ with gr.Group():
228
+ gr.Markdown("### 🎧 Listen to Your Story")
229
+ audio_output = gr.Audio(
230
+ label="Audio Story",
231
+ elem_classes="audio-player",
232
+ show_label=False
233
+ )
234
+
235
+ gr.HTML("""
236
+ <div class="footer">
237
+ Made with ❀️ for young readers everywhere! | Watch your stories come to life! ✨
238
+ </div>
239
+ """)
240
+
241
  generate_btn.click(
242
  create_story_interface,
243
  [age_input, theme_input, language_input, tts_input],
244
  [story_output, audio_output]
245
  )
246
 
247
+ if __name__ == "__main__":
248
+ iface.launch()