Spaces:
Running on Zero
Running on Zero
Download backend/validation.py from fffiloni/idol-commons: direct link, hf CLI and curl.
- Browser
- Download file 7.58 kB
-
https://huggingface.co/spaces/fffiloni/idol-commons/resolve/main/backend/validation.py
- Command line
-
hf download hf://spaces/fffiloni/idol-commons/backend/validation.py
-
curl -L -o validation.py https://huggingface.co/spaces/fffiloni/idol-commons/resolve/main/backend/validation.py
7.58 kB
| """Bounded, fixed-layout validation for locally generated IDOL results. | |
| This is a technical check; ownership, provenance and content review are separate. | |
| """ | |
| from __future__ import annotations | |
| import hashlib | |
| import io | |
| import os | |
| import stat | |
| import warnings | |
| from pathlib import Path | |
| import numpy as np | |
| from PIL import Image, ImageOps | |
| MAX_PLY_BYTES=80*1024*1024 | |
| MAX_GAUSSIANS=1048576 | |
| PROPERTIES=('x','y','z','nx','ny','nz','f_dc_0','f_dc_1','f_dc_2','opacity','scale_0','scale_1','scale_2','rot_0','rot_1','rot_2','rot_3') | |
| class InvalidAsset(ValueError): | |
| pass | |
| def validate_ply(path:Path,expected_count:int|None=None): | |
| flags=os.O_RDONLY|getattr(os,'O_NOFOLLOW',0) | |
| try:fd=os.open(path,flags) | |
| except OSError as e:raise InvalidAsset('The generated file cannot be opened safely.') from e | |
| with os.fdopen(fd,'rb') as f: | |
| info=os.fstat(f.fileno()) | |
| if not stat.S_ISREG(info.st_mode) or not 1<=info.st_size<=MAX_PLY_BYTES: | |
| raise InvalidAsset('The splat exceeds the 80 MiB limit or is not a regular file.') | |
| header=bytearray() | |
| while not header.endswith(b'end_header\n'): | |
| line=f.readline(4097-len(header)) | |
| if not line or len(header)+len(line)>4096:raise InvalidAsset('Invalid or oversized PLY header.') | |
| header.extend(line) | |
| try:lines=header.decode('ascii').splitlines() | |
| except UnicodeError as e:raise InvalidAsset('Non-ASCII PLY header.') from e | |
| if len(lines)!=21 or lines[:2]!=['ply','format binary_little_endian 1.0'] or not lines[2].startswith('element vertex '): | |
| raise InvalidAsset('Expected an IDOL binary little-endian Gaussian splat.') | |
| raw_count=lines[2][15:] | |
| if not raw_count.isascii() or not raw_count.isdecimal() or len(raw_count)>7:raise InvalidAsset('Invalid Gaussian count.') | |
| count=int(raw_count) | |
| if not 32768<=count<=MAX_GAUSSIANS or count%32 or (expected_count is not None and count!=expected_count): | |
| raise InvalidAsset('Gaussian count does not match the generation.') | |
| if lines[3:-1]!=['property float '+name for name in PROPERTIES] or lines[-1]!='end_header': | |
| raise InvalidAsset('Unsupported or ambiguous Gaussian properties.') | |
| if len(header)+68*count!=info.st_size:raise InvalidAsset('Truncated PLY or unexpected trailing data.') | |
| digest=hashlib.sha256(header);minimum=np.full(3,np.inf);maximum=np.full(3,-np.inf) | |
| left=count | |
| while left: | |
| n=min(left,8192);block=f.read(n*68) | |
| if len(block)!=n*68:raise InvalidAsset('The file changed while being validated.') | |
| digest.update(block);data=np.frombuffer(block,dtype='<f4').reshape(n,17) | |
| if not np.isfinite(data).all():raise InvalidAsset('Non-finite Gaussian data.') | |
| if np.any(np.abs(data[:,:3])>32) or np.any(data[:,3:6]!=0):raise InvalidAsset('Invalid IDOL coordinates or normals.') | |
| if np.any(np.abs(data[:,6:9])>1024) or np.any(np.abs(data[:,9])>80):raise InvalidAsset('Gaussian appearance is outside the resource profile.') | |
| if np.any(data[:,10:13]<-20) or np.any(data[:,10:13]>6):raise InvalidAsset('Gaussian scale is outside the resource profile.') | |
| norms=np.linalg.norm(data[:,13:17],axis=1) | |
| if np.any(np.abs(norms-1)>0.001):raise InvalidAsset('Invalid Gaussian rotations.') | |
| minimum=np.minimum(minimum,data[:,:3].min(axis=0));maximum=np.maximum(maximum,data[:,:3].max(axis=0));left-=n | |
| if f.read(1) or os.fstat(f.fileno()).st_size!=info.st_size:raise InvalidAsset('The file changed while being validated.') | |
| return {'bytes':info.st_size,'sha256':digest.hexdigest(),'gaussian_count':count,'header_bytes':len(header),'bounds':{'min':minimum.tolist(),'max':maximum.tolist()}} | |
| IMAGE_ERRORS={ | |
| 'size':'Choose an image smaller than 20 MiB.', | |
| 'format':'Choose a PNG, JPEG or WebP photo.', | |
| 'animation':'Animated images are not supported. Choose a still photo.', | |
| 'dimensions':'This image exceeds the safe image limits. Export a smaller JPEG or PNG, then try again.', | |
| 'aspect':'Crop the image around your object before uploading it.', | |
| 'transparent':'This image is completely transparent.', | |
| 'decode':'This image could not be read. Choose another photo or export it as JPEG or PNG.', | |
| } | |
| class InvalidImage(InvalidAsset): | |
| def __init__(self,code): | |
| self.code=code | |
| super().__init__(IMAGE_ERRORS[code]) | |
| def normalize_input(raw:bytes,destination:Path): | |
| if not 1<=len(raw)<=20*1024*1024:raise InvalidImage('size') | |
| try: | |
| with warnings.catch_warnings(): | |
| warnings.simplefilter('error',Image.DecompressionBombWarning) | |
| with Image.open(io.BytesIO(raw)) as source: | |
| if source.format not in {'PNG','JPEG','MPO','WEBP'}:raise InvalidImage('format') | |
| # JPEG photos may carry auxiliary pictures (e.g. an HDR gain map). | |
| # Pillow identifies those as MPO. Like gr.Image(type='pil'), use | |
| # only the primary picture; never iterate/decode auxiliary frames. | |
| if source.format=='MPO':source.seek(0) | |
| elif getattr(source,'n_frames',1)!=1:raise InvalidImage('animation') | |
| w,h=source.size | |
| if min(w,h)<16 or max(w,h)>8192 or w*h>16000000:raise InvalidImage('dimensions') | |
| if max(w,h)/min(w,h)>8:raise InvalidImage('aspect') | |
| source.load();image=ImageOps.exif_transpose(source).convert('RGBA') | |
| if image.getchannel('A').getextrema()[1]==0:raise InvalidImage('transparent') | |
| clean=Image.new('RGBA',image.size);clean.paste(image) | |
| destination.parent.mkdir(parents=True,exist_ok=True,mode=0o700) | |
| clean.save(destination,format='PNG');os.chmod(destination,0o600) | |
| return {'width':image.width,'height':image.height,'bytes':destination.stat().st_size,'sha256':hashlib.sha256(destination.read_bytes()).hexdigest()} | |
| except InvalidAsset:raise | |
| except (OSError,ValueError,Image.DecompressionBombError,Image.DecompressionBombWarning) as e: | |
| raise InvalidImage('decode') from e | |
| def normalize_preview(raw:bytes,destination:Path,side=1024): | |
| if len(raw)>8*1024*1024:raise InvalidAsset('Preview is too large.') | |
| try: | |
| with Image.open(io.BytesIO(raw)) as image: | |
| if image.format!='PNG' or image.size!=(side,side) or image.mode!='RGBA':raise InvalidAsset('Expected an RGBA preview at the configured size.') | |
| image.load();alpha=image.getchannel('A');minimum,maximum=alpha.getextrema() | |
| if minimum!=0 or maximum==0:raise InvalidAsset('Preview is empty or lacks a transparent background.') | |
| mask=alpha.point(lambda v:255 if v>=3 else 0);bbox=mask.getbbox() | |
| if not bbox or min(bbox[:2])<2 or max(bbox[2:])>side-2:raise InvalidAsset('Preview framing clips the object.') | |
| x0,y0,x1,y1=bbox;size=min(side,max(x1-x0,y1-y0)+24) | |
| x=max(0,min(side-size,(x0+x1-size)//2));y=max(0,min(side-size,(y0+y1-size)//2)) | |
| clean=Image.new('RGBA',image.size);clean.paste(image);clean.save(destination,'PNG') | |
| small=destination.with_name('preview-small.png');clean.resize((512,512),Image.Resampling.LANCZOS).save(small,'PNG') | |
| return {'crop':[x,y,size], 'files':{p.name:{'bytes':p.stat().st_size,'sha256':hashlib.sha256(p.read_bytes()).hexdigest()} for p in [destination,small]}} | |
| except InvalidAsset:raise | |
| except (OSError,ValueError) as e:raise InvalidAsset('Invalid preview PNG.') from e | |