memenews / utils /imgflip_api.py
rushankg's picture
Create imgflip_api.py
7cb9ea9 verified
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
"""
# Remove non-alphanumeric characters except spaces, periods, commas, and question marks
text = re.sub(r'[^\w\s.,?!]', '', text)
# Truncate to 100 characters if longer
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
"""
# Try to get API credentials from environment or secrets
username = os.environ.get("IMGFLIP_USERNAME")
password = os.environ.get("IMGFLIP_PASSWORD")
# If not found in environment, check streamlit secrets
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
# Process text fields, replacing placeholders with article content
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)
# Create payload
payload = {
"template_id": template_id,
"username": username,
"password": password,
"font": "impact",
}
# Add text boxes
for i, text in enumerate(processed_fields):
payload[f"boxes[{i}][text]"] = text
# Make the API request
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