Update memes.py
Browse files
memes.py
CHANGED
|
@@ -3,7 +3,7 @@ import streamlit as st
|
|
| 3 |
import re
|
| 4 |
import torch
|
| 5 |
import requests
|
| 6 |
-
from
|
| 7 |
from prompts import SUMMARY_PROMPT, MEME_PROMPT
|
| 8 |
|
| 9 |
IMGFLIP_URL = "https://api.imgflip.com/caption_image"
|
|
@@ -24,106 +24,61 @@ TEMPLATE_IDS = {
|
|
| 24 |
"Hide the Pain Harold": "27813981",
|
| 25 |
}
|
| 26 |
|
| 27 |
-
|
| 28 |
-
|
| 29 |
-
"""
|
| 30 |
-
Load Llama-3.2-1B and its tokenizer.
|
| 31 |
-
"""
|
| 32 |
-
st.write("π Loading Llama-3.2-1B model and tokenizer...")
|
| 33 |
-
tokenizer = AutoTokenizer.from_pretrained(
|
| 34 |
-
"meta-llama/Llama-3.2-1B",
|
| 35 |
-
trust_remote_code=True,
|
| 36 |
-
use_auth_token=st.secrets["HUGGINGFACE_TOKEN"]
|
| 37 |
-
)
|
| 38 |
-
model = AutoModelForCausalLM.from_pretrained(
|
| 39 |
-
"meta-llama/Llama-3.2-1B",
|
| 40 |
-
device_map="auto",
|
| 41 |
-
torch_dtype=torch.float16,
|
| 42 |
-
trust_remote_code=True,
|
| 43 |
-
use_auth_token=st.secrets["HUGGINGFACE_TOKEN"]
|
| 44 |
-
)
|
| 45 |
-
st.write("β
Model and tokenizer loaded.")
|
| 46 |
-
return tokenizer, model
|
| 47 |
|
| 48 |
-
|
| 49 |
-
|
| 50 |
-
|
| 51 |
-
|
| 52 |
-
|
| 53 |
-
|
| 54 |
-
|
| 55 |
-
tokenizer, model = load_llama3()
|
| 56 |
-
inputs = tokenizer(prompt, return_tensors="pt").to(model.device)
|
| 57 |
-
outputs = model.generate(
|
| 58 |
-
**inputs,
|
| 59 |
-
max_new_tokens=max_new_tokens,
|
| 60 |
-
do_sample=False,
|
| 61 |
-
pad_token_id=tokenizer.eos_token_id,
|
| 62 |
)
|
| 63 |
-
|
| 64 |
-
st.write("π‘ Model response:")
|
| 65 |
-
st.write(text)
|
| 66 |
-
return text
|
| 67 |
-
|
| 68 |
|
| 69 |
def article_to_meme(article_text: str) -> str:
|
| 70 |
-
"""
|
| 71 |
-
End-to-end pipeline:
|
| 72 |
-
1) Summarize the article via Llama-3.2-1B.
|
| 73 |
-
2) Ask Llama-3.2-1B to choose a meme template and produce two 6-8 word captions.
|
| 74 |
-
3) Parse the model's response.
|
| 75 |
-
4) Call Imgflip API to render the meme and return its URL.
|
| 76 |
-
"""
|
| 77 |
# 1) Summarize
|
| 78 |
-
st.write("
|
| 79 |
-
|
| 80 |
-
|
| 81 |
-
st.write(f"π Summary: {summary}")
|
| 82 |
|
| 83 |
-
# 2)
|
| 84 |
-
st.write("
|
| 85 |
-
|
| 86 |
-
|
| 87 |
|
| 88 |
-
# 3) Parse
|
| 89 |
-
|
| 90 |
-
|
| 91 |
-
|
| 92 |
-
|
| 93 |
-
|
| 94 |
-
|
| 95 |
-
|
|
|
|
| 96 |
|
| 97 |
-
|
| 98 |
-
|
| 99 |
-
|
| 100 |
-
|
| 101 |
-
st.write(f"π¬ text0: {text0}")
|
| 102 |
-
st.write(f"π¬ text1: {text1}")
|
| 103 |
-
|
| 104 |
-
# 4) Render the meme via Imgflip
|
| 105 |
-
st.write("βΆοΈ Step 4: Rendering meme via Imgflip...")
|
| 106 |
-
template_id = TEMPLATE_IDS.get(template)
|
| 107 |
-
if template_id is None:
|
| 108 |
-
st.error(f"β Unknown template: {template}")
|
| 109 |
raise KeyError(f"Unknown template: {template}")
|
| 110 |
-
|
| 111 |
creds = st.secrets["imgflip"]
|
| 112 |
-
|
| 113 |
-
|
| 114 |
-
|
| 115 |
-
|
| 116 |
-
|
| 117 |
-
|
| 118 |
-
|
| 119 |
-
|
| 120 |
-
|
|
|
|
| 121 |
resp.raise_for_status()
|
| 122 |
data = resp.json()
|
| 123 |
if not data.get("success", False):
|
| 124 |
-
st.error(f"β Imgflip error: {data.get('error_message')}")
|
| 125 |
raise Exception(data.get("error_message"))
|
| 126 |
|
| 127 |
meme_url = data["data"]["url"]
|
| 128 |
-
st.write(f"β
Meme
|
| 129 |
return meme_url
|
|
|
|
| 3 |
import re
|
| 4 |
import torch
|
| 5 |
import requests
|
| 6 |
+
from openai import ChatCompletion
|
| 7 |
from prompts import SUMMARY_PROMPT, MEME_PROMPT
|
| 8 |
|
| 9 |
IMGFLIP_URL = "https://api.imgflip.com/caption_image"
|
|
|
|
| 24 |
"Hide the Pain Harold": "27813981",
|
| 25 |
}
|
| 26 |
|
| 27 |
+
# OpenAI config
|
| 28 |
+
openai_api_key = st.secrets["OPENAI_API_KEY"]
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 29 |
|
| 30 |
+
def call_openai(prompt: str) -> str:
|
| 31 |
+
"""Call gpt-4o-mini once with given prompt."""
|
| 32 |
+
response = ChatCompletion.create(
|
| 33 |
+
model="gpt-4o-mini",
|
| 34 |
+
messages=[{"role": "user", "content": prompt}],
|
| 35 |
+
max_tokens=200,
|
| 36 |
+
temperature=0.7
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 37 |
)
|
| 38 |
+
return response.choices[0].message.content.strip()
|
|
|
|
|
|
|
|
|
|
|
|
|
| 39 |
|
| 40 |
def article_to_meme(article_text: str) -> str:
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 41 |
# 1) Summarize
|
| 42 |
+
st.write("β³ Summarizing article...")
|
| 43 |
+
summary = call_openai(SUMMARY_PROMPT.format(article_text=article_text))
|
| 44 |
+
st.write("β
Summary complete.")
|
|
|
|
| 45 |
|
| 46 |
+
# 2) Choose template + captions
|
| 47 |
+
st.write("β³ Generating meme captions...")
|
| 48 |
+
output = call_openai(MEME_PROMPT.format(summary=summary))
|
| 49 |
+
st.write("β
Captions generated.")
|
| 50 |
|
| 51 |
+
# 3) Parse model output
|
| 52 |
+
match_t = re.search(r"template:\s*(.+)", output, re.IGNORECASE)
|
| 53 |
+
match0 = re.search(r"text0:\s*(.+)", output, re.IGNORECASE)
|
| 54 |
+
match1 = re.search(r"text1:\s*(.+)", output, re.IGNORECASE)
|
| 55 |
+
if not (match_t and match0 and match1):
|
| 56 |
+
raise ValueError(f"Parsing failed: {output}")
|
| 57 |
+
template = match_t.group(1).strip()
|
| 58 |
+
text0 = match0.group(1).strip()
|
| 59 |
+
text1 = match1.group(1).strip()
|
| 60 |
|
| 61 |
+
# 4) Render meme
|
| 62 |
+
st.write("β³ Rendering meme...")
|
| 63 |
+
tpl_id = TEMPLATE_IDS.get(template)
|
| 64 |
+
if not tpl_id:
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 65 |
raise KeyError(f"Unknown template: {template}")
|
|
|
|
| 66 |
creds = st.secrets["imgflip"]
|
| 67 |
+
resp = requests.post(
|
| 68 |
+
IMGFLIP_URL,
|
| 69 |
+
params={
|
| 70 |
+
"template_id": tpl_id,
|
| 71 |
+
"username": creds["username"],
|
| 72 |
+
"password": creds["password"],
|
| 73 |
+
"text0": text0,
|
| 74 |
+
"text1": text1,
|
| 75 |
+
}
|
| 76 |
+
)
|
| 77 |
resp.raise_for_status()
|
| 78 |
data = resp.json()
|
| 79 |
if not data.get("success", False):
|
|
|
|
| 80 |
raise Exception(data.get("error_message"))
|
| 81 |
|
| 82 |
meme_url = data["data"]["url"]
|
| 83 |
+
st.write(f"β
Meme ready: [View here]({meme_url})")
|
| 84 |
return meme_url
|