Documentation/Install and integrate

Install and integrate

From the first export to your own image and silent video

Read export_jobs.py without downloading

Exact downloadable helper · SHA-256 96d41b10e42d064611d95cfb37d73779e16427e9c9e91debcd40fe3d406fba8f · Pinned source on GitHub ↗

"""A small development worker: one resident SDK, serial bounded jobs, private outputs.

Use only for newly generated visual files. This is an integration example, not a
public upload endpoint or a production credential manager. See own-files.md.
"""
import argparse
from datetime import datetime, timezone
import json
from pathlib import Path
import sys

PROFILES = {'economy_5s', 'economy_2s', 'resilient'}


def load_jobs(manifest):
    """Validate all operator-supplied jobs before creating an SDK or any output."""
    manifest = Path(manifest).resolve()
    data = json.loads(manifest.read_text())
    if set(data) != {'schema_version', 'publisher', 'system', 'jobs'} or data['schema_version'] != 1:
        raise ValueError('Expected schema_version=1, publisher, system and jobs')
    if not isinstance(data['publisher'], str) or not data['publisher'].strip():
        raise ValueError('Supply a truthful public publisher')
    if not isinstance(data['system'], dict) or set(data['system']) != {'name', 'version'}:
        raise ValueError('Supply public system name and version')
    if not all(isinstance(v, str) and v.strip() for v in data['system'].values()):
        raise ValueError('System values must be non-empty strings')
    if not isinstance(data['jobs'], list) or not 1 <= len(data['jobs']) <= 100:
        raise ValueError('Use 1–100 jobs per batch; admission queue belongs to your app')
    jobs, identifiers, inputs, outputs = [], set(), set(), set()
    for raw in data['jobs']:
        required = {'job_id', 'source', 'destination', 'generated_at'}
        if not isinstance(raw, dict) or not required <= set(raw) or set(raw) - required - {'video_profile', 'audio_kind'}:
            raise ValueError('Unexpected job fields')
        job_id = raw['job_id']
        if not isinstance(job_id, str) or not job_id.strip() or job_id in identifiers:
            raise ValueError('Use a unique non-empty job_id')
        if not isinstance(raw['generated_at'], str):
            raise ValueError('generated_at must be the actual per-job ISO 8601 time')
        created = datetime.fromisoformat(raw['generated_at'].replace('Z', '+00:00'))
        if created.tzinfo is None or created.utcoffset() is None or created > datetime.now(timezone.utc):
            raise ValueError('generated_at requires a timezone and cannot be in the future')
        source = (manifest.parent / raw['source']).resolve()
        destination = (manifest.parent / raw['destination']).resolve()
        if not source.is_file():
            raise ValueError('Input is not a regular file: ' + str(source))
        if source.suffix.lower() not in {'.png', '.jpg', '.jpeg', '.mp4'}:
            raise ValueError('Use JPEG/PNG or a supported silent SDR MP4')
        video = source.suffix.lower() == '.mp4'
        if destination.suffix.lower() not in ({'.mp4'} if video else {'.png', '.jpg', '.jpeg'}):
            raise ValueError('Destination must match the media kind')
        receipt = destination.with_name(destination.name + '.receipt.json')
        if destination.exists() or receipt.exists() or source == destination or destination in outputs:
            raise ValueError('Use fresh, unique destination and receipt paths')
        if video and raw.get('audio_kind') != 'none':
            raise ValueError('This example requires audio_kind=none and a silent input')
        if not video and ('video_profile' in raw or 'audio_kind' in raw):
            raise ValueError('Video options do not apply to images')
        if raw.get('video_profile', 'economy_5s') not in PROFILES:
            raise ValueError('Unknown video_profile')
        identifiers.add(job_id); inputs.add(source); outputs.add(destination)
        jobs.append(dict(job_id=job_id, source=source, destination=destination,
                         created_at=created, video=video, profile=raw.get('video_profile')))
    if inputs & outputs or any(p.with_name(p.name + '.receipt.json') in outputs | inputs for p in outputs):
        raise ValueError('Batch input/output/receipt paths must not collide')
    return data, jobs


