Update app.py
Browse files
app.py
CHANGED
@@ -1,30 +1,56 @@
|
|
1 |
-
import
|
2 |
-
from
|
3 |
-
|
4 |
-
# Load the text classification model pipeline
|
5 |
-
classifier = pipeline("text-classification",model='isom5240ust/bert-base-uncased-emotion', return_all_scores=True)
|
6 |
|
7 |
-
|
8 |
-
|
9 |
-
|
10 |
-
|
11 |
-
|
12 |
-
|
|
|
|
|
|
|
13 |
|
14 |
-
|
15 |
-
|
16 |
-
|
17 |
-
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
18 |
|
19 |
-
|
20 |
-
|
21 |
-
|
|
|
|
|
|
|
22 |
|
23 |
-
|
24 |
-
|
25 |
-
|
26 |
-
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
27 |
|
28 |
-
|
29 |
-
|
30 |
-
st.write("Score:", max_score)
|
|
|
1 |
+
from transformers import BlipProcessor, BlipForConditionalGeneration
|
2 |
+
from PIL import Image
|
|
|
|
|
|
|
3 |
|
4 |
+
def generate_caption(image_path):
|
5 |
+
image = Image.open(image_path)
|
6 |
+
processor = BlipProcessor.from_pretrained("facebook/blip-image-captioning-base")
|
7 |
+
model = BlipForConditionalGeneration.from_pretrained("facebook/blip-image-captioning-base")
|
8 |
+
inputs = processor(image, return_tensors="pt")
|
9 |
+
output = model.generate(**inputs)
|
10 |
+
caption = processor.decode(output[0], skip_special_tokens=True)
|
11 |
+
return caption
|
12 |
+
from transformers import pipeline
|
13 |
|
14 |
+
def generate_story(caption):
|
15 |
+
# 使用文本生成 pipeline
|
16 |
+
generator = pipeline("text-generation", model="gpt2")
|
17 |
+
prompt = f"由以下图片得到的描述: '{caption}',请根据这个描述生成一个完整的童话故事,故事至少100个单词。"
|
18 |
+
result = generator(prompt, max_length=300, num_return_sequences=1)
|
19 |
+
story = result[0]['generated_text']
|
20 |
+
# 添加字数判断,必要时进行调整或循环生成直到满足条件
|
21 |
+
if len(story.split()) < 100:
|
22 |
+
# 可以进行递归调用或其他逻辑扩充文本
|
23 |
+
story += " " + generate_story(caption)
|
24 |
+
return story
|
25 |
+
from gtts import gTTS
|
26 |
|
27 |
+
def text_to_speech(text, output_file="output.mp3"):
|
28 |
+
tts = gTTS(text=text, lang='en') # 注意可根据需要选择语言或使用中文
|
29 |
+
tts.save(output_file)
|
30 |
+
return output_file
|
31 |
+
import streamlit as st
|
32 |
+
from PIL import Image
|
33 |
|
34 |
+
def main():
|
35 |
+
st.title("儿童故事生成应用")
|
36 |
+
st.write("上传一张图片,我们将根据图片生成有趣的故事,并转换成语音播放给你听!")
|
37 |
+
|
38 |
+
uploaded_file = st.file_uploader("选择一张图片", type=["png", "jpg", "jpeg"])
|
39 |
+
if uploaded_file is not None:
|
40 |
+
image = Image.open(uploaded_file)
|
41 |
+
st.image(image, caption="上传的图片", use_column_width=True)
|
42 |
+
|
43 |
+
# 调用图像描述函数
|
44 |
+
caption = generate_caption(uploaded_file)
|
45 |
+
st.write("图片描述:", caption)
|
46 |
+
|
47 |
+
# 生成故事
|
48 |
+
story = generate_story(caption)
|
49 |
+
st.write("生成的故事:", story)
|
50 |
+
|
51 |
+
# 文字转语音
|
52 |
+
audio_file = text_to_speech(story)
|
53 |
+
st.audio(audio_file, format="audio/mp3")
|
54 |
|
55 |
+
if __name__ == "__main__":
|
56 |
+
main()
|
|