Ansa12 commited on
Commit
e1e334a
Β·
verified Β·
1 Parent(s): 569d0ae

Update app.py

Browse files
Files changed (1) hide show
  1. app.py +89 -82
app.py CHANGED
@@ -1,15 +1,18 @@
1
  import gradio as gr
2
  import requests
3
  import json
4
- from gtts import gTTS
5
  import re
6
  import os
7
 
8
- # Groq API configuration
9
  GROQ_API_KEY = os.environ.get("GROQ_API_KEY")
10
  GROQ_API_URL = "https://api.groq.com/openai/v1/chat/completions"
11
 
12
  def generate_story(age, theme, language):
 
 
 
 
13
  age_i = int(age)
14
  if age_i <= 6:
15
  length = "300 words"
@@ -17,16 +20,8 @@ def generate_story(age, theme, language):
17
  length = "600 words"
18
  else:
19
  length = "1000 words"
20
-
21
- # Prepare the prompt
22
- prompt = (
23
- f"Write a complete story for a {age}-year-old child. "
24
- f"Theme: {theme}. Language: {language}. Length about {length}. "
25
- "End with a clear moral of the story. "
26
- "Make it engaging and age-appropriate."
27
- )
28
-
29
- # Prepare the request payload
30
  payload = {
31
  "messages": [
32
  {
@@ -35,19 +30,23 @@ def generate_story(age, theme, language):
35
  },
36
  {
37
  "role": "user",
38
- "content": prompt
 
 
 
 
39
  }
40
  ],
41
- "model": "llama-3.1-8b-instant", # Using a model that's available on Groq
42
  "max_tokens": 2000,
43
  "temperature": 0.8
44
  }
45
-
46
  headers = {
47
  "Authorization": f"Bearer {GROQ_API_KEY}",
48
  "Content-Type": "application/json"
49
  }
50
-
51
  try:
52
  response = requests.post(GROQ_API_URL, json=payload, headers=headers)
53
  response.raise_for_status()
@@ -61,100 +60,101 @@ def generate_story(age, theme, language):
61
 
62
  def story_to_speech(story, language_code='en'):
63
  try:
64
- # Clean story for TTS
65
- clean_story = re.sub(r'[*_#~`]', '', story)
66
- tts = gTTS(text=clean_story, lang=language_code, slow=False)
 
67
  filename = "story.mp3"
68
  tts.save(filename)
69
  return filename
70
  except Exception as e:
 
71
  print(f"TTS Error: {e}")
72
  return None
73
 
74
  def create_story_interface(age, theme, language, tts_option):
75
- if not GROQ_API_KEY:
76
- error_html = '<div style="color: red; text-align: center; font-size: 1.5em;">⚠️ Please set your GROQ_API_KEY in the Hugging Face Space secrets</div>'
77
- return error_html, None
78
-
79
  story = generate_story(age, theme, language)
80
-
81
- # Remove Markdown symbols
82
- story = re.sub(r'[*_#~`]', '', story)
83
-
84
  # Split first line as title
85
  lines = story.split("\n", 1)
86
  if len(lines) > 1:
87
  title, rest_of_story = lines[0], lines[1]
88
  else:
89
  title, rest_of_story = lines[0], ""
90
-
91
- if language.lower() == "urdu": # Urdu
92
  story_html = (
93
- f'<div style="text-align:center; font-size:1.3em; direction:rtl; margin-bottom:15px; font-weight: bold; color: #2c5530;">{title}</div>'
94
- f'<div style="font-size:1.2em; direction:rtl; text-align:right; line-height: 1.6;">{rest_of_story}</div>'
95
  )
96
  lang_code = "ur"
97
  else: # English
98
  story_html = (
99
- f'<div style="text-align:center; font-size:1.3em; direction:ltr; margin-bottom:15px; font-weight: bold; color: #2c5530;">{title}</div>'
100
- f'<div style="font-size:1.2em; direction:ltr; text-align:left; line-height: 1.6;">{rest_of_story}</div>'
101
  )
102
  lang_code = "en"
