API Reference & Usage

Complete reference for every function in the jpegtrust package. Each entry includes the full signature, parameter descriptions, return type, and working examples.

Embedding

Embed provenance metadata into JPEG images. The metadata is stored as a JUMBF box inside APP11 marker segments. Existing metadata is automatically stripped before re-embedding.

embed_image(image, metadata, output, digital_source_type=None)

High-level function that reads an image file, loads metadata from a JSON file or dict, embeds it, and writes the result. This is the recommended way to embed metadata.

Parameter Type Description
image str Path to the input JPEG file
metadata str | dict Path to a JSON file, or a metadata dict
output str Path to write the output JPEG
digital_source_type str | None IPTC digital source type slug (e.g., "trainedAlgorithmicMedia", "digitalCapture"). Automatically injected as an iptc.digitalSourceType assertion.
Returns str The output file path
example
from jpegtrust import embed_image

# From a JSON file
embed_image("photo.jpg", "metadata.json", "signed.jpg")

# From a Python dict
metadata = {
    "@context": ["https://jpeg.org/jpegtrust/"],
    "declaration": {
        "claim": {"alg": "sha256"},
        "assertions": {"c2pa.actions": {"actions": []}}
    }
}
embed_image("photo.jpg", metadata, "signed.jpg")
embed_metadata(image, metadata, output_path=None, digital_source_type=None)

Low-level function that works with raw bytes. Use this when you already have image data in memory (e.g., from a web upload or stream).

Parameter Type Description
image bytes Raw JPEG image bytes
metadata dict Metadata dict to embed
output_path str | None If set, writes the result to this file
Returns bytes The embedded JPEG as bytes
example
from jpegtrust import embed_metadata

with open("photo.jpg", "rb") as f:
    image_bytes = f.read()

metadata = {"@context": ["https://jpeg.org/jpegtrust/"], ...}

# Get bytes back
result = embed_metadata(image_bytes, metadata)

# Or write directly to disk
embed_metadata(image_bytes, metadata, output_path="signed.jpg")

Extraction

Read provenance metadata from JPEG images. Supports both the JUMBF JSON format (from embed_image) and native C2PA binary manifests (via c2pa-python).

extract_from_file(image)

High-level extraction that tries two methods: first the JUMBF JSON box, then the c2pa-python SDK for real C2PA manifests. Returns a parsed indicator dict ready for verification.

Parameter Type Description
image str Path to a JPEG file
Returns dict | None Parsed indicator dict, or None if no metadata found
example
from jpegtrust import extract_from_file

indicator = extract_from_file("signed.jpg")

if indicator is None:
    print("No metadata found")
else:
    print(indicator["declaration"]["claim"]["alg"])  # "sha256"
    print(indicator["manifests"][0]["assertions"])    # {...}
extract_metadata(image)

Low-level extraction that works with raw bytes. Only reads the JUMBF JSON format (not native C2PA). Returns the raw JSON string.

Parameter Type Description
image bytes Raw JPEG image bytes
Returns str | None Raw JSON string, or None
example
import json
from jpegtrust import extract_metadata

with open("signed.jpg", "rb") as f:
    raw = extract_metadata(f.read())

if raw:
    data = json.loads(raw)
    print(json.dumps(data, indent=2))

Verification

Validate images against trust profiles. The verifier evaluates each check expression against the image metadata and produces a scored report.

Pass ≥ 0.95
Warning ≥ 0.70
Fail < 0.70
verify_image(image_path, profile_path)

High-level function that extracts metadata from an image and verifies it against a profile YAML file in one call. This is the easiest way to verify an image.

Parameter Type Description
image_path str Path to a JPEG with embedded metadata
profile_path str Path to a trust profile YAML file
Returns VerificationReport Full verification results
Raises ValueError If no metadata is found in the image
example
from jpegtrust import verify_image

report = verify_image("signed.jpg", "policy.yml")

