VEHwang's picture
Upload CoCogni4D-Bench (questions, media, scripts, render records, code) (part 6)
5afd2f7 verified
Raw History Blame Contribute Delete
2.54 kB
"""Explicit lexical prefix relocation; source references and hashes stay intact."""
from pathlib import Path, PurePosixPath
import hashlib
import json
class PathMapping:
def __init__(self, declarations=()):
self.rules = []
for declaration in declarations:
if '=' not in declaration:
raise ValueError('path-map must be SOURCE=DESTINATION')
source, target = declaration.split('=', 1)
left, right = PurePosixPath(source), Path(target)
if (not left.is_absolute() or len(left.parts) == 1 or '..' in left.parts
or not right.is_absolute() or '..' in right.parts):
raise ValueError('Path prefixes must be absolute, non-root and contain no traversal')
if any(left == a for a, _ in self.rules):
raise ValueError('Duplicate source prefix')
if not right.is_dir():
raise ValueError('Mapped destination directory does not exist')
self.rules.append((left, right))
self.rules.sort(key=lambda row: len(row[0].parts), reverse=True)
def __call__(self, path):
value = PurePosixPath(str(path))
if not value.is_absolute() or '..' in value.parts:
raise ValueError('Input reference must be an absolute path without traversal')
if not self.rules:
return Path(path)
for source, target in self.rules:
try:
suffix = value.relative_to(source)
except ValueError:
continue
return target.joinpath(*suffix.parts)
# Native references inside explicitly mapped views remain valid. This
# is necessary for new runs generated within the same service view.
for _, target in self.rules:
try:
value.relative_to(PurePosixPath(str(target)))
except ValueError:
continue
return Path(path)
raise ValueError('Undeclared input path prefix: ' + str(path))
def as_dicts(self):
return [{'source': str(left), 'destination': str(right)} for left, right in self.rules]
def signature(self):
return hashlib.sha256(json.dumps(self.as_dicts(), sort_keys=True).encode()).hexdigest()
def load(self, path, kind=None):
from embodied_pipeline.artifacts import load
return load(path, kind, **({'path_resolver': self} if self.rules else {}))
def mapping(value=None):
return value if value is not None else PathMapping()