Update app.py
Browse files
app.py
CHANGED
@@ -1,5 +1,4 @@
|
|
1 |
# app.py
|
2 |
-
|
3 |
import streamlit as st
|
4 |
from PIL import Image
|
5 |
from io import BytesIO
|
@@ -7,108 +6,95 @@ from huggingface_hub import InferenceApi
|
|
7 |
from gtts import gTTS
|
8 |
import tempfile
|
9 |
|
10 |
-
# —––––––– Page
|
11 |
-
st.set_page_config(page_title="
|
12 |
-
st.title("
|
13 |
|
14 |
-
# —–––––––
|
15 |
@st.cache_resource
|
16 |
def load_clients():
|
17 |
hf_token = st.secrets["HF_TOKEN"]
|
18 |
-
|
19 |
-
|
20 |
-
|
21 |
-
token=hf_token
|
22 |
-
)
|
23 |
-
story_client = InferenceApi(
|
24 |
-
repo_id="deepseek-ai/DeepSeek-R1-Distill-Qwen-1.5B",
|
25 |
-
task="text-generation",
|
26 |
-
token=hf_token
|
27 |
)
|
28 |
-
return caption_client, story_client
|
29 |
|
30 |
caption_client, story_client = load_clients()
|
31 |
|
32 |
-
# —––––––– Main
|
33 |
-
uploaded = st.file_uploader("Upload
|
34 |
if not uploaded:
|
35 |
-
st.info("Please upload
|
36 |
else:
|
37 |
-
#
|
38 |
img = Image.open(uploaded).convert("RGB")
|
39 |
-
st.image(img,
|
40 |
|
41 |
-
#
|
42 |
-
with st.spinner("🔍
|
43 |
try:
|
44 |
-
|
45 |
-
img.save(
|
46 |
-
|
47 |
-
|
48 |
-
|
49 |
-
if
|
50 |
-
|
51 |
-
|
52 |
-
cap_text = cap_out.get("generated_text", "").strip()
|
53 |
-
else:
|
54 |
-
cap_text = str(cap_out).strip()
|
55 |
-
|
56 |
except Exception as e:
|
57 |
-
st.error(f"🚨
|
58 |
st.stop()
|
59 |
|
60 |
-
|
61 |
-
|
62 |
-
|
63 |
-
|
64 |
-
|
65 |
-
|
66 |
-
|
67 |
-
|
68 |
-
|
69 |
-
"
|
70 |
-
"
|
71 |
-
"2) Explains what it’s doing and how it feels.\n"
|
72 |
-
"3) Concludes with a fun, imaginative ending.\n\n"
|
73 |
-
"Story:"
|
74 |
)
|
75 |
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
76 |
|
77 |
-
#
|
78 |
-
|
79 |
-
|
80 |
-
story_out = story_client(
|
81 |
-
prompt,
|
82 |
-
max_new_tokens=250, # Direct keyword arguments
|
83 |
-
temperature=0.7,
|
84 |
-
top_p=0.9,
|
85 |
-
top_k=50,
|
86 |
-
repetition_penalty=1.1,
|
87 |
-
do_sample=True,
|
88 |
-
no_repeat_ngram_size=2
|
89 |
-
)
|
90 |
-
|
91 |
-
# Handle response format
|
92 |
-
if isinstance(story_out, list):
|
93 |
-
story_text = story_out[0].get("generated_text", "")
|
94 |
-
else: # Handle single-dictionary response
|
95 |
-
story_text = story_out.get("generated_text", "")
|
96 |
-
|
97 |
-
# Extract story content after last prompt mention
|
98 |
-
story = story_text.split("Story:")[-1].strip()
|
99 |
-
|
100 |
-
except Exception as e:
|
101 |
-
st.error(f"🚨 Story generation failed: {str(e)}")
|
102 |
-
st.stop()
|
103 |
|
104 |
-
#
|
105 |
-
with st.spinner("🔊
|
106 |
try:
|
107 |
-
tts = gTTS(text=story, lang="en")
|
108 |
-
with tempfile.NamedTemporaryFile(delete=False, suffix=".mp3") as
|
109 |
-
tts.
|
110 |
-
|
111 |
-
st.audio(tmp.name, format="audio/mp3")
|
112 |
except Exception as e:
|
113 |
-
st.
|
114 |
|
|
|
|
1 |
# app.py
|
|
|
2 |
import streamlit as st
|
3 |
from PIL import Image
|
4 |
from io import BytesIO
|
|
|
6 |
from gtts import gTTS
|
7 |
import tempfile
|
8 |
|
9 |
+
# —––––––– Page Config
|
10 |
+
st.set_page_config(page_title="Magic Story Generator", layout="centered")
|
11 |
+
st.title("📖✨ Turn Images into Children's Stories")
|
12 |
|
13 |
+
# —––––––– Clients (cached)
|
14 |
@st.cache_resource
|
15 |
def load_clients():
|
16 |
hf_token = st.secrets["HF_TOKEN"]
|
17 |
+
return (
|
18 |
+
InferenceApi("Salesforce/blip-image-captioning-base", token=hf_token),
|
19 |
+
InferenceApi("deepseek-ai/DeepSeek-R1-Distill-Qwen-1.5B", token=hf_token)
|
|
|
|
|
|
|
|
|
|
|
|
|
20 |
)
|
|
|
21 |
|
22 |
caption_client, story_client = load_clients()
|
23 |
|
24 |
+
# —––––––– Main Flow
|
25 |
+
uploaded = st.file_uploader("Upload a child-friendly image:", type=["jpg", "png", "jpeg"])
|
26 |
if not uploaded:
|
27 |
+
st.info("🌈 Please upload an image to start the magic!")
|
28 |
else:
|
29 |
+
# Process Image
|
30 |
img = Image.open(uploaded).convert("RGB")
|
31 |
+
st.image(img, use_column_width=True)
|
32 |
|
33 |
+
# Generate Caption
|
34 |
+
with st.spinner("🔍 Discovering image secrets..."):
|
35 |
try:
|
36 |
+
img_bytes = BytesIO()
|
37 |
+
img.save(img_bytes, format="JPEG")
|
38 |
+
caption_response = caption_client(data=img_bytes.getvalue())
|
39 |
+
caption = caption_response[0]['generated_text'].strip() if isinstance(caption_response, list) else ""
|
40 |
+
|
41 |
+
if not caption:
|
42 |
+
st.error("😢 Couldn't understand this image. Try another one!")
|
43 |
+
st.stop()
|
|
|
|
|
|
|
|
|
44 |
except Exception as e:
|
45 |
+
st.error(f"🚨 Oops! Problem making caption: {str(e)}")
|
46 |
st.stop()
|
47 |
|
48 |
+
st.success(f"**Caption Magic:** {caption}")
|
49 |
+
|
50 |
+
# Story Generation Prompt
|
51 |
+
story_prompt = (
|
52 |
+
f"Image description: {caption}\n\n"
|
53 |
+
"Write a 50-100 word children's story that:\n"
|
54 |
+
"1. Features the main subject as a friendly character\n"
|
55 |
+
"2. Includes a simple adventure or discovery\n"
|
56 |
+
"3. Ends with a happy or funny conclusion\n"
|
57 |
+
"4. Uses simple language for ages 3-8\n\n"
|
58 |
+
"Story:\n"
|
|
|
|
|
|
|
59 |
)
|
60 |
|
61 |
+
# Generate Story
|
62 |
+
with st.spinner("📝 Writing magical story..."):
|
63 |
+
try:
|
64 |
+
story_response = story_client(
|
65 |
+
story_prompt,
|
66 |
+
max_new_tokens=200,
|
67 |
+
temperature=0.8,
|
68 |
+
top_p=0.95,
|
69 |
+
repetition_penalty=1.15,
|
70 |
+
do_sample=True,
|
71 |
+
no_repeat_ngram_size=2
|
72 |
+
)
|
73 |
+
|
74 |
+
# Process response
|
75 |
+
full_text = story_response[0]['generated_text']
|
76 |
+
story = full_text.split("Story:")[-1].strip()
|
77 |
+
|
78 |
+
# Ensure clean ending
|
79 |
+
if "." in story:
|
80 |
+
story = story.rsplit(".", 1)[0] + "."
|
81 |
+
|
82 |
+
except Exception as e:
|
83 |
+
st.error(f"🚨 Story magic failed: {str(e)}")
|
84 |
+
st.stop()
|
85 |
|
86 |
+
# Display Story
|
87 |
+
st.subheader("📚 Your Magical Story")
|
88 |
+
st.write(story)
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
89 |
|
90 |
+
# Audio Conversion
|
91 |
+
with st.spinner("🔊 Adding story voice..."):
|
92 |
try:
|
93 |
+
tts = gTTS(text=story, lang="en", slow=False)
|
94 |
+
with tempfile.NamedTemporaryFile(delete=False, suffix=".mp3") as fp:
|
95 |
+
tts.save(fp.name)
|
96 |
+
st.audio(fp.name, format="audio/mp3")
|
|
|
97 |
except Exception as e:
|
98 |
+
st.warning("⚠️ Couldn't make audio version: " + str(e))
|
99 |
|
100 |
+
st.markdown("---\n*Made with ❤️ by your friendly story wizard*")
|