memetoday / memes.py
rushankg's picture
Update memes.py
b988bd1 verified
# memes.py
import streamlit as st
import re
import torch
import requests
from openai import OpenAI
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",
}
# Initialize OpenAI client
client = OpenAI(api_key=st.secrets["OPENAI_API_KEY"])
def call_openai(prompt: str) -> str:
"""Call gpt-4o-mini via the Responses API."""
response = client.responses.create(
model="gpt-4o-mini",
instructions="You are a helpful assistant",
input=prompt,
)
return response.output_text.strip()
def article_to_meme(article_text: str) -> str:
# 1) Summarize
summary = call_openai(SUMMARY_PROMPT.format(article_text=article_text))
# 2) Choose template + captions
output = call_openai(MEME_PROMPT.format(summary=summary))
# 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
tpl_id = TEMPLATE_IDS.get(template.lower())
if not tpl_id:
raise KeyError(f"Unknown template: {template}")
resp = requests.post(
IMGFLIP_URL,
params={
"template_id": tpl_id,
"username": st.secrets["IMGFLIP_USERNAME"],
"password": st.secrets["IMGFLIP_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"]
return meme_url