formatscout
Multi-tier format-identification for disk images and directory trees. Pure Python 3.11+ stdlib. Zero third-party runtime dependencies.
Given a path, detect() returns a ScanResult: title, platform, era, confidence (0.0-1.0), a reason, optional requires_install/requires_extraction flags, and warnings, plus a status, method and authoritative flag that say how to read it (see Result contract). It never raises. A garbage or unreadable path returns confidence=0.0 with an explanatory reason instead of an exception.
Originally built for Peach 1UP, an emulator orchestration platform for retro media preservation. Extracted into a standalone package to help others do the same.
Install
pip install formatscout
Or from source, for contributors:
git clone https://github.com/rymorrisj/formatscout.git
cd formatscout
uv pip install -e .
uv pip install pytest # only needed to run the test suite
Or with plain pip:
pip install -e .
pip install pytest
Requires Python 3.11+ (magic_detect.py reads magic_signatures.toml via stdlib tomllib, added in 3.11).
Detection pipeline
For a file, Tier 1 runs first. Only a sha1 hit on a non-CHD file whose index entry has a non-None era returns immediately. An md5 or crc32 hit, and a CHD header rawsha1 claim, do not: they are held back, the suffix branch below runs (for a .chd, detect_chd), and the two are reconciled with one rule (the hit agrees with the structural evidence: it is recorded as corroboration; it disagrees: the structural result wins and adds CONFLICTING_EVIDENCE; there is no usable structural result: the hit is returned as a weak guess, HASH_WEAK for md5/crc32 and CLAIM_UNVERIFIED for a CHD claim). A CHD claim is corroboration only: it never raises the confidence or status the tags alone produced, never sets an era among a CD or DVD tag's candidates, and always adds CLAIM_UNVERIFIED. Otherwise one branch is chosen by file suffix. That branch's result is not revisited by the other signal tiers, even if it returns low confidence or era=None, with two exceptions: the held-back hash hit above, and a .chd left container_only with candidates (after any claim is reconciled), which gets one filename-title match against the index (see CHD resolution). A filename-only title match is 0.40 and a lone crc32 hit is 0.35; both are non-authoritative guesses. Directories skip Tier 1 and go straight to directory heuristics. There is no confidence threshold in the pipeline. The table below lists signal types, not a cascade.
| Tier | Resolution Strategy | Description | Confidence Range |
|---|---|---|---|
| 1 | Hash Lookup | Full-file SHA-1 (MD5/CRC32 fallback) matched against the preservation index cached at ~/.formatscout/hash_index.json. CHD containers match on the embedded rawsha1 header field instead of raw file bytes (a claim, never proof). |
1.0 (sha1), 0.85 / 0.75 as corroboration (md5 / crc32), 0.45 / 0.35 when alone (0.45 for a CHD claim alone) |
| 2 | Magic Bytes | Header signature matching at fixed byte offsets. Covers PS1, PS2, N64, NES, Dreamcast. | 0.9 |
| 3 | Structural Parsing | ISO 9660 PVD sector inspection, SYSTEM.CNF BOOT/BOOT2 keys, XDVDFS root directory (DEFAULT.XBE/DEFAULT.XEX), CHD v5 metadata tags, PE executable subsystem/OS parsing. |
0.3 – 0.9 |
| 4 | Directory Heuristics | AUTORUN.INF targets, root-level system markers (PS3_DISC.SFB, I386, SYSTEM.CNF, WIN98/95), depth-2 executable scans. | 0.4 – 0.9 |
| 5 | Extension & Size | File extension alone, or extension plus size for ambiguous cases (e.g. 4 GiB optical boundary). | 0.2 – 0.7 |
Diagram reflects the actual code path in detector.py, iso_detect.py, and directory_detect.py. If it disagrees with the table above, trust the diagram.
flowchart TD
Start(["detect(path, dir_cache)"]) --> Exists{"path.exists()?"}
Exists -- "no" --> RNone["ScanResult(confidence=0.0,<br/>reason='path does not exist')"]
Exists -- "yes" --> Hash["Tier 1: hash_lookup.lookup()<br/>sha1 (or CHD embedded rawsha1) -> md5 -> crc32<br/>against ~/.formatscout/hash_index.json"]
Hash -- "sha1 hit on a non-CHD file with an era (1.0)" --> Stamp
Hash -- "no match / index missing / md5, crc32 or CHD header claim (held back, reconciled with the suffix result)" --> Kind{"file or directory?"}
Kind -- neither --> RBad["ScanResult(confidence=0.0,<br/>reason='not a file or directory')"]
Kind -- file --> FileDispatch["_detect_file(): dispatch on suffix"]
Kind -- directory --> DirDispatch["detect_directory()"]
FileDispatch --> ExtOnly[".nds / .xiso / .xex / .z64 family<br/>.sfc family / .nes / .pkg<br/>Tier 5: extension only, confidence 0.0-0.7"]
FileDispatch --> GdCdi[".gdi / .cdi<br/>Tier 2 magic bytes: match -> 0.9<br/>no match -> Tier 5 era=dreamcast, 0.5"]
FileDispatch --> IsoBranch[".iso -> detect_iso()"]
FileDispatch --> BinBranch[".bin -> Tier 2 magic (0.9) -> Tier 3 PVD (0.7-0.9)<br/>-> bin_validator.resolve_bin_cue() (0.2-0.85)"]
FileDispatch --> CueBranch[".cue -> detect_cue(): find sibling .bin<br/>(none found -> 0.0 + warning); found -> same<br/>magic -> PVD -> resolve_bin_cue() chain as .bin"]
FileDispatch --> ChdBranch[".chd -> chd_validator.detect_chd_platform(): CHD v5 metadata chain<br/>CHGD/CHGT -> dreamcast 0.85 (guess); CHT2/CHTR/CHCD -> no era, candidates ps1/ps2;<br/>DVD tag -> no era, candidates ps2/xbox/xbox360; other versions or no tag -> no era.<br/>Never an era from size. A header claim is reconciled first (never raises confidence),<br/>then a filename-title match (0.40, guess) across the candidate eras"]
FileDispatch --> ImgBranch[".img -> Tier 5 size fallback:<br/>era=dos 0.35 if <800MB, else 0.0"]
FileDispatch --> ExeBranch[".exe -> exe_detect.detect_exe(): Tier 3 PE header<br/>MajorOSVersion/Subsystem -> dos 0.65 / win98 0.75 /<br/>winxp 0.75; else 0.0"]
FileDispatch --> NoSig["no suffix match -> confidence=0.0"]
IsoBranch --> IsoMagic["Tier 2 magic (applies_to='iso';<br/>no signature targets .iso today -> always falls through)"]
IsoMagic -- match --> IsoR1["confidence=0.9"]
IsoMagic -- "no match" --> IsoPvd["Tier 3: detect_from_pvd()<br/>ISO 9660 PVD @ sector 16"]
IsoPvd -- "SYSTEM.CNF in root: BOOT2 / BOOT key" --> IsoR1b["era=ps2 / ps1, system_cnf, authoritative"]
IsoPvd -- "PS3_DISC.SFB in root dir" --> IsoR2["era=ps3, 0.9"]
IsoPvd -- ".XBE in root dir" --> IsoR3["era=xbox, 0.8"]
IsoPvd -- "volume label / publisher keyword (Windows, then DOS after the PlayStation checks)" --> IsoR4["era=winxp/win98/win95/dos, 0.7-0.75"]
IsoPvd -- "no era from the PVD (including a PlayStation-shaped but ambiguous PVD)" --> XboxImg["xbox_image.probe_xbox_image()<br/>(XDVDFS descriptor, bounded root walk)"]
XboxImg -- "XDVDFS @ 0x10000, DEFAULT.XBE / DEFAULT.XEX in root" --> IsoR5["era=xbox / xbox360, 0.9,<br/>not authoritative"]
XboxImg -- "XDVDFS with neither executable, or an XGD layout at another offset" --> IsoR6["era=None, container_only,<br/>candidates xbox / xbox360<br/>(XGD offsets: UNSUPPORTED_LAYOUT,<br/>requires_extraction when positively identified)"]
XboxImg -- "no XDVDFS magic, PVD was serial-shaped label, Sony publisher or keyless SYSTEM.CNF" --> IsoAmb["era=None, ambiguous,<br/>candidates ps1 / ps2"]
XboxImg -- "no XDVDFS magic, any other PVD" --> IsoFb["Tier 5: _iso_size_fallback()<br/>size gives candidates only, never an era; an iso9660<br/>confirmation keeps confidence at 0.2 instead of 'no signal found'"]
DirDispatch --> Autorun["Tier 4a: _detect_from_autorun()<br/>AUTORUN.INF OPEN=/RUN= -> pointed .exe's PE header"]
Autorun -- "era resolved" --> AutoR["era=dos/win98/winxp, 0.65-0.75"]
Autorun -- "no signal" --> DirHeur["Tier 4b: _detect_from_directory()"]
DirHeur -- "root marker files (PS3_DISC.SFB, XPSP/I386, WIN98/95,<br/>SYSTEM.CNF, INSTALL.*)" --> DirR3["era resolved by marker, 0.4-0.9<br/>(PS3_DISC.SFB checked first -> ps3 0.9;<br/>SYSTEM.CNF via magic_detect.resolve_ps_generation_from_file: a BOOT2 or BOOT key, no key means no era)"]
DirHeur -- "depth-2 scan (DOS tools, .WAD,<br/>split archives, .BAT, DOS-only exts)" --> DirR4["era=dos, 0.5-0.6"]
DirHeur -- "nothing matched" --> DirR5["confidence=0.0"]
ExtOnly & GdCdi & IsoR1 & IsoR1b & IsoR2 & IsoR3 & IsoR4 & IsoAmb & IsoR5 & IsoR6 & IsoFb & BinBranch & CueBranch & ChdBranch & ImgBranch & ExeBranch & NoSig & AutoR & DirR3 & DirR4 & DirR5 --> Stamp
Stamp["_compute_requires_install(path, result.era)<br/>sets ScanResult.requires_install"] --> Final(["ScanResult returned to caller<br/>(detect() wraps all of this in try/except,<br/>any unexpected error -> confidence=0.0)"])
PE parsing (.exe files and AUTORUN.INF targets) is handled by exe_detect.detect_exe() and directory_detect._detect_from_pe(), which both delegate the header classification (MZ/PE checks, Subsystem gate, MajorOperatingSystemVersion split) to a shared exe_detect._classify_pe_header() helper; only the reason text they build from it differs. test_directory_detect.py pins that the two stay in agreement.
_compute_requires_install() in detector.py runs after era detection and only sets requires_install when era == "dos". A DOS-era .iso or .cue is always flagged. A DOS-era .img is flagged only when it is under 2 MiB. A DOS-era .bin is never flagged, even though its .cue would be. A directory is flagged when it has at least one root-level .exe, .com or .bat, and every one of them is on the blocklist in utils/blocklist.py.
Usage
from pathlib import Path
from formatscout import detect, verify, classify, hash_file
scan = detect(Path("game.iso"))
if scan.status == "identified": # era determined from proof (scan.authoritative is True)
... # scan.era, scan.title, scan.platform, scan.method
elif scan.status == "guess": # era set, but from a heuristic: confirm before trusting it
... # scan.era, scan.confidence, scan.reason, scan.warnings
elif scan.status == "ambiguous": # no era, but scan.candidates lists the likely ones
...
else: # container_only | unsupported | no_signal | error
... # scan.reason, scan.warnings, scan.issues
# scan.requires_install, scan.requires_extraction apply whatever the status
result = verify(Path("game.iso"), expected_sha1="...")
result.status # "matched" | "mismatched" | "not_in_index" | "unchecked"
result = classify(Path("game.iso"), title="Halo", era="xbox")
result.status # "verified" | "caution" | "mismatch" | "not_in_index" | "unchecked"
hashes = hash_file(Path("game.iso"))
hashes.sha1, hashes.md5, hashes.crc32
detect(), classify() and verify() also take a keyword-only index_path= to use a specific hash index, and ensure_index() fetches or checks the index up front. See Hash index.
Result contract
Use status and authoritative, not "is era None", to interpret a ScanResult. era, confidence, reason and warnings are unchanged: era still carries guesses (a .img under 800 MiB as dos at 0.35, extension-only matches at 0.5 to 0.7, a CHD GD-ROM tag as dreamcast, an exact CHD filename-title match at 0.40, a lone crc32 hit at 0.35 or md5 hit at 0.45, a CHD header hash claim at 0.45 when no tag was found; with a tag the claim adds only evidence and CLAIM_UNVERIFIED), but nothing derives an era from a CHD's logical size, and a PlayStation disc whose SYSTEM.CNF cannot be read is ambiguous between ps1 and ps2, never silently ps1. The new fields are keyword-only with defaults, so positional construction of ScanResult still works.
status |
era |
Meaning |
|---|---|---|
identified |
set | Determined from proof; authoritative is True. |
guess |
set | Transitional. Set from a heuristic (extension, directory marker, PE OS version, volume label, XDVDFS root file name, CHD GD-ROM tag, CHD title match, CHD header hash claim, md5 or crc32 hit). Exists only because era still carries guesses, and will be removed once it stops doing so. |
ambiguous |
None | The signal narrows to a few eras, listed in candidates. |
container_only |
None | Container or filesystem confirmed (iso9660, xdvdfs, chd, chd_cd, chd_dvd, bin_cue), but no platform. For a CD or DVD CHD the possible eras are in candidates. |
unsupported |
None | Recognised but not mapped to an era (.nds, an index entry with no era, a path that is neither file nor directory). |
no_signal |
None | Nothing usable found. |
error |
None | The input could not be examined (missing path, read or parse error, the detect() catch-all). |
authoritative is True only for a sha1 index hit on a non-CHD file's own bytes and a platform-unique magic signature (Dreamcast IP.BIN, N64, iNES). A CHD header rawsha1 hit is a claim, not proof: the header is forgeable and is not checked against the hunks, so it is guess. An md5 hit is corroboration only until the index stores file sizes, so it is guess too (crc32 is likewise guess). A SYSTEM.CNF read from an ISO 9660 root with a BOOT2 key (ps2) or a BOOT key (ps1) is authoritative (strict key match: the key must be exactly BOOT2 or BOOT, and a missing, empty or garbage file names no era). Everything else is not authoritative, including XDVDFS (the era comes from a root file name, DEFAULT.XBE or DEFAULT.XEX, not from the file's contents), PS3_DISC.SFB by name, the CHD GD-ROM tags (also used by NAOMI GD-ROMs), a CHD title match, and SYSTEM.CNF read from a raw .bin or a directory (their results are guess for now). It is always False when era is None.
Other fields, all defaulted:
method: the rule that produced the result. One ofhash_sha1,hash_md5,hash_crc32,chd_header_claim(index hit on the CHD header's embeddedrawsha1: a claim, not checked against the hunks),magic,structural,system_cnf,directory_marker,pe_header,extension,size_heuristic,title_match(an exact normalized filename-title match against the index, within a CHD's candidate eras),none(no rule produced a signal).container:iso9660,xdvdfs,bin_cue,chd(no recognised media tag, or an unsupported header version),chd_cd(CHT2, CHTR or CHCD tag),chd_dvd(DVD tag) orchd_gd(CHGD or CHGT tag) when confirmed, else None.candidates:Candidate(era, tier, evidence)tuples forambiguousresults and forcontainer_onlyresults where the container narrows the eras (a CD or DVD CHD, an XDVDFS volume with no or both executables).evidence: short stable codes for the specific signals, such aspvd_volume_label_keyword.issues:Issue(code, message)tuples, for exampleINDEX_UNAVAILABLE(the hash tier did not run),POINTER_REJECTED,UNEXPECTED_ERROR, and theIssueCodemembersCLAIM_UNVERIFIED,HASH_WEAK(era from an md5 or crc32 hit alone),CONFLICTING_EVIDENCE(a hash hit named another era than the structure; the structure wins),WRONG_ERA,AMBIGUOUS_CONTAINER(several candidate eras matched a CHD's title),UNSUPPORTED_LAYOUT(a recognised container layout that is not parsed, such as a full XGD image),CHD_VERSION_UNSUPPORTED(only CHD header version 5 is read),CHD_HEADER_INVALID(a v5 header whose length field is not 124:container_only, no era) andCHD_HEADER_TRUNCATED(the header ends before a field that is needed).warningsis still filled in as before.platform_hint: a platform the signal points at whenplatformis not set (for exampleNintendo DSfor.nds).
Status, Method, Tier and IssueCode are StrEnums, so scan.status == "guess" works. Constructing a ScanResult with contradictory values (an era-less result marked authoritative, an era with a status other than identified/guess) raises ValueError.
CHD resolution. A CHD's raw bytes cannot be hash-matched, and its tags only say CD, DVD or GD-ROM: CHT2/CHTR/CHCD is a CD (PS1 or PS2), the DVD tag is a DVD (PS2, Xbox or Xbox 360), CHGD/CHGT is a GD-ROM (Dreamcast, but NAOMI shares it). A header rawsha1 claim found in the index is reconciled first and only corroborates: it keeps the tag-only confidence and status, sets no era among CD or DVD candidates, and adds CLAIM_UNVERIFIED (a claim the tags rule out adds CONFLICTING_EVIDENCE instead), so it never switches the title step off. When the result is still container_only with candidates, detect() derives a title from the filename (bracketed tags and a trailing disc suffix removed) and matches it exactly, after normalization, against the hash index titles of the candidate eras only. Exactly one matching era sets that era with method title_match (a guess at 0.40, never authoritative); two or more matching eras stay container_only with AMBIGUOUS_CONTAINER; no match, or an unavailable index, leaves the result unchanged. A file called Ico (USA).chd is therefore resolved from the index, never from its size, and a PS2 game is no longer labelled ps1.
Tier buckets a confidence value; tier_for_confidence() is the one mapping. The confidence float itself is unchanged.
Tier |
confidence |
|---|---|
certain |
1.0 |
strong |
0.85 to below 1.0 |
moderate |
0.5 to below 0.85 |
weak |
above 0.0 to below 0.5 |
none |
0.0 (or below, or NaN) |
ClassifyResult keeps its statuses and existing fields, and adds keyword-only matched_era (era of the matched index entry, or for mismatch the era of the matched title: the supplied era is searched first, and WRONG_ERA is reported, with matched_era set to the other era, only when the supplied era has no title match at or above the threshold and another era does), hash_kind (sha1, chd_rawsha1, md5, crc32, or None) and issues (HASH_FAILED, INDEX_UNAVAILABLE, INDEX_MISSING, CHD_RAWSHA1_MISSING, CLAIM_UNVERIFIED, WRONG_ERA). matched_title is still set only for mismatch. VerifyResult gains the status unchecked and a keyword-only issues (INDEX_UNAVAILABLE). See Hash index for what unchecked means.
Public API
Twenty names are exported from __init__.py. Everything else is internal.
| Name | Signature | Notes |
|---|---|---|
detect |
(path, dir_cache=None, *, index_path=None) -> ScanResult |
Main entry point |
verify |
(path, expected_sha1, *, index_path=None, strict=False) -> VerifyResult |
Hash-only re-check against the index |
classify |
(path, title, era, *, threshold=0.80, index_path=None, strict=False) -> ClassifyResult |
Five-state verification, no prior hash needed |
ensure_index |
(path=None, *, force=False, timeout=None, max_bytes=None) -> Path |
Fetch or validate the hash index up front, see Hash index |
IndexUnavailable, IndexIntegrityError |
OSError subclasses |
Index failures; IndexIntegrityError is a subclass of IndexUnavailable |
hash_file |
(path) -> HashFileResult |
sha1/md5/crc32 in one read |
extract_embedded_sha1 |
(path) -> str | None |
CHD v5 embedded rawsha1, no hunk decompression |
ScanResult, VerifyResult, ClassifyResult, HashFileResult |
N/A | Result dataclasses; see result.py docstrings |
Era |
Literal["ps1", "ps2", ...] |
Type hint only, ScanResult.era's value space; runtime values are still plain str | None |
Status, Method, Tier |
StrEnum |
ScanResult.status/method and Candidate.tier values, see Result contract |
Candidate, Issue |
NamedTuple |
(era, tier, evidence) and (code, message) |
HashKind |
Literal["sha1", "chd_rawsha1", "md5", "crc32"] |
ClassifyResult.hash_kind's value space |
tier_for_confidence |
(confidence) -> Tier |
The confidence to Tier mapping |
Supported platforms / eras
Detection logic (tiers 2-5) covers PS1, PS2, PS3, Xbox, Xbox 360, Dreamcast, N64, NES, SNES, DOS, Windows 95, Windows 98, and Windows XP.
The hash index (hash_index.json, cached at ~/.formatscout/) has confirmed entries for more platforms than earlier notes suggested. At minimum: PlayStation, PlayStation 2, PlayStation 3, Xbox, Dreamcast, SNES, and NES. Example entry:
Click to view example of an hash_index.json entries
"c8a6337da7fd0b4c75f6375a79e4eea9f4da08fd": {
"title": "Mortal Kombat Gold (Europe)",
"platform": "Sega - Dreamcast",
"era": "dreamcast"
}
IBM PC compatible DATs parse and index cleanly but have no _ERA_MARKERS mapping. Redump's PC category covers DOS/Win95/98/XP under one platform-name string, so mapping to a specific era needs a per-title resolution strategy that doesn't exist yet. These entries index with era: null by design, not as an error:
Click to view example of an IBM PC compatible entry
"35e032ca9a5efa0cdc9b98df342351fc4b6e3714": {
"title": "Nintendo 64 Roku Yon Total Pack for OS2.0J (Japan) (Nintendo 64 Integrated Online Manual)",
"platform": "IBM - PC compatible",
"era": null,
"source": "IBM - PC compatible - Datfile (58837) (2026-06-15 06-43-57)",
"md5": "a344a91cb48ec6e647b2c2b66d464c16",
"crc32": "d09bab04"
}
Xbox and Xbox 360. An XDVDFS volume with its descriptor at 0x10000 is read directly: a bounded walk of the root directory (4096 entries, depth 256) looks for DEFAULT.XBE (era xbox) or DEFAULT.XEX (era xbox360); a root with neither or both is container_only with candidates xbox and xbox360. Other XGD layouts (the descriptor at the XGD1/2/3 game-partition offsets) are recognised but not parsed: container_only, the same candidates, issue UNSUPPORTED_LAYOUT. An ISO 9660 image over 4 GiB with no other signal has no era (ordinary PC DVDs are that size). A .xex file suffix still returns xbox360 at 0.7 from the extension alone. The XDVDFS directory entry layout and the XGD offsets are unverified against real media.
Hash index
Tier 1 and classify()/verify() read a hash index (hash_index.json, about 88 MB). It is not bundled in the installed package.
Which file is read. First match wins:
- the keyword-only
index_path=argument ofdetect(),classify()orverify()(or thepathargument ofensure_index()); - the
FORMATSCOUT_INDEX_PATHenvironment variable (empty or blank means unset; used as given, so expand~in your shell); - the default cache,
~/.formatscout/hash_index.json.
The home directory is looked up only when the default is needed, never at import. If it cannot be determined (and neither 1 nor 2 applies) the index counts as unavailable, see below.
Only the default cache is managed. If that file is missing it is downloaded on first use, over https only, size-capped, verified against a hardcoded sha256 and installed atomically together with a hash_index.json.meta sidecar (sha256, size, mtime, source URL) recording that this code downloaded it. A file there that carries the sidecar is re-checked against the pin once per process, and a modified one is moved aside (hash_index.json.corrupt, then .corrupt.1 to .corrupt.5, never overwriting an earlier copy) and re-downloaded. A file there with no sidecar, or any file at another path, is yours: it gets only the size cap (256 MiB) and a JSON validity check at first use, is never downloaded to, pin-checked or moved, and a sidecar next to a non-default path is ignored. A missing file at a non-default path is not an error: classify() and verify() treat it as an empty index, and detect() skips the hash tier quietly.
Implicit download is on by default. The first detect(), classify() or verify() with no index in place downloads one. To avoid that, set FORMATSCOUT_OFFLINE=1 (no download is ever attempted, an existing index is still used), point index_path= or FORMATSCOUT_INDEX_PATH at your own file, or call ensure_index() yourself at a time and with a timeout of your choosing. After a failed download no new attempt is made for 5 minutes (also across processes).
ensure_index() returns the resolved path once an index file is there and passes the checks below. It does not guarantee the file parses, only that it is present, readable and within the size cap (and matches the pin when it is the managed download). It does not parse the index or keep anything in memory, so it is cheap to call; the first detect(), classify() or verify() parses it. The checks are: the file exists (downloaded first for the default cache), is readable, is within the 256 MiB load cap, and, for the managed default file, matches the download pin. JSON validity is not checked, so a user-supplied file that is not valid JSON (or not a JSON object of objects) is returned as usable and the error surfaces at first use as IndexUnavailable (IndexIntegrityError): detect()/classify()/verify() then report INDEX_UNAVAILABLE as described below, and strict=True raises. A managed default file that matches its sidecar (and the pin) but still fails to parse is moved aside and re-downloaded at first use, under the normal backoff rules, so ensure_index() returning does not mean the next detect() will find a parseable index.
from formatscout import ensure_index, IndexUnavailable, IndexIntegrityError
try:
path = ensure_index(timeout=15, max_bytes=200_000_000) # default cache: downloads if missing
except IndexIntegrityError: # sha256 mismatch, or an oversized index file
...
except IndexUnavailable: # offline mode, backoff, failed or capped download, missing or unreadable file, no home directory
...
- For the default cache it downloads when needed, as above. For any other path (explicit or from the environment) it only validates the file and raises
IndexUnavailableif it is missing; it never downloads to it. force=Truere-downloads even when a valid index exists, and skips the 5 minute backoff (neverFORMATSCOUT_OFFLINE). The new file is downloaded and verified before anything is touched, so a failed refresh changes nothing. An unmodified copy of an earlier download is then replaced atomically; any other file at the default cache path, including an index you built there yourself, is moved aside to.corrupt(or the next free.corrupt.N) instead of being overwritten, and if all six names are taken the refresh fails and the file stays. For a non-default path,forcejust drops that path's in-process parse cache and re-validates the file.timeoutis the per-socket-operation timeout in seconds (default 30; a whole download is also limited to 600 s).max_bytesis the download size cap (default 128 MiB) and, for a path other than the default cache, an extra size cap checked on the file size. The 256 MiB load cap always applies, somax_bytescan only lower it.- The process keeps at most one parsed index (a real one is ~88 MB on disk and several times that as Python objects). Using a different index path, or a rebuilt file, replaces the previous one once the new file has parsed (a failed load keeps the working entry), so peak memory is about two parsed indexes while a replacement loads, and alternating between two index paths re-parses on every switch. Use one path per process for the hot path.
IndexUnavailableis anOSError(not aFileNotFoundError);IndexIntegrityErroris a subclass, so oneexcept IndexUnavailablecovers every index failure. The original cause is chained as__cause__.
When the index is unavailable. detect() still never raises: it skips the hash tier, appends a hash index unavailable: ...; heuristics only warning and an INDEX_UNAVAILABLE issue (same message) to the result. classify() and verify() return status="unchecked" with an INDEX_UNAVAILABLE issue instead of raising, keeping computed_sha1 (the file did hash). Check the issue code to tell this from classify()'s other unchecked case, HASH_FAILED (the file itself could not be read, computed_sha1 is None). Pass strict=True to get IndexUnavailable raised instead. verify() still lets an unreadable input file raise OSError.
Using an index you built. python -m formatscout.hashing.build_index --dats <dir> --output <path> writes the index and prints where the runtime reads and how to use the result. Then either set FORMATSCOUT_INDEX_PATH=<path>, pass index_path=<path> to detect()/classify()/verify(), or build straight to the default cache (--output ~/.formatscout/hash_index.json). When the output is the default cache, a stale sidecar left by an earlier download is deleted just before the new index is moved into place, so the file you built is treated as yours and not quarantined.
Adding a new DAT
python -m formatscout.hashing.build_index \
--dats <directory-of-dat-files> [--output <path>] [--rebuild]
Manual process, no ingestion automation. Sourced from Redump, No-Intro, and TOSEC. Only records with a sha1 value get indexed. MD5/CRC32-only entries parse without error but contribute zero rows. The run logs a skipped-record count, so this isn't silent. build_index's default --output is still formatscout/hashing/hash_index.json inside the package directory. The runtime never reads that path by default, so a locally built index is not used by detect(), classify() or verify() until you point them at it. The run ends by printing the path the runtime reads and how to use the result: pass --output with that path, set FORMATSCOUT_INDEX_PATH, or pass index_path=. See Hash index.
DAT files are third-party, untrusted input. dat_parser.parse_dat() rejects any DAT that declares XML entities in its DOCTYPE internal subset, guarding against the entity-expansion vector in ElementTree. Real Logiqx/Redump/No-Intro external DOCTYPEs are unaffected. The index write is atomic, a temp file plus os.replace(), so an interrupted run leaves the previous index intact.
Known limitations
- XDVDFS parsing (the volume descriptor fields, the root directory entry layout, the 2048-byte sector arithmetic and the XGD partition offsets) is written from format knowledge, not checked against real disc images, so treat an Xbox or Xbox 360 era from a disc image as a guess. Whether real Xbox rips carry
DEFAULT.XBEin an ISO 9660 root is also unverified. - Only CHD header version 5 is read. A v3 or v4 CHD, common in older sets, returns no era and no candidates (
CHD_VERSION_UNSUPPORTED); the CHD tag names (CHCD,CHGT, the DVD tag) and theCHT2text payload are taken from the builders used in the tests, not from realchdmanoutput. .bin/.cuepairs missing their.cuesibling return low confidence with a warning.- Every entry point takes a local, seekable
Path. No stream or object-storage handle support. detect()never raises for an input path (anindex_pathof the wrong type or an empty string is a programming error and raisesTypeError/ValueError). An unusable index (a failed or suppressed download: network error, timeout, size cap, sha256 mismatch, a recent failure within the 5 minute retry backoff, orFORMATSCOUT_OFFLINE=1; an oversized, corrupt or unreadablehash_index.json; or no home directory for the default location) does not raise fromdetect(),classify()orverify():detect()logs a warning, adds ahash index unavailable: ...; heuristics onlywarning and anINDEX_UNAVAILABLEissue, and continues without the hash tier, whileclassify()andverify()returnstatus="unchecked"with anINDEX_UNAVAILABLEissue.strict=Truemakes them raiseIndexUnavailable(anOSError, original error chained as__cause__) instead.classify()also returnsuncheckedwithHASH_FAILEDfor anOSErrorwhile hashing the file. A missing index file at a custom path is still treated as an empty index.verify()andhash_file()let read errors on the input file propagate.- Size thresholds use different units by design. The ISO fallback boundary is binary 4 GiB. The PS1/PS2 candidate ordering in
detect_from_pvd()uses decimal 4.7GB, matching how disc capacities are usually quoted. Size only orders or proposes candidate eras; it never decides an era. requires_extractionis only set when an XDVDFS volume is positively identified at an XGD game-partition offset (never from size). Callers run their own conversion tooling, such as extract-xiso. This package only detects the need.hash_index.jsonis not bundled in the installed distribution. It is downloaded once on first hash lookup (this implicit download is the default in this release), verified against a hardcoded sha256, and cached under~/.formatscout/together with ahash_index.json.metasidecar. Only a file with that sidecar is checked against the pin; any other file is yours and only gets the size cap and JSON validity check. That first run requires network access unless you supply an index (index_path=,FORMATSCOUT_INDEX_PATH) or callensure_index()earlier; withFORMATSCOUT_OFFLINE=1no download is attempted. See Hash index.
Backlog
- Split
hash_index.jsoninto a resolvable-era index and a full/PC-compatible-completeness index, published as separate release assets, so consumers can choose which one to fetch. Not built yet, just planned. - Version or update checking for the cached
hash_index.jsonis not implemented yet. It is only fetched when the local cache is missing or a downloaded copy (one with a.metasidecar) fails its check. The check runs once per process, and a failing file is renamed tohash_index.json.corrupt(or.corrupt.1to.corrupt.5if earlier copies exist, never overwriting) before refetching. An existing valid cached copy is never checked for newer releases.
Testing
uv run pytest formatscout/tests/
Known gap: xbox_image.py has no dedicated test file. It is reached only indirectly through iso_detect tests.
Contributing
Open an issue for bugs or detection gaps. For new DAT sources or platform support, include a sample of the DAT header so the _ERA_MARKERS mapping can be verified before merging. See CONTRIBUTING.md for PR expectations.
Disclaimer
We sanitize and parse all DAT files we use, but detection may still be inaccurate. Always verify files yourself.
License
MIT, see LICENSE
Metadata
Release files for formatscout 0.2.0
For a detailed explanation of source distributions (sdists) and built distributions (wheels), please see the package formats documentation.
Source distribution (sdist)
| File | Size | Uploaded | Provenance | Actions |
|---|---|---|---|---|
| formatscout-0.2.0.tar.gz | 117.4 kB | Without provenance | Details for formatscout-0.2.0.tar.gz |
Built distribution (wheel)
| File | Interpreter | ABI | Platform | Actions Reset |
|---|---|---|---|---|
| formatscout-0.2.0-py3-none-any.whl | Python 3 | none | any | Details for formatscout-0.2.0-py3-none-any.whl |
Total release size: 222.5 kB
Release files / formatscout-0.2.0.tar.gz
| Download URL | formatscout-0.2.0.tar.gz |
|---|---|
| Size | 117.4 kB |
| Tags | Source |
|
SHA-256 checksum How to use checksums |
f9a4141768f111bfeadcc61f7872898ac6f32361b61543cc500e6d5b7d28c8cb
|
|
BLAKE2b-256 checksum How to use checksums |
2e4c518733ac21e1760303802cac75a758eb5de42271c18c5a1a3c82199cef47
|
| Upload date | |
|
Uploaded using Trusted Publishing? What is trusted publishing? |
No |
| Uploaded via |
uv/0.12.1 {"installer":{"name":"uv","version":"0.12.1","subcommand":["publish"]},"python":null,"implementation":{"name":null,"version":null},"distro":null,"system":{"name":null,"release":null},"cpu":null,"openssl_version":null,"setuptools_version":null,"rustc_version":null,"ci":null}
|
Release files / formatscout-0.2.0-py3-none-any.whl
| Download URL | formatscout-0.2.0-py3-none-any.whl |
|---|---|
| Size | 105.1 kB |
| Tags | Python 3 |
|
SHA-256 checksum How to use checksums |
1ec23bdc5f3e63cdd2bd892d521b5492f135e15d34c379b9f34c59d1c9e79f6f
|
|
BLAKE2b-256 checksum How to use checksums |
59bd66b15a1a61525494a78da3649c7d497e41370d6cb8adae99cefef2a9ce4c
|
| Upload date | |
|
Uploaded using Trusted Publishing? What is trusted publishing? |
No |
| Uploaded via |
uv/0.12.1 {"installer":{"name":"uv","version":"0.12.1","subcommand":["publish"]},"python":null,"implementation":{"name":null,"version":null},"distro":null,"system":{"name":null,"release":null},"cpu":null,"openssl_version":null,"setuptools_version":null,"rustc_version":null,"ci":null}
|
Security for formatscout 0.2.0
Provenance
Provenance describes where a file came from. On PyPI, provenance is shared via attestations, which provide a verifiable record of the build or publishing details. View details, limitations and caveats.
No provenance found
None of the files in this release were uploaded with provenance metadata.
A note on package security
PyPI is a repository for distributing packages, not a service for auditing them. While third-party security researchers and our staff do their best to detect and remove malicious packages, PyPI cannot guarantee the quality, security or suitability of any given package.
To learn more about protecting yourself from malicious actors, visit our package security documentation.