File size: 2,793 Bytes
f116710 66a27f1 f116710 3946047 f116710 3946047 f116710 3946047 f116710 66a27f1 f116710 66a27f1 f116710 66a27f1 f116710 98ef818 66a27f1 f116710 66a27f1 f116710 66a27f1 f116710 66a27f1 f116710 16fef17 66a27f1 f116710 98ef818 66a27f1 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 80 81 82 83 84 85 |
# 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
|