Spaces:
Running on Zero
Running on Zero
Download stitch_cache.py from Simzy/Wan-2.2-Studio: direct link, hf CLI and curl.
- Browser
- Download file 10.9 kB
-
https://huggingface.co/spaces/Simzy/Wan-2.2-Studio/resolve/main/stitch_cache.py
- Command line
-
hf download hf://spaces/Simzy/Wan-2.2-Studio/stitch_cache.py
-
curl -L -o stitch_cache.py https://huggingface.co/spaces/Simzy/Wan-2.2-Studio/resolve/main/stitch_cache.py
10.9 kB
| """Bounded, process-local caches for CPU clip preparation. | |
| Keep the existing normalizer: this module caches its output, not a cheaper | |
| approximation. Each join stages its own hardlinks (or copies), so eviction and | |
| another session cannot remove the files currently being concatenated. | |
| """ | |
| from collections import OrderedDict | |
| import atexit | |
| import hashlib | |
| import json | |
| import math | |
| import os | |
| import shutil | |
| import stat | |
| import tempfile | |
| import threading | |
| import time | |
| import uuid | |
| _CACHE_VERSION = "normalise-h264-fast-crf20-aac-v1" | |
| def file_signature(path): | |
| """Invalidate when a source is replaced or edited, including same-size edits.""" | |
| resolved = os.path.normcase(os.path.realpath(os.fspath(path))) | |
| info = os.stat(resolved) | |
| if not stat.S_ISREG(info.st_mode): | |
| raise ValueError("A queued clip is not a regular file.") | |
| return (resolved, info.st_dev, info.st_ino, info.st_size, | |
| info.st_mtime_ns, info.st_ctime_ns) | |
| def _link_or_copy(source, destination): | |
| # Cache entries and staged parts are immutable. Both names remain valid if | |
| # the other is unlinked; copy is the fallback for different filesystems. | |
| try: | |
| os.link(source, destination) | |
| except OSError: | |
| shutil.copyfile(source, destination) | |
| class NormalizedClipCache: | |
| """An LRU bounded by both bytes and entries, isolated from other workers. | |
| Only one cache miss is encoded at a time per worker. Hits remain available | |
| while that happens, and simultaneous joins of the same clip share the | |
| completed encode. No cache path is returned to a caller for later use. | |
| """ | |
| def __init__(self, max_bytes=2 * 1024 ** 3, max_entries=128, | |
| max_age_seconds=6 * 60 * 60): | |
| self.max_bytes = max(0, int(max_bytes)) | |
| self.max_entries = max(0, int(max_entries)) | |
| self.max_age_seconds = max(0.0, float(max_age_seconds)) | |
| self._entries = OrderedDict() | |
| self._bytes = 0 | |
| self._lock = threading.RLock() | |
| self._build_lock = threading.Lock() | |
| self._directory = None | |
| atexit.register(self.close) | |
| def _discard(self, key): | |
| entry = self._entries.get(key) | |
| if entry is None: | |
| return True | |
| try: | |
| os.unlink(entry[0]) | |
| except FileNotFoundError: | |
| pass | |
| except OSError: | |
| # For example, an OS may briefly deny unlinking an open file. Keep | |
| # accounting for it and retry later rather than exceed the limit. | |
| return False | |
| del self._entries[key] | |
| self._bytes -= entry[1] | |
| return True | |
| def _expire(self): | |
| cutoff = time.monotonic() - self.max_age_seconds | |
| for key, entry in list(self._entries.items()): | |
| if entry[2] <= cutoff: | |
| self._discard(key) | |
| def _reserve(self, size): | |
| self._expire() | |
| for key in list(self._entries): | |
| if self._bytes + size <= self.max_bytes and len(self._entries) < self.max_entries: | |
| break | |
| self._discard(key) | |
| return (self._bytes + size <= self.max_bytes and | |
| len(self._entries) < self.max_entries) | |
| def _hit(self, key, output_path): | |
| with self._lock: | |
| self._expire() | |
| entry = self._entries.get(key) | |
| if entry is None: | |
| return False | |
| try: | |
| if os.path.getsize(entry[0]) != entry[1]: | |
| self._discard(key) | |
| return False | |
| # Hold the lock until the caller has its own file. Eviction | |
| # cannot race the link/copy, including on Windows. | |
| _link_or_copy(entry[0], output_path) | |
| except (FileNotFoundError, PermissionError): | |
| self._discard(key) | |
| return False | |
| self._entries[key] = (entry[0], entry[1], time.monotonic()) | |
| self._entries.move_to_end(key) | |
| return True | |
| def _publish(self, key, output_path): | |
| size = os.path.getsize(output_path) | |
| if size <= 0: | |
| raise RuntimeError("Normalizing a clip produced no complete output.") | |
| if not self.max_entries or size > self.max_bytes or not self.max_age_seconds: | |
| return | |
| with self._lock: | |
| # A stale entry whose unlink was denied must remain accounted for; | |
| # do not overwrite its record and orphan its bytes on disk. | |
| if key in self._entries and not self._discard(key): | |
| return | |
| if not self._reserve(size): | |
| return | |
| cache_path = None | |
| try: | |
| if self._directory is None: | |
| # Never share cache filenames with a different process. | |
| self._directory = tempfile.TemporaryDirectory(prefix="wan-stitch-cache-") | |
| cache_path = os.path.join(self._directory.name, uuid.uuid4().hex + ".mp4") | |
| _link_or_copy(output_path, cache_path) | |
| self._entries[key] = (cache_path, size, time.monotonic()) | |
| self._bytes += size | |
| except OSError as error: | |
| # Caching is optional; a fully prepared join can still finish | |
| # on a disk without room for an additional cached copy. | |
| if cache_path is not None: | |
| try: | |
| os.unlink(cache_path) | |
| except FileNotFoundError: | |
| pass | |
| except OSError: | |
| # A failed cross-filesystem copy may leave a partial | |
| # file. Account for its reserved upper bound until it | |
| # can be removed, under a key that can never be a hit. | |
| orphan_key = "incomplete:" + os.path.basename(cache_path) | |
| self._entries[orphan_key] = (cache_path, size, 0.0) | |
| self._bytes += size | |
| print(f"[stitch-cache] could not retain part: {type(error).__name__}", flush=True) | |
| def stage_clip(self, path, width, height, fps, output_path, *, normalise, | |
| trim_head=False, colour="", include_audio=True): | |
| """Write one join-owned part; return True when an encode was reused. | |
| `normalise` has the app's _normalise_clip signature. Its HDR mapping, | |
| audio alignment/silence, geometry, frame rate and seam trim stay intact. | |
| Bump _CACHE_VERSION if the normalization settings change at runtime. | |
| """ | |
| path, output_path = os.fspath(path), os.fspath(output_path) | |
| if os.path.normcase(os.path.realpath(path)) == os.path.normcase(os.path.realpath(output_path)): | |
| raise ValueError("A normalized part must not overwrite its source.") | |
| fps = float(fps) | |
| if not math.isfinite(fps) or fps <= 0: | |
| raise ValueError("The stitching frame rate must be positive and finite.") | |
| transform = (_CACHE_VERSION, int(width), int(height), fps.hex(), | |
| bool(trim_head), str(colour), bool(include_audio)) | |
| def signature_and_key(): | |
| signature = file_signature(path) | |
| payload = json.dumps((signature, transform), ensure_ascii=True, separators=(",", ":")) | |
| return signature, hashlib.sha256(payload.encode("utf-8")).hexdigest() | |
| before, key = signature_and_key() | |
| if self._hit(key, output_path): | |
| if file_signature(path) != before: | |
| raise RuntimeError("A queued clip changed while stitching. Retry Join.") | |
| return True | |
| with self._build_lock: | |
| # A previous join may have completed this exact part while we | |
| # waited. Re-read source metadata as well before doing any work. | |
| before, key = signature_and_key() | |
| if self._hit(key, output_path): | |
| if file_signature(path) != before: | |
| raise RuntimeError("A queued clip changed while stitching. Retry Join.") | |
| return True | |
| normalise(path, width, height, fps, output_path, | |
| trim_head=trim_head, colour=colour, include_audio=include_audio) | |
| if file_signature(path) != before: | |
| raise RuntimeError("A queued clip changed while stitching. Retry Join.") | |
| self._publish(key, output_path) | |
| return False | |
| def close(self): | |
| """Release only this worker's private cache, never original clips.""" | |
| with self._build_lock: | |
| with self._lock: | |
| if self._directory is not None: | |
| try: | |
| self._directory.cleanup() | |
| except OSError: | |
| return | |
| self._directory = None | |
| self._entries.clear() | |
| self._bytes = 0 | |
| class FileMemo: | |
| """Small metadata/frame cache; loaders must return values callers do not mutate.""" | |
| def __init__(self, max_entries=512, max_age_seconds=6 * 60 * 60): | |
| self.max_entries = max(0, int(max_entries)) | |
| self.max_age_seconds = max(0.0, float(max_age_seconds)) | |
| self._entries = OrderedDict() | |
| self._lock = threading.RLock() | |
| def get(self, path, probe_name, loader): | |
| # Separate from the encoding lock: cheap metadata hits never wait for | |
| # an H.264 encode. RLock also permits loaders to consult another probe. | |
| with self._lock: | |
| signature = file_signature(path) | |
| key = (str(probe_name), signature) | |
| now = time.monotonic() | |
| for old_key, entry in list(self._entries.items()): | |
| if now - entry[1] >= self.max_age_seconds: | |
| del self._entries[old_key] | |
| if key in self._entries: | |
| value, _ = self._entries[key] | |
| self._entries[key] = (value, now) | |
| self._entries.move_to_end(key) | |
| return value | |
| value = loader() | |
| if file_signature(path) != signature: | |
| raise RuntimeError("A queued clip changed while reading its metadata.") | |
| if value is not None and self.max_entries and self.max_age_seconds: | |
| self._entries[key] = (value, time.monotonic()) | |
| while len(self._entries) > self.max_entries: | |
| self._entries.popitem(last=False) | |
| return value | |
| _normalised = NormalizedClipCache() | |
| _metadata = FileMemo() | |
| def stage_clip(path, width, height, fps, output_path, *, normalise, | |
| trim_head=False, colour="", include_audio=True): | |
| return _normalised.stage_clip(path, width, height, fps, output_path, | |
| normalise=normalise, trim_head=trim_head, | |
| colour=colour, include_audio=include_audio) | |
| def memoize_file(path, probe_name, loader): | |
| return _metadata.get(path, probe_name, loader) | |