Assignment1 / app.py
CR7CAD's picture
Update app.py
83842b8 verified
raw
history blame
2.93 kB
# import part
import streamlit as st
from transformers import pipeline
import os
import tempfile
# function part
# img2text
def img2text(image_path):
image_to_text = pipeline("image-to-text", model="sooh-j/blip-image-captioning-base")
text = image_to_text(image_path)[0]["generated_text"]
return text
# text2story
def text2audio(story_text):
try:
# Use the HelpingAI TTS model as requested
synthesizer = pipeline("text-to-speech", model="HelpingAI/HelpingAI-TTS-v1")
# Limit text length to avoid timeouts
max_chars = 500
if len(story_text) > max_chars:
last_period = story_text[:max_chars].rfind('.')
if last_period > 0:
story_text = story_text[:last_period + 1]
else:
story_text = story_text[:max_chars]
# Generate speech
st.write("Generating audio...")
speech = synthesizer(story_text)
st.write(f"Speech output keys: {list(speech.keys())}")
# We'll pass the audio data directly to Streamlit instead of saving to a file
# This works because Streamlit's st.audio() can take raw audio data
return speech
except Exception as e:
st.error(f"Error generating audio: {str(e)}")
import traceback
st.error(traceback.format_exc())
return None
# Function to save temporary image file
def save_uploaded_image(uploaded_file):
if not os.path.exists("temp"):
os.makedirs("temp")
image_path = os.path.join("temp", uploaded_file.name)
with open(image_path, "wb") as f:
f.write(uploaded_file.getvalue())
return image_path
# main part
st.set_page_config(page_title="Your Image to Audio Story", page_icon="🦜")
st.header("Turn Your Image to Audio Story")
uploaded_file = st.file_uploader("Select an Image...")
if uploaded_file is not None:
# Display the uploaded image
st.image(uploaded_file, caption="Uploaded Image", use_container_width=True)
# Save the image temporarily
image_path = save_uploaded_image(uploaded_file)
# Stage 1: Image to Text
st.text('Processing img2text...')
caption = img2text(image_path)
st.write(caption)
# Stage 2: Text to Story
st.text('Generating a story...')
story = text2story(caption)
st.write(story)
# Stage 3: Story to Audio data
st.text('Generating audio data...')
audio_file = text2audio(story)
# Play button
if st.button("Play Audio"):
if audio_file and os.path.exists(audio_file):
# Play the audio file
st.audio(audio_file)
else:
st.error("Audio generation failed. Please try again.")
# Clean up the temporary files
try:
os.remove(image_path)
# Don't delete audio file immediately as it might still be playing
except:
pass