print(f"Status:  {report.status}")      # "pass" | "warning" | "fail"
print(f"Score:   {report.score}")       # 0.0 - 1.0
print(f"Verdict: {report.verdict}")     # "trusted" | "mostly_trusted" | "profile_mismatch"
print(f"Passed:  {report.passed_checks}/{report.total_checks}")
print(f"Failed:  {report.failed}")

# Convert to dict for JSON serialization
result_dict = report.to_dict()
verify(indicator, profile_yaml)

Low-level verification that takes an already-extracted indicator dict and a profile YAML string. Use this when you need control over extraction and profile loading separately.

Parameter Type Description
indicator dict Parsed indicator dict (from extract_from_file)
profile_yaml str Multi-document YAML string defining the trust profile
Returns VerificationReport Full verification results
example
from jpegtrust import verify, extract_from_file, load_profile

# Step 1: extract the indicator
indicator = extract_from_file("signed.jpg")

# Step 2: load the profile YAML
profile_yaml = load_profile("policy.yml")

# Step 3: verify
report = verify(indicator, profile_yaml)
print(report.status, report.score)

Profiles

Trust profiles define what checks an image must pass. They are stored as multi-document YAML files. You can create them from templates, build custom ones, or load existing files.

create_profile(template="custom", name="My Trust Profile", issuer="...", check_ids=None, language="en")

Create a trust profile from a template or a custom list of check IDs. If check_ids is provided, it overrides the template.

Parameter Type Description
template str "newsroom", "insurance", "creator", "ai-labelling", or "custom"
name str Human-readable profile name
issuer str Organization or person issuing the profile
check_ids list[str] | None Explicit list of check IDs (overrides template)
language str Language code for report text (default: "en")
Returns Profile A Profile object with metadata and checks
example
from jpegtrust import create_profile, save_profile

# From a template
profile = create_profile(template="newsroom", name="AP Wire Photo Policy")
save_profile(profile, "newsroom.yml")

# Custom: pick specific checks
profile = create_profile(
    check_ids=["signature_chain", "pixel_hash", "copyright"],
    name="Licensing Policy",
    issuer="My Platform",
)
save_profile(profile, "licensing.yml")
save_profile(profile, path)

Serialize a Profile object to YAML and write it to a file.

Parameter Type Description
profile Profile The profile to save
path str Output file path (.yml)
Returns str The file path
load_profile(path)

Read a profile YAML file and return its contents as a string. Use the result with verify().

Parameter Type Description
path str Path to a .yml profile file
Returns str The YAML content as a string
profile_to_yaml(profile)

Serialize a Profile object to a YAML string without writing to disk.

Parameter Type Description
profile Profile The profile to serialize
Returns str Multi-document YAML string
list_templates()

Get all available profile templates and their check IDs.

Returns dict[str, list[str]] Template names mapped to check ID lists
example
from jpegtrust import list_templates

for name, check_ids in list_templates().items():
    print(f"{name}: {len(check_ids)} checks")

# Output:
# newsroom: 11 checks
# insurance: 6 checks
# creator: 6 checks
# ai-labelling: 7 checks
# custom: 0 checks
list_checks()

Get all available check definitions with IDs, labels, levels, and expressions.

Returns list[CheckDefinition] All 11 available checks
example
from jpegtrust import list_checks

for check in list_checks():
    print(f"{check.id:24s} [{check.level:8s}] {check.label}")

# Output:
# signature_chain          [required] Signature chain
# capture_timestamp        [required] Capture timestamp
# author_identity          [required] Author identity
# edit_history             [required] Edit history
# ai_declaration           [required] AI declaration
# gps_location             [optional] GPS / location
# copyright                [optional] Copyright / licence
# data_mining              [optional] Data mining declaration
# pixel_hash               [required] Pixel hash binding
# digital_source_type      [required] Digital source type
# ai_labelling             [optional] AI labelling

Available checks reference

