Automating Meme Creation from News Headlines Using Python
Want to share your content on python-bloggers? click here.
Introduction
In today’s digital world, memes have become a powerful tool for sharing information, humor, and social commentary. This blog post explores how we can automate meme creation using Python by fetching news headlines, downloading relevant images, generating witty captions, and overlaying the text on the images. We will use various libraries and APIs, including Google News, Pixabay, and Google’s Gemini AI, to make this process seamless and efficient.
Overview
The script follows a structured approach:
- Fetch news headlines using Google’s RSS feed.
- Download images from Pixabay based on random categories.
- Generate witty meme text using Gemini AI, taking into account both the headline and the downloaded image.
- Overlay text on the image to create a meme.
- Save and display the final meme.
Required Libraries

Before running the script, ensure you have installed the necessary libraries:
pip install requests Pillow beautifulsoup4 google-generativeai
Step-by-Step Breakdown
1. Fetching News Headlines
We use Google’s RSS feed to fetch the latest news headlines:
import requests from bs4 import BeautifulSoup URL = 'https://news.google.com/rss/search?q=today%27s+news' def fetch_headlines(): """Fetch headlines from Google News and save them to a text file.""" response = requests.get(URL) if response.status_code == 200: soup = BeautifulSoup(response.content, 'xml') items = soup.find_all('item', limit=5) headlines = [item.title.text for item in items] with open('notepad.txt', 'w', encoding='utf-8') as file: for headline in headlines: file.write(headline + 'n') return headlines else: print(f'Failed to retrieve news. Status code: {response.status_code}') return []
This function fetches the top 5 headlines and saves them in a text file.
2. Downloading Images from Pixabay
We use the Pixabay API to fetch random images for meme creation:
This function selects a random search category, downloads images from Pixabay, and extracts metadata tags as image descriptions.
import os import random PIXABAY_API_KEY = '' # Add your API key here SEARCH_TERMS = ['nature', 'technology', 'food', 'cities'] DOWNLOAD_DIR = r' ’ #ADD PATH IMAGE_COUNT = 5 def download_pixabay_images(): """Download random images from Pixabay and extract descriptions.""" search_term = random.choice(SEARCH_TERMS) url = f'https://pixabay.com/api/?key={PIXABAY_API_KEY}&q={search_term}&image_type=photo&per_page={IMAGE_COUNT}' response = requests.get(url) if response.status_code == 200: data = response.json() images = data['hits'] downloaded_images = [] image_descriptions = [] for img in images: img_url = img['largeImageURL'] img_tags = img['tags'] # Use Pixabay's tags as an image description img_data = requests.get(img_url).content img_name = img_url.split('/')[-1] with open(os.path.join(DOWNLOAD_DIR, img_name), 'wb') as handler: handler.write(img_data) downloaded_images.append(os.path.join(DOWNLOAD_DIR, img_name)) image_descriptions.append(img_tags) return downloaded_images, image_descriptions else: print(f'Failed to retrieve images. Status code: {response.status_code}') return [], []
3. Generating Meme Text with Gemini AI
Google’s Gemini API helps generate witty meme captions from news headlines while considering the image context:
import google.generativeai as genai genai.configure(api_key='') # Add your Gemini API key here def generate_content_with_gemini(headline, image_description): """Generate content using Gemini AI based on the headline and image description.""" model = genai.GenerativeModel("gemini-1.5-flash") prompt = f"Create a funny meme caption based on this news headline: '{headline}' and this image description: '{image_description}'" response = model.generate_content(prompt) if response and hasattr(response, 'text'): return response.text.strip() else: return "Breaking News: AI refuses to joke!"
This function ensures the meme text is customized using both the news headline and the associated image context.
4. Overlaying Text on an Image
We use the Pillow library to add text to the downloaded images:
from PIL import Image, ImageDraw, ImageFont def create_meme(image_path, text): """Overlay text on an image to create a meme.""" img = Image.open(image_path) draw = ImageDraw.Draw(img) try: font = ImageFont.truetype("arial.ttf", 40) except IOError: font = ImageFont.load_default() text_position = (10, img.height - 70) draw.text(text_position, text, fill="white", font=font) meme_image_path = os.path.join(DOWNLOAD_DIR, f'meme_{os.path.basename(image_path)}') img.save(meme_image_path) return meme_image_path
This function uses a readable font and ensures the text is properly placed on the image.
5. Running the Script
We now bring everything together in the main function:
def main(): headlines = fetch_headlines() if headlines: downloaded_images, image_descriptions = download_pixabay_images() for headline, image_path, img_desc in zip(headlines, downloaded_images, image_descriptions): meme_text = generate_content_with_gemini(headline, img_desc) create_meme(image_path, meme_text) if __name__ == '__main__': main()
The script now analyzes both the news headline and the image metadata to create a more relevant and engaging meme.
Conclusion
This Python project automates the process of creating memes from current news headlines, incorporating image context for more relevant and humorous results. It showcases how different APIs and libraries can be integrated to fetch data, process images, and generate text dynamically. This is a fun yet practical application of AI in content creation. It can be implemented to generate content for various social media platforms- like Instagram, YouTube etc.
Hrishitva Patel https://www.linkedin.com/in/hrishitva-patel/ |
Want to share your content on python-bloggers? click here.