|
|
|
|
|
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" |
|
|
|
|
|
|
|
|
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_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: |
|
|
|
|
|
st.write("β³ Summarizing article...") |
|
|
summary = call_openai(SUMMARY_PROMPT.format(article_text=article_text)) |
|
|
st.write("β
Summary complete.") |
|
|
|
|
|
|
|
|
st.write("β³ Generating meme captions...") |
|
|
output = call_openai(MEME_PROMPT.format(summary=summary)) |
|
|
st.write("β
Captions generated.") |
|
|
|
|
|
|
|
|
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() |
|
|
|
|
|
|
|
|
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 |
|
|
|