Rathapoom commited on
Commit
dfb26ce
·
verified ·
1 Parent(s): e046fa6

Update app.py

Browse files
Files changed (1) hide show
  1. app.py +165 -77
app.py CHANGED
@@ -1,86 +1,174 @@
1
  import streamlit as st
2
  import openai
3
- from datetime import datetime
4
-
5
- # Custom CSS for layout
6
- st.markdown("""
7
- <style>
8
- .box-container {
9
- background-color: #ffffff;
10
- border-radius: 10px;
11
- padding: 20px;
12
- margin: 10px 0;
13
- border: 2px solid #eee;
14
- box-shadow: 0 2px 5px rgba(0,0,0,0.1);
15
- }
16
-
17
- .story-box {
18
- max-height: 300px;
19
- overflow-y: auto;
20
- padding: 15px;
21
- background-color: #f8f9fa;
22
- border-radius: 8px;
23
- }
24
-
25
- .input-box {
26
- background-color: #ffffff;
27
- padding: 15px;
28
- border-radius: 8px;
29
- }
30
- </style>
31
- """, unsafe_allow_html=True)
32
-
33
- # ตั้งค่า API Key
34
- openai.api_key = st.secrets["OPENAI_API_KEY"]
35
 
36
  # Initialize session state variables
37
  if 'story' not in st.session_state:
38
- st.session_state.story = ["Once upon a time, in a magical forest..."]
39
- if 'story_started' not in st.session_state:
40
- st.session_state.story_started = False
41
-
42
- def continue_story(user_input):
43
- """Get story continuation from OpenAI API"""
44
- story_context = " ".join(st.session_state.story)
45
-
46
- response = openai.ChatCompletion.create(
47
- model="gpt-4o-mini",
48
- messages=[
49
- {"role": "system", "content": "You are a creative storyteller helping to continue a story with interesting details. Keep it simple and coherent."},
50
- {"role": "user", "content": f"Story so far: {story_context}"},
51
- {"role": "user", "content": f"Continue with: {user_input}"}
52
- ],
 
 
 
 
53
  temperature=0.7,
54
- max_tokens=50
55
  )
56
- return response.choices[0].message.content.strip()
57
-
58
- # Main application
59
- st.title("🎨 Interactive Story Adventure")
60
- st.subheader("Let's create a fun story together!")
61
-
62
- # Start story button
63
- if not st.session_state.story_started:
64
- if st.button("Start Story"):
65
- st.session_state.story_started = True
66
- st.success("Story started! Let's add to it.")
67
-
68
- # Display story so far
69
- st.write("### 📖 Our Story So Far:")
70
- for entry in st.session_state.story:
71
- st.markdown(f"<div class='box-container story-box'>{entry}</div>", unsafe_allow_html=True)
72
-
73
- # Add user input for the story continuation
74
- if st.session_state.story_started:
75
- user_input = st.text_input("Add your sentence:", "")
76
-
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
77
  if st.button("Submit"):
78
- # Add the user's input to the story
79
- st.session_state.story.append(user_input)
80
-
81
- # Generate AI continuation
82
- ai_continuation = continue_story(user_input)
83
- st.session_state.story.append(ai_continuation)
84
-
85
- # Rerun to display updated story
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
86
  st.experimental_rerun()
 
1
  import streamlit as st
2
  import openai
3
+ import datetime
4
+ import json
5
+
6
+ # Set your OpenAI API key
7
+ openai.api_key = 'YOUR_OPENAI_API_KEY'
8
+
9
+ # Set up the Streamlit page configuration
10
+ st.set_page_config(
11
+ page_title="JoyStory - Interactive Story Adventure",
12
+ page_icon=":book:",
13
+ layout="wide",
14
+ initial_sidebar_state="collapsed",
15
+ )
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
16
 
17
  # Initialize session state variables
18
  if 'story' not in st.session_state:
19
+ st.session_state.story = []
20
+ if 'achievements' not in st.session_state:
21
+ st.session_state.achievements = []
22
+ if 'level' not in st.session_state:
23
+ st.session_state.level = 'Beginner'
24
+ if 'unique_words' not in st.session_state:
25
+ st.session_state.unique_words = set()
26
+ if 'total_words' not in st.session_state:
27
+ st.session_state.total_words = 0
28
+ if 'badges' not in st.session_state:
29
+ st.session_state.badges = []
30
+
31
+ # Function to generate AI response
32
+ def generate_ai_response(user_input, level):
33
+ prompt = f"Continue the story in a way that is engaging and suitable for a {level.lower()} English learner.\n\nStory so far:\n{''.join(st.session_state.story)}\nUser input: {user_input}\nAI continuation:"
34
+ response = openai.Completion.create(
35
+ engine='gpt-4o-mini'
36
+ prompt=prompt,
37
+ max_tokens=100,
38
  temperature=0.7,
 
39
  )
