Download app.py from HirModel/video-atomization-trace-stack-runtime: direct link, hf CLI and curl.
- Browser
- Download file 32.8 kB
-
https://huggingface.co/spaces/HirModel/video-atomization-trace-stack-runtime/resolve/main/app.py
- Command line
-
hf download hf://spaces/HirModel/video-atomization-trace-stack-runtime/app.py
-
curl -L -o app.py https://huggingface.co/spaces/HirModel/video-atomization-trace-stack-runtime/resolve/main/app.py
32.8 kB
| import os | |
| import cv2 | |
| import json | |
| import hashlib | |
| import subprocess | |
| import tempfile | |
| import zipfile | |
| from datetime import datetime, timezone | |
| from pathlib import Path | |
| import gradio as gr | |
| import pandas as pd | |
| from PIL import Image | |
| # Hugging Face / Gradio compatibility guard. | |
| # Gradio 4.44.x can crash while generating API metadata when gradio_client | |
| # receives boolean JSON-schema fragments such as additionalProperties: true. | |
| # The UI route does not depend on that schema text, so preserve runtime behavior | |
| # and map those boolean schema fragments to a safe Any type. | |
| def _install_gradio_schema_guard() -> None: | |
| try: | |
| import gradio_client.utils as client_utils | |
| except Exception: | |
| return | |
| original = getattr(client_utils, "_json_schema_to_python_type", None) | |
| if original is None or getattr(original, "_hir_schema_guard", False): | |
| return | |
| def guarded_json_schema_to_python_type(schema, defs=None): | |
| if isinstance(schema, bool): | |
| return "Any" | |
| return original(schema, defs) | |
| guarded_json_schema_to_python_type._hir_schema_guard = True | |
| client_utils._json_schema_to_python_type = guarded_json_schema_to_python_type | |
| _install_gradio_schema_guard() | |
| APP_TITLE = "Substrate Video Atomization Runtime v0.1.1" | |
| BOUNDARY_NOTE = ( | |
| "This demo performs source-bound video atomization and trace-stack rehydration. " | |
| "It is not video compression, not a codec replacement, and not a physical hologram generator. " | |
| "The output is a source-bound data-hologram review surface with receipts. " | |
| "The source video remains authority." | |
| ) | |
| DATA_HOLOGRAM_VERSION = "0.2" | |
| RUNTIME_TRAIL_LOOP_LAW = ( | |
| "pressure → gate → capsule → route → action/review → receipt → readiness" | |
| ) | |
| VIDEO_ATOMIZATION_LOOP_LAW = ( | |
| "media pressure → atom gate → frame/scene/motion capsule → transfer route " | |
| "→ rehydration surface → receipt → human validation / memory readiness" | |
| ) | |
| RESONANT_INGRESS_TRACE_LAW = ( | |
| "signal → bounded ingress → trace capsule → fusion/relation layer → pressure form " | |
| "→ route integrity → OAM scan → human validation" | |
| ) | |
| PROVENANCE_POLICY = "PROVENANCE_IS_PART_OF_THE_DATA" | |
| REHYDRATION_BOUNDARY = "REVIEW_SURFACE_ONLY" | |
| ANTI_LAUNDERING_RULES = [ | |
| "no frame atom becomes source replacement", | |
| "no scene atom becomes identity, intent, or external-context claim", | |
| "no motion atom becomes identity, intent, or causality claim", | |
| "no provenance loss hidden by successful transfer", | |
| "no rehydration surface becomes final settlement", | |
| "no memory candidate without receipt", | |
| "human validation remains settlement authority", | |
| ] | |
| def sha256_file(path: str) -> str: | |
| h = hashlib.sha256() | |
| with open(path, "rb") as f: | |
| for chunk in iter(lambda: f.read(1024 * 1024), b""): | |
| h.update(chunk) | |
| return h.hexdigest() | |
| def sha256_bytes(data: bytes) -> str: | |
| return hashlib.sha256(data).hexdigest() | |
| def format_time(seconds: float) -> str: | |
| if seconds is None: | |
| seconds = 0.0 | |
| seconds = max(float(seconds), 0.0) | |
| h = int(seconds // 3600) | |
| m = int((seconds % 3600) // 60) | |
| s = seconds % 60 | |
| return f"{h:02d}:{m:02d}:{s:06.3f}" | |
| def safe_float(value, default=0.0): | |
| try: | |
| if value is None: | |
| return default | |
| return float(value) | |
| except Exception: | |
| return default | |
| def safe_int(value, default=0): | |
| try: | |
| if value is None: | |
| return default | |
| return int(value) | |
| except Exception: | |
| return default | |
| def write_json(path: Path, obj) -> None: | |
| path.parent.mkdir(parents=True, exist_ok=True) | |
| path.write_text(json.dumps(obj, indent=2, ensure_ascii=False), encoding="utf-8") | |
| def make_run_dir() -> Path: | |
| stamp = datetime.now(timezone.utc).strftime("%Y%m%dT%H%M%SZ") | |
| return Path(tempfile.mkdtemp(prefix=f"video_atomization_{stamp}_")) | |
| def coerce_uploaded_path(uploaded) -> str | None: | |
| """Return a filesystem path from Gradio File/Video payload variants.""" | |
| if uploaded is None: | |
| return None | |
| if isinstance(uploaded, (str, os.PathLike)): | |
| return str(uploaded) | |
| if isinstance(uploaded, dict): | |
| for key in ("path", "name", "orig_name"): | |
| value = uploaded.get(key) | |
| if value and os.path.exists(str(value)): | |
| return str(value) | |
| return None | |
| name = getattr(uploaded, "name", None) | |
| if name and os.path.exists(str(name)): | |
| return str(name) | |
| return None | |
| def make_preview_mp4(video_payload, target_dir: Path | None = None) -> str | None: | |
| """Create a browser-stable MP4 preview path without mutating the source video.""" | |
| video_path = coerce_uploaded_path(video_payload) | |
| if not video_path or not os.path.exists(video_path): | |
| return None | |
| if target_dir is None: | |
| target_dir = Path(tempfile.mkdtemp(prefix="video_atomization_preview_")) | |
| target_dir.mkdir(parents=True, exist_ok=True) | |
| preview_path = target_dir / "source_video_preview.mp4" | |
| # First try a fast stream-copy with +faststart. This fixes many browser/Gradio | |
| # preview failures without the cost of a full transcode. | |
| faststart_cmd = [ | |
| "ffmpeg", "-y", "-hide_banner", "-loglevel", "error", | |
| "-i", video_path, | |
| "-map", "0:v:0", "-map", "0:a?", | |
| "-c", "copy", | |
| "-movflags", "+faststart", | |
| str(preview_path), | |
| ] | |
| try: | |
| subprocess.run(faststart_cmd, check=True, timeout=90) | |
| if preview_path.exists() and preview_path.stat().st_size > 0: | |
| return str(preview_path) | |
| except Exception: | |
| pass | |
| # Fallback: browser-safe H.264/AAC transcode. This is slower, but bounded to | |
| # preview generation and still keeps the original file as the canonical source. | |
| transcode_cmd = [ | |
| "ffmpeg", "-y", "-hide_banner", "-loglevel", "error", | |
| "-i", video_path, | |
| "-map", "0:v:0", "-map", "0:a?", | |
| "-c:v", "libx264", "-preset", "veryfast", "-crf", "23", | |
| "-pix_fmt", "yuv420p", | |
| "-c:a", "aac", "-b:a", "128k", | |
| "-movflags", "+faststart", | |
| str(preview_path), | |
| ] | |
| try: | |
| subprocess.run(transcode_cmd, check=True, timeout=240) | |
| if preview_path.exists() and preview_path.stat().st_size > 0: | |
| return str(preview_path) | |
| except Exception: | |
| pass | |
| # Last resort: return the source path so the rest of the route still holds. | |
| return video_path | |
| def prepare_video_preview(video_payload): | |
| preview_path = make_preview_mp4(video_payload) | |
| if not preview_path: | |
| return None, "Preview waiting for source video." | |
| return preview_path, "Preview rehydrated from source-bound upload. Source remains canonical authority." | |
| def classify_pressure(motion_delta: float, scene_threshold: float) -> str: | |
| if motion_delta >= scene_threshold * 1.6: | |
| return "STRAINED_SCENE_BREAK_PRESSURE" | |
| if motion_delta >= scene_threshold: | |
| return "HELD_WITH_SCENE_BOUNDARY" | |
| return "HELD" | |
| def build_markdown_receipt(receipt: dict, source_capsule: dict, trace_stack: dict, data_hologram: dict | None = None) -> str: | |
| lines = [ | |
| "# HIR × OAM Video Atomization Receipt", | |
| "", | |
| f"- Receipt type: `{receipt['receipt_type']}`", | |
| f"- Route state: `{receipt['pressure_state']}`", | |
| f"- Source mutation: `{receipt['source_mutation']}`", | |
| f"- Canonical anchor: `{receipt['canonical_anchor']}`", | |
| f"- Atomization state: `{receipt['atomization_state']}`", | |
| f"- Trace-stack state: `{receipt['trace_stack_state']}`", | |
| f"- Data-hologram state: `{receipt['data_hologram_state']}`", | |
| f"- Human review: `{receipt['human_review']}`", | |
| f"- Provenance policy: `{receipt.get('provenance_policy', PROVENANCE_POLICY)}`", | |
| "", | |
| "## Source", | |
| "", | |
| f"- Filename: `{source_capsule.get('filename')}`", | |
| f"- SHA-256: `{source_capsule.get('sha256')}`", | |
| f"- Duration: `{source_capsule.get('duration_seconds')}` seconds", | |
| f"- FPS: `{source_capsule.get('fps')}`", | |
| f"- Frame count: `{source_capsule.get('frame_count')}`", | |
| "", | |
| "## Data Hologram v0.2 law", | |
| "", | |
| f"- Runtime Trail loop: `{RUNTIME_TRAIL_LOOP_LAW}`", | |
| f"- Video atomization loop: `{VIDEO_ATOMIZATION_LOOP_LAW}`", | |
| f"- Resonant Ingress trace law: `{RESONANT_INGRESS_TRACE_LAW}`", | |
| f"- Rehydration boundary: `{REHYDRATION_BOUNDARY}`", | |
| "- Provenance is part of the data and must not be silently flattened during transfer.", | |
| "", | |
| "## Boundary", | |
| "", | |
| BOUNDARY_NOTE, | |
| "", | |
| "## Trace stack layers", | |
| "", | |
| ] | |
| for layer in trace_stack.get("stack_layers", []): | |
| lines.append(f"- `{layer}`") | |
| if data_hologram: | |
| lines.extend([ | |
| "", | |
| "## Hologram preservation fields", | |
| "", | |
| ]) | |
| for field in data_hologram.get("preservation_fields", []): | |
| lines.append(f"- `{field}`") | |
| lines.extend([ | |
| "", | |
| "## Anti-laundering rules", | |
| "", | |
| ]) | |
| for rule in ANTI_LAUNDERING_RULES: | |
| lines.append(f"- {rule}") | |
| lines.extend([ | |
| "", | |
| "## Settlement", | |
| "", | |
| "Machine route surface only. Human retains settlement authority.", | |
| ]) | |
| return "\n".join(lines) | |
| def create_run_packet(run_dir: Path, packet_name: str = "video_atomization_run_packet.zip") -> str: | |
| packet_path = run_dir / packet_name | |
| with zipfile.ZipFile(packet_path, "w", compression=zipfile.ZIP_DEFLATED) as z: | |
| for path in run_dir.rglob("*"): | |
| if path == packet_path or path.is_dir(): | |
| continue | |
| z.write(path, path.relative_to(run_dir)) | |
| return str(packet_path) | |
| def build_data_hologram_manifest(source_capsule: dict, atom_manifest: dict, frame_atoms: list, scene_atoms: list, motion_atoms: list) -> dict: | |
| """Build the source-bound review-surface structure for Data Hologram v0.2.""" | |
| source_hash = source_capsule.get("sha256") | |
| motion_values = [safe_float(m.get("motion_delta"), 0.0) for m in motion_atoms] | |
| max_motion = max(motion_values) if motion_values else 0.0 | |
| avg_motion = sum(motion_values) / len(motion_values) if motion_values else 0.0 | |
| strained_motion_atoms = [m for m in motion_atoms if str(m.get("pressure_state", "")).startswith("STRAINED")] | |
| return { | |
| "manifest_type": "SOURCE_BOUND_DATA_HOLOGRAM_MANIFEST", | |
| "schema_version": DATA_HOLOGRAM_VERSION, | |
| "hologram_type": "SOURCE_BOUND_DATA_HOLOGRAM", | |
| "hologram_state": "FORMED", | |
| "source_video_sha256": source_hash, | |
| "canonical_anchor": "SOURCE_VIDEO_REMAINS_AUTHORITY", | |
| "source_mutation": "BLOCKED", | |
| "transfer_mode": "ATOMIZED_SOURCE_STRUCTURE", | |
| "rehydration_boundary": REHYDRATION_BOUNDARY, | |
| "rehydration_state": "REHYDRATED_SOURCE_BOUND_REVIEW_SURFACE", | |
| "optical_hologram_state": "NOT_GENERATED_IN_THIS_DEMO", | |
| "provenance_policy": PROVENANCE_POLICY, | |
| "source_account_boundary": { | |
| "source_remains_authority": True, | |
| "rehydration_is_review_surface_only": True, | |
| "atomized_layer_replaces_source": False, | |
| "automatic_settlement": False, | |
| "human_validation_required": True, | |
| }, | |
| "operating_laws": { | |
| "runtime_trail_loop": RUNTIME_TRAIL_LOOP_LAW, | |
| "video_atomization_loop": VIDEO_ATOMIZATION_LOOP_LAW, | |
| "resonant_ingress_trace_law": RESONANT_INGRESS_TRACE_LAW, | |
| }, | |
| "preservation_fields": [ | |
| "source_hash", | |
| "frame_position", | |
| "timestamp", | |
| "motion_delta_pressure", | |
| "scene_interval_closure", | |
| "claim_boundary", | |
| "provenance_reference", | |
| "source_return_context", | |
| "human_validation_state", | |
| ], | |
| "ingress_accounts": [ | |
| { | |
| "ingress_type": "bounded_visual_trace", | |
| "runtime_name": "frame_atoms", | |
| "count": len(frame_atoms), | |
| "account_boundary": "sampled frame only; does not support full-scene, identity, intent, or external-context claim", | |
| "capsule_state": "CAPSULED_SOURCE_BOUND", | |
| }, | |
| { | |
| "ingress_type": "temporal_pressure_trace", | |
| "runtime_name": "motion_delta_atoms", | |
| "count": len(motion_atoms), | |
| "max_motion_delta": round(max_motion, 6), | |
| "average_motion_delta": round(avg_motion, 6), | |
| "strained_count": len(strained_motion_atoms), | |
| "account_boundary": "motion pressure only; does not support identity, intent, causality, or external-context claim", | |
| }, | |
| { | |
| "ingress_type": "interval_closure_trace", | |
| "runtime_name": "scene_atoms", | |
| "count": len(scene_atoms), | |
| "account_boundary": "scene interval only; does not support identity, intent, or external-context claim", | |
| }, | |
| { | |
| "ingress_type": "provenance_trace", | |
| "runtime_name": "source_return_context", | |
| "count": 1, | |
| "account_boundary": "provenance is carried as source-bound receipt context, not as automatic truth or final settlement", | |
| }, | |
| ], | |
| "trace_fusion_review": { | |
| "fusion_mode": "GATED_RELATION_REVIEW_NOT_CONFIDENCE_BLEND", | |
| "frame_atoms_may_enter": "ONLY_AS_SOURCE_BOUND_VISUAL_TRACE", | |
| "motion_atoms_may_enter": "ONLY_AS_TEMPORAL_PRESSURE_TRACE", | |
| "scene_atoms_may_enter": "ONLY_AS_INTERVAL_CLOSURE_TRACE", | |
| "provenance_may_enter": "ONLY_AS_RECEIPT_BOUND_SOURCE_RETURN_CONTEXT", | |
| "strained_accounts_visible": True, | |
| "must_stop_accounts_laundered": False, | |
| }, | |
| "route_integrity": { | |
| "atom_manifest_state": "FORMED", | |
| "trace_stack_state": "STACKED", | |
| "source_return_state": "PRESENT", | |
| "provenance_survival_state": "RECEIPT_BOUND", | |
| "review_surface_state": "GENERATED", | |
| }, | |
| "anti_laundering_rules": ANTI_LAUNDERING_RULES, | |
| "memory_readiness_candidate": { | |
| "state": "ELIGIBLE_ONLY_AFTER_HUMAN_VALIDATION", | |
| "law": "memory can prime readiness; memory does not grant permission", | |
| "quarantine_required_if": [ | |
| "source hash mismatch", | |
| "missing atom receipt", | |
| "provenance break hidden by transfer", | |
| "human validation rejected", | |
| ], | |
| }, | |
| "human_validation": { | |
| "state": "REQUIRED", | |
| "settlement_authority": "HUMAN", | |
| "review_questions": [ | |
| "What arrived?", | |
| "What held?", | |
| "What degraded?", | |
| "What provenance survived?", | |
| "What needs repair?", | |
| "What still requires human validation?", | |
| ], | |
| }, | |
| "atom_counts": atom_manifest.get("atom_counts", {}), | |
| } | |
| def atomize_video(video_path, sample_every_seconds=1.0, scene_threshold=32.0, max_frame_atoms=72): | |
| source_video_path = coerce_uploaded_path(video_path) | |
| if not source_video_path: | |
| empty = pd.DataFrame() | |
| return ( | |
| None, | |
| {"error": "No video uploaded."}, | |
| empty, | |
| empty, | |
| {"error": "No data hologram generated."}, | |
| {"error": "No trace stack generated."}, | |
| {"error": "No receipt generated."}, | |
| {"human_validation_state": "NOT_AVAILABLE"}, | |
| [], | |
| None, | |
| "Upload a video and run the route." | |
| ) | |
| run_dir = make_run_dir() | |
| frames_dir = run_dir / "frame_atoms" | |
| manifests_dir = run_dir / "manifests" | |
| receipts_dir = run_dir / "receipts" | |
| frames_dir.mkdir(parents=True, exist_ok=True) | |
| manifests_dir.mkdir(parents=True, exist_ok=True) | |
| receipts_dir.mkdir(parents=True, exist_ok=True) | |
| sample_every_seconds = max(safe_float(sample_every_seconds, 1.0), 0.1) | |
| scene_threshold = max(safe_float(scene_threshold, 32.0), 1.0) | |
| max_frame_atoms = max(safe_int(max_frame_atoms, 72), 1) | |
| source_hash = sha256_file(source_video_path) | |
| file_size = os.path.getsize(source_video_path) | |
| filename = os.path.basename(source_video_path) | |
| cap = cv2.VideoCapture(source_video_path) | |
| if not cap.isOpened(): | |
| empty = pd.DataFrame() | |
| return ( | |
| make_preview_mp4(source_video_path, run_dir), | |
| {"error": "OpenCV could not read this video. Try MP4/H.264, WebM, or MOV."}, | |
| empty, | |
| empty, | |
| {"error": "No data hologram generated."}, | |
| {"error": "No trace stack generated."}, | |
| {"error": "No receipt generated."}, | |
| {"human_validation_state": "NOT_AVAILABLE"}, | |
| [], | |
| None, | |
| "Could not read the video file." | |
| ) | |
| fps = safe_float(cap.get(cv2.CAP_PROP_FPS), 0.0) | |
| frame_count = safe_int(cap.get(cv2.CAP_PROP_FRAME_COUNT), 0) | |
| width = safe_int(cap.get(cv2.CAP_PROP_FRAME_WIDTH), 0) | |
| height = safe_int(cap.get(cv2.CAP_PROP_FRAME_HEIGHT), 0) | |
| duration = frame_count / fps if fps else 0.0 | |
| source_capsule = { | |
| "capsule_type": "SOURCE_VIDEO_CAPSULE", | |
| "source_id": "video_source_001", | |
| "filename": filename, | |
| "sha256": source_hash, | |
| "size_bytes": file_size, | |
| "width": width, | |
| "height": height, | |
| "fps": round(fps, 6), | |
| "frame_count": frame_count, | |
| "duration_seconds": round(duration, 6), | |
| "route_state": "SOURCE_HASHED", | |
| "source_mutation": "BLOCKED", | |
| "canonical_anchor": "SOURCE_VIDEO_REMAINS_AUTHORITY", | |
| "boundary": BOUNDARY_NOTE, | |
| } | |
| frame_atoms = [] | |
| scene_atoms = [] | |
| motion_atoms = [] | |
| gallery_items = [] | |
| sample_interval = max(int(round(fps * sample_every_seconds)), 1) if fps else 30 | |
| previous_gray = None | |
| current_scene_start = 0.0 | |
| scene_index = 0 | |
| atom_index = 0 | |
| frame_idx = 0 | |
| while True: | |
| ok, frame = cap.read() | |
| if not ok: | |
| break | |
| timestamp = frame_idx / fps if fps else 0.0 | |
| gray = cv2.cvtColor(frame, cv2.COLOR_BGR2GRAY) | |
| motion_delta = 0.0 | |
| pressure_state = "HELD" | |
| if previous_gray is not None: | |
| diff = cv2.absdiff(gray, previous_gray) | |
| motion_delta = float(diff.mean()) | |
| pressure_state = classify_pressure(motion_delta, scene_threshold) | |
| motion_atoms.append({ | |
| "motion_atom_id": f"motion_atom_{frame_idx:06d}", | |
| "frame_index": frame_idx, | |
| "time": format_time(timestamp), | |
| "source_video_sha256": source_hash, | |
| "motion_delta": round(motion_delta, 6), | |
| "pressure_state": pressure_state, | |
| "ingress_account": "temporal pressure trace", | |
| "provenance_state": "SOURCE_RETURN_PRESENT", | |
| "claim_boundary": "motion pressure only; does not support identity, intent, causality, or external-context claim" | |
| }) | |
| if motion_delta >= scene_threshold: | |
| scene_atoms.append({ | |
| "scene_id": f"scene_atom_{scene_index:06d}", | |
| "time_start": format_time(current_scene_start), | |
| "time_end": format_time(timestamp), | |
| "source_video_sha256": source_hash, | |
| "scene_boundary_reason": f"motion_delta {motion_delta:.3f} >= threshold {scene_threshold:.3f}", | |
| "pressure_state": "HELD_WITH_BOUNDARY", | |
| "claim_boundary": "scene interval only; does not support identity, intent, or external-context claim", | |
| "rehydration_state": "ELIGIBLE_SOURCE_BOUND", | |
| "human_review": "REQUIRED_BEFORE_PUBLIC_CLAIM", | |
| "ingress_account": "interval closure trace", | |
| "provenance_state": "SOURCE_RETURN_PRESENT" | |
| }) | |
| scene_index += 1 | |
| current_scene_start = timestamp | |
| should_sample = frame_idx % sample_interval == 0 and atom_index < max_frame_atoms | |
| if should_sample: | |
| rgb = cv2.cvtColor(frame, cv2.COLOR_BGR2RGB) | |
| img = Image.fromarray(rgb) | |
| frame_name = f"frame_atom_{atom_index:06d}.jpg" | |
| img_path = frames_dir / frame_name | |
| img.save(img_path, quality=90) | |
| local_hash = sha256_file(str(img_path)) | |
| atom = { | |
| "atom_id": f"frame_atom_{atom_index:06d}", | |
| "atom_type": "frame", | |
| "frame_index": frame_idx, | |
| "time_start": format_time(timestamp), | |
| "time_end": format_time(timestamp + (1.0 / fps if fps else 0.0)), | |
| "source_video_sha256": source_hash, | |
| "local_hash": local_hash, | |
| "sample_path": f"frame_atoms/{frame_name}", | |
| "motion_delta": round(motion_delta, 6), | |
| "claim_boundary": "sampled frame only; does not support full-scene, identity, intent, or external-context claim", | |
| "pressure_state": pressure_state, | |
| "trace_capsule_state": "CAPSULED_SOURCE_BOUND", | |
| "rehydration_state": "ELIGIBLE_SOURCE_BOUND", | |
| "human_review": "REQUIRED_BEFORE_PUBLIC_CLAIM", | |
| "ingress_account": "bounded visual trace", | |
| "provenance_state": "SOURCE_RETURN_PRESENT" | |
| } | |
| frame_atoms.append(atom) | |
| gallery_items.append((str(img_path), atom["atom_id"])) | |
| atom_index += 1 | |
| previous_gray = gray | |
| frame_idx += 1 | |
| cap.release() | |
| if duration > current_scene_start or not scene_atoms: | |
| scene_atoms.append({ | |
| "scene_id": f"scene_atom_{scene_index:06d}", | |
| "time_start": format_time(current_scene_start), | |
| "time_end": format_time(duration), | |
| "source_video_sha256": source_hash, | |
| "scene_boundary_reason": "final interval closure", | |
| "pressure_state": "HELD", | |
| "claim_boundary": "scene interval only; does not support identity, intent, or external-context claim", | |
| "rehydration_state": "ELIGIBLE_SOURCE_BOUND", | |
| "human_review": "REQUIRED_BEFORE_PUBLIC_CLAIM", | |
| "ingress_account": "interval closure trace", | |
| "provenance_state": "SOURCE_RETURN_PRESENT" | |
| }) | |
| atom_manifest = { | |
| "manifest_type": "VIDEO_ATOM_MANIFEST", | |
| "source_video_sha256": source_hash, | |
| "atom_counts": { | |
| "frame_atoms": len(frame_atoms), | |
| "scene_atoms": len(scene_atoms), | |
| "motion_atoms": len(motion_atoms), | |
| }, | |
| "sampling": { | |
| "sample_every_seconds": sample_every_seconds, | |
| "sample_interval_frames": sample_interval, | |
| "max_frame_atoms": max_frame_atoms, | |
| "scene_threshold": scene_threshold, | |
| }, | |
| "frame_atoms": frame_atoms, | |
| "scene_atoms": scene_atoms, | |
| "motion_atoms_summary": { | |
| "count": len(motion_atoms), | |
| "note": "Full motion atom list is included as motion_atoms.json in the run packet." | |
| } | |
| } | |
| data_hologram = build_data_hologram_manifest( | |
| source_capsule=source_capsule, | |
| atom_manifest=atom_manifest, | |
| frame_atoms=frame_atoms, | |
| scene_atoms=scene_atoms, | |
| motion_atoms=motion_atoms, | |
| ) | |
| trace_stack = { | |
| "manifest_type": "TRACE_STACK_DATA_HOLOGRAM_MANIFEST", | |
| "trace_stack_id": "trace_stack_001", | |
| "source_video_sha256": source_hash, | |
| "stack_layers": [ | |
| "source_capsule", | |
| "frame_trace_capsules", | |
| "scene_trace_capsules", | |
| "motion_delta_atoms", | |
| "claim_boundaries", | |
| "pressure_states", | |
| "rehydration_states", | |
| "provenance_trace", | |
| "data_hologram_v0_2", | |
| "human_validation_state" | |
| ], | |
| "stack_law": VIDEO_ATOMIZATION_LOOP_LAW, | |
| "ingress_law": RESONANT_INGRESS_TRACE_LAW, | |
| "data_hologram_state": "FORMED", | |
| "data_hologram_schema_version": DATA_HOLOGRAM_VERSION, | |
| "rehydration_state": "REHYDRATED_SOURCE_BOUND_REVIEW_SURFACE", | |
| "rehydration_boundary": REHYDRATION_BOUNDARY, | |
| "optical_hologram_state": "NOT_GENERATED_IN_THIS_DEMO", | |
| "provenance_policy": PROVENANCE_POLICY, | |
| "source_mutation": "BLOCKED", | |
| "canonical_anchor": "SOURCE_VIDEO_REMAINS_AUTHORITY", | |
| "anti_laundering_rules": ANTI_LAUNDERING_RULES, | |
| "boundary": "Data hologram only. Physical hologram translation requires a later optical modulation layer.", | |
| "data_hologram_manifest_ref": "manifests/source_bound_data_hologram_v0_2.json" | |
| } | |
| receipt = { | |
| "receipt_type": "HIR_OAM_VIDEO_ATOMIZATION_RECEIPT", | |
| "generated_utc": datetime.now(timezone.utc).isoformat(), | |
| "source_held": True, | |
| "source_mutation": "BLOCKED", | |
| "atomization_state": "ATOMIZED_SOURCE_BOUND", | |
| "trace_capsule_state": "CAPSULED_PER_ATOM", | |
| "trace_stack_state": "STACKED", | |
| "data_hologram_state": "FORMED", | |
| "rehydration_state": "REHYDRATED_REVIEW_SURFACE", | |
| "pressure_state": "HELD_WITH_BOUNDARY", | |
| "human_review": "REQUIRED", | |
| "canonical_anchor": "SOURCE_VIDEO_REMAINS_AUTHORITY", | |
| "provenance_policy": PROVENANCE_POLICY, | |
| "rehydration_boundary": REHYDRATION_BOUNDARY, | |
| "runtime_trail_loop": RUNTIME_TRAIL_LOOP_LAW, | |
| "resonant_ingress_trace_law": RESONANT_INGRESS_TRACE_LAW, | |
| "claims_blocked": [ | |
| "not a codec", | |
| "not monolithic compression", | |
| "not a physical hologram generator", | |
| "not source replacement", | |
| "not automatic settlement", | |
| "not provenance laundering", | |
| "not final validation without human review" | |
| ], | |
| "anti_laundering_rules": ANTI_LAUNDERING_RULES | |
| } | |
| human_validation = { | |
| "capsule_type": "HUMAN_VALIDATION_CAPSULE", | |
| "human_validation_state": "REQUIRED", | |
| "machine_route_surface": "GENERATED", | |
| "settlement_authority": "HUMAN", | |
| "available_actions": [ | |
| "APPROVE", | |
| "REJECT", | |
| "DEFER", | |
| "REPAIR", | |
| "FORK", | |
| "QUARANTINE", | |
| "REQUEST_MORE_ATOMS" | |
| ], | |
| "settlement_note": "Machine generated route surface only. Human retains settlement authority.", | |
| "review_questions": [ | |
| "What arrived?", | |
| "What held?", | |
| "What degraded?", | |
| "What provenance survived?", | |
| "What needs repair?", | |
| "What still requires human validation?" | |
| ] | |
| } | |
| write_json(manifests_dir / "source_video_capsule.json", source_capsule) | |
| write_json(manifests_dir / "atom_manifest.json", atom_manifest) | |
| write_json(manifests_dir / "trace_stack_data_hologram_manifest.json", trace_stack) | |
| write_json(manifests_dir / "source_bound_data_hologram_v0_2.json", data_hologram) | |
| write_json(manifests_dir / "motion_atoms.json", motion_atoms) | |
| write_json(receipts_dir / "hir_oam_video_atomization_receipt.json", receipt) | |
| write_json(receipts_dir / "human_validation_capsule.json", human_validation) | |
| (receipts_dir / "HIR_OAM_VIDEO_RECEIPT.md").write_text( | |
| build_markdown_receipt(receipt, source_capsule, trace_stack, data_hologram), | |
| encoding="utf-8" | |
| ) | |
| frame_df = pd.DataFrame(frame_atoms) | |
| scene_df = pd.DataFrame(scene_atoms) | |
| packet_path = create_run_packet(run_dir) | |
| summary = ( | |
| f"Route complete. Source held. {len(frame_atoms)} frame atoms, " | |
| f"{len(scene_atoms)} scene atoms, {len(motion_atoms)} motion atoms. " | |
| "Trace stack formed. Data Hologram v0.2 review surface generated. Provenance remains receipt-bound. Human validation required." | |
| ) | |
| preview_path = make_preview_mp4(source_video_path, run_dir) | |
| return ( | |
| preview_path, | |
| source_capsule, | |
| frame_df, | |
| scene_df, | |
| data_hologram, | |
| trace_stack, | |
| receipt, | |
| human_validation, | |
| gallery_items, | |
| packet_path, | |
| summary | |
| ) | |
| custom_css = """ | |
| .gradio-container { max-width: 1280px !important; } | |
| #receipt_summary textarea { font-size: 1.05rem; } | |
| """ | |
| with gr.Blocks(title=APP_TITLE, css=custom_css) as demo: | |
| gr.Markdown( | |
| """ | |
| # Substrate Video Atomization Runtime v0.1.1 | |
| Upload a short video and run a source-bound atomization route. | |
| This Space hashes the source video, samples frame atoms, detects scene intervals, records motion-delta pressure, | |
| applies trace capsules, stacks the traces into Data Hologram v0.2, and returns an HIR × OAM receipt. | |
| **Boundary:** this is not video compression, not a codec replacement, and not a physical hologram generator. | |
| This release demonstrates atomized transfer, source-return rehydration, provenance-aware receipts, and human validation. | |
| **Operating law:** media pressure → atom gate → frame/scene/motion capsule → transfer route → rehydration surface → receipt → human validation. | |
| """ | |
| ) | |
| with gr.Row(): | |
| video_input = gr.File( | |
| label="Upload source video file", | |
| file_types=["video", ".mp4", ".mov", ".webm", ".mkv"], | |
| type="filepath" | |
| ) | |
| video_output = gr.Video( | |
| label="Source video preview / rehydrated browser-safe MP4", | |
| format="mp4", | |
| interactive=False | |
| ) | |
| preview_status = gr.Textbox( | |
| label="Preview Status", | |
| value="Upload a video to rehydrate a browser-safe source preview.", | |
| interactive=False | |
| ) | |
| with gr.Row(): | |
| sample_every_seconds = gr.Slider( | |
| minimum=0.25, | |
| maximum=5.0, | |
| value=1.0, | |
| step=0.25, | |
| label="Sample every N seconds" | |
| ) | |
| scene_threshold = gr.Slider( | |
| minimum=5.0, | |
| maximum=90.0, | |
| value=32.0, | |
| step=1.0, | |
| label="Scene boundary motion threshold" | |
| ) | |
| max_frame_atoms = gr.Slider( | |
| minimum=4, | |
| maximum=160, | |
| value=72, | |
| step=4, | |
| label="Maximum frame atoms" | |
| ) | |
| run_btn = gr.Button("Run Video Atomization Route", variant="primary") | |
| route_summary = gr.Textbox( | |
| label="Route Summary", | |
| elem_id="receipt_summary", | |
| interactive=False | |
| ) | |
| gr.Markdown( | |
| """ | |
| ### Receipt Boundary | |
| `SOURCE_VIDEO_REMAINS_AUTHORITY` · `PROVENANCE_IS_PART_OF_THE_DATA` · `REHYDRATION_SURFACE_ONLY` · `HUMAN_VALIDATION_REQUIRED` | |
| """ | |
| ) | |
| with gr.Tabs(): | |
| with gr.Tab("Source Capsule"): | |
| source_json = gr.JSON(label="Source Video Capsule") | |
| with gr.Tab("Frame Atoms"): | |
| frame_table = gr.Dataframe(label="Frame Trace Capsules", wrap=True) | |
| with gr.Tab("Scene Atoms"): | |
| scene_table = gr.Dataframe(label="Scene Trace Capsules", wrap=True) | |
| with gr.Tab("Data Hologram v0.2"): | |
| data_hologram_json = gr.JSON(label="Source-Bound Data Hologram Manifest") | |
| with gr.Tab("Trace Stack"): | |
| trace_json = gr.JSON(label="Stacked Trace Field") | |
| with gr.Tab("HIR × OAM Receipt"): | |
| receipt_json = gr.JSON(label="Route Receipt") | |
| with gr.Tab("Human Validation"): | |
| validation_json = gr.JSON(label="Human Validation Capsule") | |
| with gr.Tab("Frame Atom Strip"): | |
| gallery = gr.Gallery(label="Sampled Frame Atoms", columns=4, height=520) | |
| with gr.Tab("Download Run Packet"): | |
| run_packet = gr.File(label="Download JSON receipts and sampled frame atoms") | |
| video_input.change( | |
| prepare_video_preview, | |
| inputs=[video_input], | |
| outputs=[video_output, preview_status] | |
| ) | |
| run_btn.click( | |
| atomize_video, | |
| inputs=[video_input, sample_every_seconds, scene_threshold, max_frame_atoms], | |
| outputs=[ | |
| video_output, | |
| source_json, | |
| frame_table, | |
| scene_table, | |
| data_hologram_json, | |
| trace_json, | |
| receipt_json, | |
| validation_json, | |
| gallery, | |
| run_packet, | |
| route_summary | |
| ] | |
| ) | |
| if __name__ == "__main__": | |
| demo.launch( | |
| server_name="0.0.0.0", | |
| server_port=int(os.environ.get("PORT", "7860")), | |
| show_error=True, | |
| ) |