Ansa12 commited on
Commit
e91ce40
·
verified ·
1 Parent(s): 354be17

Update app.py

Browse files
Files changed (1) hide show
  1. app.py +44 -187
app.py CHANGED
@@ -4,234 +4,91 @@ import gradio as gr
4
  from gtts import gTTS
5
  import re
6
 
7
- # -------------------------------------------------------------
8
- # GET API KEY
9
- # -------------------------------------------------------------
10
- groq_key = os.environ.get("Groq_API_Key")
11
- if not groq_key:
12
- raise ValueError("Groq_API_Key not found in environment variables. Please add it to your Hugging Face Space secrets.")
13
-
14
  client = Groq(api_key=groq_key)
15
 
16
- # -------------------------------------------------------------
17
- # STORY GENERATION LOGIC
18
- # -------------------------------------------------------------
19
  def generate_story(age, theme, language):
20
- system_msg = {
21
- "role": "system",
22
- "content": "You write age-appropriate stories with complete endings and a moral."
23
- }
24
-
25
  age_i = int(age)
26
- if age_i <= 6:
27
- length = "300 words"
28
- elif age_i <= 9:
29
- length = "600 words"
30
- else:
31
- length = "1000 words"
32
-
33
  user_msg = {
34
  "role": "user",
35
- "content": (
36
- f"Write a complete story for a {age}-year-old child. "
37
- f"Theme: {theme}. Language: {language}. Length about {length}. "
38
- "End with a clear moral of the story."
39
- )
40
  }
41
-
42
  response = client.chat.completions.create(
43
  messages=[system_msg, user_msg],
44
- model="llama-3.3-70b-versatile",
45
  max_tokens=2000,
46
  temperature=0.8
47
  )
48
-
49
  return response.choices[0].message.content.strip()
50
 
51
- # -------------------------------------------------------------
52
- # TEXT TO SPEECH
53
- # -------------------------------------------------------------
54
- def story_to_speech(story, language_code="en"):
55
  tts = gTTS(text=story, lang=language_code)
56
- filename = "story.mp3"
57
  tts.save(filename)
58
  return filename
59
 
60
- # -------------------------------------------------------------
61
- # PROCESS STORY + AUDIO
62
- # -------------------------------------------------------------
63
  def create_story_interface(age, theme, language, tts_option):
64
  story = generate_story(age, theme, language)
65
  story = re.sub(r'[*_#`~]', '', story)
66
-
67
  lines = story.split("\n", 1)
68
- if len(lines) > 1:
69
- title, rest_of_story = lines[0], lines[1]
70
- else:
71
- title, rest_of_story = lines[0], ""
72
-
73
  if language.lower().startswith("u"):
74
- story_html = (
75
- f'<div style="text-align:center; font-size:1.3em; direction:rtl; margin-bottom:5px;">{title}</div>'
76
- f'<div style="font-size:1.2em; direction:rtl; text-align:right;">{rest_of_story}</div>'
77
- )
78
  lang_code = "ur"
79
  else:
80
- story_html = (
81
- f'<div style="text-align:center; font-size:1.3em; direction:ltr; margin-bottom:5px;">{title}</div>'
82
- f'<div style="font-size:1.2em; direction:ltr; text-align:left;">{rest_of_story}</div>'
83
- )
84
  lang_code = "en"
85
-
86
  audio_file = story_to_speech(story, lang_code) if tts_option else None
87
  return story_html, audio_file
88
 
89
- # -------------------------------------------------------------
90
- # UI OPTIONS
91
- # -------------------------------------------------------------
92
  age_options = [str(i) for i in range(3, 13)]
93
- theme_options = [
94
- "Adventure", "Animals", "Fantasy", "Educational",
95
- "Friendship", "Magic", "Science", "Mystery",
96
- "Space", "Nature", "Kindness", "Courage"
97
- ]
98
  language_options = ["English", "Urdu"]
99
 