103
-
104
  # Generate audio if TTS is enabled
105
  audio_file = story_to_speech(story, lang_code) if tts_option else None
106
-
107
- return story_html, audio_file
108
 
109
  # Age options
110
  age_options = [str(i) for i in range(3, 13)]
111
 
112
  # Theme options
113
  theme_options = [
114
- "Adventure", "Animals", "Fantasy", "Educational", "Friendship",
115
- "Magic", "Science", "Mystery", "Space", "Nature", "Kindness", "Courage"
 
116
  ]
117
 
118
- # Language options
119
  language_options = ["English", "Urdu"]
120
 
121
  # Custom CSS for child-friendly interface
122
  custom_css = """
123
  @import url('https://fonts.googleapis.com/css2?family=Comic+Neue:wght@400;700&display=swap');
 
124
  .gradio-container {
125
  font-family: 'Comic Neue', cursive !important;
126
  background: linear-gradient(135deg, #ffafbd, #ffc3a0) !important;
127
- padding: 20px;
128
  }
 
129
  .main-header {
130
  text-align: center;
131
  font-weight: bold !important;
132
- font-size: 3em !important;
133
- margin: 20px 0;
 
134
  text-shadow: 2px 2px 4px rgba(0,0,0,0.1);
135
  color: #12979B;
136
  }
137
- .subtitle {
138
- text-align: center;
139
- font-size: 1.3em !important;
140
- color: white;
141
- margin-bottom: 30px;
142
- text-shadow: 1px 1px 2px rgba(0,0,0,0.2);
143
- }
144
  .story-container {
145
- background: #fff5ee;
146
  border-radius: 20px;
147
  padding: 25px;
148
  border: 5px solid #FFD166;
149
  box-shadow: 0 8px 25px rgba(0,0,0,0.1);
150
  min-height: 400px;
 
151
  }
 
152
  .control-panel {
153
  background: #fff5ee;
154
  border-radius: 15px;
155
  padding: 20px;
156
  border: 3px dashed #4ECDC4;
 
 
 
157
  }
 
158
  .generate-btn {
159
  background: linear-gradient(45deg, #FF6B6B, #FF9E7D) !important;
160
  border: none !important;
@@ -163,113 +163,120 @@ custom_css = """
163
  font-size: 1.2em !important;
164
  font-weight: bold !important;
165
  color: white !important;
166
- margin: 20px 0;
167
  width: 100%;
168
  }
 
169
  .generate-btn:hover {
170
  transform: scale(1.05);
171
  box-shadow: 0 5px 15px rgba(255, 107, 107, 0.4);
172
  }
 
173
  .dropdown, .checkbox {
174
  background: white !important;
175
  border-radius: 10px !important;
176
  border: 2px solid #96CEB4 !important;
177
  margin: 10px 0;
178
  }
 
179
  .audio-player {
180
  border-radius: 15px !important;
181
- margin: 20px 0;
 
 
 
 
 
 
 
 
 
182
  }
 
183
  .footer {
184
  text-align: center;
185
  margin-top: 20px;
186
  color: #666;
187
  font-style: italic;
 
188
  }
189
  """
190
 
191
- # Create the interface
192
  with gr.Blocks(css=custom_css, theme=gr.themes.Soft()) as iface:
193
  gr.HTML("""
194
  <div class="main-header">
195
- 🌈 StoryTime AI πŸŽͺ
196
  </div>
197
  """)
198
-
199
  gr.HTML("""
200
  <div class="subtitle">
201
- 🎯 Create amazing stories that spark imagination and teach valuable lessons!
202
  </div>
