CR7CAD commited on
Commit
4f45e40
·
verified ·
1 Parent(s): beb2f0b

Update app.py

Browse files
Files changed (1) hide show
  1. app.py +73 -41
app.py CHANGED
@@ -1,73 +1,105 @@
 
1
  import streamlit as st
2
  from transformers import pipeline
3
  from PIL import Image
4
- import io
5
  import tempfile
6
  from gtts import gTTS
 
7
 
8
- # Cache models for faster execution
9
  @st.cache_resource
10
  def load_models():
11
- return {
 
12
  "image_captioner": pipeline("image-to-text", model="sooh-j/blip-image-captioning-base"),
13
  "story_generator": pipeline("text-generation", model="Qwen/Qwen2.5-1.5B-Instruct")
14
  }
 
15
 
16
- # Convert image to text
17
  @st.cache_data
18
- def img2text(image_bytes, models):
19
- image = Image.open(io.BytesIO(image_bytes))
20
- return models["image_captioner"](image)[0]["generated_text"]
 
21
 
22
- # Generate a short story based on the caption
23
  @st.cache_data
24
- def text2story(caption, models):
25
- response = models["story_generator"](
26
- f"Expand this caption into a short, engaging story under 100 words:\n\n{caption}",
 
 
 
 
 
 
 
 
 
 
 
 
 
27
  max_new_tokens=100,
 
28
  temperature=0.7,
29
  top_p=0.9,
30
- repetition_penalty=1.2
 
31
  )
32
- return response[0]['generated_text'].strip()
 
 
 
33
 
34
- # Convert text to audio
35
  @st.cache_data
36
- def text2audio(text):
 
37
  temp_file = tempfile.NamedTemporaryFile(delete=False, suffix='.mp3')
38
- gTTS(text=text, lang='en').save(temp_file.name)
39
- with open(temp_file.name, 'rb') as audio_file:
 
 
 
 
 
40
  audio_bytes = audio_file.read()
 
 
41
  return audio_bytes
42
 
43
- # Load models once
44
  models = load_models()
45
 
46
- # Streamlit UI
47
- st.title("📷 Image to Audio Story")
48
 
49
- uploaded_file = st.file_uploader("Upload an image", type=["jpg", "png", "jpeg"])
 
50
 
51
- if uploaded_file:
52
- # Resize and display image
53
  image = Image.open(uploaded_file)
54
- image.thumbnail((400, 400)) # Resize to max 400x400 pixels
55
- st.image(image, caption="Uploaded Image", use_column_width=True)
56
-
57
- # Convert image to bytes
58
- image_bytes = io.BytesIO()
59
- image.save(image_bytes, format="JPEG")
60
- image_bytes = image_bytes.getvalue()
61
-
62
- with st.spinner("Generating story..."):
63
- caption = img2text(image_bytes, models)
64
  story = text2story(caption, models)
65
- audio = text2audio(story)
66
-
67
- # Display results
68
- st.write(f"**Caption:** {caption}")
69
- st.write(f"**Story:** {story}")
70
-
 
 
71
  # Play audio button
72
- if st.button("🔊 Play Audio"):
73
- st.audio(audio, format="audio/mp3")
 
1
+ # Imports - just the essentials
2
  import streamlit as st
3
  from transformers import pipeline
4
  from PIL import Image
5
+ import os
6
  import tempfile
7
  from gtts import gTTS
8
+ import io
9
 
10
+ # Preload and cache all models at app startup
11
  @st.cache_resource
12
  def load_models():
13
+ """Load all models and cache them for faster execution"""
14
+ models = {
15
  "image_captioner": pipeline("image-to-text", model="sooh-j/blip-image-captioning-base"),
16
  "story_generator": pipeline("text-generation", model="Qwen/Qwen2.5-1.5B-Instruct")
17
  }
18
+ return models
19
 
20
+ # Simple image-to-text function using cached model
21
  @st.cache_data
22
+ def img2text(image, _models):
23
+ """Convert image to text with caching"""
24
+ result = _models["image_captioner"](image)
25
+ return result[0]["generated_text"]
26
 
 
27
  @st.cache_data
28
+ def text2story(caption, _models):
29
+ """Generate a short story from image caption"""
30
+ story_generator = _models["story_generator"]
31
+
32
+ # Format prompt
33
+ prompt = f"""<|system|>
34
+ You are a creative short story writer. Write a brief, engaging story that expands on the given image caption.
35
+ The story should be under 100 words and have a natural beginning, middle, and end.
36
+ <|user|>
37
+ Image caption: "{caption}"
38
+ Create a short story that expands on this image caption and brings it to life.
39
+ <|assistant|>"""
40
+
41
+ # Generate story
42
+ response = story_generator(
43
+ prompt,
44
  max_new_tokens=100,
45
+ do_sample=True,
46
  temperature=0.7,
47
  top_p=0.9,
48
+ repetition_penalty=1.2,
49
+ eos_token_id=story_generator.tokenizer.eos_token_id
50
  )
51
+
52
+ # Extract just the assistant's response
53
+ story_text = response[0]['generated_text'].split("<|assistant|>")[-1].strip()
54
+ return story_text
55
 
56
+ # Text-to-speech function
57
  @st.cache_data
58
+ def text2audio(story_text):
59
+ """Convert text to audio"""
60
  temp_file = tempfile.NamedTemporaryFile(delete=False, suffix='.mp3')
61
+ temp_filename = temp_file.name
62
+ temp_file.close()
63
+
64
+ tts = gTTS(text=story_text, lang='en')
65
+ tts.save(temp_filename)
66
+
67
+ with open(temp_filename, 'rb') as audio_file:
68
  audio_bytes = audio_file.read()
69
+
70
+ os.unlink(temp_filename)
71
  return audio_bytes
72
 
73
+ # Load models at startup
74
  models = load_models()
75
 
76
+ # Streamlit app interface
77
+ st.title("Image to Audio Story")
78
 
79
+ # File uploader
80
+ uploaded_file = st.file_uploader("Upload an image")
81
 
82
+ if uploaded_file is not None:
83
+ # Display image at a smaller size (200px width instead of 300px)
84
  image = Image.open(uploaded_file)
85
+ st.image(image, caption="Uploaded Image", width=200)
86
+
87
+ # Process image
88
+ with st.spinner("Processing..."):
89
+ # Generate caption directly from the image (no need to convert to bytes)
90
+ caption = img2text(image, models)
91
+ st.write(f"**Caption:** {caption}")
92
+
93
+ # Generate story
 
94
  story = text2story(caption, models)
95
+ word_count = len(story.split())
96
+ st.write(f"**Story ({word_count} words):**")
97
+ st.write(story)
98
+
99
+ # Generate audio
100
+ if 'audio' not in st.session_state:
101
+ st.session_state.audio = text2audio(story)
102
+
103
  # Play audio button
104
+ if st.button("Play the audio"):
105
+ st.audio(st.session_state.audio, format="audio/mp3")