40
+ ai_output = response.choices[0].text.strip()
41
+ return ai_output
42
+
43
+ # Function to get vocabulary suggestions
44
+ def get_vocabulary_suggestions():
45
+ suggestions = openai.Completion.create(
46
+ engine='gpt-4o-mini',
47
+ prompt=f"Provide 3 interesting words suitable for a {st.session_state.level.lower()} English learner to use in the next part of the story.",
48
+ max_tokens=20,
49
+ n=1,
50
+ stop=None,
51
+ temperature=0.5,
52
+ )
53
+ words = suggestions.choices[0].text.strip().split(', ')
54
+ return words
55
+
56
+ # Function to get creative prompts
57
+ def get_creative_prompt():
58
+ prompt = openai.Completion.create(
59
+ engine='gpt-4o-mini',
60
+ prompt="Ask an open-ended question to inspire the next part of the story.",
61
+ max_tokens=30,
62
+ n=1,
63
+ stop=None,
64
+ temperature=0.7,
65
+ )
66
+ question = prompt.choices[0].text.strip()
67
+ return question
68
+
69
+ # Function to provide feedback
70
+ def get_feedback(user_input):
71
+ feedback_prompt = f"Provide one positive, simple feedback on the following sentence for a {st.session_state.level.lower()} English learner:\n\n{user_input}"
72
+ feedback = openai.Completion.create(
73
+ engine='gpt-4o-mini',
74
+ prompt=feedback_prompt,
75
+ max_tokens=50,
76
+ temperature=0.5,
77
+ )
78
+ return feedback.choices[0].text.strip()
79
+
80
+ # Function to update achievements
81
+ def update_achievements(user_input):
82
+ words = set(user_input.lower().split())
83
+ st.session_state.unique_words.update(words)
84
+ st.session_state.total_words += len(words)
85
+ # Example achievement: Use 50 unique words
86
+ if len(st.session_state.unique_words) >= 50 and '50 Unique Words' not in st.session_state.badges:
87
+ st.session_state.badges.append('50 Unique Words')
88
+ st.success("Achievement Unlocked: 50 Unique Words!")
89
+
90
+ # Layout the UI
91
+ st.title("📖 JoyStory - Interactive Story Adventure")
92
+
93
+ col1, col2 = st.columns([3, 1])
94
+
95
+ with col1:
96
+ # Story Display Box
97
+ st.header("Story So Far")
98
+ story_display = st.empty()
99
+ if st.session_state.story:
100
+ story_display.markdown('\n\n'.join(st.session_state.story))
101
+ else:
102
+ st.info("Your story will appear here as you write it.")
103
+
104
+ # User Input Box
105
+ st.header("Your Turn to Write")
106
+ user_input = st.text_area("Continue the story:", height=100)
107
  if st.button("Submit"):
108
+ if user_input.strip() == "":
109
+ st.warning("Please enter some text to continue the story.")
110
+ else:
111
+ st.session_state.story.append(f"**You:** {user_input}")
112
+ update_achievements(user_input)
113
+ feedback = get_feedback(user_input)
114
+ st.session_state.story.append(f"**Feedback:** {feedback}")
115
+
116
+ ai_response = generate_ai_response(user_input, st.session_state.level)
117
+ st.session_state.story.append(f"**AI:** {ai_response}")
118
+ story_display.markdown('\n\n'.join(st.session_state.story))
119
+
120
+ with col2:
121
+ # Help and Suggestions Box
122
+ st.header("Need Some Help?")
123
+ if st.button("Get Vocabulary Suggestions"):
124
+ vocab_suggestions = get_vocabulary_suggestions()
125
+ st.write("Try using these words in your next sentence:")
126
+ for word in vocab_suggestions:
127
+ st.write(f"- {word}")
128
+
129
+ if st.button("Get a Creative Prompt"):
130
+ creative_prompt = get_creative_prompt()
131
+ st.write(creative_prompt)
132
+
133
+ # Rewards and Progress Box
134
+ st.header("Achievements")
135
+ if st.session_state.badges:
136
+ for badge in st.session_state.badges:
137
+ st.success(f"🏆 {badge}")
138
+ else:
139
+ st.write("No achievements yet. Keep writing to earn badges!")
140
+
141
+ # Story Saving
142
+ if st.button("Save Story"):
143
+ story_data = {
144
+ 'level': st.session_state.level,
145
+ 'date': datetime.datetime.now().isoformat(),
146
+ 'story': st.session_state.story,
147
+ 'achievements': st.session_state.badges,
148
+ 'total_words': st.session_state.total_words,
149
+ 'unique_words': list(st.session_state.unique_words),
150
+ }
151
+ story_json = json.dumps(story_data, indent=4)
152
+ st.download_button(
153
+ label="Download Story",
154
+ data=story_json,
155
+ file_name='joystory.json',
156
+ mime='application/json',
157
+ )
158
+
159
+ # Sidebar for selecting language level
160
+ with st.sidebar:
161
+ st.header("Settings")
162
+ level = st.radio(
163
+ "Select your English level:",
164
+ ('Beginner', 'Intermediate', 'Advanced'),
165
+ index=['Beginner', 'Intermediate', 'Advanced'].index(st.session_state.level)
166
+ )
167
+ st.session_state.level = level
168
+ if st.button("Start New Story"):
169
+ st.session_state.story = []
170
+ st.session_state.achievements = []
171
+ st.session_state.unique_words = set()
172
+ st.session_state.total_words = 0
173
+ st.session_state.badges = []
174
  st.experimental_rerun()