Assignment1 / app.py
smtsead's picture
Update app.py
3a25fa2 verified
raw
history blame
2.32 kB
# import part
import streamlit as st
from transformers import pipeline
# function part
# img2text
def img2text(url):
image_to_text_model = pipeline("image-to-text", model="Salesforce/blip-image-captioning-base")
text = image_to_text_model(url)[0]["generated_text"]
# Make the caption more fun and descriptive
fun_caption = f"Wow! {text.capitalize()}! ๐ŸŒŸ"
return fun_caption
# text2story
def text2story(text):
# Use a text-generation model to create a fun and realistic story
story_generator = pipeline("text-generation", model="gpt2")
# Add a prompt to guide the story generation (avoid magical elements)
prompt = f"Write a fun and realistic story for kids based on this: {text}. Keep it simple and under 95 words."
story = story_generator(prompt, max_length=95, num_return_sequences=1)[0]["generated_text"]
# Ensure the story is simple and fun for kids
simple_story = story[:95] # Limit to 95 words
return simple_story
# text2audio
def text2audio(story_text):
# Use a TTS model to convert text to audio
tts = pipeline("text-to-speech", model="facebook/fastspeech2-en-ljspeech")
audio_data = tts(story_text)
return audio_data
# main part
st.set_page_config(page_title="Story Explorer", page_icon="๐Ÿฆœ")
st.header("Story Explorer: Turn Your Picture into a Fun Story! ๐ŸŽจ๐Ÿ“–")
uploaded_file = st.file_uploader("Choose a picture...", type=["jpg", "png", "jpeg"])
if uploaded_file is not None:
bytes_data = uploaded_file.getvalue()
with open(uploaded_file.name, "wb") as file:
file.write(bytes_data)
st.image(uploaded_file, caption="Your Picture", use_container_width=True)
# Stage 1: Image to Text
st.text('Letโ€™s explore your picture! ๐Ÿงโœจ')
scenario = img2text(uploaded_file.name)
st.write(f"**Hereโ€™s what I see in your picture:** {scenario}")
# Stage 2: Text to Story
st.text('Creating a fun story for you! ๐Ÿ“–')
story = text2story(scenario)
st.write(f"**Hereโ€™s your story:** {story}")
# Stage 3: Story to Audio data
st.text('Turning your story into audio... ๐ŸŽง')
audio_data = text2audio(story)
# Play button
if st.button("Play Audio"):
st.audio(audio_data['audio'], format="audio/wav", start_time=0, sample_rate=audio_data['sampling_rate'])