Poojashetty357 commited on
Commit
688b946
Β·
verified Β·
1 Parent(s): f2692e4

Create app.py

Browse files
Files changed (1) hide show
  1. app.py +122 -0
app.py ADDED
@@ -0,0 +1,122 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # πŸ“Œ Step 1: Install required packages
2
+ !pip install --upgrade openai gradio fpdf gTTS
3
+
4
+ # πŸ“Œ Step 2: Import Libraries
5
+ from dotenv import load_dotenv
6
+ import os
7
+ import gradio as gr
8
+ from openai import OpenAI
9
+ from fpdf import FPDF
10
+ from datetime import datetime
11
+ from gtts import gTTS
12
+
13
+ # πŸ“Œ Step 3: Load environment variables from .env file
14
+ load_dotenv()
15
+ api_key = os.getenv("OPENAI_API_KEY")
16
+ client = OpenAI(api_key=api_key)
17
+
18
+ # πŸ“Œ Step 4: Directory to save stories
19
+ story_dir = "/content/storybot_stories"
20
+ os.makedirs(story_dir, exist_ok=True)
21
+
22
+ # πŸ“Œ Step 5: Save story to PDF
23
+ def save_story_as_pdf(story_text, character_name=""):
24
+ date_str = datetime.now().strftime("%Y-%m-%d_%H-%M-%S")
25
+ file_name = f"{character_name or 'story'}_{date_str}.pdf"
26
+ file_path = os.path.join(story_dir, file_name)
27
+
28
+ pdf = FPDF()
29
+ pdf.add_page()
30
+ pdf.set_font("Arial", 'B', 16)
31
+ pdf.cell(200, 10, txt=f"{character_name}'s Adventure", ln=True, align='C')
32
+ pdf.set_font("Arial", size=12)
33
+ pdf.ln(10)
34
+
35
+ for line in story_text.split('\n'):
36
+ pdf.multi_cell(0, 10, line)
37
+
38
+ pdf.add_page()
39
+ pdf.set_font("Arial", 'I', 14)
40
+ pdf.cell(200, 10, txt="The End", ln=True, align='C')
41
+ pdf.ln(10)
42
+ pdf.set_font("Arial", size=10)
43
+ pdf.cell(200, 10, txt="Created with Magic StoryBot", ln=True, align='C')
44
+
45
+ pdf.output(file_path)
46
+ return file_path
47
+
48
+ # πŸ“Œ Step 6: Convert story to speech
49
+ def text_to_speech(text):
50
+ tts = gTTS(text)
51
+ audio_path = "/content/story_audio.mp3"
52
+ tts.save(audio_path)
53
+ return audio_path
54
+
55
+ # πŸ“Œ Step 7: Generate story from LLM
56
+ def generate_story(age_group, theme, character_name, tone, length):
57
+ length_instruction = {
58
+ "Short": "about 100 words",
59
+ "Medium": "about 200 words",
60
+ "Long": "about 350 words"
61
+ }.get(length, "about 150 words")
62
+
63
+ system_prompt = f"""
64
+ You are a children's storyteller. Create a {length_instruction}, age-appropriate story for a child aged {age_group}.
65
+ Use the theme "{theme}" and the main character's name is "{character_name}".
66
+ Make the tone of the story {tone.lower()}. End it with the phrase "The End".
67
+ """
68
+
69
+ messages = [
70
+ {"role": "system", "content": system_prompt},
71
+ {"role": "user", "content": "Please generate the story now."}
72
+ ]
73
+
74
+ try:
75
+ response = client.chat.completions.create(
76
+ model="gpt-3.5-turbo",
77
+ messages=messages,
78
+ temperature=0.7,
79
+ max_tokens=1024,
80
+ stop=None
81
+ )
82
+ print("LLM Response:", response) # Debug print
83
+ story = response.choices[0].message.content
84
+ except Exception as e:
85
+ print("LLM ERROR:", e)
86
+ story = f"An error occurred: {str(e)}"
87
+
88
+ audio_path = text_to_speech(story)
89
+ return story, story, audio_path
90
+
91
+ # πŸ“Œ Step 8: Gradio Interface
92
+ with gr.Blocks() as app:
93
+ gr.Markdown("## πŸ“– Magic StoryBot for Kids")
94
+
95
+ age_group = gr.Dropdown(["1–3", "3–5", "6–8", "9–12"], label="Select Age Group")
96
+ theme = gr.Dropdown(["Animals", "Adventure", "Magic", "Mystery", "Bedtime"], label="Choose a Story Theme")
97
+ character_name = gr.Textbox(label="Main Character's Name", placeholder="e.g., Luna, Max")
98
+ tone = gr.Dropdown(["Happy", "Funny", "Gentle", "Spooky", "Exciting", "Calm"], label="Story Tone")
99
+ length = gr.Radio(["Short", "Medium", "Long"], label="Story Length")
100
+
101
+ story_output = gr.Textbox(label="Generated Story", lines=10)
102
+ story_audio = gr.Audio(label="Listen", autoplay=True)
103
+ pdf_output = gr.File(label="Download Your Story", file_types=[".pdf"], visible=True)
104
+
105
+ def start_story(age, theme, name, tone, length):
106
+ story, _, audio = generate_story(age, theme, name, tone, length)
107
+ return story, audio
108
+
109
+ def export_pdf(story, name):
110
+ pdf_path = save_story_as_pdf(story, name)
111
+ return pdf_path
112
+
113
+ start_btn = gr.Button("🌟 Generate Story")
114
+ save_btn = gr.Button("πŸ“₯ Save Story as PDF")
115
+
116
+ start_btn.click(start_story,
117
+ inputs=[age_group, theme, character_name, tone, length],
118
+ outputs=[story_output, story_audio])
119
+
120
+ save_btn.click(export_pdf, inputs=[story_output, character_name], outputs=pdf_output)
121
+
122
+ app.launch()