100
- # -------------------------------------------------------------
101
- # CUSTOM CSS
102
- # -------------------------------------------------------------
103
- custom_css = """
104
- @import url('https://fonts.googleapis.com/css2?family=Comic+Neue:wght@400;700&display=swap');
105
- .gradio-container {
106
- font-family: 'Comic Neue', cursive !important;
107
- background: linear-gradient(135deg, #ffafbd, #ffc3a0) !important;
108
- padding-top: 10px !important;
109
- margin-top: -70px !important;
110
- }
111
- .main-header {
112
- text-align: center;
113
- font-weight: bold !important;
114
- font-size: 3.2em !important;
115
- margin-top: 40px !important;
116
- margin-bottom: 20px !important;
117
- text-shadow: 2px 2px 4px rgba(0,0,0,0.1);
118
- color: #12979B;
119
- }
120
- .story-container {
121
- background:#fff5ee;
122
- border-radius: 20px;
123
- padding: 25px;
124
- border: 5px solid #FFD166;
125
- box-shadow: 0 8px 25px rgba(0,0,0,0.1);
126
- min-height: 400px;
127
- margin-top: -20px !important;
128
- }
129
- .control-panel {
130
- background: #fff5ee;
131
- border-radius: 15px;
132
- padding: 20px;
133
- border: 3px dashed #4ECDC4;
134
- font-size: 1.2em !important;
135
- font-weight: 600;
136
- margin-top: -20px !important;
137
- }
138
- .generate-btn {
139
- background: linear-gradient(45deg, #FF6B6B, #FF9E7D) !important;
140
- border: none !important;
141
- border-radius: 50px !important;
142
- padding: 10px 22px !important;
143
- font-size: 1em !important;
144
- font-weight: bold !important;
145
- color: white !important;
146
- margin-top: 20px !important;
147
- }
148
- .generate-btn:hover {
149
- transform: scale(1.05);
150
- box-shadow: 0 5px 15px rgba(255, 107, 107, 0.4);
151
- }
152
- .dropdown, .checkbox {
153
- background: white !important;
154
- border-radius: 10px !important;
155
- border: 2px solid #96CEB4 !important;
156
- }
157
- .audio-player {
158
- border-radius: 15px !important;
159
- margin-top: 20px;
160
- }
161
- .subtitle {
162
- text-align: left;
163
- font-size: 1.5em !important;
164
- font-weight: 600;
165
- color: white;
166
- margin-top: -10px !important;
167
- margin-bottom: 20px;
168
- text-shadow: 1px 1px 2px rgba(0,0,0,0.1);
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
- # -------------------------------------------------------------
183
- # BUILD GRADIO INTERFACE
184
- # -------------------------------------------------------------
185
- with gr.Blocks() as iface: # Removed theme argument
186
- gr.HTML(f"<style>{custom_css}</style>")
187
-
188
- gr.HTML('<div class="main-header">🌈 StoryTime AI🎪</div>')
189
- gr.HTML('<div class="subtitle">🎯 Create amazing stories that spark imagination and teach valuable lessons!</div>')
190
-
191
  with gr.Row():
192
- # LEFT PANEL
193
  with gr.Column(scale=1, min_width=300):
194
  with gr.Group(elem_classes="control-panel"):
195
- gr.Markdown("### 🎨 Story Settings")
196
-
197
- with gr.Group():
198
- gr.Markdown("👶 Child's Age")
199
- age_input = gr.Dropdown(age_options, value="5", show_label=False)
200
-
201
- with gr.Group():
202
- gr.Markdown("🎭 Story Theme")
203
- theme_input = gr.Dropdown(theme_options, value="Adventure", show_label=False)
204
-
205
- with gr.Group():
206
- gr.Markdown("🌍 Language")
207
- language_input = gr.Dropdown(language_options, value="English", show_label=False)
208
-
209
- with gr.Group():
210
- gr.Markdown("🔊 Audio Options")
211
- tts_input = gr.Checkbox(label="🎵 Include Audio Story", value=True)
212
-
213
  generate_btn = gr.Button("✨ Create Magical Story! ✨", elem_classes="generate-btn")
214
-
215
- # RIGHT PANEL
216
  with gr.Column(scale=2):
217
  with gr.Group(elem_classes="story-container"):
218
- story_output = gr.Markdown(
219
- "Your story will appear here! Choose settings and click the magic button! 🎇",
220
- show_label=False
221
- )
222
-
223
- audio_output = gr.Audio(elem_classes="audio-player", show_label=False)
224
-
225
- gr.HTML('<div class="footer">Made with ❤ for young readers everywhere! | Watch your stories come to life! ✨</div>')
226
-
227
  generate_btn.click(
228
  create_story_interface,
229
  [age_input, theme_input, language_input, tts_input],
230
  [story_output, audio_output]
231
  )
232
- # -------------------------------------------------------------
233
- # LAUNCH APP
234
- # -------------------------------------------------------------
235
- if __name__ == "__main__":
236
- iface.launch()
237
 
 
 
4
  from gtts import gTTS
5
  import re
6
 
7
+ groq_key = os.environ.get("GROQ_API_KEY")
 
 
 
 
 
 
8
  client = Groq(api_key=groq_key)
9
 
 
 
 
10
  def generate_story(age, theme, language):
11
+ system_msg = {"role": "system", "content": "You write age-appropriate stories with complete endings and a moral."}
 
 
 
 
12
  age_i = int(age)
13
+ length = "300 words" if age_i <= 6 else "600 words" if age_i <= 9 else "1000 words"
 
 
 
 
 
 
14
  user_msg = {
15
  "role": "user",
16
+ "content": f"Write a complete story for a {age}-year-old child. Theme: {theme}. Language: {language}. Length about {length}. End with a clear moral of the story."
 
 
 
 
17
  }
 
18
  response = client.chat.completions.create(
19
  messages=[system_msg, user_msg],
20
+ model="openai/gpt-oss-20b",
21
  max_tokens=2000,
22
  temperature=0.8
23
  )
 
24
  return response.choices[0].message.content.strip()
25
 
26
+ def story_to_speech(story, language_code='en'):
 
 
 
27
  tts = gTTS(text=story, lang=language_code)
28
+ filename = "/tmp/story.mp3"
29
  tts.save(filename)
30
  return filename
31
 
 
 
 
32
  def create_story_interface(age, theme, language, tts_option):
33
  story = generate_story(age, theme, language)
34
  story = re.sub(r'[*_#`~]', '', story)
 
35
  lines = story.split("\n", 1)
36
+ title, rest_of_story = (lines[0], lines[1]) if len(lines) > 1 else (lines[0], "")
 
 
 
 
37
  if language.lower().startswith("u"):
38
+ story_html = f'<div style="text-align:center; font-size:1.3em; direction:rtl; margin-bottom:5px;">{title}</div><div style="font-size:1.2em; direction:rtl; text-align:right;">{rest_of_story}</div>'
 
 
 
39
  lang_code = "ur"
40
  else:
41
+ story_html = f'<div style="text-align:center; font-size:1.3em; direction:ltr; margin-bottom:5px;">{title}</div><div style="font-size:1.2em; direction:ltr; text-align:left;">{rest_of_story}</div>'
 
 
 
42
  lang_code = "en"
 
43
  audio_file = story_to_speech(story, lang_code) if tts_option else None
44
  return story_html, audio_file
45
 
 
 
 
46
  age_options = [str(i) for i in range(3, 13)]
47
+ theme_options = ["Adventure","Animals","Fantasy","Educational","Friendship","Magic","Science","Mystery","Space","Nature","Kindness","Courage"]
 
 
 
 
48
  language_options = ["English", "Urdu"]
49
 
50
+ # -----------------------------------------------
51
+ # GRADIO APP
52
+ # -----------------------------------------------
53
+ with gr.Blocks() as iface:
54
+ gr.HTML("""<style>
55
+ @import url('https://fonts.googleapis.com/css2?family=Comic+Neue:wght@400;700&display=swap');
56
+ .gradio-container { font-family: 'Comic Neue', cursive !important; background: linear-gradient(135deg, #ffafbd, #ffc3a0) !important; padding-top: 10px !important; margin-top: -70px !important;}
57
+ .main-header { text-align: center; font-weight: bold !important; font-size: 3.2em !important; margin-top: 40px !important; margin-bottom: 20px !important; text-shadow: 2px 2px 4px rgba(0,0,0,0.1); color: #12979B;}
58
+ .story-container { background:#fff5ee; border-radius: 20px; padding: 25px; border: 5px solid #FFD166; box-shadow: 0 8px 25px rgba(0,0,0,0.1); min-height: 400px; margin-top: -20px !important;}
59
+ .control-panel { background: #fff5ee; border-radius: 15px; padding: 20px; border: 3px dashed #4ECDC4; font-size: 1.2em !important; font-weight: 600; margin-top: -20px !important;}
60
+ .generate-btn { background: linear-gradient(45deg, #FF6B6B, #FF9E7D) !important; border: none !important; border-radius: 50px !important; padding: 10px 22px !important; font-size: 1em !important; font-weight: bold !important; color: white !important; margin-top: 20px !important;}
61
+ .generate-btn:hover { transform: scale(1.05); box-shadow: 0 5px 15px rgba(255, 107, 107, 0.4);}
62
+ .dropdown, .checkbox { background: white !important; border-radius: 10px !important; border: 2px solid #96CEB4 !important;}
63
+ .audio-player { border-radius: 15px !important; margin-top: 20px;}
64
+ .subtitle { text-align: left; font-size: 1.5em !important; font-weight: 600; color: white; margin-top: -10px !important; margin-bottom: 20px; text-shadow: 1px 1px 2px rgba(0,0,0,0.1);}
65
+ .footer { text-align: center; margin-top: 20px; color: #666; font-style: italic; font-size: 1.5em !important;}
66
+ </style>
67
+ """)
68
+
69
+
70
+ gr.HTML("""<div class="main-header">🌈 StoryTime AI🎪</div>""")
71
+ gr.HTML("""<div class="subtitle">🎯 Create amazing stories that spark imagination and teach valuable lessons!</div>""")
72
+
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
73
  with gr.Row():
 
74
  with gr.Column(scale=1, min_width=300):
75
  with gr.Group(elem_classes="control-panel"):
76
+ age_input = gr.Dropdown(age_options, label="👶 Child's Age", value="5")
77
+ theme_input = gr.Dropdown(theme_options, label="🎭 Story Theme", value="Adventure")
78
+ language_input = gr.Dropdown(language_options, label="🌍 Language", value="English")
79
+ tts_input = gr.Checkbox(label="🎵 Include Audio Story", value=True)
 
 
 
 
 
 
 
 
 
 
 
 
 
 
80
  generate_btn = gr.Button("✨ Create Magical Story! ✨", elem_classes="generate-btn")
 
 
81
  with gr.Column(scale=2):
82
  with gr.Group(elem_classes="story-container"):
83
+ story_output = gr.Markdown("Your story will appear here!", show_label=False)
84
+ audio_output = gr.Audio(label="Audio Story", elem_classes="audio-player")
85
+
86
+ gr.HTML("""<div class="footer">Made with ❤️ for young readers everywhere! | Watch your stories come to life! ✨</div>""")
87
+
 
 
 
 
88
  generate_btn.click(
89
  create_story_interface,
90
  [age_input, theme_input, language_input, tts_input],
91
  [story_output, audio_output]
92
  )
 
 
 
 
 
93
 
94
+ iface.launch(ssr_mode=False)