File size: 2,921 Bytes
7cb9ea9
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
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
86
87
88
89
90
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