203
  """)
204
 
 
 
 
 
205
  with gr.Row():
206
  with gr.Column(scale=1, min_width=300):
207
  with gr.Group(elem_classes="control-panel"):
208
  gr.Markdown("### 🎨 Story Settings")
209
-
210
  age_input = gr.Dropdown(
211
  age_options,
212
  label="πŸ‘Ά Child's Age",
213
  value="5",
214
  info="Select age 3-12 years"
215
  )
216
-
217
  theme_input = gr.Dropdown(
218
  theme_options,
219
  label="🎭 Story Theme",
220
  value="Adventure",
221
  info="Choose your favorite theme"
222
  )
223
-
224
  language_input = gr.Dropdown(
225
  language_options,
226
  label="🌍 Language",
227
  value="English",
228
  info="English or Urdu"
229
  )
230
-
231
  tts_input = gr.Checkbox(
232
  label="πŸ”Š Include Audio Story",
233
  value=True,
234
- info="Listen to the story"
235
  )
236
-
237
  generate_btn = gr.Button(
238
  "✨ Create Magical Story! ✨",
239
  elem_classes="generate-btn"
240
  )
241
-
242
  with gr.Column(scale=2):
243
  with gr.Group(elem_classes="story-container"):
244
  gr.Markdown("### πŸ“– Your Magical Story")
245
- story_output = gr.HTML(
246
- "<div style='text-align: center; color: #666; font-style: italic;'>Your story will appear here! Choose settings and click the magic button! πŸŽ‡</div>"
 
247
  )
248
-
249
  with gr.Group():
250
  gr.Markdown("### 🎧 Listen to Your Story")
251
  audio_output = gr.Audio(
252
- label="",
253
  show_label=False
254
  )
255
-
256
  gr.HTML("""
257
  <div class="footer">
258
- Made with ❀️ for young readers everywhere! | Watch your stories come to life! ✨
259
  </div>
260
  """)
261
-
262
- # Handle the case when API key is not set
263
- if not GROQ_API_KEY:
264
- gr.HTML("""
265
- <div style="background: #ffebee; padding: 20px; border-radius: 10px; border: 2px solid #f44336; margin: 20px 0;">
266
- <h3 style="color: #c62828; margin: 0;">⚠️ Configuration Required</h3>
267
- <p style="margin: 10px 0 0 0; color: #d32f2f;">
268
- Please set your GROQ_API_KEY in the Hugging Face Space secrets to use this app.
269
- </p>
270
- </div>
271
- """)
272
-
273
  generate_btn.click(
274
  create_story_interface,
275
  [age_input, theme_input, language_input, tts_input],
@@ -277,4 +284,4 @@ with gr.Blocks(css=custom_css, theme=gr.themes.Soft()) as iface:
277
  )
278
 
279
  if __name__ == "__main__":
280
- iface.launch(share=False)
 
1
  import gradio as gr
2
  import requests
3
  import json
 
4
  import re
5
  import os
6
 
7
+ # Groq API configuration - will be set via Hugging Face secrets
8
  GROQ_API_KEY = os.environ.get("GROQ_API_KEY")
9
  GROQ_API_URL = "https://api.groq.com/openai/v1/chat/completions"
10
 
11
  def generate_story(age, theme, language):
12
+ # Check if API key is available
13
+ if not GROQ_API_KEY:
14
+ return "❌ Please set your GROQ_API_KEY in Hugging Face Space secrets to generate stories."
15
+
16
  age_i = int(age)
17
  if age_i <= 6:
18
  length = "300 words"
 
20
  length = "600 words"
21
  else:
22
  length = "1000 words"
23
+
24
+ # Prepare the request payload for Groq API
 
 
 
 
 
 
 
 
25
  payload = {
26
  "messages": [
27
  {
 
30
  },
31
  {
32
  "role": "user",
33
+ "content": (
34
+ f"Write a complete story for a {age}-year-old child. "
35
+ f"Theme: {theme}. Language: {language}. Length about {length}. "
36
+ "End with a clear moral of the story."
37
+ )
38
  }
39
  ],
40
+ "model": "llama-3.1-8b-instant",
41
  "max_tokens": 2000,
42
  "temperature": 0.8
43
  }
44
+
45
  headers = {
46
  "Authorization": f"Bearer {GROQ_API_KEY}",
47
  "Content-Type": "application/json"
48
  }
49
+
50
  try:
51
  response = requests.post(GROQ_API_URL, json=payload, headers=headers)
52
  response.raise_for_status()
 
60
 
61
  def story_to_speech(story, language_code='en'):
62
  try:
63
+ # For Hugging Face deployment, we'll use a simple audio generation
64
+ # Note: gTTS might not work reliably on Hugging Face, so we provide alternative
65
+ from gtts import gTTS
66
+ tts = gTTS(text=story, lang=language_code)
67
  filename = "story.mp3"
68
  tts.save(filename)
69
  return filename
70
  except Exception as e:
71
+ # Fallback: Return a message about audio being unavailable
72
  print(f"TTS Error: {e}")
73
  return None
74
 
75
  def create_story_interface(age, theme, language, tts_option):
 
 
 
 
76
  story = generate_story(age, theme, language)
77
+
78
+ # Remove Markdown symbols (*, #, _, etc.) to prevent asterisks showing up
79
+ story = re.sub(r'[*_#`~]', '', story)
80
+
81
  # Split first line as title
82
  lines = story.split("\n", 1)
83
  if len(lines) > 1:
84
  title, rest_of_story = lines[0], lines[1]
85
  else:
86
  title, rest_of_story = lines[0], ""
87
+
88
+ if language.lower().startswith("u"): # Urdu
89
  story_html = (
90
+ f'<div style="text-align:center; font-size:1.3em; direction:rtl; margin-bottom:5px;">{title}</div>'
91
+ f'<div style="font-size:1.2em; direction:rtl; text-align:right;">{rest_of_story}</div>'
92
  )
93
  lang_code = "ur"
94
  else: # English
95
  story_html = (
96
+ f'<div style="text-align:center; font-size:1.3em; direction:ltr; margin-bottom:5px;">{title}</div>'
97
+ f'<div style="font-size:1.2em; direction:ltr; text-align:left;">{rest_of_story}</div>'
98
  )
99
  lang_code = "en"
100
+
101
  # Generate audio if TTS is enabled
102
  audio_file = story_to_speech(story, lang_code) if tts_option else None
103
+
104
+ return story, audio_file
105
 
106
  # Age options
107
  age_options = [str(i) for i in range(3, 13)]
108
 
109
  # Theme options
110
  theme_options = [
111
+ "Adventure", "Animals", "Fantasy", "Educational",
112
+ "Friendship", "Magic", "Science", "Mystery",
113
+ "Space", "Nature", "Kindness", "Courage"
114
  ]
115
 
 
116
  language_options = ["English", "Urdu"]
117
 
118
  # Custom CSS for child-friendly interface
119
  custom_css = """
