A while back I shared how I use ExifTool to get extensive metadata for any file. I want to make that info dump pretty with Rich, a text formatting library for Python.
“But Brian,”" I hear you cry. “ExifTool is Perl. Why would I want to use both Perl and Python?”
Because it’s fun, obviously.
You want a “real” reason? Okay fine. I haven’t found anything that can get the depth of file information I get from ExifTool. I haven’t found a formatting library that’s as pleasant to use as Rich — maybe TTY Toolkit?
Besides — ExifTool is a standalone command line tool. We don’t need to write any Perl to use it. Heck, we don’t even need to figure out the system calls. Sven Marnach is way ahead of us with the extremely helpful pyexiftool.
Rich and pyexiftool make Python an easy choice for this task.
Setting up
If you want to play along at home, make sure you have the dependencies.
I get an error message telling me what richexif.py needs to do its thing. Nice.
I confirmed that Typer handles the CLI bits, and Rich handles the formatting. Now for pyexiftool.
Oh and I’ll skip logging output from here on. Rich’s logging handler output is a joy to look at, but really that stuff is for me. For you it’ll just add noise.
Some metadata
I need exiftool, of course. Plus a Rich Console object, masterminding the display details for my terminal.
import exiftool
from rich.console import Console
console = Console()
exiftool’s get_metadata grabs everything ExifTool sees about a file. It also provides methods for ExifTool tags, but I won’t mess with them today. Tags — the official name for our metadata keys — are most useful when you already know what you’re looking for. We’re just checking stuff out.
For now, a little abstraction layer over pyexiftool’s ExifTool.
defget_metadata(filename):
"""Return a dictionary of file metadata."""with exiftool.ExifTool() as et:
return et.get_metadata(filename)
main gets the metadata and asks console to print it.
Holy crap that’s a lot. Some of it could be considered sensitive information — unless you read my now page. But it’s all there! Even in the snipped version you can learn a lot. Hello from my Windows partition in West Seattle during February of 2021!
TIP
Uncomfortable sharing that much with every photo you upload? You can scrub
those tags right out. With ExifTool, of course.
But back to the other gripe about all this metadata. It’s way too much for me to take in all at once. I need some kind of filter!
Filtering the firehose
deffilter_metadata(metadata, filter):
"""Return a copy of the metadata where fields contain the substring `filter`."""return {k: v for k, v in metadata.items() if filter in k}
There’s no kind of transformation here. If a field constrains the exact substring described in filter, use it.
Adding a Typer Option lets us ask for a filter from the command line.
Now that I’m not overwhelmed by the quantity of output, I’m a little underwhelmed by the quality.
{'File:ImageWidth': 3672,
'File:ImageHeight': 2066,
'EXIF:ImageWidth': 4032,
'EXIF:ImageHeight': 2268,
'EXIF:ExifImageWidth': 4032,
'EXIF:ExifImageHeight': 2268,
'EXIF:ImageUniqueID': 'J12LLKL00SM',
'EXIF:ThumbnailImage': '(Binary data 6788 bytes, use -b option to extract)',
'Composite:ImageSize': '3672 2066'}
It’s nice. Don’t get me wrong. But all we’ve added to default exiftool behavior is some color.
I’ve played with Rich a bit. I know we can do better.
A metadata table!
Rich lets us create and display tables in the terminal.
from rich.table import Table
We need to build the table, defining columns and adding values row by row.
deffile_table(filename, metadata):
"""Return a Rich Table showing the metadata for a file.""" table = Table("Field", "Value", title=filename)
for key, value in metadata.items():
table.add_row(key, str(value))
return table
WARNING
Hey, don’t miss that str(value)! Rich tables need strings, and take nothing for granted with the values you give it. Numeric values won’t necessarily convert straight to strings without a little help.
We can do more than tables though. with that type:tag split, there’s kind of a heirarchy. We could add a column for the tag type, but why not use a Tree?
from rich.tree import Tree
Hang on a second while we build our little tree with its branches.
deffile_tree(filename, metadata):
tree = Tree(f"[bold]{filename}")
branches = {}
tagged_values = [(k.split(":"), v) for k, v in metadata.items()]
for tags, value in tagged_values:
root_tag = tags[0]
if root_tag notin branches:
branches[root_tag] = tree.add(f"[bold]{root_tag}")
if len(tags) ==2:
branches[root_tag].add(f"[italic]{tags[1]}:[/italic] {value}")
else:
branches[tags[0]].add(str(value))
return tree
Except now we have two ways to display metadata. Three, if you count the dictionary we started with. How are we going to show this tree without discarding our table code?
For now, a callback table that says what to call for each of the options.
from rich.tree import Tree
DISPLAYS = {
"table": lambda f, m: file_table(f, m),
"tree": lambda f, m: file_tree(f, m),
}
We don’t need to use lambdas here. Functions can be passed around same as any other value. But if I wrap them in a lambda I can build my constant table before Python knows the functions exist.
Typer uses callback functions to validate options. They do any processing or checks they need to, then return the supplied value if everything goes well.
defvalidate_display(value):
"""Return value if valid, or panic if it isn't."""if value notin DISPLAYS:
raise typer.BadParameter(f"Format must be one of: {DISPLAYS.keys()}")
return value
Add the --display Option, making sure to point Typer at the callback. main itself knows the value is safe, or the script never would have reached it. So I can grab the displayer and call it without fear of consequence.