ID Level Description
signature_chain required Valid cryptographic signature anchored to a trust root
capture_timestamp required UTC time set by camera at the moment of exposure
author_identity required Name and credential of the person who made the image
edit_history required Complete chain of signed actions from capture to publication
ai_declaration required Explicit statement about whether AI was used
gps_location optional Geolocation embedded or explicitly withheld
copyright optional Rights declaration and usage terms
data_mining optional Data mining usage permissions
pixel_hash required SHA-256 of pixel data matches signed hash
digital_source_type required IPTC digital source type declaration is present
ai_labelling optional Whether the declared source type indicates AI usage (EU AI Act Art. 50)

Batch operations

Process entire directories of images at once. All batch functions accept a glob pattern to filter files.

batch_embed(input_dir, metadata, output_dir, pattern="*.jpg")

Embed the same metadata into all matching images in a directory.

Parameter Type Description
input_dir str Directory containing source images
metadata str | dict Path to JSON file, or a dict
output_dir str Output directory (created if missing)
pattern str Glob pattern (default: "*.jpg")
Returns list[str] List of output file paths
example
from jpegtrust import batch_embed

outputs = batch_embed("./photos", "metadata.json", "./signed")
print(f"Embedded {len(outputs)} images")

# With a custom pattern
outputs = batch_embed("./photos", "metadata.json", "./signed", pattern="*.jpeg")
batch_extract(input_dir, output_dir=None, pattern="*.jpg")

Extract metadata from all matching images. Optionally write each result as a .json file.

Parameter Type Description
input_dir str Directory containing images
output_dir str | None If set, writes .json files here
pattern str Glob pattern (default: "*.jpg")
Returns list[dict] List of filename/metadata dicts
example
from jpegtrust import batch_extract

# Just get the data
results = batch_extract("./signed")
for r in results:
    if r["metadata"]:
        print(f"{r['filename']}: has metadata")

# Also write JSON files
results = batch_extract("./signed", output_dir="./extracted")
batch_verify(input_dir, profile, pattern="*.jpg")

Verify all matching images against a trust profile. Returns individual results and a summary.

Parameter Type Description
input_dir str Directory containing images
profile str Path to a trust profile YAML file
pattern str Glob pattern (default: "*.jpg")
Returns dict Results list + summary with total/passed/warnings/failed/errors counts
example
import sys
from jpegtrust import batch_verify

result = batch_verify("./uploads", "policy.yml")

summary = result["summary"]
print(f"Total: {summary['total']}")
print(f"Passed: {summary['passed']}")
print(f"Failed: {summary['failed']}")

# Use in CI: fail if any image doesn't pass
if summary["failed"] > 0 or summary["errors"] > 0:
    sys.exit(1)

Data types

These dataclasses are returned by the API functions. Import them from jpegtrust._types if you need type annotations.

VerificationReport

The result of a verification. Contains the status, score, verdict, and detailed results for each check.

Field Type Description
status "pass" | "warning" | "fail" Overall trust status
score float 0.0 to 1.0 (passed / total checks)
verdict str "trusted", "mostly_trusted", or "profile_mismatch"
profile str Profile name from metadata
passed list[str] IDs of checks that passed
failed list[str] IDs of checks that failed
total_checks int Total checks evaluated
passed_checks int Number of checks that passed
sections list Detailed per-section results
c2pa C2PAInfo | None C2PA detection and validation info
to_dict() → dict Convert to plain dict for JSON serialization
Profile

A trust profile containing metadata and a list of checks.

Field Type Description
metadata ProfileMetadata Profile metadata (name, issuer, date, version, language)
checks list[CheckDefinition] The enabled checks for this profile
ProfileMetadata
Field Type Default
name str (required)
issuer str (required)
date str (required)
version str "1.0.0"
language str "en"
CheckDefinition
Field Type Description
id str Unique identifier (e.g., "signature_chain")
label str Human-readable name
description str What this check validates
level "required" | "optional" Severity level
expression str json-formula expression to evaluate
report_true str Text shown when the check passes
report_false str Text shown when the check fails
C2PAInfo

