DEV Community

StagingBench Team
StagingBench Team

Posted on AI-assisted

Parse image size strings without trusting them

A size string looks simple until an empty field or a formatting change reaches your calculation. In StagingBench's published results, all 119 output dimensions match the widthxheight form. That is a result to verify, rather than an assumption to build into a parser.

The goal here is narrow: parse output dimensions, preserve missing or malformed values, and count widths in bands. The calculation says nothing about image quality or whether the returned dimensions preserve the original resolution.

Give the parser a complete match

Use the strict pattern r"(\d+)x(\d+)" with re.fullmatch. The pattern supplies the numeric groups and the literal separator. fullmatch requires the entire value to match, so accepted dimensions cannot have extra text attached.

A pattern used with an ordinary search could find valid looking dimensions inside an otherwise invalid value. Requiring a complete match makes the acceptance rule explicit. This example also deliberately rejects spaces around the separator instead of silently removing them.

Run the calculation

The following script uses only the standard library. It reads outputs.csv, a flat export with the columns tool, room and output_resolution taken from the room records in results.json. It keeps a parsed tuple or None for every record, calculates width bands, and computes rounded megapixels for the first three rows. Those megapixel values remain available in a variable; only the band counts are printed.

import csv
import re
from collections import Counter
from decimal import Decimal


def parse_size(value):
    match = re.fullmatch(r"(\d+)x(\d+)", value or "")
    return tuple(map(int, match.groups())) if match else None


with open("outputs.csv", newline="", encoding="utf-8") as source:
    rows = list(csv.DictReader(source))

sizes = [parse_size(row["output_resolution"]) for row in rows]
bands = Counter({"<1000": 0, "1000-1999": 0, "2000+": 0})
unparsable = sum(size is None for size in sizes)

for size in sizes:
    if size is None:
        continue
    width, height = size
    band = "<1000" if width < 1000 else "1000-1999" if width < 2000 else "2000+"
    bands[band] += 1

first_three_megapixels = [
    None if size is None else
    round(Decimal(size[0]) * Decimal(size[1]) / Decimal(1000000), 2)
    for size in sizes[:3]
]

for value in ("2336x1760", "", "2336 x 1760", "abc"):
    size = parse_size(value)
    assert size == ((2336, 1760) if value == "2336x1760" else None)

for band, count in bands.items():
    print(f"{band}: {count}")
print(f"unparsable: {unparsable}")
Enter fullscreen mode Exit fullscreen mode

Actual output from running the script:

<1000: 10
1000-1999: 51
2000+: 58
unparsable: 0
Enter fullscreen mode Exit fullscreen mode

Keep absence visible

The sizes list preserves a position for every input record. A value that cannot be parsed becomes None, so it remains available for counting and later inspection. The band calculation explicitly skips it.

Do not replace None with a numeric width. Doing that would turn an unknown measurement into an apparently measured image and could put it into a width band. Keeping None also preserves a useful distinction between an output with dimensions and an output whose dimensions are not usable.

Here, the unparsable count is zero. The explicit handling still belongs in the code because the parser should express what happens when a value fails its contract. A clean set of results should not make that contract disappear.

Why splitting is not the validation rule

Calling split('x') can separate the width from the height, but separation alone does not establish that the whole value has the required shape. You still need checks for missing components, extra separators, and text that does not represent dimensions.

The regular expression puts that shape in a single rule, and fullmatch applies it to the whole field. Integer conversion happens only after that check succeeds. This keeps validation and conversion in a clear order.

Exercise the failure path

The small assertion loop checks "2336x1760", "", "2336 x 1760", and "abc". The compact size becomes a pair of integers. The empty field, spaced variant, and alphabetic text remain None. These assertions ran with the calculation.

Rejecting the spaced variant is intentional. If a later input needs a different format, decide on that format explicitly rather than letting an incidental conversion decide what counts as valid.

Read the counts at their actual scope

The band key depends only on width. Height is retained in the parsed tuple and used for the megapixel calculation, but it does not move an image between width bands. The first three rows each produce a rounded value of 4.11 megapixels.

These counts describe recorded outputs. They do not measure whether resolution was kept against the source photo. StagingBench's methodology makes that a comparison with the original width and height. Parse the measurement faithfully first, then apply the separate comparison you actually need.

Top comments (0)