351 lines
20 KiB
Python
351 lines
20 KiB
Python
#!/usr/bin/env python3
|
|
"""Bounded CPU-only recovery export; no AI, no models, never edits the source pack."""
|
|
import argparse
|
|
import copy
|
|
from decimal import Decimal
|
|
from fractions import Fraction
|
|
import hashlib
|
|
import json
|
|
import math
|
|
from pathlib import Path
|
|
import shutil
|
|
import subprocess
|
|
|
|
import numpy as np
|
|
from PIL import Image, ImageDraw, ImageFont
|
|
|
|
ROOT = Path(__file__).resolve().parents[1]
|
|
FFMPEG = '/home/ubuntu/gori-bin/ffmpeg'
|
|
FFPROBE = '/home/ubuntu/miniconda3/envs/gori-speech/bin/ffprobe'
|
|
LEVELS = np.array([0, .25, .5, .75, 1.])
|
|
|
|
|
|
def require(condition, reason):
|
|
if not condition:
|
|
raise ValueError(reason)
|
|
|
|
|
|
def digest(path):
|
|
with Path(path).open('rb') as stream:
|
|
return hashlib.file_digest(stream, 'sha256').hexdigest()
|
|
|
|
|
|
def write_json(path, data):
|
|
with path.open('x') as stream:
|
|
json.dump(data, stream, indent=2)
|
|
stream.write('\n')
|
|
|
|
|
|
def safe_file(root, name):
|
|
require(isinstance(name, str) and not name.startswith('/') and
|
|
all(part not in ('', '.', '..') for part in name.split('/')), 'relative file required')
|
|
path = (root/name).resolve(strict=True)
|
|
require(path.is_relative_to(root.resolve()) and path.is_file(), 'file escape')
|
|
return path
|
|
|
|
|
|
def decode(path, body):
|
|
probe = json.loads(subprocess.check_output([FFPROBE, '-v', 'error', '-show_streams',
|
|
'-show_frames', '-of', 'json', str(path)], timeout=60))
|
|
require(len(probe['streams']) == 1, 'silent single video track required')
|
|
stream = probe['streams'][0]
|
|
require(stream['codec_name'] == 'h264' and (stream['width'], stream['height']) == (480, 848), 'body shape/codec')
|
|
us = lambda value: int((Decimal(value)*1_000_000).to_integral_value())
|
|
pts = [us(frame['best_effort_timestamp_time']) for frame in probe['frames']]
|
|
require(pts == body['ptsUs'] and len(pts) == body['frameCount'], 'actual N/PTS mismatch')
|
|
require(us(stream['duration']) == body['durationUs'] and
|
|
Fraction(stream['r_frame_rate']) == Fraction(body['fpsNumerator'], body['fpsDenominator']), 'actual timing mismatch')
|
|
require(digest(path) == body['sha256'], 'body bytes changed')
|
|
raw = subprocess.check_output([FFMPEG, '-nostdin', '-v', 'error', '-xerror', '-i', str(path),
|
|
'-map', '0:v:0', '-pix_fmt', 'rgb24', '-f', 'rawvideo', '-'], timeout=60)
|
|
frames = np.frombuffer(raw, np.uint8).reshape(-1, 848, 480, 3)
|
|
require(len(frames) == body['frameCount'], 'full decode N')
|
|
return frames
|
|
|
|
|
|
def make_patches(frames, pts, destination):
|
|
"""Same source-seam deformation method as owner runtime04, local ROI arithmetic."""
|
|
first = frames[0].astype(float)
|
|
roi = first[103:137, 202:265]
|
|
score = roi[:, :, 0]-roi[:, :, 1]+.20*(255-roi.mean(axis=2))
|
|
ys, xs = np.where(score > np.percentile(score, 88))
|
|
cx, cy = float(np.median(xs)+202), float(np.median(ys)+103)
|
|
require(210 < cx < 252 and 111 < cy < 133, 'own first-frame lip center outside fixture bounds')
|
|
x0, x1, y0, y1 = int(cx-31), int(cx+32), int(cy-30), int(cy+17)
|
|
reference = first[y0:y1, x0:x1].mean(axis=2)
|
|
yy, xx = np.mgrid[y0:y1, x0:x1]
|
|
tracking_mask = ((yy < cy-9) | (xx < cx-22) | (xx > cx+23)) & (yy < cy+12)
|
|
patches, tracks = [], []
|
|
for i, frame in enumerate(frames):
|
|
f = frame.astype(float)
|
|
gray = f.mean(axis=2)
|
|
scores = {}
|
|
for dy in range(-8, 9):
|
|
for dx in range(-14, 15):
|
|
diff = gray[y0+dy:y1+dy, x0+dx:x1+dx]-reference
|
|
diff -= diff[tracking_mask].mean()
|
|
scores[dx, dy] = float((diff[tracking_mask]**2).mean())
|
|
dx, dy = min(scores, key=scores.get)
|
|
require(abs(dx) < 14 and abs(dy) < 8, 'tracking hit search boundary; manual review required')
|
|
cxi, cyi = cx+dx, cy+dy
|
|
left, right = int(round(cxi-15)), int(round(cxi+15))
|
|
curve = []
|
|
for x in range(left, right+1):
|
|
rows = np.arange(int(round(cyi-4)), int(round(cyi+5)))
|
|
pixels = f[rows, x]
|
|
darkness = pixels.mean(axis=1)-.6*(pixels[:, 0]-pixels[:, 1])
|
|
curve.append(float(rows[np.argmin(darkness)]))
|
|
curve = np.convolve(np.pad(curve, 2, mode='edge'), np.ones(5)/5, mode='valid')
|
|
# These bounds contain the same mask>.005 support as the owner's full-frame computation.
|
|
Y, X = np.mgrid[int(cyi)-22:int(cyi)+23, int(cxi)-19:int(cxi)+20]
|
|
seam = np.interp(X, np.arange(left, right+1), curve)
|
|
dist = Y-seam
|
|
taper = np.clip(1-((X-cxi)/17)**2, 0, 1)**1.5
|
|
vertical = np.exp(-(dist/5)**2)
|
|
mask = taper*vertical
|
|
support_y, support_x = np.where(mask > .005)
|
|
ys = slice(support_y.min(), support_y.max()+1)
|
|
xs = slice(support_x.min(), support_x.max()+1)
|
|
bx, by = int(X[ys, xs].min()), int(Y[ys, xs].min())
|
|
height, width = mask[ys, xs].shape
|
|
require(width <= 128 and height <= 128, 'patch shape cap')
|
|
levels = []
|
|
for li, aperture in enumerate(LEVELS):
|
|
gap = aperture*1.1*taper
|
|
source_y = np.clip(Y-np.where(dist >= 0, gap*.65, -gap*.35)*vertical, 0, 847)
|
|
j0 = np.floor(source_y).astype(int)
|
|
j1 = np.minimum(j0+1, 847)
|
|
fraction = (source_y-j0)[..., None]
|
|
warped = f[j0, X]*(1-fraction)+f[j1, X]*fraction
|
|
seam_rows = np.clip(np.rint(seam).astype(int), 0, 847)
|
|
interior = f[seam_rows, X]*.65
|
|
inside = np.clip((gap*.55-np.abs(dist-.05*aperture))/.6, 0, 1)*taper
|
|
warped = warped*(1-inside[..., None])+interior*inside[..., None]
|
|
if li == 0:
|
|
warped = f[Y, X]
|
|
rgba = np.dstack([np.rint(warped[ys, xs]).astype(np.uint8),
|
|
np.rint(mask[ys, xs]*255).astype(np.uint8)])
|
|
name = f'patches/{i:03d}-l{li}.png'
|
|
Image.fromarray(rgba).save(destination/name)
|
|
levels.append({'levelIndex': li, 'aperture': float(aperture), 'path': name,
|
|
'sha256': digest(destination/name)})
|
|
patches.append({'frameIndex': i, 'ptsUs': pts[i], 'x': bx, 'y': by,
|
|
'width': width, 'height': height, 'path': levels[4]['path'], 'sha256': levels[4]['sha256'],
|
|
'levels': levels, 'observedLipSeamPixels': curve.tolist(), 'seamSourceXRange': [left, right+1]})
|
|
tracks.append({'frameIndex': i, 'ptsUs': pts[i], 'dx': dx, 'dy': dy,
|
|
'ssd': scores[dx, dy], 'searchBoundary': False})
|
|
return patches, tracks, [cx, cy]
|
|
|
|
|
|
def compose(frame, patch, runtime, level):
|
|
if level == 0:
|
|
return frame
|
|
rgba = np.asarray(Image.open(runtime/patch['levels'][level]['path']).convert('RGBA'))
|
|
x, y, w, h = (patch[k] for k in ('x', 'y', 'width', 'height'))
|
|
output = frame.copy()
|
|
alpha = rgba[:, :, 3:4]/255.
|
|
output[y:y+h, x:x+w] = np.clip(np.rint(frame[y:y+h, x:x+w]*(1-alpha)+rgba[:, :, :3]*alpha), 0, 255).astype(np.uint8)
|
|
return output
|
|
|
|
|
|
def encode(frames, path, width=480, height=848):
|
|
proc = subprocess.Popen([FFMPEG, '-nostdin', '-n', '-v', 'error', '-xerror', '-f', 'rawvideo',
|
|
'-pix_fmt', 'rgb24', '-s', f'{width}x{height}', '-r', '24', '-i', '-', '-an', '-c:v',
|
|
'libx264', '-threads', '2', '-crf', '16', '-pix_fmt', 'yuv420p', '-g', '12', '-movflags', '+faststart', str(path)], stdin=subprocess.PIPE)
|
|
try:
|
|
for frame in frames:
|
|
proc.stdin.write(frame.tobytes())
|
|
finally:
|
|
proc.stdin.close()
|
|
require(proc.wait() == 0, 'preview encoder failed')
|
|
subprocess.run([FFMPEG, '-nostdin', '-v', 'error', '-xerror', '-i', str(path), '-f', 'null', '-'], check=True, timeout=60)
|
|
|
|
|
|
def previews(index, output, bodies, runtimes):
|
|
font = ImageFont.truetype('/usr/share/fonts/truetype/dejavu/DejaVuSans.ttf', 13)
|
|
all_items, trace = [], []
|
|
for edge in index['edges']:
|
|
if edge.get('nativeLoop'):
|
|
continue
|
|
own = runtimes['bridge:'+edge['id']]
|
|
source = runtimes[edge['from']]
|
|
target = runtimes[edge['to']]
|
|
items = [(edge['from'], (edge['fromFrame']-k) % len(bodies[edge['from']])) for k in range(47, -1, -1)]
|
|
items += [('bridge:'+edge['id'], i) for i in range(len(bodies['bridge:'+edge['id']]))]
|
|
items += [(edge['to'], (edge['toFrame']+k) % len(bodies[edge['to']])) for k in range(48)]
|
|
start = len(all_items)
|
|
all_items.extend(items)
|
|
trace.append({'edgeId': edge['id'], 'startFrame': start, 'bridgeStartFrame': start+48,
|
|
'bridgeEndFrameExclusive': start+48+25, 'endFrameExclusive': len(all_items),
|
|
'syntheticTalk': True, 'realPCM': False, 'realDevice': 'not_run'})
|
|
# Both junctions, own layers kept at the same fixed aperture for seam review.
|
|
dense = items[36:60]+items[61:85]
|
|
require(len(dense) == 48, 'dense junction inventory')
|
|
for view, box, width in [('face', (170, 45, 295, 165), 250), ('full', (0, 0, 480, 848), 180)]:
|
|
height = round((box[3]-box[1])*width/(box[2]-box[0]))
|
|
sheet = Image.new('RGB', (4*width, 12*(height+24)+26), (20, 20, 25))
|
|
draw = ImageDraw.Draw(sheet)
|
|
draw.text((3, 3), edge['id']+' own mouths at level3 / candidate', font=font, fill='white')
|
|
for k, (key, i) in enumerate(dense):
|
|
root, manifest = runtimes[key]
|
|
frame = compose(bodies[key][i], manifest['patches'][i], root, 3)
|
|
x, y = k % 4*width, k//4*(height+24)+26
|
|
sheet.paste(Image.fromarray(frame).crop(box).resize((width, height)), (x, y))
|
|
draw.text((x+3, y+height+2), f'{key[:19]} f{i}', font=font, fill='white')
|
|
sheet.save(output/'review'/f'{edge["id"]}-{view}-talk-junctions.png')
|
|
# All25 frames and all5 levels: engineering localization/shape evidence.
|
|
sheet = Image.new('RGB', (5*180, 25*144), (20, 20, 25))
|
|
draw = ImageDraw.Draw(sheet)
|
|
for i in range(25):
|
|
for level in range(5):
|
|
frame = compose(bodies['bridge:'+edge['id']][i], own[1]['patches'][i], own[0], level)
|
|
sheet.paste(Image.fromarray(frame).crop((190, 98, 272, 148)).resize((180, 110)), (level*180, i*144))
|
|
draw.text((level*180+2, i*144+112), f'f{i} L{level} / own1.1px', font=font, fill='white')
|
|
sheet.save(output/'review'/f'{edge["id"]}-all25-fivelevels.png')
|
|
# Four isolated five-second windows, each has true source→bridge→target cursors.
|
|
# Between windows the cut is explicitly a new independent fixture, not a graph edge.
|
|
require(len(all_items) == 484, '20.167s preview frame count')
|
|
def render(annotated=False, mouth=False):
|
|
for k, (key, i) in enumerate(all_items):
|
|
root, manifest = runtimes[key]
|
|
# Synthetic TALK crosses every bridge; one phase per window, not reset at boundaries.
|
|
local = k % 121
|
|
alpha = .5-.5*math.cos(math.pi*local/5) if local < 6 else 1-.88*math.sin(2*math.pi*((local-6) % 12)/11)**2
|
|
level = int(np.argmin(np.abs(LEVELS-alpha)))
|
|
frame = compose(bodies[key][i], manifest['patches'][i], root, level)
|
|
if annotated:
|
|
image = Image.fromarray(frame.copy())
|
|
draw = ImageDraw.Draw(image)
|
|
draw.rectangle((0, 0, 479, 58), fill=(20, 20, 25))
|
|
draw.text((3, 3), 'SYNTHETIC TALK / NO PCM / NOT DEVICE', font=font, fill='white')
|
|
draw.text((3, 21), f'window{k//121+1} t{k/24:.3f}s {key[:31]} f{i} L{level}', font=font, fill='white')
|
|
draw.text((3, 39), 'independent windows; ownbody/ownbridge; pending Pi', font=font, fill='white')
|
|
frame = np.asarray(image)
|
|
if mouth:
|
|
frame = np.asarray(Image.fromarray(frame).crop((190, 98, 272, 148)).resize((656, 400)))
|
|
yield frame
|
|
encode(render(), output/'review/bridge-talk-20s-clean.mp4')
|
|
encode(render(annotated=True), output/'review/bridge-talk-20s-annotated.mp4')
|
|
encode(render(mouth=True), output/'review/bridge-talk-20s-mouth.mp4', 656, 400)
|
|
write_json(output/'review/synthetic-intent-trace.json', {'fps': 24, 'frames': len(all_items), 'durationSeconds': len(all_items)/24,
|
|
'windowCuts': 'four independent fixtures, not continuous graph edges', 'windows': trace,
|
|
'TTSintentOnly': True, 'audio': False, 'naturalness': 'not_certified'})
|
|
|
|
|
|
def finalize(source, source_sha, output, old):
|
|
index=copy.deepcopy(old)
|
|
bridge_reports=[]
|
|
for edge in index['edges']:
|
|
if edge.get('nativeLoop'): continue
|
|
path=output/'runtime-bridges'/edge['id']/'manifest.json'
|
|
runtime=json.loads(path.read_bytes());body=runtime['body']
|
|
require(body['sha256']==edge['clip']['sha256'] and body['ptsUs']==edge['clip']['ptsUs'],'recovery binding drift')
|
|
require(digest(path.parent/body['path'])==body['sha256'],'recovery body drift')
|
|
for patch in runtime['patches']:
|
|
for level in patch['levels']:
|
|
require(digest(path.parent/level['path'])==level['sha256'],'recovery patch drift')
|
|
edge['mouthRuntimeManifest']={'path':str(path.relative_to(output)),'sha256':digest(path)}
|
|
edge['mouthAllowed']=True
|
|
bridge_reports.append({'edgeId':edge['id'],'bodySha256':body['sha256'],'N':body['frameCount'],'ptsUs':body['ptsUs'],'runtimeSha256':digest(path),'ownPatchCount':len(runtime['patches'])*5,'rgbaBytes':sum(p['width']*p['height']*4*5 for p in runtime['patches']),'firstFrameLipCenter':runtime['sourceSpecificLipLocalization']['firstFrameCenter']})
|
|
for row in old['files']:
|
|
require(digest(safe_file(output,row['path']))==row['sha256'],'copied source payload drift')
|
|
for name in ('bridge-talk-20s-clean.mp4','bridge-talk-20s-annotated.mp4','bridge-talk-20s-mouth.mp4'):
|
|
require((output/'review'/name).stat().st_size>0,'preview absent')
|
|
(output/'docs').mkdir(exist_ok=True)
|
|
write_json(output/'docs/free-recovery-provenance.json', {'sourceIndexSha256': source_sha,
|
|
'exportScriptSha256': digest(Path(__file__)), 'methodReusedFrom': 'asset owner build_own_mouth_current.py',
|
|
'methodSourceSha256': digest(source.parent.parent/'docs/build_own_mouth_current.py'),
|
|
'sourcePayloadUnmodified': True, 'reusedPixelsFromEndpoint': False,
|
|
'controlCurves': 'same authored scalar phase contract; every bridge has own serialized state PTS; only control timing reused',
|
|
'sourceVideosUnchanged': True, 'AIcalls': 0, 'knownFeeUSD': 0, 'bridgeReports': bridge_reports,
|
|
'naturalness': 'pending_independent_Pi', 'realDevice': 'not_run'})
|
|
index['reviewStatus'] = 'recovery_bridge_own_mouth_pending_new_exact_Pi_pin'
|
|
index['advancedGateKeep'] = False
|
|
index['publishApproval'] = False
|
|
index['sceneTimeline'] = 'See review/synthetic-intent-trace.json; four separate TALK windows, not full graph execution'
|
|
index['files'] = [{'path': str(path.relative_to(output)), 'sha256': digest(path), 'bytes': path.stat().st_size}
|
|
for path in sorted(output.rglob('*')) if path.is_file() and path != output/'manifest.json']
|
|
write_json(output/'manifest.json', index)
|
|
|
|
|
|
def main():
|
|
parser = argparse.ArgumentParser(description=__doc__)
|
|
parser.add_argument('--source-manifest', type=Path, required=True)
|
|
parser.add_argument('--source-sha', required=True)
|
|
parser.add_argument('--output', type=Path, required=True)
|
|
parser.add_argument('--finish-existing',action='store_true',help='Finish metadata only after an interrupted export; all original/own file hashes still verified')
|
|
args = parser.parse_args()
|
|
source = args.source_manifest.resolve(strict=True)
|
|
output = args.output.resolve()
|
|
require(digest(source) == args.source_sha, 'old index drift')
|
|
require(not output.is_relative_to(source.parent) and not (output/'manifest.json').exists(), 'new independent index required')
|
|
require(args.finish_existing or not output.exists(),'existing output preserved; explicit metadata finish only')
|
|
old = json.loads(source.read_bytes())
|
|
require(old['actions'] == [] and len(old['edges']) == 7, 'only current partial P4a recovery')
|
|
for row in old['files']:
|
|
path = safe_file(source.parent, row['path'])
|
|
require(digest(path) == row['sha256'] and path.stat().st_size == row['bytes'], 'old indexed file drift')
|
|
if args.finish_existing:
|
|
finalize(source,args.source_sha,output,old)
|
|
require(digest(source)==args.source_sha,'old index drift')
|
|
print('RECOVERY_BRIDGE_INDEX_READY',digest(output/'manifest.json'),flush=True)
|
|
return
|
|
output.mkdir(parents=True)
|
|
for row in old['files']:
|
|
destination = output/row['path']
|
|
destination.parent.mkdir(parents=True, exist_ok=True)
|
|
shutil.copyfile(safe_file(source.parent, row['path']), destination)
|
|
index = copy.deepcopy(old)
|
|
bodies, runtimes = {}, {}
|
|
for row in index['conversationPackages']:
|
|
path = output/row['runtimeManifest']['path']
|
|
runtime = json.loads(path.read_bytes())
|
|
bodies[row['id']] = decode(path.parent/runtime['body']['path'], runtime['body'])
|
|
runtimes[row['id']] = (path.parent, runtime)
|
|
template = runtimes[index['fallbackPackageId']][1]
|
|
bridge_reports = []
|
|
for edge in index['edges']:
|
|
if edge.get('nativeLoop'):
|
|
continue
|
|
clip = edge['clip']
|
|
require(clip['frameCount'] == 25, 'current bridge actual25 required')
|
|
frames = decode(output/clip['path'], clip)
|
|
destination = output/'runtime-bridges'/edge['id']
|
|
for folder in ('body', 'patches', 'docs'):
|
|
(destination/folder).mkdir(parents=True)
|
|
shutil.copyfile(output/clip['path'], destination/'body/bridge.mp4')
|
|
patches, tracking, center = make_patches(frames, clip['ptsUs'], destination)
|
|
body = dict(clip, path='body/bridge.mp4')
|
|
runtime = {'schemaVersion': 2, 'identityId': 'a01', 'packId': 'a01-expression-action-v1-'+edge['id']+'-runtime-04',
|
|
'publishApproval': False, 'runtimeReady': True, 'naturalQualityStatus': 'pending_independent_Pi',
|
|
'advancedGateKeep': False, 'rightsStatus': 'unknown', 'deviceTestStatus': 'not_run',
|
|
'playbackMode': 'one_shot', 'body': body, 'patchFormat': {
|
|
'bodySha256': body['sha256'], 'format': 'PNG RGBA 8bit', 'alphaEncoding': 'straight_unassociated',
|
|
'apertureLevels': LEVELS.tolist(), 'requiresRendererExtension': True,
|
|
'loopMapping': 'actual displayed bridge frame index only; no wrap'},
|
|
'patches': patches, 'mouthStates': copy.deepcopy(template['mouthStates']),
|
|
'stateRouting': copy.deepcopy(template['stateRouting']), 'amplitudeSourcePx': 1.1,
|
|
'sourceSpecificLipLocalization': {'firstFrameCenter': center, 'method': 'own first-frame red/dark lip ROI; own cheek/nose SSD; own per-frame lip seam',
|
|
'neutralPatchReuse': False, 'trackingBoundaryFrames': []},
|
|
'additionalAICalls': 0, 'knownAdditionalFeeUSD': 0}
|
|
write_json(destination/'manifest.json', runtime)
|
|
write_json(destination/'docs/tracking.json', tracking)
|
|
edge['mouthRuntimeManifest'] = {'path': str((destination/'manifest.json').relative_to(output)), 'sha256': digest(destination/'manifest.json')}
|
|
edge['mouthAllowed'] = True
|
|
bodies['bridge:'+edge['id']] = frames
|
|
runtimes['bridge:'+edge['id']] = (destination, runtime)
|
|
bridge_reports.append({'edgeId': edge['id'], 'bodySha256': body['sha256'], 'N': len(frames), 'ptsUs': body['ptsUs'],
|
|
'runtimeSha256': digest(destination/'manifest.json'), 'ownPatchCount': len(patches)*5,
|
|
'rgbaBytes': sum(p['width']*p['height']*4*5 for p in patches), 'firstFrameLipCenter': center})
|
|
print('BRIDGE_OWN_MOUTH_EXPORTED', edge['id'], edge['mouthRuntimeManifest']['sha256'], flush=True)
|
|
previews(index, output, bodies, runtimes)
|
|
finalize(source,args.source_sha,output,old)
|
|
require(digest(source) == args.source_sha, 'old index changed during recovery')
|
|
for row in old['files']:
|
|
require(digest(safe_file(source.parent, row['path'])) == row['sha256'], 'old source payload changed during recovery')
|
|
print('RECOVERY_BRIDGE_INDEX_READY', digest(output/'manifest.json'), 'files', len(index['files']), flush=True)
|
|
|
|
|
|
if __name__ == '__main__':
|
|
main()
|