Chan Meng commited on
Commit
07ac17e
·
1 Parent(s): debc9c4
Files changed (4) hide show
  1. .gitignore +6 -2
  2. app.py +104 -29
  3. requirements.txt +3 -0
  4. stories_data.json +28 -0
.gitignore CHANGED
@@ -1,2 +1,6 @@
1
-
2
- /.venv
 
 
 
 
 
1
+ .env
2
+ stories_data.json
3
+ __pycache__/
4
+ .pytest_cache/
5
+ .venv/
6
+ /venv
app.py CHANGED
@@ -2,12 +2,97 @@ import streamlit as st
2
  import random
3
  import json
4
  import os
 
 
 
 
 
5
 
6
  # 定义表情列表
7
  EMOJI_LIST = ["😀", "😎", "🌞", "🌈", "🐶", "🏠", "🚀", "📚", "🎉", "🍕", "🎸", "🏆"]
8
 
9
  # 定义数据文件路径
10
  DATA_FILE = "stories_data.json"
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
11
 
12
  def load_stories():
13
  """从文件加载故事数据"""
@@ -32,16 +117,6 @@ def save_stories_to_file(stories):
32
  if 'stories' not in st.session_state:
33
  st.session_state.stories = load_stories()
34
 
35
- def generate_simple_story(emojis):
36
- templates = [
37
- "从前有一天,{} 和 {} 一起去冒险。在路上他们遇到了 {},并且学会了 {} 的重要性。",
38
- "{} 和 {} 是最好的朋友。有一天他们决定去 {},这是一次 {} 的经历!",
39
- "在充满 {} 的世界里,{} 发现了 {} 的意义。这让大家开始了一场 {} 的庆祝!"
40
- ]
41
- story_template = random.choice(templates)
42
- story_emojis = random.sample(emojis, 4) if len(emojis) >= 4 else emojis + random.sample(EMOJI_LIST, 4 - len(emojis))
43
- return story_template.format(*story_emojis)
44
-
45
  def save_story(story):
46
  """保存新故事并更新文件"""
47
  st.session_state.stories.append({"story": story, "votes": 0})
@@ -55,43 +130,43 @@ def main():
55
  st.set_page_config(page_title="Emoji Story Generator", page_icon="📚")
56
  st.title("Emoji Story Generator")
57
 
58
- # 添加表情选择器
59
- selected_emojis = st.multiselect("选择表情符号", EMOJI_LIST)
60
 
61
  if selected_emojis:
62
- st.write("你选择了:", " ".join(selected_emojis))
63
 
64
- # 添加生成故事按钮
65
- if st.button("生成故事"):
66
- story = generate_simple_story(selected_emojis)
67
- save_story(story)
68
- st.write("生成的故事:")
69
- st.write(story)
70
- st.success("故事已保存!")
 
71
 
72
- # 显示已保存的故事
73
  if st.session_state.stories:
74
- st.header("已生成的故事")
75
 
76
- # 按照点赞数排序显示故事
77
  sorted_stories = sorted(st.session_state.stories,
78
  key=lambda x: x['votes'],
79
  reverse=True)
80
 
81
- # 使用列布局来优化显示效果
82
  for idx, story_data in enumerate(sorted_stories):
83
  col1, col2 = st.columns([4, 1])
84
  with col1:
85
- st.write(f"{idx + 1}. {story_data['story']} (点赞数: {story_data['votes']})")
86
  with col2:
87
- # 为每个故事添加点赞按钮
88
  if st.button(f"👍", key=f"vote_{idx}"):
89
  story_data['votes'] += 1
90
- update_votes() # 保存更新后的投票数据
91
- st.success(f"点赞成功!")
92
  st.experimental_rerun()
93
  else:
94
- st.write("请至少选择一个表情符号。")
95
 
96
  if __name__ == "__main__":
97
  main()
 
2
  import random
3
  import json
4
  import os
5
+ from dotenv import load_dotenv
6
+ import requests
7
+
8
+ # 加载环境变量
9
+ load_dotenv()
10
 
11
  # 定义表情列表
