7.5. Better Outputs#

7.5.1. How to Strip Outputs and Execute Interactive Code in a Python Script#

Hide code cell content
!pip install strip-interactive

Have you ever seen a tutorial with an interactive Python code and wished to execute it in a Python script like above?

It might be time-consuming to delete all >>> symbols and remove all outputs, especially when the code is long. That is why I created strip-interactive.

from strip_interactive import run_interactive

code = """
>>> import numpy as np
>>> print(np.array([1,2,3]))
[1 2 3]
>>> print(np.array([4,5,6]))
[4 5 6]

clean_code = run_interactive(code)
[1 2 3]
[4 5 6]

Link to the article about strip-interactive.

Link to strip-interactive.

7.5.2. Pyfiglet: Make Large and Unique Letters Out of Ordinary Text in Python#

Hide code cell content
!pip install pyfiglet

If you want to make large and unique letters out of ordinary text using Python, try pyfiglet. Below are some outputs of pyfiglet:

import pyfiglet
from termcolor import colored, cprint

out = pyfiglet.figlet_format("Hello")
 _   _      _ _       
| | | | ___| | | ___  
| |_| |/ _ \ | |/ _ \ 
|  _  |  __/ | | (_) |
|_| |_|\___|_|_|\___/ 
out = pyfiglet.figlet_format("Hello", font='slant')
    __  __     ____    
   / / / /__  / / /___ 
  / /_/ / _ \/ / / __ \
 / __  /  __/ / / /_/ /
/_/ /_/\___/_/_/\____/ 
cprint(pyfiglet.figlet_format('Hello', font='bell'), 'blue')
 __  __         .    .         
 |   |    ___   |    |     __. 
 |___|  .'   `  |    |   .'   \
 |   |  |----'  |    |   |    |
 /   /  `.___, /\__ /\__  `._.'

This could be used as the welcome message for your Python package 🙂

Link to pyfiglet.

Link to termcolor.

7.5.3. Python Fire: Generate a CLI for Any Python Objects in Two Lines of Code#

Hide code cell content
!pip install fire

Have you ever wanted to adjust the values of Python objects from the command line, but found it inconvenient to do so? With Python Fire, you can easily generate a command-line interface for any Python object in just two lines of code.

To see how Python Fire works, let’s look at an example. Start with creating file named fire_example.py:

%%writefile fire_example.py
import fire

def get_mean(numbers: list):
    return sum(numbers) / len(numbers)

def get_modulo(num1: int, num2: int):
    return num1 % num2

if __name__ == "__main__":
Writing fire_example.py

Then run the following command on your terminal:

$ python fire_example.py get_mean "[1, 2, 3]"
$ python fire_example.py get_modulo --num1=3 --num2=2

Link to Python Fire.

7.5.4. Typer: Build a Command-Line Interface in a Few Lines of Code#

Hide code cell content
!pip install typer 

While Python Fire is easy to use, it doesn’t provide much flexibility in terms of customization. Typer offers tools for building CLI applications in Python with a more explicit syntax. Typer also uses type annotations to validate user input.

To see how Typer works, let’s look at an example. Start with creating file named typer_example.py:

%%writefile typer_example.py
import typer

app = typer.Typer()

def add_numbers(x: float, y: float):
    """Adds two numbers and prints the result."""
    result = x + y
    print(f"The sum of {x} and {y} is {result}.")

if __name__ == "__main__":
Writing typer_example.py

Then run the following command on your terminal:

$ python typer_example.py hello world

And you should see an output like below:

Hide code cell source
!python typer_example.py hello world
Usage: typer_example.py [OPTIONS] X Y
Try 'typer_example.py --help' for help.

Error: Invalid value for 'X': 'hello' is not a valid float.

You can see that when the input is not a valid float, Typer raised a TypeError with a helpful error message.

Providing the valid inputs will give the following output:

$ python typer_example.py 3 2
The sum of 3.0 and 2.0 is 5.0.

Link to Typer.

My full article about Typer.

7.5.5. Generate a Tree View with rich#

Hide code cell content
!pip install rich 

If you want to generate a tree view of a specific structure such as files in a directory, use rich.tree. rich also allows you to add color to each branch using brackets.

from rich.tree import Tree
from rich import print

tree = Tree("[cyan]My Project")
src = tree.add("[red]src")
My Project
├── data
├── model
└── src
    └── process_data.py

Link to rich.

7.5.6. latexify_py: Generates a LaTex Math Description From a Python Function#

Hide code cell content
!pip install latexify-py

Have you ever wanted to add math description for your Python function but found it time-consuming to do so? latexify_py allows you to add LaTex math description with only one decorator.

import math
import latexify

def solve(a, b, c):
    return (-b + math.sqrt(b**2 - 4*a*c)) / (2*a)

\[ \displaystyle \mathrm{solve}(a, b, c)\triangleq \frac{-b + \sqrt{b^{2} - 4ac}}{2a} \]
def sinc(x):
    if x == 0:
        return 1
        return math.sin(x) / x

\[\begin{split} \displaystyle \mathrm{sinc}(x)\triangleq \left\{ \begin{array}{ll} 1, & \mathrm{if} \ x=0 \\ \frac{\sin{\left({x}\right)}}{x}, & \mathrm{otherwise} \end{array} \right. \end{split}\]

Link to latexify_py.

7.5.7. ManimML: Create Animations of Common ML Concepts in Python#

If you want to create animations and visualizations for common ML concepts in Python, try ManimML.

The GIF below is the visualization of Variational Autoencoder made by ManimML.

Link to ManimML.

ManimML is built on top of Manim.

7.5.8. Great Tables: Create Scientific-Looking Tables in Python#

Hide code cell content
!pip install great_tables 

If you want to create visually appealing and scientific-looking tables in Python, use Great Tables. With Great Tables, you can customize your table by mixing and matching various elements such as headers, footers, and cell value formats.

from great_tables import GT, md
from great_tables.data import islands

islands_mini = islands.head(10).sort_values(by="size", ascending=False) # pandas DataFrame

    GT(islands_mini, rowname_col="name")
        title="Large Landmasses of the World",
        subtitle="The top ten largest are presented",
        source_note="Source: The World Almanac and Book of Facts, 1975, page 406."
            "Reference: McNeil, D. R. (1977) *Interactive Data Analysis*. Wiley."
    .fmt_number(columns="size", sep_mark=",", decimals=0)
Large Landmasses of the World
The top ten largest are presented
landmass size
Asia 16,988
Africa 11,506
Antarctica 5,500
Australia 2,968
Borneo 280
Baffin 184
Britain 84
Celebes 73
Banks 23
Axel Heiberg 16
Source: The World Almanac and Book of Facts, 1975, page 406.
Reference: McNeil, D. R. (1977) Interactive Data Analysis. Wiley.

Link to Great Tables.

7.5.9. Camelot: PDF Table Extraction for Humans#

Hide code cell content
!pip install "camelot-py[base]" "opencv-python" "pypdf2<3"

With Camelot, you can extract tables from PDFs using Python and convert the data into a more structured format, such as a pandas DataFrame or a CSV file for efficient analysis, manipulation, and integration.

To see how Camelot works, start by reading the PDF file named ‘foo.pdf’ and extracts all the tables present in the file.

import camelot
tables = camelot.read_pdf('foo.pdf')
<TableList n=1>

The output shows that there is one table extracted from the PDF file.

Export the extracted tables to a CSV file named ‘foo.csv’. Camelot also supports exporting tables to other formats like JSON, Excel, HTML, Markdown, and SQLite databases.

    'accuracy': 99.02,
    'whitespace': 12.24,
    'order': 1,
    'page': 1
tables[0].to_csv('foo.csv') # to_json, to_excel, to_html, to_markdown, to_sqlite
tables[0].df # get a pandas DataFrame!
0 1 2 3 4 5 6
0 Cycle \nName KI \n(1/km) Distance \n(mi) Percent Fuel Savings
1 Improved \nSpeed Decreased \nAccel Eliminate \nStops Decreased \nIdle
2 2012_2 3.30 1.3 5.9% 9.5% 29.2% 17.4%
3 2145_1 0.68 11.2 2.4% 0.1% 9.5% 2.7%
4 4234_1 0.59 58.7 8.5% 1.3% 8.5% 3.3%
5 2032_2 0.17 57.8 21.7% 0.3% 2.7% 1.2%
6 4171_1 0.07 173.9 58.1% 1.6% 2.1% 0.5%

Link to Camelot.