memetoday / memes.py
rushankg's picture
Update memes.py
66a27f1 verified
raw
history blame
2.79 kB
# memes.py
import streamlit as st
import re
import torch
import requests
from openai import ChatCompletion
from prompts import SUMMARY_PROMPT, MEME_PROMPT
IMGFLIP_URL = "https://api.imgflip.com/caption_image"
# 12 template names β†’ Imgflip template_ids
TEMPLATE_IDS = {
"Drake Hotline Bling": "181913649",
"UNO Draw 25 Cards": "217743513",
"Bernie Asking For Support": "222403160",
"Disaster Girl": "97984",
"Waiting Skeleton": "109765",
"Always Has Been": "252600902",
"Woman Yelling at Cat": "188390779",
"I Bet He's Thinking About Other Women": "110163934",
"One Does Not Simply": "61579",
"Success Kid": "61544",
"Oprah You Get A": "28251713",
"Hide the Pain Harold": "27813981",
}
# OpenAI config
openai_api_key = st.secrets["OPENAI_API_KEY"]
def call_openai(prompt: str) -> str:
"""Call gpt-4o-mini once with given prompt."""
response = ChatCompletion.create(
model="gpt-4o-mini",
messages=[{"role": "user", "content": prompt}],
max_tokens=200,
temperature=0.7
)
return response.choices[0].message.content.strip()
def article_to_meme(article_text: str) -> str:
# 1) Summarize
st.write("⏳ Summarizing article...")
summary = call_openai(SUMMARY_PROMPT.format(article_text=article_text))
st.write("βœ… Summary complete.")
# 2) Choose template + captions
st.write("⏳ Generating meme captions...")
output = call_openai(MEME_PROMPT.format(summary=summary))
st.write("βœ… Captions generated.")
# 3) Parse model output
match_t = re.search(r"template:\s*(.+)", output, re.IGNORECASE)
match0 = re.search(r"text0:\s*(.+)", output, re.IGNORECASE)
match1 = re.search(r"text1:\s*(.+)", output, re.IGNORECASE)
if not (match_t and match0 and match1):
raise ValueError(f"Parsing failed: {output}")
template = match_t.group(1).strip()
text0 = match0.group(1).strip()
text1 = match1.group(1).strip()
# 4) Render meme
st.write("⏳ Rendering meme...")
tpl_id = TEMPLATE_IDS.get(template)
if not tpl_id:
raise KeyError(f"Unknown template: {template}")
creds = st.secrets["imgflip"]
resp = requests.post(
IMGFLIP_URL,
params={
"template_id": tpl_id,
"username": creds["username"],
"password": creds["password"],
"text0": text0,
"text1": text1,
}
)
resp.raise_for_status()
data = resp.json()
if not data.get("success", False):
raise Exception(data.get("error_message"))
meme_url = data["data"]["url"]
st.write(f"βœ… Meme ready: [View here]({meme_url})")
return meme_url