Information about C2PA content credentials detected in the image.

Field Type Description
detected bool Whether C2PA markers were found
message str | None Status message
manifest_count int | None Number of manifests found
validation "valid" | "invalid" | "partial" | None Overall validation status
signature_valid bool | None Whether signature is valid
content_intact bool | None Whether content hash matches
validation_details list[str] | None Detailed validation messages

CLI reference

The jpegtrust command-line tool provides access to all package features. Install with pip and the jpegtrust command becomes available.

jpegtrust embed

Embed metadata into a single JPEG image.

jpegtrust embed <IMAGE> <METADATA> [-o OUTPUT] [--digital-source-type TYPE]
Argument / Option Description
IMAGE Path to input JPEG (required)
METADATA Path to JSON metadata file (required)
-o, --output Output path (default: <image>_embedded.jpg)
--digital-source-type IPTC digital source type slug (e.g., trainedAlgorithmicMedia, digitalCapture)
example
jpegtrust embed photo.jpg metadata.json -o signed.jpg
jpegtrust extract

Extract metadata from a JPEG. Prints JSON to stdout or writes to a file.

jpegtrust extract <IMAGE> [-o OUTPUT]
Argument / Option Description
IMAGE Path to JPEG file (required)
-o, --output Write JSON to file instead of stdout
examples
# Print to terminal
jpegtrust extract signed.jpg

# Save to file
jpegtrust extract signed.jpg -o metadata.json

# Pipe to jq
jpegtrust extract signed.jpg | jq '.manifests[0].status'
jpegtrust verify

Verify an image against a trust profile.

jpegtrust verify <IMAGE> <PROFILE> [--format json|text]
Argument / Option Description
IMAGE Path to JPEG (required)
PROFILE Path to profile YAML (required)
--format "text" (default) or "json"
examples
# Human-readable
jpegtrust verify signed.jpg policy.yml

# JSON for scripting
jpegtrust verify signed.jpg policy.yml --format json
jpegtrust profile create

Create a trust profile from a template or custom checks.

jpegtrust profile create [--template NAME] [--name NAME] [--issuer NAME] [--checks IDS] [-o FILE]
Option Description
--template Template name (default: "custom")
--name Profile name
--issuer Issuer name
--checks Comma-separated check IDs (overrides template)
-o, --output Write YAML to file (otherwise stdout)
examples
# From a template
jpegtrust profile create --template newsroom -o newsroom.yml

# Custom checks
jpegtrust profile create --checks signature_chain,pixel_hash,copyright \
  --name "My Policy" --issuer "My Org" -o custom.yml

# Preview to stdout (don't save)
jpegtrust profile create --template insurance
jpegtrust profile list-templates

Show all available templates and their checks.

jpegtrust profile list-templates
jpegtrust profile list-checks

Show all available check IDs with levels and labels.

jpegtrust profile list-checks
jpegtrust profile list-source-types

List all valid IPTC digital source types. AI-related types are marked with [AI].

jpegtrust profile list-source-types
jpegtrust batch embed

Embed metadata into all images in a directory.

jpegtrust batch embed <INPUT_DIR> <METADATA> -o <OUTPUT_DIR> [--pattern GLOB]
example
jpegtrust batch embed ./photos metadata.json -o ./signed --pattern "*.jpeg"
jpegtrust batch extract

Extract metadata from all images in a directory.

jpegtrust batch extract <INPUT_DIR> [-o OUTPUT_DIR] [--pattern GLOB]
example
jpegtrust batch extract ./signed -o ./extracted
jpegtrust batch verify

Verify all images in a directory against a profile.

jpegtrust batch verify <INPUT_DIR> <PROFILE> [--pattern GLOB] [--format json|text]
example
jpegtrust batch verify ./signed policy.yml --format json