Disclosure: I am associated with NightVisio, the brand behind nightvisio.co.uk. This article includes links to the official website and the product page. Any product details mentioned here are limited to what that site currently states. I have not added file formats, codecs, frame rates, sensors, detection distances, optical zoom, thermal imaging, or battery runtimes that the site does not publish.
A night-vision recorder is only as useful as the files you can still find next week. Once you have transferred stills and clips off a memory card and onto a laptop, the interesting work is no longer in the field. It is on disk: what arrived, whether a backup copy is bit-for-bit identical, what resolution each file actually has, and how to browse the set without uploading anything to a third-party gallery.
This article walks through a local Python workflow that does those four jobs. It inventories a folder of exported media, copies the files to a backup directory, verifies each copy with SHA-256, inspects width and height with ffprobe when that tool is available, and writes a simple HTML contact sheet you can open from the backup folder. The script is a generic sample. It is not a dump of a hidden device protocol, and it does not assume a particular container or codec.
The product I will use as a real-world example is the NightVisio 4K night vision binoculars. The official site describes easy-to-use infrared night vision binoculars for adults, with a 4.5-inch HD screen, 36MP photos, 4K recording support, 8X digital zoom, 850nm infrared illumination with seven levels, a 4500mAh rechargeable lithium battery charged with the supplied USB cable, and a 32GB TF card included so the kit is ready to record out of the box. The site also says you can review files on the screen or transfer them later. That transfer step is the starting point for this workflow. The zoom is digital, not optical, and the night vision is infrared (light amplification plus IR illumination), not thermal imaging.
Keep the device claims and the workflow claims apart
This distinction matters more than it first appears. The NightVisio site publishes photo resolution as 36MP and video as 4K recording support. It does not publish the container, the codec, the frame rate, a sensor model, a detection distance, or a battery-runtime figure in hours. A local indexing script should not fill those gaps with guesses.
So the workflow below is intentionally format-agnostic:
- It walks a folder you already have on disk, after a normal file transfer from a card or cable.
- It includes a configurable extension list as a starting point only. That list is not a statement of what the binoculars write.
- It records facts it can measure locally: relative path, byte size, modification time, and a SHA-256 digest.
- It asks
ffprobefor width, height, and duration whenffprobeis installed. Ifffprobeis missing, inventory and checksums still run. - It never claims that a probed width is “4K,” that a still is “36MP,” or that a codec name is a NightVisio specification. Those would be inferences, and this article does not make them.
If you point the script at files from some other camera, the same rules apply. The code is measuring files, not endorsing a product page.
Design constraints: local, boring, and conservative
The default way to lose a folder of night recordings is not a dramatic disk failure. It is a messy Downloads directory, a half-finished copy, and no record of what was in the set. An equally common way to leak them is to drop the same folder into a cloud album “just to preview it.” Wildlife clips, garden checks, farmyard recordings, and casual property footage are ordinary uses named on the NightVisio site, and they can still be sensitive. The workflow stays on the machine that already holds the files.
A few implementation constraints follow from that:
- No network calls. The script hashes, copies, and writes HTML. It does not fetch a library, call an API, or embed remote assets.
- No symlink following. A leftover link in an export folder should not pull in a file from elsewhere on the disk.
- No hidden-directory descent. Files under
.directories are skipped, which avoids accidental inclusion of cache folders. - Backup paths cannot escape the backup root, and the source and backup folders must be distinct and not nested. A typo should not copy a tree onto itself.
- Subprocess calls use an argument list, not
shell=True, and they have a timeout. - The HTML sheet uses relative file names and only the leaf names of the source and backup folders, so the page does not need to embed an absolute home-directory path.
- The sheet does not parse or display EXIF or GPS. If you need metadata redaction, do that as a separate, explicit step. This tool does not open that door by accident.
Optional tools are optional. ffprobe improves the index. ffmpeg can extract a poster frame for a video so the contact sheet has something to show. Neither is required for a verified backup.
What the script actually does
Save the complete listing at the end of this article as nv_media_index.py. The command line is small:
python3 nv_media_index.py \ --source /path/to/export \ --backup /path/to/backup By default the HTML page is written to BACKUP/index.html. You can override that with --html, limit the walk with --extensions .jpg,.png,.mp4, skip copying with --skip-backup, or skip poster frames with --no-posters.
The walk itself is deliberately plain. Path.rglob visits the export tree. Each candidate must be a regular file, not a symlink, must not sit under a hidden path segment, and must match the extension set. That is enough to inventory a card dump that includes subfolders, while ignoring a stray text note or a link you did not mean to archive.
Checksums use SHA-256 over 1 MiB chunks. A digest of the source file is computed first. After shutil.copy2, the destination is hashed independently and compared. A mismatch is recorded as an issue and the process returns a non-zero exit status. The copy is not “probably fine” because the progress bar finished.
ffprobe is invoked only when shutil.which("ffprobe") finds a binary. The arguments request JSON for stream width, height, and codec type, plus format duration. The script then prefers a stream marked as video if several streams exist, and it stores width, height, and duration when they parse cleanly. It does not store or display a codec name in the HTML sheet. That is intentional. A codec string from ffprobe is a fact about one file on your disk, but publishing it next to a product name is how an article accidentally invents a device specification. If you need the codec for your own debugging, run ffprobe directly on that file.
For videos, when ffmpeg is available, the script writes a small poster JPEG beside the backup copy (*_poster.jpg) so the contact sheet can show a still. If ffmpeg is not installed, the poster step is skipped and the backup itself is still verified. A missing optional tool is not treated as a failed copy.
The HTML page is a local contact sheet plus a table. Still images are shown with CSS-constrained thumbnails pointing at the backup files. Videos use the poster frame when one was created, otherwise a placeholder that still links to the file. The table lists relative path, size, UTC modification time, resolution, duration, the full SHA-256 digest, and a short note about whether ffprobe ran. Filenames are passed through html.escape. Opening the page does not require a web server; it is just a file next to the backup copies.
A careful first run
Use a folder you can afford to copy, not your only archive. Pick a backup path on a disk with enough free space, and do not nest it inside the source tree. After the run, the standard output reports the number of files indexed, the HTML path, the backup path, and the number of issues.
Then do the unglamorous checks:
- Open
index.htmlfrom the backup folder and confirm that the names you expect are present, and that notes or sidecars you did not include in--extensionsare absent. - Compare the table’s SHA-256 values with an independent hash if a file matters enough to doubt the copy.
- Treat resolution and duration as
ffprobeoutput for that file, not as a specification for the recorder. - Remember that a 36MP still, when a file really is that large, will be a heavy
<img>source. The CSS limits display size, but the browser still has to read the file. The script does not transcode stills; it only makes an optional poster for video extensions.
If you are transferring from the 32GB TF card that the NightVisio kit includes, finish the copy to local disk first, then point this workflow at the local folder. The script is not a card-imaging tool, and it does not try to talk to the binoculars.
What I tested — and what I did not
I tested the script in this environment with synthetic files labelled example_, not with footage captured from NightVisio binoculars. The results below describe those example files only. They are not measurements of the product, and they are not benchmark figures.
The example source tree contained:
-
example_still.png— a generated 320×180 still -
example_subdir/example_wide.jpg— a generated 1280×720 still in a subfolder -
example_clip.mp4— a generated 640×360 clip of 2 seconds -
example_notes.txt— a text file that should be ignored -
example_link.png— a symlink to the first still, which should be ignored
The files were generated with ffmpeg test sources so I would have known sizes to check. I then ran:
python3 nv_media_index.py \ --source example_source \ --backup example_backup The process exited 0, indexed 3 files, and reported 0 issues. The text file and the symlink were not included. Independent SHA-256 digests of the three source files matched the copies in the backup folder:
-
example_clip.mp4(14,877 bytes) —fed4e0a583ff15cd812811b10539887a5ee564dfa76bfdcaf2c2ff68fad27f1b -
example_still.png(691 bytes) —0e8d19409d0a18452ef47e06da931ca543ca174365584792baf64d594ab9b889 -
example_subdir/example_wide.jpg(34,920 bytes) —1f20d24b8bde0c4a9e60abc5710dae7109c0972f3824aaa01aa96200cd56ac54
When ffprobe was on the PATH, the HTML table showed 320×180 for example_still.png, 1280×720 for example_wide.jpg, and 640×360 with a duration of 2.00 seconds for example_clip.mp4. The JPEG still also carried a tiny duration of 0.04 seconds in the ffprobe output, which the sheet reported rather than “correcting.” That is the right behaviour for an indexer: print the metadata that is there. A poster frame example_clip_poster.jpg was created for the example clip. The HTML page contained the three relative paths, did not mention the text file or the symlink, and did not embed the absolute /tmp test directory.
I also ran the same command with a filtered PATH that hid ffprobe and ffmpeg. The process still exited 0, indexed the same three files, and the independently checked checksums still matched. Resolution was omitted, the probe note recorded that ffprobe was not found, and the video poster was skipped. A backup path nested under the source was rejected with an error. A missing source directory returned exit status 2.
I have not tested this script against a live NightVisio export, against every container ffprobe can read, or as a long-running backup of a full 32GB card. If a file uses an extension that is not in your --extensions list, it will be skipped. If ffprobe cannot read a file, the inventory row should still appear with a probe note and a checksum.
Limits you should leave in place
A checksum confirms that two byte sequences are the same. It does not confirm that the original recording is a faithful scene, or that a file is “4K,” or that a still is 36 megapixels. Those product figures remain what the official site states about the binoculars; they are not outputs of this script.
Digital zoom, infrared level, and battery behaviour are also out of scope. The NightVisio site says performance depends on distance, reflectivity, and infrared level, and that battery life depends on infrared and recording use, with lower IR settings typically lasting longer. It does not publish a runtime in hours. Nothing in a folder index can add those numbers.
Do not turn the contact sheet into an accidental gallery on a public host. It is a local HTML file with relative links to local media. If you later share the backup, you are sharing the recordings themselves. If you need to send someone an inventory without the footage, send the table — or a CSV you derive from it — not the backup folder.
Finally, keep the extension list honest. If your export uses a suffix the default set does not include, add that suffix after you have seen it on disk. Do not assume MP4, JPEG, or any other container just because a product page says “4K recording support” or “36MP photos.”
The complete script
The listing below is the script I ran against the example files. Copy it as nv_media_index.py and run it with Python 3. It needs only the standard library. ffprobe and ffmpeg are optional.
#!/usr/bin/env python3 """Inventory exported media, checksum a local backup, and write an HTML index. This is a generic local workflow. It does not assume a particular camera container, codec, frame rate, or sensor, and it does not upload files. """ from __future__ import annotations import argparse import hashlib import html import json import shutil import subprocess import sys from dataclasses import dataclass, field from datetime import datetime, timezone from pathlib import Path from typing import Iterable # Starting set only. Adjust to match the files you actually exported. # This list is not a claim about any specific device's output formats. DEFAULT_EXTENSIONS = { ".jpg", ".jpeg", ".png", ".webp", ".tif", ".tiff", ".mp4", ".mov", ".m4v", ".avi", ".mkv", } CHUNK_SIZE = 1024 * 1024 FFPROBE_TIMEOUT_SEC = 8 FFMPEG_TIMEOUT_SEC = 20 VIDEO_EXTENSIONS = {".mp4", ".mov", ".m4v", ".avi", ".mkv"} @dataclass class MediaRecord: relative_path: str source_path: Path backup_path: Path | None size_bytes: int modified_utc: str sha256: str width: int | None = None height: int | None = None duration_sec: float | None = None probe_note: str = "ffprobe not run" thumb_rel: str | None = None issues: list[str] = field(default_factory=list) @property def resolution(self) -> str: if self.width and self.height: return f"{self.width}×{self.height}" return "—" def parse_extensions(raw: str | None) -> set[str]: if not raw: return set(DEFAULT_EXTENSIONS) items = {item.strip().lower() for item in raw.split(",") if item.strip()} return {item if item.startswith(".") else f".{item}" for item in items} def iter_media_files(source: Path, extensions: set[str]) -> Iterable[Path]: """Yield regular files under source, skipping hidden names and symlinks.""" for path in sorted(source.rglob("*")): if not path.is_file() or path.is_symlink(): continue if any(part.startswith(".") for part in path.relative_to(source).parts): continue if path.suffix.lower() in extensions: yield path def sha256_file(path: Path) -> str: digest = hashlib.sha256() with path.open("rb") as handle: while chunk := handle.read(CHUNK_SIZE): digest.update(chunk) return digest.hexdigest() def utc_mtime(path: Path) -> str: stamp = datetime.fromtimestamp(path.stat().st_mtime, tz=timezone.utc) return stamp.strftime("%Y-%m-%d %H:%M:%S UTC") def ffprobe_cmd() -> str | None: return shutil.which("ffprobe") def probe_with_ffprobe(path: Path) -> tuple[int | None, int | None, float | None, str]: binary = ffprobe_cmd() if not binary: return None, None, None, "ffprobe not found; resolution skipped" command = [ binary, "-v", "error", "-show_entries", "stream=width,height,codec_type", "-show_entries", "format=duration", "-of", "json", str(path), ] try: completed = subprocess.run( command, check=False, capture_output=True, text=True, timeout=FFPROBE_TIMEOUT_SEC, ) except (OSError, subprocess.TimeoutExpired) as exc: return None, None, None, f"ffprobe failed: {exc}" if completed.returncode != 0: err = (completed.stderr or completed.stdout or "unknown error").strip() return None, None, None, f"ffprobe failed: {err[:200]}" try: payload = json.loads(completed.stdout or "{}") except json.JSONDecodeError: return None, None, None, "ffprobe returned invalid JSON" width = height = None for stream in payload.get("streams") or []: if stream.get("width") and stream.get("height"): # Prefer a video stream when several streams are present. if stream.get("codec_type") == "video" or width is None: width = int(stream["width"]) height = int(stream["height"]) if stream.get("codec_type") == "video": break duration = None raw_duration = (payload.get("format") or {}).get("duration") if raw_duration not in (None, "N/A", ""): try: duration = float(raw_duration) except (TypeError, ValueError): duration = None if width and height: return width, height, duration, "ffprobe" return None, None, duration, "ffprobe ran, no width/height found" def safe_backup_path(source_root: Path, source_file: Path, backup_root: Path) -> Path: relative = source_file.resolve().relative_to(source_root.resolve()) dest = (backup_root.resolve() / relative) if not dest.is_relative_to(backup_root.resolve()): raise ValueError(f"refusing to write outside backup root: {dest}") return dest def copy_and_verify(source_file: Path, dest: Path, expected_digest: str) -> str | None: dest.parent.mkdir(parents=True, exist_ok=True) shutil.copy2(source_file, dest) copied_digest = sha256_file(dest) if copied_digest != expected_digest: return f"checksum mismatch after copy (src={expected_digest} dst={copied_digest})" return None def maybe_poster_frame(source_file: Path, thumb_path: Path) -> str | None: """Create a small JPEG poster for videos when ffmpeg is available.""" binary = shutil.which("ffmpeg") if not binary: return "ffmpeg not found; video poster skipped" thumb_path.parent.mkdir(parents=True, exist_ok=True) command = [ binary, "-hide_banner", "-loglevel", "error", "-y", "-i", str(source_file), "-frames:v", "1", "-vf", "scale=320:-2", str(thumb_path), ] try: completed = subprocess.run( command, check=False, capture_output=True, text=True, timeout=FFMPEG_TIMEOUT_SEC, ) except (OSError, subprocess.TimeoutExpired) as exc: return f"ffmpeg poster failed: {exc}" if completed.returncode != 0 or not thumb_path.is_file(): err = (completed.stderr or "unknown error").strip() return f"ffmpeg poster failed: {err[:200]}" return None def format_size(num: int) -> str: value = float(num) for unit in ("B", "KB", "MB", "GB"): if value < 1024 or unit == "GB": if unit == "B": return f"{int(value)} {unit}" return f"{value:.1f} {unit}" value /= 1024 return f"{num} B" def write_html(records: list[MediaRecord], html_path: Path, source: Path, backup: Path) -> None: rows = [] cards = [] for rec in records: issue_html = "" if rec.issues: issue_html = ( "<div class='issues'>" + "<br>".join(html.escape(item) for item in rec.issues) + "</div>" ) duration = f"{rec.duration_sec:.2f} s" if rec.duration_sec is not None else "—" rel = html.escape(rec.relative_path) href = html.escape(rec.relative_path) if rec.thumb_rel: img = f'<a href="{href}"><img src="{html.escape(rec.thumb_rel)}" alt="{rel}"></a>' elif recSource:https://dev.to/nightvisio/a-local-python-workflow-for-inventorying-exported-night-vision-media-5cap