Assignment1 / app.py
smtsead's picture
Update app.py
459e2b4 verified
raw
history blame
2.63 kB
# import part
import streamlit as st
from transformers import pipeline
from gtts import gTTS # Using gTTS for text-to-speech
import os
import re # For removing unwanted words
# 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 facebook/bart-large-cnn for text generation
story_generator = pipeline("text-generation", model="facebook/bart-large-cnn")
# Add a more explicit prompt to guide the story generation
prompt = f"Write a fun and realistic story for kids based on this: {text}. The story should be under 95 words and suitable for children aged 3-10. Avoid using the word 'illustration'."
story = story_generator(prompt, max_length=95, num_return_sequences=1)[0]["generated_text"]
# Remove the prompt from the generated story
story = story.replace(prompt, "").strip()
# Remove the word "illustration" (case-insensitive) using regex
story = re.sub(r"\billustration\b", "", story, flags=re.IGNORECASE)
return story[:95] # Limit to 95 words
# text2audio
def text2audio(story_text):
# Use gTTS for text-to-speech conversion
tts = gTTS(text=story_text, lang="en")
audio_file = "story_audio.mp3"
tts.save(audio_file)
return audio_file
# 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_file = text2audio(story)
# Play button
if st.button("Play Audio"):
st.audio(audio_file, format="audio/mp3")
# Clean up the audio file after use
os.remove(audio_file)