12
  EMOJI_LIST = ["😀", "😎", "🌞", "🌈", "🐶", "🏠", "🚀", "📚", "🎉", "🍕", "🎸", "🏆"]
13
 
14
  # 定义数据文件路径
15
  DATA_FILE = "stories_data.json"
16
+ HUGGINGFACE_API_TOKEN = os.getenv("HUGGINGFACE_API_TOKEN")
17
+ API_URL = "https://api-inference.huggingface.co/models/HuggingFaceH4/zephyr-7b-beta"
18
+
19
+ def query_huggingface(payload):
20
+ """调用Hugging Face API"""
21
+ headers = {
22
+ "Authorization": f"Bearer {HUGGINGFACE_API_TOKEN}",
23
+ "Content-Type": "application/json"
24
+ }
25
+
26
+ # 调整payload格式为Zephyr模型的要求
27
+ simplified_payload = {
28
+ "inputs": payload["inputs"],
29
+ "parameters": {
30
+ "max_new_tokens": 250,
31
+ "temperature": 0.7,
32
+ "top_p": 0.9,
33
+ "do_sample": True,
34
+ "return_full_text": False
35
+ }
36
+ }
37
+
38
+ try:
39
+ st.write("Calling API...")
40
+ response = requests.post(API_URL, headers=headers, json=simplified_payload, timeout=60)
41
+
42
+ if response.status_code != 200:
43
+ st.error(f"API call failed, status code: {response.status_code}")
44
+ st.write(f"Error message: {response.text}")
45
+ return None
46
+
47
+ result = response.json()
48
+ st.write("API response:", result)
49
+ return result
50
+
51
+ except Exception as e:
52
+ st.error(f"API request error: {str(e)}")
53
+ return None
54
+
55
+ def generate_story_with_ai(emojis):
56
+ """Generate story using AI"""
57
+ emoji_text = ' '.join(emojis)
58
+ prompt = f"""Create a fun and engaging short story using these emojis: {emoji_text}
59
+
60
+ Instructions:
61
+ 1. Create a story that naturally incorporates all the given emojis
62
+ 2. The story should be fun and suitable for all ages
63
+ 3. Include a clear beginning, middle, and end
64
+ 4. Keep it concise (around 100-150 words)
65
+ 5. Make it creative and engaging
66
+
67
+ Story beginning:
68
+ Once upon a sunny day,"""
69
+
70
+ try:
71
+ with st.spinner('Creating story...'):
72
+ response = query_huggingface({"inputs": prompt})
73
+
74
+ if response and isinstance(response, list) and len(response) > 0:
75
+ # Get generated text
76
+ story = response[0].get('generated_text', '').strip()
77
+
78
+ # Clean up story text
79
+ story = story.replace(prompt, '').strip()
80
+
81
+ # Check if story is empty
82
+ if not story:
83
+ st.error("Generated story is empty, please try again")
84
+ return None
85
+
86
+ # Format final story
87
+ final_story = f"Once upon a sunny day, {story}\n\n(Emojis used: {emoji_text})"
88
+ return final_story
89
+
90
+ st.error("Failed to generate story, please try again")
91
+ return None
92
+
93
+ except Exception as e:
94
+ st.error(f"Error generating story: {str(e)}")
95
+ return None
96
 
97
  def load_stories():
98
  """从文件加载故事数据"""
 
117
  if 'stories' not in st.session_state:
118
  st.session_state.stories = load_stories()
119
 
 
 
 
 
 
 
 
 
 
 
120
  def save_story(story):
121
  """保存新故事并更新文件"""
122
  st.session_state.stories.append({"story": story, "votes": 0})
 
130
  st.set_page_config(page_title="Emoji Story Generator", page_icon="📚")
131
  st.title("Emoji Story Generator")
132
 
133
+ # Add emoji selector
134
+ selected_emojis = st.multiselect("Choose emojis for your story", EMOJI_LIST)
135
 
136
  if selected_emojis:
137
+ st.write("Selected emojis:", " ".join(selected_emojis))
138
 
