# ZMF Studios 0.2 integration. Generated from editable modules in source/. import json as _json import tempfile as _tempfile from pathlib import Path as _Path import sys as _sys _zmf_modules = _Path(_tempfile.mkdtemp(prefix='zmf-runtime-')) _zmf_sources = {'core': '"""ZMF full-body research pipeline. CPU stages do not download or run AI."""\nfrom __future__ import annotations\nimport hashlib\nimport json\nimport math\nimport os\nfrom pathlib import Path\nimport shutil\nimport subprocess\nimport tempfile\nimport uuid\nimport zipfile\n\nMODEL_ID = \'Wan-AI/Wan2.2-Animate-14B-Diffusers\'\nMODEL_REVISION = \'6f4df10861c758af86ac3c979aacc1bf5c03eff0\'\nFPS = 8\nFRAMES = 17\nWIDTH, HEIGHT = 384, 256\nCONTROL_NAMES = (\'src_pose.mp4\', \'src_face.mp4\', \'src_bg.mp4\', \'src_mask.mp4\')\n\n\ndef run(args, timeout=90):\n p = subprocess.run([str(x) for x in args], capture_output=True, text=True, timeout=timeout)\n if p.returncode:\n raise ValueError(\'Media processing failed: \' + p.stderr[-1200:])\n return p.stdout\n\n\ndef probe(path):\n path = Path(path)\n if not path.is_file() or path.stat().st_size > 300 * 1024 * 1024:\n raise ValueError(\'Choose a local clip smaller than 300 MB.\')\n data = json.loads(run([\'ffprobe\', \'-v\', \'error\', \'-count_frames\', \'-select_streams\', \'v:0\',\n \'-show_entries\', \'stream=width,height,avg_frame_rate,nb_read_frames,duration:format=duration\',\n \'-of\', \'json\', path]))\n if not data.get(\'streams\'):\n raise ValueError(\'No decodable video stream was found.\')\n s = data[\'streams\'][0]\n a, b = s.get(\'avg_frame_rate\', \'0/1\').split(\'/\')\n fps = float(a) / max(float(b), 1)\n duration = float(s.get(\'duration\', data.get(\'format\', {}).get(\'duration\', 0)))\n return dict(width=int(s[\'width\']), height=int(s[\'height\']), fps=fps,\n frames=int(s.get(\'nb_read_frames\', 0)), duration=duration)\n\n\ndef digest(path):\n h = hashlib.sha256()\n with open(path, \'rb\') as f:\n for block in iter(lambda: f.read(1024 * 1024), b\'\'):\n h.update(block)\n return h.hexdigest()\n\n\ndef write_manifest(folder, values):\n folder = Path(folder)\n path = folder / \'job.json\'\n current = json.loads(path.read_text()) if path.exists() else {}\n current.update(values)\n tmp = folder / \'job.json.tmp\'\n tmp.write_text(json.dumps(current, indent=2))\n os.replace(tmp, path)\n return current\n\n\ndef prepare(clip, reference, root, start=0, permission=False):\n if not permission:\n raise ValueError(\'Confirm permission to use the footage and likeness.\')\n start = float(start)\n if not math.isfinite(start) or start < 0:\n raise ValueError(\'Start time must be a finite nonnegative number.\')\n info = probe(clip)\n if info[\'duration\'] < start + FRAMES / FPS:\n raise ValueError(\'Select a range with at least 2.125 seconds remaining.\')\n # Preserve source aspect ratio with letterboxing; never stretch a camera-roll clip.\n w, h = (HEIGHT, WIDTH) if info[\'height\'] > info[\'width\'] else (WIDTH, HEIGHT)\n folder = Path(root) / str(uuid.uuid4())\n folder.mkdir(parents=True)\n write_manifest(folder, dict(schema=\'zmf-fullbody-dev-0.1\', id=folder.name,\n state=\'preparing\', model=MODEL_ID, revision=MODEL_REVISION, trained_by_zmf=False,\n fps=FPS, frames=FRAMES, width=w, height=h, start=start,\n source_sha256=digest(clip), reference_sha256=digest(reference), permission=True,\n payment_fallback=False, gpu_verified=False))\n try:\n scale = f\'scale={w}:{h}:force_original_aspect_ratio=decrease,pad={w}:{h}:(ow-iw)/2:(oh-ih)/2,fps={FPS}\'\n run([\'ffmpeg\', \'-y\', \'-v\', \'error\', \'-ss\', start, \'-i\', clip, \'-vf\', scale,\n \'-frames:v\', FRAMES, \'-an\', \'-c:v\', \'libx264\', \'-pix_fmt\', \'yuv420p\', folder/\'source.mp4\'])\n run([\'ffmpeg\', \'-y\', \'-v\', \'error\', \'-i\', reference, \'-vf\',\n f\'scale={w}:{h}:force_original_aspect_ratio=decrease,pad={w}:{h}:(ow-iw)/2:(oh-ih)/2\',\n \'-frames:v\', \'1\', folder/\'reference.png\'])\n run([\'ffmpeg\', \'-y\', \'-v\', \'error\', \'-i\', folder/\'source.mp4\', \'-frames:v\', \'1\', folder/\'first-frame.png\'])\n if probe(folder/\'source.mp4\')[\'frames\'] != FRAMES:\n raise ValueError(\'Decoder returned fewer frames than required.\')\n write_manifest(folder, {\'state\':\'awaiting_controls\'})\n return folder\n except Exception as e:\n write_manifest(folder, {\'state\':\'failed\', \'error\':str(e)})\n raise\n\n\ndef validate_controls(folder):\n folder = Path(folder)\n j = json.loads((folder/\'job.json\').read_text())\n for name in CONTROL_NAMES:\n p = probe(folder/name)\n if p[\'frames\'] != j[\'frames\'] or abs(p[\'fps\'] - j[\'fps\']) > .01:\n raise ValueError(name + \' must match the prepared clip frame count and FPS.\')\n # Face crops intentionally have their own dimensions in the upstream format.\n if name != \'src_face.mp4\' and (p[\'width\'], p[\'height\']) != (j[\'width\'], j[\'height\']):\n raise ValueError(name + \' has mismatched spatial dimensions.\')\n # A completely empty/full mask cannot meaningfully isolate a character.\n raw = subprocess.run([\'ffmpeg\',\'-v\',\'error\',\'-i\',str(folder/\'src_mask.mp4\'),\n \'-frames:v\',\'1\',\'-f\',\'rawvideo\',\'-pix_fmt\',\'gray\',\'-\'], capture_output=True, check=True).stdout\n fraction = sum(x > 127 for x in raw) / max(len(raw), 1)\n if not .005 < fraction < .95:\n raise ValueError(\'Mask must isolate the whole actor; white generates, black preserves.\')\n return j\n\n\ndef attach_controls(folder, files):\n if len(files) != len(CONTROL_NAMES):\n raise ValueError(\'Pose, face, background and mask controls are all required.\')\n folder = Path(folder)\n write_manifest(folder, {\'state\':\'validating_controls\'})\n try:\n for src, name in zip(files, CONTROL_NAMES):\n shutil.copyfile(src, folder/name)\n validate_controls(folder)\n write_manifest(folder, {\'state\':\'ready_for_gpu\'})\n except Exception as e:\n write_manifest(folder, {\'state\':\'controls_invalid\', \'error\':str(e)})\n raise\n\n\ndef checkpoint(folder):\n folder = Path(folder)\n output = folder.parent / (folder.name + \'.zip\')\n with zipfile.ZipFile(output, \'w\', zipfile.ZIP_DEFLATED) as z:\n for p in folder.iterdir():\n if p.is_file() and p.name in (set(CONTROL_NAMES) | {\'source.mp4\',\'reference.png\',\'first-frame.png\',\'job.json\',\'result.mp4\',\'voice-reference.wav\',\'voice.wav\',\'dialogue.wav\',\'final.mp4\'}):\n z.write(p, p.name)\n return output\n\n\ndef restore(archive, root):\n folder = Path(root) / str(uuid.uuid4())\n folder.mkdir(parents=True)\n allowed = set(CONTROL_NAMES) | {\'source.mp4\',\'reference.png\',\'first-frame.png\',\'job.json\',\'result.mp4\',\'voice-reference.wav\',\'voice.wav\',\'dialogue.wav\',\'final.mp4\'}\n with zipfile.ZipFile(archive) as z:\n if sum(i.file_size for i in z.infolist()) > 500 * 1024 * 1024:\n raise ValueError(\'Checkpoint expands beyond 500 MB.\')\n if len({i.filename for i in z.infolist()}) != len(z.infolist()):\n raise ValueError(\'Duplicate checkpoint entries.\')\n if len(z.infolist()) > len(allowed):\n raise ValueError(\'Too many checkpoint entries.\')\n for entry in z.infolist():\n if entry.filename not in allowed:\n raise ValueError(\'Unexpected checkpoint path.\')\n with z.open(entry) as src, open(folder/entry.filename, \'wb\') as out:\n shutil.copyfileobj(src, out)\n j = json.loads((folder/\'job.json\').read_text())\n if j.get(\'schema\') != \'zmf-fullbody-dev-0.1\' or j.get(\'model\') != MODEL_ID or j.get(\'revision\') != MODEL_REVISION:\n raise ValueError(\'Unsupported checkpoint model/schema.\')\n if j.get(\'frames\') != FRAMES or j.get(\'fps\') != FPS or (j.get(\'width\'),j.get(\'height\')) not in [(WIDTH,HEIGHT),(HEIGHT,WIDTH)]:\n raise ValueError(\'Checkpoint exceeds the fixed test limits.\')\n if not (folder/\'source.mp4\').is_file() or not (folder/\'reference.png\').is_file():\n raise ValueError(\'Checkpoint is missing its source or reference.\')\n # Revalidate all controls before any future GPU request; never trust archived state.\n write_manifest(folder, {\'id\':folder.name, \'state\':\'restored_unverified\', \'gpu_verified\':False})\n return folder\n', 'assets': '"""Public, revision-pinned model downloads. No inference APIs or paid fallback."""\nfrom pathlib import Path\nimport os\nimport zipfile\nimport urllib.request\nimport shutil\nimport core\n\nCACHE = Path(os.getenv(\'ZMF_MODEL_CACHE\', str(Path.home()/\'.cache/zmf\')))\nWAN_SHA = \'1ea34ff48f87168174e12956e200b1d908b1c5ff\'\nPREP_ID = \'Wan-AI/Wan2.2-Animate-14B\'\nPREP_SHA = \'cb93a225fbaf1ca100f54e79da8f994995b689b3\'\nVOICE_ID = \'ResembleAI/chatterbox-turbo-ONNX\'\nVOICE_SHA = \'d21799bd0354adb85e348b8a0442a8405110a2cf\'\nSAM_SHA = \'0e78a118995e66bb27d78518c4bd9a3e95b4e266\'\nVOICE_PARTS = (\'speech_encoder\',\'embed_tokens\',\'language_model\',\'conditional_decoder\')\n\ndef voice_assets():\n from huggingface_hub import snapshot_download\n return Path(snapshot_download(VOICE_ID, revision=VOICE_SHA,\n allow_patterns=[\'onnx/*_q4.onnx\',\'onnx/*_q4.onnx_data\',\'tokenizer.json\',\'tokenizer_config.json\']))\n\ndef body_assets():\n from huggingface_hub import snapshot_download\n root = Path(snapshot_download(PREP_ID, revision=PREP_SHA,\n allow_patterns=[\'process_checkpoint/det/*\',\'process_checkpoint/pose2d/*\',\n \'process_checkpoint/sam2/sam2_hiera_large.pt\']))\n snapshot_download(core.MODEL_ID, revision=core.MODEL_REVISION,\n allow_patterns=[\'*.json\',\'**/*.json\',\'**/*.safetensors\',\'**/*.model\',\'**/*.txt\'])\n sam_source()\n code = upstream_code()\n return code, root/\'process_checkpoint\'\n\ndef upstream_code():\n dest = CACHE/(\'Wan2.2-\'+WAN_SHA)\n entry = dest/\'wan/modules/animate/preprocess/process_pipepline.py\'\n if entry.exists():\n return entry.parent\n CACHE.mkdir(parents=True,exist_ok=True)\n archive = CACHE/\'wan-source.zip\'\n url = f\'https://codeload.github.com/Wan-Video/Wan2.2/zip/{WAN_SHA}\'\n with urllib.request.urlopen(url,timeout=90) as src, open(archive,\'wb\') as out:\n shutil.copyfileobj(src,out)\n with zipfile.ZipFile(archive) as z:\n for entry in z.infolist():\n parts = Path(entry.filename).parts\n if \'..\' in parts or not parts or parts[0] != dest.name:\n raise ValueError(\'Unexpected upstream archive path.\')\n if not entry.is_dir():\n p = CACHE.joinpath(*parts)\n p.parent.mkdir(parents=True,exist_ok=True)\n with z.open(entry) as src, open(p,\'wb\') as out:\n shutil.copyfileobj(src,out)\n archive.unlink()\n return dest/\'wan/modules/animate/preprocess\'\n\ndef lip_asset():\n CACHE.mkdir(parents=True,exist_ok=True)\n dest = CACHE/\'wav2lip_96.onnx\'\n if not dest.exists():\n tmp = dest.with_suffix(\'.part\')\n with urllib.request.urlopen(\'https://github.com/facefusion/facefusion-assets/releases/download/models-3.0.0/wav2lip_96.onnx\',timeout=90) as src, open(tmp,\'wb\') as out:\n shutil.copyfileobj(src,out)\n tmp.replace(dest)\n return dest\n\n\ndef sam_source():\n dest=CACHE/(\'sam2-\'+SAM_SHA)\n if not (dest/\'sam2/__init__.py\').exists():\n CACHE.mkdir(parents=True,exist_ok=True)\n archive=CACHE/\'sam-source.zip\'\n with urllib.request.urlopen(f\'https://codeload.github.com/facebookresearch/sam2/zip/{SAM_SHA}\',timeout=90) as src,open(archive,\'wb\') as out:\n shutil.copyfileobj(src,out)\n with zipfile.ZipFile(archive) as z:\n for entry in z.infolist():\n parts=Path(entry.filename).parts\n if \'..\' in parts or not parts or parts[0]!=dest.name:\n raise ValueError(\'Unexpected SAM source path.\')\n if not entry.is_dir():\n p=CACHE.joinpath(*parts);p.parent.mkdir(parents=True,exist_ok=True)\n with z.open(entry) as src,open(p,\'wb\') as out:shutil.copyfileobj(src,out)\n archive.unlink()\n return dest\n', 'auto_controls': '"""Run official single-person Wan preprocessing inside the ZeroGPU process."""\nfrom pathlib import Path\nimport json\nimport sys\nimport gc\nimport core\nimport assets\n\n\ndef build(folder, code, checkpoints, single_person):\n if not single_person:\n raise ValueError(\'Automatic tracking currently requires a shot with exactly one person.\')\n import torch\n # Upstream uses sibling absolute imports. The source is locked to a reviewed commit.\n code = Path(code)\n if code.name != \'preprocess\' or assets.WAN_SHA not in str(code):\n raise ValueError(\'Unrecognized preprocessing source.\')\n if str(code) not in sys.path:\n sys.path.insert(0,str(code))\n sam=str(assets.sam_source())\n if sam not in sys.path:sys.path.insert(0,sam)\n from process_pipepline import ProcessPipeline\n folder, checkpoints = Path(folder), Path(checkpoints)\n j = json.loads((folder/\'job.json\').read_text())\n core.write_manifest(folder,{\'state\':\'preprocessing\'})\n pipe = None\n try:\n pipe = ProcessPipeline(\n det_checkpoint_path=str(checkpoints/\'det/yolov10m.onnx\'),\n pose2d_checkpoint_path=str(checkpoints/\'pose2d/vitpose_h_wholebody.onnx\'),\n sam_checkpoint_path=str(checkpoints/\'sam2/sam2_hiera_large.pt\'),\n flux_kontext_path=None)\n # ONNX is deliberately CPU-only: CUDA allocation belongs to Spaces/PyTorch.\n pipe.pose2d.model.set_device(\'cpu\')\n if pipe.pose2d.detector is not None:pipe.pose2d.detector.set_device(\'cpu\')\n out = folder/\'conditioning\'\n out.mkdir(exist_ok=True)\n with torch.inference_mode(), torch.autocast(\'cuda\',dtype=torch.bfloat16):\n pipe(video_path=str(folder/\'source.mp4\'),refer_image_path=str(folder/\'reference.png\'),\n output_path=str(out),resolution_area=[j[\'width\'],j[\'height\']],fps=core.FPS,\n iterations=3,k=7,w_len=1,h_len=1,retarget_flag=False,use_flux=False,replace_flag=True)\n core.attach_controls(folder,[out/n for n in core.CONTROL_NAMES])\n core.write_manifest(folder,{\'automatic_controls\':True,\'tracking_scope\':\'single_person\'})\n finally:\n del pipe\n gc.collect()\n torch.cuda.empty_cache()\n', 'backend': '"""Real Wan-Animate replacement adapter; untested on ZeroGPU. No paid API path."""\nimport json\nimport os\nfrom pathlib import Path\nimport core\n\n_PIPE = None\n\ndef load_pipeline():\n global _PIPE\n if _PIPE is None:\n import torch\n from diffusers import WanAnimatePipeline\n # Load directly to the allocated GPU rather than first holding all 14B\n # weights in the Space\'s limited CPU RAM. Downloads happen separately.\n _PIPE = WanAnimatePipeline.from_pretrained(core.MODEL_ID, revision=core.MODEL_REVISION,\n torch_dtype=torch.bfloat16, device_map=\'cuda\', low_cpu_mem_usage=True,\n local_files_only=True)\n _PIPE.vae.to(dtype=torch.float32)\n _PIPE.vae.enable_tiling()\n\n return _PIPE\n\n\ndef generate(folder, seed=42):\n import torch\n from diffusers.utils import load_image, load_video, export_to_video\n folder = Path(folder)\n j = core.validate_controls(folder)\n if not j.get(\'permission\'):\n raise ValueError(\'Likeness permission is required.\')\n for n in [\'result.mp4\',\'final.mp4\']:\n (folder/n).unlink(missing_ok=True)\n pipe = load_pipeline()\n core.write_manifest(folder, {\'state\':\'generating\', \'seed\':int(seed)})\n try:\n result = pipe(image=load_image(str(folder/\'reference.png\')),\n pose_video=load_video(str(folder/\'src_pose.mp4\')),\n face_video=load_video(str(folder/\'src_face.mp4\')),\n background_video=load_video(str(folder/\'src_bg.mp4\')),\n mask_video=load_video(str(folder/\'src_mask.mp4\')),\n prompt=\'The reference character, with the same face, hair, body and clothing, moves naturally in the original scene. Consistent lighting.\',\n negative_prompt=\'identity drift, extra limbs, flickering, distorted clothing, blurry\',\n width=j[\'width\'], height=j[\'height\'], segment_frame_length=core.FRAMES,\n num_inference_steps=20, guidance_scale=1.0, mode=\'replace\',\n generator=torch.Generator(device=\'cuda\').manual_seed(int(seed))).frames[0]\n export_to_video(result, str(folder/\'result.mp4\'), fps=core.FPS)\n out = core.probe(folder/\'result.mp4\')\n if out[\'frames\'] != core.FRAMES:\n raise ValueError(\'Model output frame count did not match the requested shot.\')\n core.write_manifest(folder, {\'state\':\'completed\', \'ai_modified\':True,\n \'result_sha256\':core.digest(folder/\'result.mp4\'), \'audio\':\'silent\',\n \'quality_review\':\'required\', \'gpu_verified\':True})\n return str(folder/\'result.mp4\')\n except Exception as e:\n core.write_manifest(folder, {\'state\':\'failed_gpu\', \'error\':str(e)})\n raise\n\n\ndef release_pipeline():\n global _PIPE\n import gc\n import torch\n _PIPE = None\n gc.collect()\n torch.cuda.empty_cache()\n', 'voice': '"""Real Chatterbox Turbo Q4 ONNX voice cloning; CPU, no paid service."""\nfrom pathlib import Path\nimport json\nimport numpy as np\nimport core\nimport assets\n\n\ndef clone(folder, reference, text, permission, model_dir=None, progress=lambda s:None, max_tokens=250):\n import onnxruntime as ort\n import soundfile as sf\n from tokenizers import Tokenizer\n folder = Path(folder)\n if not permission:\n raise ValueError(\'Confirm permission to clone this voice.\')\n if not text or not text.strip() or len(text)>250:\n raise ValueError(\'Enter 1–250 characters of dialogue; short shots need a short line.\')\n if not reference:\n raise ValueError(\'Upload or record a clean voice sample.\')\n # Bound decoding even when an uploaded audio container is very long.\n core.run([\'ffmpeg\',\'-y\',\'-v\',\'error\',\'-i\',reference,\'-t\',\'15\',\'-ac\',\'1\',\'-ar\',\'24000\',folder/\'voice-reference.pending.wav\'])\n audio,sr = sf.read(folder/\'voice-reference.pending.wav\',dtype=\'float32\')\n if len(audio)1.5:raise ValueError(\'Dialogue is too long for this shot. Use a shorter line; your draft is saved.\')\n filters=[]\n if ratio>1:filters.append(f\'atempo={ratio:.8f}\')\n filters+=[\'apad\',f\'atrim=duration={target}\']\n core.run([\'ffmpeg\',\'-y\',\'-v\',\'error\',\'-i\',folder/\'voice.wav\',\'-af\',\',\'.join(filters),\n \'-ar\',\'16000\',\'-ac\',\'1\',folder/\'dialogue.wav\'])\n core.write_manifest(folder,{\'dialogue_speed\':max(1,ratio),\'audio_mode\':\'replace_entire_soundtrack\'})\n return folder/\'dialogue.wav\'\n', 'lipsync': '"""Wav2Lip ONNX inference with fail-closed single-face detection and audio mux."""\nfrom pathlib import Path\nimport json\nimport numpy as np\nimport core\nimport assets\n\n\ndef mel_spectrogram(wav):\n import librosa\n import scipy.signal\n pre=scipy.signal.lfilter([1,-.97],[1],wav)\n magnitude=np.abs(librosa.stft(pre,n_fft=800,hop_length=200,win_length=800))\n mel=librosa.filters.mel(sr=16000,n_fft=800,n_mels=80,fmin=55,fmax=7600)@magnitude\n db=20*np.log10(np.maximum(1e-5,mel))-20\n return np.clip(8*((db+100)/100)-4,-4,4).astype(np.float32)\n\n\ndef run(folder, noncommercial, model_path=None, progress=lambda s:None):\n import cv2\n import soundfile as sf\n import onnxruntime as ort\n from voice import fit_dialogue\n folder=Path(folder)\n if not noncommercial:\n raise ValueError(\'This Wav2Lip model is restricted to noncommercial use.\')\n if not (folder/\'result.mp4\').exists():raise ValueError(\'Generate the full-body shot first.\')\n audio=fit_dialogue(folder)\n wav,sr=sf.read(audio,dtype=\'float32\')\n mel=mel_spectrogram(wav)\n options=ort.SessionOptions();options.intra_op_num_threads=2\n session=ort.InferenceSession(str(model_path or assets.lip_asset()),sess_options=options,\n providers=[\'CPUExecutionProvider\'])\n cascade=cv2.CascadeClassifier(cv2.data.haarcascades+\'haarcascade_frontalface_default.xml\')\n if cascade.empty():raise ValueError(\'Face detector failed to load.\')\n cap=cv2.VideoCapture(str(folder/\'result.mp4\'))\n frames=[];last=None\n try:\n while True:\n ok,frame=cap.read()\n if not ok:break\n frames.append(frame)\n finally:cap.release()\n if len(frames)!=core.FRAMES:raise ValueError(\'Unexpected result frame count.\')\n outdir=folder/\'lipframes\';outdir.mkdir(exist_ok=True)\n for i,frame in enumerate(frames):\n h,w=frame.shape[:2]\n # Upscale detection only; full-body previews can have very small faces.\n gray=cv2.cvtColor(cv2.resize(frame,None,fx=2,fy=2),cv2.COLOR_BGR2GRAY)\n boxes=cascade.detectMultiScale(gray,1.08,4,minSize=(32,32))\n if len(boxes)!=1:\n raise ValueError(f\'Frame {i+1}: need one clear frontal face for lip-sync; found {len(boxes)}. Body result and voice remain saved.\')\n x,y,bw,bh=[float(v)/2 for v in boxes[0]]\n center=((x+bw/2)/w,(y+bh/2)/h)\n if last and np.linalg.norm(np.array(center)-last)>.2:\n raise ValueError(\'Face tracking jumped; use a steadier shot.\')\n last=np.array(center)\n x1=max(0,int(x-.05*bw));x2=min(w,int(x+1.05*bw))\n y1=max(0,int(y-.03*bh));y2=min(h,int(y+1.15*bh))\n full=cv2.resize(frame[y1:y2,x1:x2],(96,96)).astype(np.float32)/255\n masked=full.copy();masked[48:]=0\n target=np.concatenate([masked,full],axis=2).transpose(2,0,1)[None]\n start=int(i/core.FPS*80)\n chunk=mel[:,start:start+16]\n if chunk.shape[1]<16:chunk=np.pad(chunk,((0,0),(0,16-chunk.shape[1])),mode=\'edge\')\n output=session.run(None,{\'source\':chunk[None,None].astype(np.float32),\'target\':target})[0]\n if not np.isfinite(output).all():raise ValueError(\'Lip model returned invalid pixels.\')\n prediction=np.clip(output[0].transpose(1,2,0)*255,0,255).astype(np.uint8)\n prediction=cv2.resize(prediction,(x2-x1,y2-y1))\n yy,xx=np.mgrid[0:y2-y1,0:x2-x1].astype(np.float32)\n xx=(xx+.5)/(x2-x1);yy=(yy+.5)/(y2-y1)\n alpha=np.clip((1-np.sqrt(((xx-.5)/.5)**2+((yy-.55)/.55)**2))*8,0,1)*np.clip((yy-.4)*8,0,1)\n frame[y1:y2,x1:x2]=(prediction*alpha[...,None]+frame[y1:y2,x1:x2]*(1-alpha[...,None])).astype(np.uint8)\n cv2.imwrite(str(outdir/f\'{i:04d}.png\'),frame)\n progress(f\'Lip-sync: {i+1}/{len(frames)} frames\')\n core.run([\'ffmpeg\',\'-y\',\'-v\',\'error\',\'-framerate\',core.FPS,\'-i\',outdir/\'%04d.png\',\n \'-i\',audio,\'-map\',\'0:v:0\',\'-map\',\'1:a:0\',\'-frames:v\',core.FRAMES,\'-c:v\',\'libx264\',\n \'-pix_fmt\',\'yuv420p\',\'-c:a\',\'aac\',\'-movflags\',\'+faststart\',folder/\'final.mp4\'])\n info=core.probe(folder/\'final.mp4\')\n if info[\'frames\']!=core.FRAMES:raise ValueError(\'Export frame count mismatch.\')\n core.write_manifest(folder,{\'state\':\'completed_with_dialogue\',\'lip_model\':\'Wav2Lip96\',\n \'commercial_use\':False,\'ai_modified\':True,\'quality_review\':\'required\',\n \'final_sha256\':core.digest(folder/\'final.mp4\')})\n return str(folder/\'final.mp4\')\n'} for _name, _source in _zmf_sources.items(): (_zmf_modules / (_name + '.py')).write_text(_source) _sys.path.insert(0, str(_zmf_modules)) """ZMF 0.2 integration build: staged real inference, with resumable exports.""" import json import tempfile from pathlib import Path import gradio as gr import spaces import core import assets from backend import generate, release_pipeline ROOT=Path(tempfile.mkdtemp(prefix='zmf-shots-')) CSS=''' .gradio-container {max-width:900px!important;background:#151713;color:#f5efdc} #masthead {border-left:5px solid #dba955;padding:18px;background:#24271f} button.primary {background:#c9903d!important;color:#161811!important} @media(max-width:640px){.gradio-container{padding:12px!important}button{min-height:48px!important}} ''' @spaces.GPU(duration=60) def controls_gpu(folder,code,checkpoints,single): from auto_controls import build build(folder,code,checkpoints,single) @spaces.GPU(duration=120,size='xlarge') def body_gpu(folder,seed): try:return generate(folder,seed) finally:release_pipeline() def job(folder): p=Path(folder) if folder else None if not p or p.parent!=ROOT or not (p/'job.json').is_file(): raise gr.Error('Prepare a shot or restore a checkpoint first.') return p def pack(folder,message): return str(core.checkpoint(folder)),message def prepare(clip,reference,start,permission,single): if not single:raise gr.Error('Use a shot containing one person for this version.') if not clip or not reference:raise gr.Error('Upload a clip and the replacement actor’s full-body image.') p=core.prepare(clip,reference,ROOT,start,permission) core.write_manifest(p,{'single_person_confirmed':True,'app_version':'0.2-integration'}) return str(p),str(p/'first-frame.png'),*pack(p,'Shot saved. Next: extract motion and mask.'),None,None def restore(archive): if not archive:raise gr.Error('Choose a downloaded checkpoint ZIP.') p=core.restore(archive,ROOT) video=p/('final.mp4' if (p/'final.mp4').exists() else 'result.mp4') return str(p),str(p/'first-frame.png'),*pack(p,'Checkpoint restored. Existing outputs are available; review before continuing.'),str(video) if video.exists() else None,str(p/'voice.wav') if (p/'voice.wav').exists() else None def controls(folder,progress=gr.Progress()): p=job(folder) try: yield pack(p,'Downloading public body models on the server. This first download is large; no GPU is allocated yet.') code,checkpoints=assets.body_assets() yield pack(p,'Requesting free ZeroGPU for automatic motion/mask extraction…') j=json.loads((p/'job.json').read_text()) controls_gpu(str(p),str(code),str(checkpoints),j.get('single_person_confirmed',False)) yield pack(p,'Motion and whole-body mask saved. Review the mask, then render the actor.') except Exception as e: core.write_manifest(p,{'state':'controls_failed','error':str(e)}) yield pack(p,'Stopped; progress saved. No paid fallback. '+str(e)) def preview_mask(folder): p=job(folder);mask=p/'src_mask.mp4' if not mask.exists():raise gr.Error('Extract the motion and mask first.') return str(mask) def body(folder,seed,mask_approved): p=job(folder) try: if not mask_approved:raise ValueError('Review the mask and confirm it covers the intended person.') core.validate_controls(p) yield None,*pack(p,'Requesting free ZeroGPU for full-body replacement…') result=body_gpu(str(p),seed) yield result,*pack(p,'Body render saved. Review face, hair, clothes, motion and background; then add dialogue.') except Exception as e: core.write_manifest(p,{'state':'body_failed','error':str(e)}) yield None,*pack(p,'Body stage stopped; checkpoint available. '+str(e)) def clone(folder,sample,text,permission,progress=gr.Progress()): from voice import clone as clone_voice p=job(folder) try: result=clone_voice(p,sample,text,permission,progress=lambda s:progress(0,desc=s)) return result,*pack(p,'Cloned voice saved. Listen before lip-syncing; use a short line for this shot.') except Exception as e: core.write_manifest(p,{'state':'voice_failed','error':str(e)}) draft=p/'voice.wav' return str(draft) if draft.exists() else None,*pack(p,'Voice stage stopped; checkpoint available. '+str(e)) def sync(folder,noncommercial,progress=gr.Progress()): from lipsync import run p=job(folder) try: result=run(p,noncommercial,progress=lambda s:progress(0,desc=s)) return result,*pack(p,'AI-modified MP4 exported. Watch and listen before using it. Download the MP4 and checkpoint to keep them.') except Exception as e: core.write_manifest(p,{'state':'lipsync_failed','error':str(e)}) return None,*pack(p,'Lip-sync stopped; body and voice are preserved. '+str(e)) with gr.Blocks(title='ZMF Studios · FullBody Lab') as demo: gr.Markdown('# ZMF STUDIOS\n### INDIE / AI LAB · 0.2 integration',elem_id='masthead') gr.Markdown('Real pretrained AI stages. **GPU execution and visual quality still need live validation.** ' 'Use one person and one short line: 2.125 seconds, 17 frames, 384×256 (or portrait). ' 'Models run on this Hugging Face Space, **not locally on your iPhone**. No paid fallback.') folder=gr.State('') with gr.Accordion('Resume a saved production',open=False): saved=gr.File(label='Checkpoint ZIP',file_types=['.zip']) restore_btn=gr.Button('Restore saved shot') with gr.Tab('1 · Cast & shot'): clip=gr.File(label='Camera-roll video · max 300 MB',file_types=['video']) reference=gr.Image(label='Replacement actor · full body, desired clothes and hair',type='filepath',sources=['upload']) gr.Markdown('The reference supplies the entire appearance. Upload another outfit reference to change clothing. ' 'A face portrait alone cannot specify an accurate full body or outfit.') start=gr.Number(label='Start time in seconds',value=0,minimum=0) permission=gr.Checkbox(label='I have permission to use this footage and person’s likeness.') single=gr.Checkbox(label='This short shot contains exactly one person.') prepare_btn=gr.Button('Save shot and reference',variant='primary') preview=gr.Image(label='Prepared first frame',interactive=False) with gr.Tab('2 · Replace actor'): controls_btn=gr.Button('Extract motion & whole-body mask',variant='primary') gr.Markdown('First use downloads the body models to the server. GPU limits may interrupt work; resume from a checkpoint.') mask_btn=gr.Button('Show mask preview') mask=gr.Video(label='White = replacement region',interactive=False) approved=gr.Checkbox(label='The mask covers the intended actor, including their hair and clothes.') seed=gr.Number(label='Render seed',value=42,precision=0) body_btn=gr.Button('Render full-body replacement',variant='primary') with gr.Tab('3 · Voice & lips'): sample=gr.Audio(label='Actor voice sample · 3–15 seconds of clean solo speech',sources=['upload','microphone'],type='filepath') text=gr.Textbox(label='New dialogue · one short line',max_length=250,placeholder='Hello. Welcome to ZMF Studios.') voice_permission=gr.Checkbox(label='I have permission to clone this voice.') clone_btn=gr.Button('Clone voice & save dialogue',variant='primary') voice_output=gr.Audio(label='Review cloned voice',interactive=False) gr.Markdown('Lip-sync uses Wav2Lip (noncommercial). Requires a clear frontal face; a tiny or occluded face may fail. ' 'New dialogue replaces the entire soundtrack. Background music and other speakers are not preserved.') nc=gr.Checkbox(label='This lip-sync export is for noncommercial use.') sync_btn=gr.Button('Lip-sync & export MP4',variant='primary') status=gr.Textbox(label='Stage / recovery',interactive=False) output=gr.Video(label='Rendered shot',interactive=False) archive=gr.File(label='Save progress · download checkpoint ZIP',interactive=False) gr.Markdown('**Save the checkpoint to Files on your iPhone after each completed stage.** ' 'Space storage can disappear on restart; the ZIP contains the shot, reference, controls, voice and outputs. ' 'This update does not train new weights, reconstruct ancestors, or unlock studio tiers.') prepare_btn.click(prepare,[clip,reference,start,permission,single],[folder,preview,archive,status,output,voice_output],concurrency_id='studio',concurrency_limit=1) restore_btn.click(restore,[saved],[folder,preview,archive,status,output,voice_output],concurrency_id='studio') controls_btn.click(controls,[folder],[archive,status],concurrency_id='studio') mask_btn.click(preview_mask,[folder],[mask],concurrency_id='studio') body_btn.click(body,[folder,seed,approved],[output,archive,status],concurrency_id='studio') clone_btn.click(clone,[folder,sample,text,voice_permission],[voice_output,archive,status],concurrency_id='studio') sync_btn.click(sync,[folder,nc],[output,archive,status],concurrency_id='studio') if __name__=='__main__': demo.queue(default_concurrency_limit=1,max_size=8).launch(max_file_size='300mb',ssr_mode=False,css=CSS)