|
import requests |
|
import os |
|
import re |
|
from typing import Dict, List, Any, Optional |
|
import streamlit as st |
|
|
|
def clean_text(text: str) -> str: |
|
""" |
|
Clean text for meme generation by limiting length and removing special characters. |
|
|
|
Args: |
|
text: The text to clean |
|
|
|
Returns: |
|
Cleaned text |
|
""" |
|
|
|
text = re.sub(r'[^\w\s.,?!]', '', text) |
|
|
|
|
|
if len(text) > 100: |
|
text = text[:97] + '...' |
|
|
|
return text |
|
|
|
def create_meme(template_id: str, text_fields: List[str], article_title: str, article_abstract: str) -> Optional[str]: |
|
""" |
|
Create a meme using the Imgflip API. |
|
|
|
Args: |
|
template_id: Imgflip template ID |
|
text_fields: Predefined text fields for the template |
|
article_title: Article title to use in text fields |
|
article_abstract: Article abstract to use in text fields |
|
|
|
Returns: |
|
URL of the generated meme image, or None if creation failed |
|
""" |
|
|
|
username = os.environ.get("IMGFLIP_USERNAME") |
|
password = os.environ.get("IMGFLIP_PASSWORD") |
|
|
|
|
|
if not username or not password: |
|
try: |
|
username = st.secrets["IMGFLIP_USERNAME"] |
|
password = st.secrets["IMGFLIP_PASSWORD"] |
|
except Exception: |
|
st.error("Imgflip credentials not found. Please set the IMGFLIP_USERNAME and IMGFLIP_PASSWORD environment variables or in Streamlit secrets.") |
|
return None |
|
|
|
|
|
processed_fields = [] |
|
|
|
for field in text_fields: |
|
if field == "{TITLE}": |
|
processed_fields.append(clean_text(article_title)) |
|
elif field == "{ABSTRACT}": |
|
processed_fields.append(clean_text(article_abstract)) |
|
else: |
|
processed_fields.append(field) |
|
|
|
|
|
payload = { |
|
"template_id": template_id, |
|
"username": username, |
|
"password": password, |
|
"font": "impact", |
|
} |
|
|
|
|
|
for i, text in enumerate(processed_fields): |
|
payload[f"boxes[{i}][text]"] = text |
|
|
|
|
|
try: |
|
response = requests.post("https://api.imgflip.com/caption_image", data=payload) |
|
response.raise_for_status() |
|
|
|
data = response.json() |
|
|
|
if data.get("success"): |
|
return data.get("data", {}).get("url") |
|
else: |
|
st.error(f"Failed to create meme: {data.get('error_message')}") |
|
return None |
|
|
|
except requests.exceptions.RequestException as e: |
|
st.error(f"Error calling Imgflip API: {e}") |
|
return None |