139
+ # Add generate story button
140
+ if st.button("Generate Story"):
141
+ story = generate_story_with_ai(selected_emojis)
142
+ if story: # Only save if story generation was successful
143
+ save_story(story)
144
+ st.write("Generated Story:")
145
+ st.write(story)
146
+ st.success("Story saved!")
147
 
148
+ # Display saved stories
149
  if st.session_state.stories:
150
+ st.header("Generated Stories")
151
 
152
+ # Sort stories by votes
153
  sorted_stories = sorted(st.session_state.stories,
154
  key=lambda x: x['votes'],
155
  reverse=True)
156
 
157
+ # Use columns for layout
158
  for idx, story_data in enumerate(sorted_stories):
159
  col1, col2 = st.columns([4, 1])
160
  with col1:
161
+ st.write(f"{idx + 1}. {story_data['story']} (Likes: {story_data['votes']})")
162
  with col2:
 
163
  if st.button(f"👍", key=f"vote_{idx}"):
164
  story_data['votes'] += 1
165
+ update_votes()
166
+ st.success(f"Liked!")
167
  st.experimental_rerun()
168
  else:
169
+ st.write("Please select at least one emoji.")
170
 
171
  if __name__ == "__main__":
172
  main()
requirements.txt ADDED
@@ -0,0 +1,3 @@
 
 
 
 
1
+ streamlit==1.22.0
2
+ python-dotenv==0.19.2
3
+ requests==2.28.1
stories_data.json CHANGED
@@ -18,5 +18,33 @@
18
  {
19
  "story": "从前有一天,🍕 和 🏠 一起去冒险。在路上他们遇到了 🌞,并且学会了 📚 的重要性。",
20
  "votes": 0
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
21
  }
22
  ]
 
18
  {
19
  "story": "从前有一天,🍕 和 🏠 一起去冒险。在路上他们遇到了 🌞,并且学会了 📚 的重要性。",
20
  "votes": 0
21
+ },
22
+ {
23
+ "story": "从前有一天,📚 和 😎 一起去冒险。在路上他们遇到了 🐶,并且学会了 🎉 的重要性。",
24
+ "votes": 0
25
+ },
26
+ {
27
+ "story": "在充满 😎 的世界里,📚 发现了 🐶 的意义。这让大家开始了一场 🍕 的庆祝!",
28
+ "votes": 0
29
+ },
30
+ {
31
+ "story": "从前有一天,😎 和 🐶 一起去冒险。在路上他们遇到了 🍕,并且学会了 📚 的重要性。",
32
+ "votes": 0
33
+ },
34
+ {
35
+ "story": "从前有一天,🐶 和 📚 一起去冒险。在路上他们遇到了 😎,并且学会了 🎉 的重要性。",
36
+ "votes": 0
37
+ },
38
+ {
39
+ "story": "😎 和 🎉 是最好的朋友。有一天他们决定去 📚,这是一次 🐶 的经历!",
40
+ "votes": 0
41
+ },
42
+ {
43
+ "story": "生 成 一 个 有 趣 的 故 事 , 包 含 这 些 表 情 :\n\n(使用的表情: 🌞 🏠 📚 🍕)",
44
+ "votes": 1
45
+ },
46
+ {
47
+ "story": "Once upon a sunny day, Max the golden retriever woke up with a wagging tail and a big smile on his face. He loved nothing more than going on adventures with his best friend, Lily, who was always ready for a fun-filled day. Max padded over to his favorite spot on the couch, where Lily was already curled up with her nose buried in a book. Max nudged her playfully with his nose, and Lily giggled as she closed her book and joined Max for breakfast.\n\nStory middle:\nAfter breakfast, Max and Lily decided to take a walk in the park. Max was excited to run around and sniff all the interesting smells, but Lily had other plans. She spotted a small library tucked away in the corner of the park and begged Max to come with her. Max was hesitant at first, but Lily promised him a special treat if he agreed. Max reluctantly followed Lily to the library, where they spent the next hour browsing through the books. Max was surprised to find that some of the books even had pictures of dogs! Lily picked out a few of her favorites, and Max settled down for a snooze on the floor.\n\nStory end\n\n(Emojis used: 😎 🐶 📚 🍕)",
48
+ "votes": 3
49
  }
50
  ]