File size: 32,837 Bytes
290b2ed ebf1ba6 290b2ed 2ea449e 290b2ed ebf1ba6 290b2ed 4ba4ac9 290b2ed 4ba4ac9 290b2ed ebf1ba6 290b2ed 4ba4ac9 290b2ed 4ba4ac9 290b2ed 4ba4ac9 290b2ed 4ba4ac9 290b2ed 4ba4ac9 290b2ed ebf1ba6 290b2ed 4ba4ac9 290b2ed ebf1ba6 290b2ed ebf1ba6 290b2ed ebf1ba6 290b2ed 4ba4ac9 290b2ed 4ba4ac9 290b2ed 4ba4ac9 290b2ed 4ba4ac9 290b2ed 4ba4ac9 290b2ed 4ba4ac9 290b2ed 4ba4ac9 290b2ed 4ba4ac9 290b2ed 4ba4ac9 290b2ed 4ba4ac9 290b2ed 4ba4ac9 290b2ed 4ba4ac9 290b2ed 4ba4ac9 290b2ed 4ba4ac9 290b2ed 4ba4ac9 290b2ed 4ba4ac9 290b2ed 4ba4ac9 290b2ed 4ba4ac9 290b2ed ebf1ba6 290b2ed ebf1ba6 290b2ed 4ba4ac9 290b2ed ebf1ba6 290b2ed 4ba4ac9 290b2ed 4ba4ac9 290b2ed ebf1ba6 4ba4ac9 290b2ed ebf1ba6 290b2ed 4ba4ac9 290b2ed 4ba4ac9 290b2ed ebf1ba6 290b2ed 4ba4ac9 290b2ed 2ea449e c39471d 2ea449e | 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 214 215 216 217 218 219 220 221 222 223 224 225 226 227 228 229 230 231 232 233 234 235 236 237 238 239 240 241 242 243 244 245 246 247 248 249 250 251 252 253 254 255 256 257 258 259 260 261 262 263 264 265 266 267 268 269 270 271 272 273 274 275 276 277 278 279 280 281 282 283 284 285 286 287 288 289 290 291 292 293 294 295 296 297 298 299 300 301 302 303 304 305 306 307 308 309 310 311 312 313 314 315 316 317 318 319 320 321 322 323 324 325 326 327 328 329 330 331 332 333 334 335 336 337 338 339 340 341 342 343 344 345 346 347 348 349 350 351 352 353 354 355 356 357 358 359 360 361 362 363 364 365 366 367 368 369 370 371 372 373 374 375 376 377 378 379 380 381 382 383 384 385 386 387 388 389 390 391 392 393 394 395 396 397 398 399 400 401 402 403 404 405 406 407 408 409 410 411 412 413 414 415 416 417 418 419 420 421 422 423 424 425 426 427 428 429 430 431 432 433 434 435 436 437 438 439 440 441 442 443 444 445 446 447 448 449 450 451 452 453 454 455 456 457 458 459 460 461 462 463 464 465 466 467 468 469 470 471 472 473 474 475 476 477 478 479 480 481 482 483 484 485 486 487 488 489 490 491 492 493 494 495 496 497 498 499 500 501 502 503 504 505 506 507 508 509 510 511 512 513 514 515 516 517 518 519 520 521 522 523 524 525 526 527 528 529 530 531 532 533 534 535 536 537 538 539 540 541 542 543 544 545 546 547 548 549 550 551 552 553 554 555 556 557 558 559 560 561 562 563 564 565 566 567 568 569 570 571 572 573 574 575 576 577 578 579 580 581 582 583 584 585 586 587 588 589 590 591 592 593 594 595 596 597 598 599 600 601 602 603 604 605 606 607 608 609 610 611 612 613 614 615 616 617 618 619 620 621 622 623 624 625 626 627 628 629 630 631 632 633 634 635 636 637 638 639 640 641 642 643 644 645 646 647 648 649 650 651 652 653 654 655 656 657 658 659 660 661 662 663 664 665 666 667 668 669 670 671 672 673 674 675 676 677 678 679 680 681 682 683 684 685 686 687 688 689 690 691 692 693 694 695 696 697 698 699 700 701 702 703 704 705 706 707 708 709 710 711 712 713 714 715 716 717 718 719 720 721 722 723 724 725 726 727 728 729 730 731 732 733 734 735 736 737 738 739 740 741 742 743 744 745 746 747 748 749 750 751 752 753 754 755 756 757 758 759 760 761 762 763 764 765 766 767 768 769 770 771 772 773 774 775 776 777 778 779 780 781 782 783 784 785 786 787 788 789 790 791 792 793 794 795 796 797 798 799 800 801 802 803 804 805 806 807 808 809 810 811 812 813 814 815 816 817 818 819 820 821 822 823 824 825 826 827 828 829 830 831 832 833 834 835 836 837 838 839 840 841 842 843 844 845 846 847 848 849 850 851 852 853 854 855 856 857 858 859 860 861 862 863 864 865 866 867 868 869 870 871 | 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,
) |