Sumayyea's picture
Update app.py
dbd626b verified
Raw History Blame Contribute Delete
5.39 kB
import requests
from PIL import Image, ImageDraw, ImageFont
import streamlit as st
import random
st.title("Social Poster Generator")
st.markdown("Create and share beautiful, real-quote posters for social media.")
platform = st.selectbox(
"Choose Platform", ["LinkedIn", "Instagram", "TikTok", "Facebook", "Other"]
)
quote_type = st.selectbox(
"Type of Content",
["Author", "Topic", "Islamic Verse", "Hadith", "AI Generated"]
)
user_input = st.text_input("Enter author, topic, or keyword (optional)")
# ---------- Local fallback quotes ----------
local_quotes = [
{"q": "The best way to predict the future is to invent it.", "a": "Alan Kay"},
{"q": "Life is what happens when you're busy making other plans.", "a": "John Lennon"},
{"q": "Be yourself; everyone else is already taken.", "a": "Oscar Wilde"},
{"q": "Success is not final, failure is not fatal: It is the courage to continue that counts.", "a": "Winston Churchill"}
]
# ---------- Generate Poster Button ----------
if st.button("Generate Poster", key="main_gen_poster"):
st.write("Generating...")
quote, ref = None, None
# -----------------
# HADITH
# -----------------
if quote_type == "Hadith":
try:
res = requests.get("https://random-hadith-api.herokuapp.com/randomHadith", timeout=5)
if res.status_code != 200:
st.error("Hadith API returned an error.")
else:
data = res.json()
quote = data.get("data", {}).get("hadith")
ref = data.get("data", {}).get("book", "Unknown Hadith Collection")
if quote:
st.success(f'"{quote}"')
st.info(f"Reference: {ref}")
else:
st.info("No hadith found from the API.")
except Exception as e:
st.error(f"API error: {e}")
# -----------------
# ISLAMIC VERSE
# -----------------
elif quote_type == "Islamic Verse":
try:
surah = random.randint(1, 114)
ayah = random.randint(1, 7) # simple range to avoid errors
url = f"https://api.alquran.cloud/v1/ayah/{surah}:{ayah}/en.asad"
res = requests.get(url, timeout=5)
data = res.json()
if data.get("status") == "OK":
quote = data["data"]["text"]
ref = f'{data["data"]["surah"]["englishName"]} {data["data"]["numberInSurah"]}'
st.success(f'"{quote}"')
st.info(f"Reference: {ref}")
else:
st.info("No verse found. Try again.")
except Exception as e:
st.error(f"API error: {e}")
# -----------------
# AI GENERATED
# -----------------
elif quote_type == "AI Generated":
quote = "Your AI-generated inspirational message goes here!"
ref = "AI Model"
st.success(quote)
st.info(ref)
# -----------------
# AUTHOR / TOPIC QUOTES
# -----------------
elif quote_type in ["Author", "Topic"]:
try:
# Attempt to get random quote from ZenQuotes
res = requests.get("https://zenquotes.io/api/random", timeout=5)
data = res.json()
if isinstance(data, list) and len(data) > 0:
q = data[0]
quote = q.get("q")
ref = q.get("a")
else:
# fallback to local list
q = random.choice(local_quotes)
quote = q["q"]
ref = q["a"]
st.success(f'"{quote}"')
st.info(f"Reference: {ref}")
except Exception:
# Always fallback to local quotes if ZenQuotes fails
q = random.choice(local_quotes)
quote = q["q"]
ref = q["a"]
st.success(f'"{quote}"')
st.info(f"Reference: {ref}")
else:
st.info("Please enter a valid author/topic or select a different type above.")
# -----------------
# OPTIONAL: Generate poster image using PIL
# -----------------
if quote:
try:
img = Image.new("RGB", (800, 600), color=(255, 255, 255))
draw = ImageDraw.Draw(img)
font_size = 30
try:
font = ImageFont.truetype("arial.ttf", font_size)
except:
font = ImageFont.load_default()
# Wrap text
lines = []
words = quote.split()
line = ""
for word in words:
if len(line + " " + word) <= 40:
line += " " + word
else:
lines.append(line.strip())
line = word
lines.append(line.strip())
# Draw text
y_text = 100
for l in lines:
# Pillow >=10 replacement for textsize
bbox = draw.textbbox((0, 0), l, font=font)
w = bbox[2] - bbox[0]
h = bbox[3] - bbox[1]
draw.text(((800 - w) / 2, y_text), l, font=font, fill=(0, 0, 0))
y_text += h + 10
# Draw reference
draw.text((800-400, 500), f"- {ref}", font=font, fill=(0, 0, 0))
st.image(img)
except Exception as e:
st.warning(f"Could not generate poster image: {e}")