Ansa12 commited on
Commit
75db4f2
Β·
verified Β·
1 Parent(s): a000f7f

Update app.py

Browse files
Files changed (1) hide show
  1. app.py +200 -27
app.py CHANGED
@@ -4,13 +4,14 @@ import json
4
  import re
5
  import os
6
 
7
- # Groq API configuration
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
  if not GROQ_API_KEY:
13
- return "❌ Please set your GROQ_API_KEY in Hugging Face Space secrets to generate stories."
14
 
15
  age_i = int(age)
16
  if age_i <= 6:
@@ -20,6 +21,7 @@ def generate_story(age, theme, language):
20
  else:
21
  length = "1000 words"
22
 
 
23
  payload = {
24
  "messages": [
25
  {
@@ -48,11 +50,13 @@ def generate_story(age, theme, language):
48
  try:
49
  response = requests.post(GROQ_API_URL, json=payload, headers=headers)
50
  response.raise_for_status()
 
51
  data = response.json()
52
  story = data["choices"][0]["message"]["content"].strip()
53
  return story
 
54
  except Exception as e:
55
- return f"Error generating story: {str(e)}"
56
 
57
  def story_to_speech(story, language_code='en'):
58
  try:
@@ -67,54 +71,223 @@ def story_to_speech(story, language_code='en'):
67
 
68
  def create_story_interface(age, theme, language, tts_option):
69
  story = generate_story(age, theme, language)
 
 
70
  story = re.sub(r'[*_#`~]', '', story)
71
 
72
- if language.lower().startswith("u"):
 
73
  lang_code = "ur"
74
- else:
75
  lang_code = "en"
76
 
77
  audio_file = story_to_speech(story, lang_code) if tts_option else None
 
78
  return story, audio_file
79
 
80
- # Options
81
  age_options = [str(i) for i in range(3, 13)]
82
- theme_options = ["Adventure", "Animals", "Fantasy", "Educational", "Friendship", "Magic", "Science", "Mystery", "Space", "Nature", "Kindness", "Courage"]
 
 
 
 
 
 
 
83
  language_options = ["English", "Urdu"]
84
 
85
- # Simple interface without complex styling
86
- with gr.Blocks(title="StoryTime AI - Magical Story Generator") as iface:
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
87
 
88
- gr.Markdown("# 🌈 StoryTime AI πŸŽͺ")
89
- gr.Markdown("### 🎯 Create amazing stories that spark imagination and teach valuable lessons!")
 
 
 
 
 
 
 
 
 
 
90
 
 
91
  if not GROQ_API_KEY:
92
- gr.Warning("⚠️ Please set GROQ_API_KEY in Hugging Face Space secrets")
 
 
 
 
 
 
 
 
 
 
93
 
94
  with gr.Row():
95
- with gr.Column():
 
 
96
  gr.Markdown("### 🎨 Story Settings")
97
- age_input = gr.Dropdown(age_options, label="πŸ‘Ά Child's Age", value="5")
98
- theme_input = gr.Dropdown(theme_options, label="🎭 Story Theme", value="Adventure")
99
- language_input = gr.Dropdown(language_options, label="🌍 Language", value="English")
100
- tts_input = gr.Checkbox(label="πŸ”Š Include Audio Story", value=True)
101
- generate_btn = gr.Button("✨ Create Magical Story! ✨", variant="primary")
 
 
102
 
103
- with gr.Column():
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
104
  gr.Markdown("### πŸ“– Your Magical Story")
105
- story_output = gr.Markdown("Your story will appear here! πŸŽ‡")
106
-
 
 
 
 
107
  gr.Markdown("### 🎧 Listen to Your Story")
108
- audio_output = gr.Audio(label="Audio Story")
 
 
 
 
109
 
110
- gr.Markdown("---")
111
- gr.Markdown("Made with ❀️ for young readers everywhere! | Watch your stories come to life! ✨")
 
 
 
 
112
 
113
  generate_btn.click(
114
  create_story_interface,
115
- [age_input, theme_input, language_input, tts_input],
116
- [story_output, audio_output]
117
  )
118
 
 
119
  if __name__ == "__main__":
120
- iface.launch()
 
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**\n\nTo use this app:\n1. Go to your Space Settings β†’ Repository secrets\n2. Add a new secret:\n - Name: `GROQ_API_KEY`\n - Value: Your Groq API key from https://console.groq.com\n3. Restart the Space"
15
 
16
  age_i = int(age)
17
  if age_i <= 6:
 
21
  else:
22
  length = "1000 words"
23
 
24
+ # Prepare the request payload for Groq API
25
  payload = {
26
  "messages": [
27
  {
 
50
  try:
51
  response = requests.post(GROQ_API_URL, json=payload, headers=headers)
52
  response.raise_for_status()
53
+
54
  data = response.json()
55
  story = data["choices"][0]["message"]["content"].strip()
56
  return story
57
+
58
  except Exception as e:
59
+ return f"Error generating story: {str(e)}\n\nPlease check your API key and try again."
60
 
61
  def story_to_speech(story, language_code='en'):
62
  try:
 
71
 
72
  def create_story_interface(age, theme, language, tts_option):
73
  story = generate_story(age, theme, language)
74
+
75
+ # Remove Markdown symbols (*, #, _, etc.) to prevent asterisks showing up
76
  story = re.sub(r'[*_#`~]', '', story)
77
 
78
+ # Generate audio if TTS is enabled
79
+ if language.lower().startswith("u"): # Urdu
80
  lang_code = "ur"
81
+ else: # English
82
  lang_code = "en"
83
 
84
  audio_file = story_to_speech(story, lang_code) if tts_option else None
85
+
86
  return story, audio_file
87
 
88
+ # Age options
89
  age_options = [str(i) for i in range(3, 13)]
90
+
91
+ # Theme options
92
+ theme_options = [
93
+ "Adventure", "Animals", "Fantasy", "Educational",
94
+ "Friendship", "Magic", "Science", "Mystery",
95
+ "Space", "Nature", "Kindness", "Courage"
96
+ ]
97
+
98
  language_options = ["English", "Urdu"]
99
 
100
+ # Custom CSS for child-friendly interface
101
+ custom_css = """
102
+ @import url('https://fonts.googleapis.com/css2?family=Comic+Neue:wght@400;700&display=swap');
103
+
104
+ .gradio-container {
105
+ font-family: 'Comic Neue', cursive !important;
106
+ background: linear-gradient(135deg, #ffafbd, #ffc3a0) !important;
107
+ padding: 20px !important;
108
+ }
109
+
110
+ .main-header {
111
+ text-align: center;
112
+ font-weight: bold !important;
113
+ font-size: 3.2em !important;
114
+ margin: 20px 0 !important;
115
+ text-shadow: 2px 2px 4px rgba(0,0,0,0.1);
116
+ color: #12979B;
117
+ }
118
+
119
+ .story-container {
120
+ background: #fff5ee !important;
121
+ border-radius: 20px !important;
122
+ padding: 25px !important;
123
+ border: 5px solid #FFD166 !important;
124
+ box-shadow: 0 8px 25px rgba(0,0,0,0.1) !important;
125
+ min-height: 400px !important;
126
+ margin: 20px 0 !important;
127
+ }
128
+
129
+ .control-panel {
130
+ background: #fff5ee !important;
131
+ border-radius: 15px !important;
132
+ padding: 20px !important;
133
+ border: 3px dashed #4ECDC4 !important;
134
+ margin: 20px 0 !important;
135
+ }
136
+
137
+ .generate-btn {
138
+ background: linear-gradient(45deg, #FF6B6B, #FF9E7D) !important;
139
+ border: none !important;
140
+ border-radius: 50px !important;
141
+ padding: 15px 30px !important;
142
+ font-size: 1.2em !important;
143
+ font-weight: bold !important;
144
+ color: white !important;
145
+ margin: 20px 0 !important;
146
+ width: 100% !important;
147
+ }
148
+
149
+ .generate-btn:hover {
150
+ transform: scale(1.05) !important;
151
+ box-shadow: 0 5px 15px rgba(255, 107, 107, 0.4) !important;
152
+ }
153
+
154
+ .dropdown, .checkbox {
155
+ background: white !important;
156
+ border-radius: 10px !important;
157
+ border: 2px solid #96CEB4 !important;
158
+ margin: 10px 0 !important;
159
+ }
160
+
161
+ .audio-player {
162
+ border-radius: 15px !important;
163
+ margin: 20px 0 !important;
164
+ }
165
+
166
+ .subtitle {
167
+ text-align: center !important;
168
+ font-size: 1.5em !important;
169
+ font-weight: 600 !important;
170
+ color: white !important;
171
+ margin: 20px 0 !important;
172
+ text-shadow: 1px 1px 2px rgba(0,0,0,0.1) !important;
173
+ }
174
+
175
+ .footer {
176
+ text-align: center !important;
177
+ margin: 20px 0 !important;
178
+ color: #666 !important;
179
+ font-style: italic !important;
180
+ font-size: 1.1em !important;
181
+ }
182
+
183
+ .warning-box {
184
+ background: #fff3cd !important;
185
+ border: 2px solid #ffeaa7 !important;
186
+ border-radius: 10px !important;
187
+ padding: 15px !important;
188
+ margin: 20px 0 !important;
189
+ }
190
+ """
191
+
192
+ # Create the interface with CSS
193
+ with gr.Blocks(css=custom_css, theme=gr.themes.Soft()) as iface:
194
 
195
+ # Header
196
+ gr.HTML("""
197
+ <div class="main-header">
198
+ 🌈 StoryTime AI πŸŽͺ
199
+ </div>
200
+ """)
201
+
202
+ gr.HTML("""
203
+ <div class="subtitle">
204
+ 🎯 Create amazing stories that spark imagination and teach valuable lessons!
205
+ </div>
206
+ """)
207
 
208
+ # API Key warning
209
  if not GROQ_API_KEY:
210
+ gr.HTML("""
211
+ <div class="warning-box">
212
+ <h3 style="color: #856404; margin: 0 0 10px 0;">⚠️ Setup Required</h3>
213
+ <p style="color: #856404; margin: 0;">
214
+ To generate stories, please add your <strong>GROQ_API_KEY</strong> in the Hugging Face Space settings:<br>
215
+ 1. Go to your Space β†’ Settings β†’ Repository secrets<br>
216
+ 2. Add new secret: Name = <code>GROQ_API_KEY</code>, Value = your_api_key<br>
217
+ 3. Get your API key from: <a href="https://console.groq.com" target="_blank">https://console.groq.com</a>
218
+ </p>
219
+ </div>
220
+ """)
221
 
222
  with gr.Row():
223
+ # Left Column - Controls
224
+ with gr.Column(scale=1, min_width=300):
225
+ gr.HTML('<div class="control-panel">')
226
  gr.Markdown("### 🎨 Story Settings")
227
+
228
+ age_input = gr.Dropdown(
229
+ age_options,
230
+ label="πŸ‘Ά Child's Age",
231
+ value="5",
232
+ info="Select age 3-12 years"
233
+ )
234
 
235
+ theme_input = gr.Dropdown(
236
+ theme_options,
237
+ label="🎭 Story Theme",
238
+ value="Adventure",
239
+ info="Choose your favorite theme"
240
+ )
241
+
242
+ language_input = gr.Dropdown(
243
+ language_options,
244
+ label="🌍 Language",
245
+ value="English",
246
+ info="English or Urdu"
247
+ )
248
+
249
+ tts_input = gr.Checkbox(
250
+ label="πŸ”Š Include Audio Story",
251
+ value=True,
252
+ info="Generate audio narration"
253
+ )
254
+
255
+ generate_btn = gr.Button(
256
+ "✨ Create Magical Story! ✨",
257
+ elem_classes="generate-btn"
258
+ )
259
+ gr.HTML('</div>')
260
+
261
+ # Right Column - Output
262
+ with gr.Column(scale=2):
263
+ gr.HTML('<div class="story-container">')
264
  gr.Markdown("### πŸ“– Your Magical Story")
265
+ story_output = gr.Markdown(
266
+ "🌟 **Welcome to StoryTime AI!** 🌟\n\nChoose your story settings on the left and click the magic button to create a wonderful story! Your adventure begins here...",
267
+ show_label=False
268
+ )
269
+ gr.HTML('</div>')
270
+
271
  gr.Markdown("### 🎧 Listen to Your Story")
272
+ audio_output = gr.Audio(
273
+ label="",
274
+ show_label=False,
275
+ interactive=False
276
+ )
277
 
278
+ # Footer
279
+ gr.HTML("""
280
+ <div class="footer">
281
+ Made with ❀️ for young readers everywhere! | Watch your stories come to life! ✨
282
+ </div>
283
+ """)
284
 
285
  generate_btn.click(
286
  create_story_interface,
287
+ inputs=[age_input, theme_input, language_input, tts_input],
288
+ outputs=[story_output, audio_output]
289
  )
290
 
291
+ # Launch without SSR to avoid the warning
292
  if __name__ == "__main__":
293
+ iface.launch(ssr_mode=False)