File size: 2,498 Bytes
f116710 53c76e6 f116710 b988bd1 f116710 3a1a5df f116710 66a27f1 3a1a5df 66a27f1 3a1a5df f116710 3a1a5df f116710 98ef818 66a27f1 f116710 66a27f1 f116710 66a27f1 f116710 66a27f1 b988bd1 66a27f1 f116710 66a27f1 1a8bd06 66a27f1 f116710 98ef818 |
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 |
# 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
|