Spaces:
Build error
Build error
Update app.py
Browse files12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879801 unmodified line828384858687882 unmodified lines919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130# Imports - just the essentialsimport streamlit as stfrom transformers import pipelinefrom PIL import Imageimport osimport tempfilefrom gtts import gTTS# Preload and cache all models at app startup@st.cache_resourcedef load_models():"""Load all models and cache them for faster execution"""models = {"image_captioner": pipeline("image-to-text", model="sooh-j/blip-image-captioning-base"),"story_generator": pipeline("text-generation", model="microsoft/phi-2")}return models# Convert PIL Image to bytes for caching compatibilitydef get_image_bytes(pil_img):"""Convert PIL image to bytes for hashing"""import iobuf = io.BytesIO()pil_img.save(buf, format='JPEG')return buf.getvalue()# Simple image-to-text function using cached model@st.cache_datadef img2text(image_bytes, _models):"""Convert image to text with caching - using underscore for unhashable arg"""import iopil_img = Image.open(io.BytesIO(image_bytes))result = _models["image_captioner"](pil_img)return result[0]["generated_text"]@st.cache_datadef text2story(caption, _models):"""Generate a short story from image caption.Args:caption: Caption describing the image_models: Dictionary containing loaded modelsReturns:A generated story that expands on the image caption"""story_generator = _models["story_generator"]# Format prompt to ensure the story expands on the image captionprompt = f"""<|system|>You are a creative short story writer. Write a brief, engaging story that expands on the given image caption.The story should be under 100 words and have a natural beginning, middle, and end.<|user|>Image caption: "{caption}"Create a short story that expands on this image caption and brings it to life.<|assistant|>"""# Generate story with parameters tuned for brevity and coherenceresponse = story_generator(prompt,max_new_tokens=120, # Allow enough tokens for a complete storydo_sample=True,temperature=0.7, # Balanced creativitytop_p=0.9, # Focus on more likely tokensrepetition_penalty=1.2, # Avoid repetitive patternseos_token_id=story_generator.tokenizer.eos_token_id)# Extract just the generated story textraw_story = response[0]['generated_text']# Parse out just the assistant's response from the conversation formatstory_text = raw_story.split("<|assistant|>")[-1].strip()return story_text# Text-to-speech function@st.cache_datadef text2audio(story_text):"""Convert text to audio"""1 unmodified linetemp_filename = temp_file.nametemp_file.close()tts = gTTS(text=story_text, lang='en')tts.save(temp_filename)with open(temp_filename, 'rb') as audio_file:2 unmodified linesos.unlink(temp_filename)return audio_bytes# Load models at startup - this happens before the app interface is displayedmodels = load_models()st.write("✅ Models loaded and cached!")# Streamlit app interfacest.title("Image to Audio Story")# File uploaderuploaded_file = st.file_uploader("Upload an image")if uploaded_file is not None:# Display imageimage = Image.open(uploaded_file)st.image(image, caption="Uploaded Image", use_container_width=True)# Process imagewith st.spinner("Processing..."):# Convert to bytes for cachingimage_bytes = get_image_bytes(image)# Generate captioncaption = img2text(image_bytes, models)st.write(f"**Caption:** {caption}")# Generate story that expands on the captionstory = text2story(caption, models)word_count = len(story.split())st.write(f"**Story ({word_count} words):**")st.write(story)# Pre-generate audioif 'audio' not in st.session_state:st.session_state.audio = text2audio(story)# Play audio buttonif st.button("Play the audio"):st.audio(st.session_state.audio, format="audio/mp3")123456789101112131415161718192021222324252627282930313233343536373839404142434445464748491 unmodified line51525354555657582 unmodified lines61626364656667686970717273747576777879808182838485868788899091# Imports - only what's neededimport streamlit as stfrom transformers import pipelinefrom PIL import Imageimport tempfilefrom gtts import gTTSimport os# Preload models at startup with minimal settings@st.cache_resourcedef load_models():"""Load models with optimized settings"""return {"image_captioner": pipeline("image-to-text", model="sooh-j/blip-image-captioning-base"),"story_generator": pipeline("text-generation", model="Qwen/Qwen2.5-1.5B-Instruct")}# Image-to-text with caching@st.cache_datadef img2text(image, _models):"""Convert image to text"""result = _models["image_captioner"](image)return result[0]["generated_text"]# Story generation with optimized settings@st.cache_datadef text2story(caption, _models):"""Generate a short story - optimized for speed"""prompt = f"""<|system|>You are a short story writer. Write a brief story based on this image caption.<|user|>Image caption: "{caption}"<|assistant|>"""# Reduced parameters for faster generationresponse = _models["story_generator"](prompt,max_new_tokens=75, # Shorter storiesdo_sample=True,temperature=0.7,top_p=0.9)return response[0]['generated_text'].split("<|assistant|>")[-1].strip()# Text-to-speech with minimal processing@st.cache_datadef text2audio(story_text):"""Convert text to audio"""1 unmodified linetemp_filename = temp_file.nametemp_file.close()# Lower quality for faster generationtts = gTTS(text=story_text, lang='en', slow=False)tts.save(temp_filename)with open(temp_filename, 'rb') as audio_file:2 unmodified linesos.unlink(temp_filename)return audio_bytes# Load models at startupmodels = load_models()# Streamlit app interface - minimal UIst.title("Image to Audio Story")uploaded_file = st.file_uploader("Upload an image")if uploaded_file is not None:# Display smaller imageimage = Image.open(uploaded_file)st.image(image, user_container_width=True) # Even smaller for faster loading# Process with minimal UI updateswith st.spinner("Creating story..."):# Generate captioncaption = img2text(image, models)st.write(f"**Caption:** {caption}")# Generate shorter storystory = text2story(caption, models)st.write(f"**Story:**")st.write(story)# Generate audio only on demandif st.button("Generate & Play Audio"):audio = text2audio(story)st.audio(audio, format="audio/mp3")
app.py+35-74