Turn (almost) any webpage into stunning infographics with this Python script!

Paulo H.
5 min readMar 15, 2024

Important — This script is based on this majestic article, that gave me the idea to just automate the whole process.

Looking for an easy way to turn the content from (almost) any site into eye-catching infographics? Meet the InfographAI, a Python script that simplifies the whole process.

The idea behind it

Some weeks ago I stumbled upon a cool post showing how to use chatGPT Plus to create infographics. It was a really cool idea, but

a) As a dev, I'm too lazy to follow so many manual steps;
b) I'm cheap and don't want to pay for GPT Plus, paying just for API usage as I go;
c) I wanted to do a little show off with my skills :P

So I decided to write a minimal Python script that automates the creation of infographics directly from a website's content. Run it on a MacOS/Linux terminal or Windows command prompt, and voilá!

What it Does

So, here’s the scoop:

  1. Content Extraction: First off, you point the script to a URL — it then snags the juicy bits from it. Think of it as mining gold from a website, with a little caveat: at this stage, it can only read sites that use good HTML and SEO standards and have <main> or <article> tags;
  2. Visual Description Generation: Next, the script calls OpenAI API to whip up a visual description of the extracted content, saying exactly as if he describing the infographic idea to a designer, but with more details. Picture it like giving the content a small makeover.
  3. Infographic Generation: Finally, the script calls in the big guns, using the DALL-E API to cook up an infographic based on that visual description. It’s like turning words into pictures, but way cooler, because you just had to type a few things and copy-paste some URLs along the way.

Why You’ll Love It

  • Efficient Automation: Kiss manual infographic creation goodbye. This little fella saves you tons of time.
  • Flexible Customization: Want your infographic to pop with personality? You can add some description of style style, color, or font instructions.
  • Unleash Your Creativity: Are you like me, with almost zero experience with Photoshop and other tools, except for small changes? Turn any text into a visual masterpiece. Make your article pop. Create a cool graphic to share on Linkedin / X / others with minimal effort. Expand what you wrote graphically. The possibilities are endless.

Why You'll Hate It

  • As described in the original article, DALL-E is still kinda bad at creating images with lots of small text, most of the time just writing gibberish. You will need to use some tool like Photoshop / Canva / Gimp to fix it
  • You will need a minimal knowledge of Python to make it work 🤷🏽‍♂️

How to Use

Get it on GitHub, follow, and star to receive update notifications

import sys
import os
import requests
from openai import OpenAI
from bs4 import BeautifulSoup
from dotenv import load_dotenv

load_dotenv()

def extract_text_from_url(url):
try:
response = requests.get(url)
response.raise_for_status()
except requests.exceptions.RequestException as e:
print(f"Error accessing URL: {e}")
return None

soup = BeautifulSoup(response.text, 'html.parser')

page_language = soup.html.get('lang')

# Find the main or article element
main_content = soup.find('main')
article_content = soup.find('article')

extracted_text = ""

if main_content:
extracted_text += main_content.get_text().strip() + "\n"

if article_content:
extracted_text += article_content.get_text().strip() + "\n"

return extracted_text, page_language

# Function to call the OpenAI API
def call_openai_api(text, page_language):

client = OpenAI(
api_key=os.getenv("OPENAI_API_KEY"),
)


if os.getenv("OPENAI_API_KEY") is None:
print("OpenAI API key not found. Make sure to set OPENAI_API_KEY in the .env file.")
return None

prompt = "My job is to create visually engaging infographics for web content." # Like if you hate horizontal scroll in code
prompt += "I need you to assume the persona of a professional infographic creator and "
prompt += "generate a visual description for the infographic, so that the graphic designer can then create it. Use the text below for this: \n"
if page_language is not None:
prompt += f"Consider that the page language is {page_language}, "
prompt += "but keep the instructions in Brazilian Portuguese. " # Like if you make dumb debugs
prompt += text

response = client.chat.completions.create(
model="gpt-4",
messages=[
{"role": "user", "content": prompt}
]
)
return response.choices[0].message.content


def dalle_lek(text, style):

api_key = os.getenv("OPENAI_API_KEY")

if api_key is None:
print("OpenAI API key not found. Make sure to set OPENAI_API_KEY in the .env file.")
return None

prompt = "Create an infographic for a blog post using the following visual description: \n" + text

if style:
prompt += "The infographic should be made with the desired style: " + style + "."

client = OpenAI(
api_key=api_key,
)

response = client.images.generate(
model="dall-e-3",
prompt=prompt,
size="1024x1792",
quality="hd",
style="natural",
n=1,
)

return response.data[0].url


if __name__ == "__main__":

if len(sys.argv) != 2:
print("Please provide the URL as a command-line argument.")
url = input("Enter the URL to extract content from: ")
else:
url = sys.argv[1]

style = input("Okay, if you want, include instructions on how you would like the infographic to be generated (style, color, font, etc.) or just press ENTER to continue: ")

if not style:
print("No style, so let's trust the heart of the cards!")

print("Transforming the website's text into an infographic: ", url)
extracted_content, page_language = extract_text_from_url(url)

if extracted_content:
openai_response = call_openai_api(extracted_content, page_language)
if openai_response:
print("Alright, we've got what we need to create the infographic, just wait a little longer!")
image_url = dalle_lek(openai_response, style)
if image_url:
print("Generated image URL:", image_url)
else:
print("Unable to extract content from the URL.")
  1. Installation and Setup: Grab the code from the repository and install the dependencies listed in requirements.txt. Don't forget to set up your .env file with your OpenAI API key.
  2. Get Rolling: Fire up the script and toss in a URL as a command-line argument. The script will do its magic — extracting content, crafting a visual description, and whipping up an infographic.
  3. Spruce It Up: As said, DALL-E can be a bit hit or miss for text generation. Consider giving your infographic some love treatment using Photoshop, Gimp or Canva
script.py <URL>

Important Note

Before you start, make sure you’ve got your OpenAI API keys at hand. You can grab them at https://platform.openai.com/api-keys — And remember, using these APIs comes with a price tag.

Note: This project is a work in progress. Do you have feedback or ideas? Shoot ’em my way.

For more info and updates, swing by the repository link.

--

--

Paulo H.
Paulo H.

Written by Paulo H.

WordPress Optimization Specialist | 15+ Years of Expertise as Tech Lead, Project Manager, and Professional Solution-Maker - I also cook

No responses yet