def run(manifest, identity_dir, registry_path):
    # Development only: the production kit owns credential, timestamp and trust setup.
    data, jobs = load_jobs(manifest)
    from ariadne_mark.pipeline import SDK
    from ariadne_mark.provenance import Action, GenerativeSystem, MediaKind, ProvenanceRecord
    from ariadne_mark.registry import Registry
    from ariadne_mark.signing import SigningIdentity
    from ariadne_mark.watermark import LazyWatermarker
    identity = SigningIdentity.from_directory(Path(identity_dir), allow_dev=True)
    if not identity.development:
        raise ValueError('This example requires a development identity; use the production kit for real credentials')
    # Construct after a process fork, then reuse for every accepted queue job.
    with SDK(identity=identity, registry=Registry(Path(registry_path)),
             marker=LazyWatermarker(threads=2), verification_scope='current') as sdk:
        for job in jobs:
            record = ProvenanceRecord.create(publisher=data['publisher'],
                system=GenerativeSystem(**data['system']),
                media_kind=MediaKind.VIDEO if job['video'] else MediaKind.IMAGE,
                action=Action.CREATED, created_at=job['created_at'])
            options = {'audio_kind': 'none'} if job['video'] else {}
            if job['profile'] is not None:
                options['video_profile'] = job['profile']
            receipt = sdk.mark(job['source'], job['destination'], record, **options)
            report = sdk.verify(job['destination'])
            if (report['c2pa'].get('signature') != 'valid'
                    or report['c2pa'].get('token') != receipt['token']
                    or report['watermark'].get('token') != receipt['token']
                    or report['c2pa'].get('record') != record.to_dict()):
                raise RuntimeError('Independent local read-back failed; keep staging private and investigate')
            print(json.dumps({'job_id': job['job_id'], 'status': 'accepted_in_private_staging',
                'output': str(job['destination']), 'receipt': receipt,
                'verification': report}), flush=True)


def main():
    parser = argparse.ArgumentParser(description=__doc__)
    parser.add_argument('manifest', type=Path)
    parser.add_argument('--identity', type=Path, required=True)
    parser.add_argument('--registry', type=Path, required=True)
    parser.add_argument('--allow-dev', action='store_true', required=True)
    args = parser.parse_args()
    try:
        run(args.manifest, args.identity, args.registry)
    except Exception as exc:
        print(json.dumps({'status': 'stopped', 'error': type(exc).__name__, 'message': str(exc),
                          'publication': 'No original-file fallback; inspect earlier accepted jobs separately'}), file=sys.stderr)
        return 2
    return 0


if __name__ == '__main__':
    sys.exit(main())

Use this single route for 0.7.3a4, Linux x86-64/Python 3.12, CPU. It covers newly generated JPEG/PNG and final silent SDR MP4. Bring the file's real generation time and public publisher/system/version. Audio generation and credentialed inputs need a different workflow; see formats and upstream inputs.

1. Provision once and prove the installation

Download Release 0.7.3a4, read START_HERE.txt, then run its FIRST_EXPORT.sh. It checks artifact hashes and demonstrates an image and all three video modes. Its Docker route builds from source; there is no published ready-made Docker image to pull. Allow about 10 GB free for the build. Alternatively use the qualified wheel setup with FFmpeg/ffprobe and Node/npm installed. Do not install the unrelated PyPI ariadne package.

The remaining commands run inside that provisioned environment. If using Docker, mount a private working directory, use the image ID from your completed build, and enter its shell with --entrypoint /bin/bash. Match the container UID to the workspace owner, allocate two CPUs/4 GiB for this evaluation and keep keys outside source control. Processing needs provisioned models, not network downloads.

2. Describe your own jobs

Download the worker and job manifest into the working directory. Put your files under inputs/; create private staging/. Replace both placeholder generation times with each file's actual generation time, including timezone. Neither batch start time nor file modification time is a substitute. Set truthful public product names; never use account IDs, prompts or emails. The JSON manifest is trusted operator input, not an upload API.

mkdir -p inputs staging .private registry
ariadne init-dev .private/dev
python export_jobs.py jobs.example.json --identity .private/dev \
  --registry registry/assets.sqlite3 --allow-dev > accepted.jsonl