120
  @import url('https://fonts.googleapis.com/css2?family=Comic+Neue:wght@400;700&display=swap');
121
+
122
  .gradio-container {
123
  font-family: 'Comic Neue', cursive !important;
124
  background: linear-gradient(135deg, #ffafbd, #ffc3a0) !important;
125
+ padding-top: 10px !important;
126
  }
127
+
128
  .main-header {
129
  text-align: center;
130
  font-weight: bold !important;
131
+ font-size: 3.2em !important;
132
+ margin-top: 40px !important;
133
+ margin-bottom: 20px !important;
134
  text-shadow: 2px 2px 4px rgba(0,0,0,0.1);
135
  color: #12979B;
136
  }
137
+
 
 
 
 
 
 
138
  .story-container {
139
+ background:#fff5ee;
140
  border-radius: 20px;
141
  padding: 25px;
142
  border: 5px solid #FFD166;
143
  box-shadow: 0 8px 25px rgba(0,0,0,0.1);
144
  min-height: 400px;
145
+ margin-top: 20px !important;
146
  }
147
+
148
  .control-panel {
149
  background: #fff5ee;
150
  border-radius: 15px;
151
  padding: 20px;
152
  border: 3px dashed #4ECDC4;
153
+ font-size: 1.2em !important;
154
+ font-weight: 600;
155
+ margin-top: 20px !important;
156
  }
157
+
158
  .generate-btn {
159
  background: linear-gradient(45deg, #FF6B6B, #FF9E7D) !important;
160
  border: none !important;
 
163
  font-size: 1.2em !important;
164
  font-weight: bold !important;
165
  color: white !important;
166
+ margin-top: 20px !important;
167
  width: 100%;
168
  }
169
+
170
  .generate-btn:hover {
171
  transform: scale(1.05);
172
  box-shadow: 0 5px 15px rgba(255, 107, 107, 0.4);
173
  }
174
+
175
  .dropdown, .checkbox {
176
  background: white !important;
177
  border-radius: 10px !important;
178
  border: 2px solid #96CEB4 !important;
179
  margin: 10px 0;
180
  }
181
+
182
  .audio-player {
183
  border-radius: 15px !important;
184
+ margin-top: 20px;
185
+ }
186
+
187
+ .subtitle {
188
+ text-align: center;
189
+ font-size: 1.5em !important;
190
+ font-weight: 600;
191
+ color: white;
192
+ margin-bottom: 20px;
193
+ text-shadow: 1px 1px 2px rgba(0,0,0,0.1);
194
  }
195
+
196
  .footer {
197
  text-align: center;
198
  margin-top: 20px;
199
  color: #666;
200
  font-style: italic;
201
+ font-size: 1.1em !important;
202
  }
203
  """
204
 
 
205
  with gr.Blocks(css=custom_css, theme=gr.themes.Soft()) as iface:
206
  gr.HTML("""
207
  <div class="main-header">
208
+ 🌈 StoryTime AI πŸŽͺ
209
  </div>
210
  """)
211
+
212
  gr.HTML("""
213
  <div class="subtitle">
214
+ 🎯 Create amazing stories that spark imagination and teach valuable lessons!
215
  </div>
216
  """)
217
 
218
+ # API Key warning
219
+ if not GROQ_API_KEY:
220
+ gr.Warning("⚠️ Please set GROQ_API_KEY in Hugging Face Space secrets to use this app")
221
+
222
  with gr.Row():
223
  with gr.Column(scale=1, min_width=300):
224
  with gr.Group(elem_classes="control-panel"):
225
  gr.Markdown("### 🎨 Story Settings")
226
+
227
  age_input = gr.Dropdown(
228
  age_options,
229
  label="πŸ‘Ά Child's Age",
230
  value="5",
231
  info="Select age 3-12 years"
232
  )
233
+
234
  theme_input = gr.Dropdown(
235
  theme_options,
236
  label="🎭 Story Theme",
237
  value="Adventure",
238
  info="Choose your favorite theme"
239
  )
240
+
241
  language_input = gr.Dropdown(
242
  language_options,
243
  label="🌍 Language",
244
  value="English",
245
  info="English or Urdu"
246
  )
247
+
248
  tts_input = gr.Checkbox(
249
  label="πŸ”Š Include Audio Story",
250
  value=True,
251
+ info="Listen to the story (may not work in all environments)"
252
  )
253
+
254
  generate_btn = gr.Button(
255
  "✨ Create Magical Story! ✨",
256
  elem_classes="generate-btn"
257
  )
258
+
259
  with gr.Column(scale=2):
260
  with gr.Group(elem_classes="story-container"):
261
  gr.Markdown("### πŸ“– Your Magical Story")
262
+ story_output = gr.Markdown(
263
+ "Your story will appear here! Choose settings and click the magic button! πŸŽ‡",
264
+ show_label=False
265
  )
266
+
267
  with gr.Group():
268
  gr.Markdown("### 🎧 Listen to Your Story")
269
  audio_output = gr.Audio(
270
+ label="Audio Story",
271
  show_label=False
272
  )
273
+
274
  gr.HTML("""
275
  <div class="footer">
276
+ Made with ❀️ for young readers everywhere! | Watch your stories come to life! ✨
277
  </div>
278
  """)
279
+
 
 
 
 
 
 
 
 
 
 
 
280
  generate_btn.click(
281
  create_story_interface,
282
  [age_input, theme_input, language_input, tts_input],
 
284
  )
285
 
286
  if __name__ == "__main__":
287
+ iface.launch()