Create app.py
Browse files
app.py
ADDED
@@ -0,0 +1,68 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
1 |
+
import streamlit as st
|
2 |
+
from transformers import pipeline
|
3 |
+
from gtts import gTTS
|
4 |
+
import io
|
5 |
+
import os
|
6 |
+
|
7 |
+
# function part
|
8 |
+
# img2text
|
9 |
+
def img2text(url):
|
10 |
+
image_to_text_model = pipeline("image-to-text", model="Salesforce/blip-image-captioning-base")
|
11 |
+
text = image_to_text_model(url)[0]["generated_text"]
|
12 |
+
return text
|
13 |
+
|
14 |
+
# text2story
|
15 |
+
def text2story(text):
|
16 |
+
story_generator = pipeline("text-generation", model="Qwen/QwQ-32B")
|
17 |
+
story = story_generator(text, max_length=200, num_return_sequences=1)[0]["generated_text"]
|
18 |
+
return story
|
19 |
+
|
20 |
+
# text2audio
|
21 |
+
def text2audio(story_text):
|
22 |
+
# 创建 gTTS 对象
|
23 |
+
tts = gTTS(text=story_text, lang='en')
|
24 |
+
# 创建一个字节流对象用于存储音频数据
|
25 |
+
audio_file = io.BytesIO()
|
26 |
+
# 将音频数据写入字节流
|
27 |
+
tts.write_to_fp(audio_file)
|
28 |
+
# 将文件指针移到开头
|
29 |
+
audio_file.seek(0)
|
30 |
+
return audio_file
|
31 |
+
|
32 |
+
st.set_page_config(page_title="Your Image to Audio Story",
|
33 |
+
page_icon="🦜")
|
34 |
+
st.header("Turn Your Image to Audio Story")
|
35 |
+
uploaded_file = st.file_uploader("Select an Image...")
|
36 |
+
|
37 |
+
if uploaded_file is not None:
|
38 |
+
# 保存上传的文件到临时文件
|
39 |
+
temp_file_path = "temp_image.jpg"
|
40 |
+
bytes_data = uploaded_file.getvalue()
|
41 |
+
with open(temp_file_path, "wb") as file:
|
42 |
+
file.write(bytes_data)
|
43 |
+
st.image(uploaded_file, caption="Uploaded Image",
|
44 |
+
use_column_width=True)
|
45 |
+
|
46 |
+
# Stage 1: Image to Text
|
47 |
+
st.text('Processing img2text...')
|
48 |
+
scenario = img2text(temp_file_path)
|
49 |
+
st.write(scenario)
|
50 |
+
|
51 |
+
# 删除临时文件
|
52 |
+
if os.path.exists(temp_file_path):
|
53 |
+
os.remove(temp_file_path)
|
54 |
+
|
55 |
+
# Stage 2: Text to Story
|
56 |
+
st.text('Generating a story...')
|
57 |
+
story = text2story(scenario)
|
58 |
+
st.write(story)
|
59 |
+
|
60 |
+
# Stage 3: Story to Audio data
|
61 |
+
st.text('Generating audio data...')
|
62 |
+
audio_data = text2audio(story)
|
63 |
+
|
64 |
+
# Play button
|
65 |
+
if st.button("Play Audio"):
|
66 |
+
st.audio(audio_data,
|
67 |
+
format="audio/mpeg",
|
68 |
+
start_time=0)
|