The example validates the complete manifest before any export, accepts at most 100 jobs, constructs the SDK after the worker process starts, and processes serially with verification_scope="current". This scope covers this new issuer's current TrustMark image/video schemes. Use all and provision legacy engines when your verifier must also inspect older schemes; it costs additional resources and does not expand what a current-only negative says about other formats.

Omit video_profile to keep Economy5s; select economy_2s or resilient per video job. All presets share one Node worker in this SDK process. No cadence, strength or SDK gate is changed by this example. audio_kind="none" requires a silent video; do not use it to misdescribe an audio track.

A success line contains the job ID, receipt and a fresh local read-back. Confirm signature, expected ID and source record. Development issuer trust remains separate from a mathematically valid signature. The SDK also saves a sidecar .receipt.json and registry entry. Keep those files private until you deliberately publish the relevant public data. Only hand accepted staged output to your app's publication step.

3. Run an independent verifier

Start a separate process without the provider private key. Give it a read-only mount of the registry directory and approved public-source config. SQLite readers need access to the database and its supporting files; mount the directory, not a stale copied database. Review public names before writing public-sources.json:

{"schema_version":1,"sources":[{"publisher":"Your public studio name","system":{"name":"Your generator","version":"1.0"}}]}

Generate the separate report key once, then start the verifier:

ariadne report keygen .private/verifier-report
ariadne serve --host 127.0.0.1 --port 8080 --threads 2 \
  --verification-scope current --registry registry/assets.sqlite3 \
  --public-sources public-sources.json \
  --report-key .private/verifier-report/report.key \
  --verifier-id http://127.0.0.1:8080

The loopback URL is for this local evaluation. Public deployment needs HTTPS, real operator contact/privacy details and the production path. Pin .private/verifier-report/report.pub through your own trusted channel.

In another terminal in the provisioned environment:

curl --fail-with-body --max-time 330 -H 'Content-Type: application/octet-stream' \
  --data-binary @staging/video-001.mp4 \
  'http://127.0.0.1:8080/verify?format=mp4' > verification.json
ariadne report verify verification.json \
  --public-key .private/verifier-report/report.pub \
  --asset staging/video-001.mp4 --verifier-id http://127.0.0.1:8080

Repeat with staging/image-001.png and format=png. Compare the returned ID with that job's receipt. GET /records/{token} resolves the reviewed registry entry. A registry match is operator evidence; it does not authenticate an edited copy. HTTP200 means inspection completed, not necessarily that a mark was found. Read watermark.status, watermark.search, c2pa.signature and issuer trust. A clean negative can take much longer than a positive. Result contract.

4. Connect your queue and handle failures

The manifest loop is a small worker example, not a durable message broker. In your app, retain the generation timestamp and idempotency key when accepting a job. Admit only a bounded number of pending jobs, then return back pressure (HTTP429/Retry-After where appropriate). Create a fresh staging path for every attempt. Publish once, only after accepted receipt/read-back; reconcile retries against your own job ledger. Never start one model process per web request or fork a live SDK. Keep exporter and verifier capacities separate.

Nonzero worker exit stops this batch. Earlier accepted jobs may remain; inspect their receipts before retrying. Existing outputs, duplicate IDs, naive/future timestamps and input/output collisions fail before marking. Unsupported media or a failed SDK gate stops export. If the extra local read-back fails after an SDK export, preserve the candidate privately for investigation. Never replace failed output with the unmarked input.

Back up registry/config and protect keys; rehearse restore before relying on recovery. The SDK's gate is not a replacement for testing your actual CDN/download bytes. Follow the operator evidence template and cost worksheet before enabling user traffic.

Evidence for this example

Server acceptance exercises the published 0.7.3a4 runtime with JPEG, PNG, 720p/24fps and portrait 1080p/29.97fps silent MP4, all three modes, individual source times, independent HTTP/registry/JWS verification and rejected malformed jobs. The script is in the repository. These deterministic engineering fixtures check integration behavior, not real-world durability, production public trust or a capacity SLA. The acceptance summary and logs are retained separately from the immutable release evidence.