motionkit2d 1.0.0__py3-none-any.whl

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (45) hide show
  1. motionkit2d/__init__.py +49 -0
  2. motionkit2d/__main__.py +115 -0
  3. motionkit2d/acceleration.py +121 -0
  4. motionkit2d/assets.py +319 -0
  5. motionkit2d/audio.py +87 -0
  6. motionkit2d/audio_analysis.py +55 -0
  7. motionkit2d/camera.py +56 -0
  8. motionkit2d/catalog.py +79 -0
  9. motionkit2d/characters/__init__.py +4 -0
  10. motionkit2d/characters/actions.py +125 -0
  11. motionkit2d/characters/builder.py +15 -0
  12. motionkit2d/characters/expressions.py +81 -0
  13. motionkit2d/compiler.py +162 -0
  14. motionkit2d/composition.py +50 -0
  15. motionkit2d/constraints.py +91 -0
  16. motionkit2d/cues.py +15 -0
  17. motionkit2d/draw.py +416 -0
  18. motionkit2d/dynamics.py +109 -0
  19. motionkit2d/effects.py +131 -0
  20. motionkit2d/environments.py +86 -0
  21. motionkit2d/export.py +235 -0
  22. motionkit2d/fonts/LICENSE.txt +130 -0
  23. motionkit2d/fonts/LiberationSans-Regular.ttf +0 -0
  24. motionkit2d/fonts/LiberationSerif-Bold.ttf +0 -0
  25. motionkit2d/fonts/LiberationSerif-Regular.ttf +0 -0
  26. motionkit2d/gpu.py +512 -0
  27. motionkit2d/layout.py +89 -0
  28. motionkit2d/manifest.py +96 -0
  29. motionkit2d/mixer.py +92 -0
  30. motionkit2d/preset_library.py +41 -0
  31. motionkit2d/presets.py +33 -0
  32. motionkit2d/props.py +126 -0
  33. motionkit2d/qc.py +78 -0
  34. motionkit2d/quality.py +122 -0
  35. motionkit2d/rig.py +325 -0
  36. motionkit2d/scene_graph.py +154 -0
  37. motionkit2d/timeline.py +174 -0
  38. motionkit2d/transitions.py +51 -0
  39. motionkit2d/typography.py +118 -0
  40. motionkit2d/visual_effects.py +104 -0
  41. motionkit2d-1.0.0.dist-info/METADATA +140 -0
  42. motionkit2d-1.0.0.dist-info/RECORD +45 -0
  43. motionkit2d-1.0.0.dist-info/WHEEL +5 -0
  44. motionkit2d-1.0.0.dist-info/entry_points.txt +2 -0
  45. motionkit2d-1.0.0.dist-info/top_level.txt +1 -0
@@ -0,0 +1,96 @@
1
+ """Data-only project resolution, portable manifests and full-timeline preflight."""
2
+ import json
3
+ import os
4
+ from pathlib import Path
5
+ import tempfile
6
+ from math import isfinite
7
+
8
+ from .compiler import ManifestError
9
+ from .rig import sample
10
+
11
+
12
+ def read_json(path):
13
+ def pairs(items):
14
+ result={}
15
+ for key,value in items:
16
+ if key in result: raise ManifestError(f'Duplicate JSON key: {key}')
17
+ result[key]=value
18
+ return result
19
+ def invalid(value): raise ManifestError(f'Nonfinite JSON number: {value}')
20
+ try: return json.loads(Path(path).read_text(encoding='utf-8-sig'),object_pairs_hook=pairs,parse_constant=invalid)
21
+ except (OSError,json.JSONDecodeError) as error: raise ManifestError(f'{path}: {error}') from error
22
+
23
+
24
+ def resolve_manifest(path,*,_stack=()):
25
+ path=Path(path).resolve()
26
+ if path in _stack or len(_stack)>=32: raise ManifestError('Manifest include cycle/depth limit')
27
+ data=read_json(path)
28
+ if not isinstance(data,dict): raise ManifestError('Manifest must be an object')
29
+ if type(data.get('schema_version')) is not int or data['schema_version']!=1:
30
+ raise ManifestError('schema_version must be integer 1 in every included manifest')
31
+ includes=data.pop('includes',[]); preset_files=data.pop('preset_files',[])
32
+ if not isinstance(includes,list) or not isinstance(preset_files,list): raise ManifestError('includes/preset_files require arrays')
33
+ merged={'schema_version':1,'video':{},'presets':{},'scenes':[],'audio':[]}
34
+ def presets(values):
35
+ if not isinstance(values,dict): raise ManifestError('Preset file must contain a node-config map')
36
+ duplicates=merged['presets'].keys()&values.keys()
37
+ if duplicates: raise ManifestError(f'Duplicate presets: {sorted(duplicates)}')
38
+ merged['presets'].update(values)
39
+ for name in includes:
40
+ if not isinstance(name,str): raise ManifestError('Include path must be a string')
41
+ child=resolve_manifest(path.parent/name,_stack=(*_stack,path))
42
+ # Unknown child fields must not disappear during merge.
43
+ if child.keys()-merged.keys(): raise ManifestError('Unknown included manifest fields')
44
+ if child.get('schema_version')!=1: raise ManifestError('Included schema_version must be 1')
45
+ merged['video'].update(child.get('video',{})); presets(child.get('presets',{}))
46
+ merged['scenes'].extend(child.get('scenes',[])); merged['audio'].extend(child.get('audio',[]))
47
+ for name in preset_files:
48
+ if not isinstance(name,str): raise ManifestError('Preset path must be a string')
49
+ presets(read_json(path.parent/name))
50
+ for cue in data.get('audio',[]):
51
+ if isinstance(cue,dict) and isinstance(cue.get('path'),str): cue['path']=str((path.parent/cue['path']).resolve())
52
+ presets(data.pop('presets',{}))
53
+ merged['video'].update(data.pop('video',{}))
54
+ merged['scenes'].extend(data.pop('scenes',[])); merged['audio'].extend(data.pop('audio',[]))
55
+ # Preserve unknown fields for the compiler to reject.
56
+ merged.update(data)
57
+ return merged
58
+
59
+
60
+ def save_manifest(data,path):
61
+ """Atomic UTF-8 JSON; reject NaN and unserializable runtime callbacks."""
62
+ payload=json.dumps(data,ensure_ascii=False,indent=2,allow_nan=False)+'\n'
63
+ path=Path(path); path.parent.mkdir(parents=True,exist_ok=True)
64
+ fd,name=tempfile.mkstemp(dir=path.parent,prefix='.motionkit-',suffix='.json')
65
+ try:
66
+ with os.fdopen(fd,'w',encoding='utf-8') as file: file.write(payload)
67
+ os.replace(name,path)
68
+ finally: Path(name).unlink(missing_ok=True)
69
+ return path
70
+
71
+
72
+ def preflight(video,*,check_audio=True):
73
+ """Sample graph properties at every output frame, without raster rendering."""
74
+ from .scene_graph import SceneGraph
75
+ checked=0
76
+ for scene,length in zip(video.scenes,video.lengths):
77
+ graph=scene.paint
78
+ if not isinstance(graph,SceneGraph): continue
79
+ graph.validate()
80
+ for i in range(length):
81
+ t=i/video.fps; sample(graph.camera,t)
82
+ for node in graph.nodes.values():
83
+ graph.world_transform(node.id,t)
84
+ opacity=sample(node.opacity,t)
85
+ if not isfinite(opacity) or not 0<=opacity<=1: raise ManifestError(f'{node.id}@{t}: invalid opacity')
86
+ if not isinstance(sample(node.visible,t),bool): raise ManifestError(f'{node.id}: visible must be boolean')
87
+ if hasattr(node.content,'world_transform'): node.content.world_transform(t)
88
+ if hasattr(node.content,'pose'): sample(node.content.pose,t)
89
+ if hasattr(node.content,'face'): sample(node.content.face,t)
90
+ checked+=1
91
+ if check_audio:
92
+ from .audio import source_duration
93
+ for cue in video.audio:
94
+ if not Path(cue.path).is_file(): raise ManifestError(f'Missing audio: {cue.path}')
95
+ if source_duration(cue.path)<=cue.source_offset: raise ManifestError(f'Empty audio trim: {cue.path}')
96
+ return {'status':'PASS','scenes':len(video.scenes),'graph_frames_checked':checked,'frame_count':video.frame_count}
motionkit2d/mixer.py ADDED
@@ -0,0 +1,92 @@
1
+ """Standalone FFmpeg mixer, two-pass loudness mastering and explicit TTS adapters."""
2
+ import json
3
+ import math
4
+ import os
5
+ from pathlib import Path
6
+ import re
7
+ import shutil
8
+ import subprocess
9
+ import tempfile
10
+ import wave
11
+
12
+ from .audio import audio_filters
13
+ from .effects import Key, Track
14
+
15
+
16
+ def _ffmpeg(*args):
17
+ binary=shutil.which('ffmpeg')
18
+ if not binary: raise FileNotFoundError('ffmpeg required')
19
+ return subprocess.run([binary,'-hide_banner','-y',*map(str,args)],capture_output=True,check=True)
20
+
21
+
22
+ def _publish(path,writer):
23
+ path=Path(path)
24
+ if path.suffix.lower()!='.wav': raise ValueError('Output must be WAV')
25
+ path.parent.mkdir(parents=True,exist_ok=True)
26
+ fd,name=tempfile.mkstemp(prefix='.motionkit-',suffix='.wav',dir=path.parent); os.close(fd)
27
+ temporary=Path(name)
28
+ try:
29
+ writer(temporary)
30
+ with wave.open(str(temporary),'rb') as source:
31
+ if not source.getnframes(): raise ValueError('Empty synthesized/mixed audio')
32
+ os.replace(temporary,path)
33
+ finally: temporary.unlink(missing_ok=True)
34
+ return path
35
+
36
+
37
+ def mix_audio(cues,path,*,seconds,rate=48000):
38
+ cues=tuple(cues)
39
+ if not math.isfinite(seconds) or seconds<=0 or type(rate) is not int or rate<1000: raise ValueError('Invalid mix duration/rate')
40
+ if any(Path(c.path).resolve()==Path(path).resolve() for c in cues): raise ValueError('Cannot overwrite audio source')
41
+ def write(output):
42
+ if not cues:
43
+ _ffmpeg('-v','error','-f','lavfi','-i',f'anullsrc=r={rate}:cl=stereo','-t',seconds,'-c:a','pcm_s16le',output)
44
+ else:
45
+ inputs=[arg for cue in cues for arg in ('-i',str(cue.path))]
46
+ # Video exporter reserves input zero for video; audio-only starts at zero.
47
+ filters=audio_filters(cues,seconds,rate)
48
+ filters=[re.sub(r'\[(\d+):a:0\]',lambda m:f'[{int(m[1])-1}:a:0]',f) for f in filters]
49
+ _ffmpeg('-v','error',*inputs,'-filter_complex',';'.join(filters),'-map','[mix]','-ar',rate,'-c:a','pcm_s16le',output)
50
+ return _publish(path,write)
51
+
52
+
53
+ def loudness(path,*,target_lufs=-16,true_peak=-1,lra=11):
54
+ if not -70<=target_lufs<=-5 or not -9<=true_peak<=0 or not 1<=lra<=50: raise ValueError('Invalid loudness target')
55
+ result=_ffmpeg('-i',path,'-af',f'loudnorm=I={target_lufs}:TP={true_peak}:LRA={lra}:print_format=json','-f','null','-')
56
+ blocks=re.findall(r'\{[^{}]+\}',result.stderr.decode(errors='replace'))
57
+ if not blocks: raise ValueError('FFmpeg did not return loudness measurements')
58
+ data=json.loads(blocks[-1])
59
+ return {k:(float(v) if math.isfinite(float(v)) else None) if k!='normalization_type' else v for k,v in data.items()}
60
+
61
+
62
+ def normalize_audio(source,destination,*,target_lufs=-16,true_peak=-1,lra=11):
63
+ if Path(source).resolve()==Path(destination).resolve(): raise ValueError('Use a separate mastering destination')
64
+ measured=loudness(source,target_lufs=target_lufs,true_peak=true_peak,lra=lra)
65
+ required=('input_i','input_tp','input_lra','input_thresh','target_offset')
66
+ if any(measured[k] is None for k in required): raise ValueError('Cannot normalize silence/nonfinite loudness')
67
+ spec=f'loudnorm=I={target_lufs}:TP={true_peak}:LRA={lra}:linear=true'
68
+ for parameter,key in [('measured_I','input_i'),('measured_TP','input_tp'),('measured_LRA','input_lra'),('measured_thresh','input_thresh'),('offset','target_offset')]:
69
+ spec+=f':{parameter}={measured[key]}'
70
+ return _publish(destination,lambda output:_ffmpeg('-v','error','-i',source,'-af',spec,'-ar',48000,'-c:a','pcm_s16le',output))
71
+
72
+
73
+ class BeatTrack(Track):
74
+ def __init__(self,beat_map,values,*,ease='smooth'):
75
+ values=tuple(values)
76
+ if len(values)!=len(beat_map.times): raise ValueError('One value per beat required')
77
+ super().__init__(*(Key(t,v,ease) for t,v in zip(beat_map.times,values)))
78
+
79
+
80
+ class SpeechSynthesizer:
81
+ """Provider(text, temporary_wav_path, **options) writes PCM WAV.
82
+
83
+ No provider selected implicitly and no network call in the engine. Provider
84
+ callbacks may use an SDK, local model, or an OS voice at the caller's choice.
85
+ """
86
+ def __init__(self,provider):
87
+ if not callable(provider): raise TypeError('Explicit TTS provider required')
88
+ self.provider=provider
89
+
90
+ def synthesize(self,text,path,**options):
91
+ if not isinstance(text,str) or not text.strip(): raise ValueError('Speech text cannot be empty')
92
+ return _publish(path,lambda output:self.provider(text,output,**options))
@@ -0,0 +1,41 @@
1
+ """Load project catalogs without treating historical capability labels as runtime.
2
+
3
+ Adapters are explicit Python callbacks owned by a project. Catalog data never
4
+ selects/imports a Python symbol or executes a module.
5
+ """
6
+ from copy import deepcopy
7
+ import json
8
+ from pathlib import Path
9
+
10
+
11
+ class PresetLibrary:
12
+ def __init__(self):
13
+ self._presets={}
14
+ self._adapters={}
15
+
16
+ def load_catalog(self,path):
17
+ data=json.loads(Path(path).read_text(encoding='utf-8-sig'))
18
+ category=data['category']; presets=data['presets']
19
+ if not isinstance(category,str) or not isinstance(presets,list): raise ValueError('Invalid catalog')
20
+ pending={}
21
+ for preset in presets:
22
+ id=preset['id']
23
+ if not isinstance(id,str) or not id or id in self._presets or id in pending: raise ValueError('Duplicate/invalid preset id')
24
+ if not isinstance(preset.get('params',{}),dict): raise ValueError('Preset params must be an object')
25
+ pending[id]={'category':category,**deepcopy(preset)}
26
+ self._presets.update(pending)
27
+ return self
28
+
29
+ def register_adapter(self,category,factory):
30
+ if category in self._adapters or not callable(factory): raise ValueError('Category adapter must be unique and callable')
31
+ self._adapters[category]=factory
32
+
33
+ def describe(self):
34
+ return [dict(id=id,category=p['category'],historical_capability=p.get('capability','unverified'),
35
+ adapter_registered=p['category'] in self._adapters) for id,p in self._presets.items()]
36
+
37
+ def resolve(self,id,**parameter_overrides):
38
+ preset=deepcopy(self._presets[id]); category=preset['category']
39
+ if category not in self._adapters: raise ValueError(f'Preset {id}: no adapter registered for {category}')
40
+ preset['params']={**preset.get('params',{}),**parameter_overrides}
41
+ return self._adapters[category](preset)
motionkit2d/presets.py ADDED
@@ -0,0 +1,33 @@
1
+ """Reusable painters that can be combined with user-authored scenes."""
2
+ from .draw import GOLD, WHITE, lamp, say, stage
3
+ from .effects import tween
4
+
5
+
6
+ def stage_painter(*,theme='green',floor=None,seed=541,dust=60,focus=(.5,.5)):
7
+ """Return a background painter. A None floor leaves the stage seamless."""
8
+ def paint(image,frame):
9
+ stage(image,frame.t,theme=theme,floor=floor,seed=seed,dust=dust,focus=focus)
10
+ return paint
11
+
12
+
13
+ def spotlight_painter(*,x=None,y=64,floor=None,spread=1,pole=180,fade=.55):
14
+ """Return a stage painter with a lamp that lights up on cue."""
15
+ def paint(image,frame):
16
+ floor_y=frame.height*.89 if floor is None else floor
17
+ center=frame.width*.48 if x is None else x
18
+ stage(image,frame.t,theme='warm')
19
+ lamp(image,tween(frame.t,0,fade,.1,1),x=center,y=y,floor=floor_y,spread=spread,pole=pole)
20
+ return paint
21
+
22
+
23
+ def title_card(title,subtitle='',*,theme='plum',accent=GOLD,title_size=None,subtitle_size=None):
24
+ """Return a centered title scene painter with a delayed subtitle."""
25
+ def paint(image,frame):
26
+ stage(image,frame.t,theme=theme)
27
+ w,h=frame.width,frame.height
28
+ size=title_size or min(w*.085,h*.138)
29
+ sub=subtitle_size or min(w*.035,h*.052)
30
+ say(image,frame.t,.04,w/2,h*.44,title,size,style='bold',c=accent,glow=True,duration=.42)
31
+ if subtitle:
32
+ say(image,frame.t,.38,w/2,h*.58,subtitle,sub,c=WHITE)
33
+ return paint
motionkit2d/props.py ADDED
@@ -0,0 +1,126 @@
1
+ """Reusable procedural props with explicit semantic anchors."""
2
+ from . import draw
3
+ from .catalog import Asset
4
+
5
+
6
+ def phone(im, color, screen):
7
+ d=draw.draw(im)
8
+ draw.rect(d,0,0,80,160,12,color)
9
+ draw.rect(d,6,12,68,132,6,screen)
10
+ draw.line(d,[(30,152),(50,152)],'#BFCAD9',3,True)
11
+
12
+
13
+ def laptop(im, color, screen):
14
+ d=draw.draw(im)
15
+ draw.rect(d,8,0,144,90,6,color)
16
+ draw.rect(d,15,7,130,75,2,screen)
17
+ draw.polygon(d,[(8,90),(152,90),(160,106),(0,106)],color)
18
+
19
+
20
+ def bed(im, color, fabric):
21
+ d=draw.draw(im)
22
+ draw.rect(d,0,5,15,105,4,color)
23
+ draw.rect(d,10,46,220,46,6,fabric)
24
+ draw.rect(d,17,34,52,23,7,'#EEE8DE')
25
+ for x in (8,215): draw.rect(d,x,88,10,28,2,color)
26
+
27
+
28
+ def table(im, color):
29
+ d=draw.draw(im)
30
+ draw.rect(d,0,0,180,13,4,color)
31
+ for x in (12,156): draw.rect(d,x,10,12,105,2,color)
32
+
33
+
34
+ def sofa(im, color):
35
+ d=draw.draw(im)
36
+ draw.rect(d,10,0,190,80,15,color)
37
+ draw.rect(d,0,45,210,55,10,color)
38
+ draw.line(d,[(25,76),(185,76)],'#D0D1DC',3)
39
+ for x in (20,180): draw.rect(d,x,96,10,16,2,'#58483E')
40
+
41
+
42
+ def window(im, color, glass):
43
+ d=draw.draw(im)
44
+ draw.rect(d,0,0,140,160,4,color)
45
+ draw.rect(d,7,7,126,146,1,glass)
46
+ draw.line(d,[(70,7),(70,153)],color,6)
47
+ draw.line(d,[(7,80),(133,80)],color,6)
48
+
49
+
50
+ def book(im, color):
51
+ d=draw.draw(im)
52
+ draw.rect(d,0,0,60,80,3,color)
53
+ draw.line(d,[(8,3),(8,77)],'#DAD6C6',3)
54
+ draw.line(d,[(18,25),(48,25)],'#E9E6D9',3)
55
+
56
+
57
+ def cup(im, color):
58
+ d=draw.draw(im)
59
+ draw.oval(d,57,23,14,15,None,color,5)
60
+ draw.rect(d,3,0,50,58,8,color)
61
+ draw.oval(d,28,5,22,5,'#4C3025')
62
+
63
+
64
+ def bottle(im, color):
65
+ d=draw.draw(im)
66
+ draw.rect(d,15,0,20,20,3,'#BAC7D5')
67
+ draw.rect(d,3,17,44,83,10,color)
68
+ draw.rect(d,3,43,44,30,1,'#DCEDE5')
69
+
70
+
71
+ def gift(im, color, ribbon):
72
+ d=draw.draw(im)
73
+ draw.rect(d,0,18,80,65,2,color)
74
+ draw.rect(d,32,18,16,65,0,ribbon)
75
+ draw.line(d,[(8,8),(40,20),(72,8),(58,0),(40,20),(22,0),(8,8)],ribbon,5,True)
76
+
77
+
78
+ def letter(im, color):
79
+ d=draw.draw(im)
80
+ draw.rect(d,0,0,100,65,3,color)
81
+ draw.line(d,[(0,0),(50,36),(100,0)],'#978A83',2)
82
+
83
+
84
+ def flower(im, color):
85
+ d=draw.draw(im)
86
+ draw.line(d,[(30,28),(30,100)],'#5F9E72',5,True)
87
+ draw.polygon(d,[(30,70),(7,53),(15,78)],'#5F9E72')
88
+ for x,y in ((15,18),(43,18),(15,40),(43,40)): draw.oval(d,x,y,13,13,color)
89
+ draw.oval(d,29,29,10,10,'#F3C96A')
90
+
91
+
92
+ def bubble(im, color):
93
+ d=draw.draw(im)
94
+ draw.rect(d,0,0,150,65,14,color)
95
+ draw.polygon(d,[(20,60),(15,82),(47,60)],color)
96
+ for x in (45,75,105): draw.oval(d,x,32,4,4,'#596C83')
97
+
98
+
99
+ def mirror(im, color):
100
+ d=draw.draw(im)
101
+ draw.oval(d,40,60,38,58,color)
102
+ draw.oval(d,40,60,31,51,'#B6D2E3')
103
+ draw.line(d,[(22,80),(48,27)],'#E8F5FA',3)
104
+
105
+
106
+ def register_props(registry):
107
+ specs=[
108
+ ('electronics.phone',(80,160),{'grip':(40,110),'screen':(40,65)},phone,dict(color='#263449',screen='#85B7C9')),
109
+ ('electronics.tablet',(80,160),{'grip':(40,110),'screen':(40,65)},phone,dict(color='#C2C8D4',screen='#5A718D')),
110
+ ('electronics.laptop',(160,106),{'surface':(80,90)},laptop,dict(color='#788598',screen='#334C6D')),
111
+ ('home.bed',(230,116),{'seat':(115,46),'bedside':(240,116)},bed,dict(color='#806853',fabric='#859AB3')),
112
+ ('home.table',(180,115),{'surface':(90,0)},table,dict(color='#A98963')),
113
+ ('home.sofa',(210,112),{'seat':(105,76)},sofa,dict(color='#827C9F')),
114
+ ('home.window',(140,160),{'sill':(70,160)},window,dict(color='#BFC6CF',glass='#4F6A8C')),
115
+ ('personal.book',(60,80),{'grip':(7,40)},book,dict(color='#B06E79')),
116
+ ('food.cup',(74,60),{'grip':(65,23),'rim':(28,5)},cup,dict(color='#E1D5C0')),
117
+ ('food.bottle',(50,100),{'grip':(25,55)},bottle,dict(color='#74B9CF')),
118
+ ('gifts.box',(80,83),{'grip':(40,18)},gift,dict(color='#B47893',ribbon='#E9CA7A')),
119
+ ('gifts.letter',(100,65),{'grip':(50,32)},letter,dict(color='#E8DBBC')),
120
+ ('gifts.flower',(60,105),{'grip':(30,85)},flower,dict(color='#EBA0AA')),
121
+ ('symbols.mirror',(80,120),{},mirror,dict(color='#BD9E6C')),
122
+ ('ui.chat',(150,82),{'tail':(15,82)},bubble,dict(color='#D6E1EE')),
123
+ ]
124
+ for name,size,anchors,paint,defaults in specs:
125
+ common={'center':(size[0]/2,size[1]/2),'bottom':(size[0]/2,size[1]),**anchors}
126
+ registry.register(Asset(name,size,common,paint,defaults))
motionkit2d/qc.py ADDED
@@ -0,0 +1,78 @@
1
+ """End-to-end quality reports with explicit incomplete coverage and CLI gating."""
2
+ from dataclasses import asdict
3
+ import subprocess
4
+ import tempfile
5
+
6
+ from PIL import Image
7
+
8
+ from . import draw
9
+ from .export import _binary, verify
10
+ from .quality import Finding, validate_graph, validate_frames, validate_audio, validate_glyphs, validate_attachment
11
+ from .scene_graph import SceneGraph
12
+ from .rig import Attachment
13
+ from .typography import AnimatedText
14
+
15
+
16
+ def decoded_frames(path,width,height):
17
+ """Bounded-memory full decode. Raise on truncated frames or FFmpeg failure."""
18
+ with tempfile.TemporaryFile() as errors:
19
+ process=subprocess.Popen([_binary('ffmpeg'),'-v','error','-i',str(path),'-an','-f','rawvideo','-pix_fmt','rgb24','pipe:1'],stdout=subprocess.PIPE,stderr=errors)
20
+ try:
21
+ size=width*height*3
22
+ while True:
23
+ payload=bytearray()
24
+ while len(payload)<size:
25
+ chunk=process.stdout.read(size-len(payload))
26
+ if not chunk: break
27
+ payload.extend(chunk)
28
+ if not payload: break
29
+ if len(payload)!=size: raise ValueError('Truncated decoded frame')
30
+ yield Image.frombytes('RGB',(width,height),bytes(payload))
31
+ if process.wait():
32
+ errors.seek(0); raise ValueError(errors.read().decode(errors='replace'))
33
+ finally:
34
+ process.stdout.close()
35
+ if process.poll() is None: process.kill()
36
+ process.wait()
37
+
38
+
39
+ def quality_report(video,*,decoded_path=None,expect_audio=None):
40
+ findings=[]; coverage={}; count=0
41
+ if decoded_path is not None:
42
+ verify(video,decoded_path,audio=bool(video.audio) if expect_audio is None else expect_audio)
43
+ coverage['metadata']='PASS'
44
+ images=decoded_frames(decoded_path,video.width,video.height)
45
+ else:
46
+ coverage['metadata']='NOT TESTED'
47
+ images=(video.frame(i) for i in range(video.frame_count))
48
+ def counted():
49
+ nonlocal count
50
+ for image in images:
51
+ count+=1; yield image
52
+ try: findings.extend(validate_frames(counted(),fps=video.fps))
53
+ finally: images.close()
54
+ coverage['frames']='PASS' if count==video.frame_count else 'FAIL'
55
+ if count!=video.frame_count:
56
+ findings.append(Finding('frame_count','FAIL','error','video',str(video.frame_count),str(count)))
57
+ graph_count=0
58
+ for scene,length in zip(video.scenes,video.lengths):
59
+ graph=scene.paint
60
+ if not isinstance(graph,SceneGraph): continue
61
+ graph_count+=1; times=tuple(sorted({0,(length//2)/video.fps,(length-1)/video.fps}))
62
+ findings.extend(validate_graph(graph,video.width,video.height,times=times))
63
+ for node in graph.nodes.values():
64
+ if isinstance(node.content,Attachment): findings.extend(validate_attachment(node.content,times=times))
65
+ if isinstance(node.content,AnimatedText):
66
+ text=node.content
67
+ findings.append(validate_glyphs(text.content,draw.font(text.size,text.font).path))
68
+ coverage['layout']='PASS' if graph_count==len(video.scenes) else 'NOT TESTED'
69
+ if decoded_path is not None and (bool(video.audio) if expect_audio is None else expect_audio):
70
+ findings.extend(validate_audio(decoded_path)); coverage['audio']='PASS'
71
+ else: coverage['audio']='N/A' if not video.audio else 'NOT TESTED'
72
+ failed=any(f.status=='FAIL' for f in findings) or 'FAIL' in coverage.values()
73
+ incomplete=any(f.status=='NOT TESTED' for f in findings) or 'NOT TESTED' in coverage.values()
74
+ return {'status':'FAIL' if failed else 'INCOMPLETE' if incomplete else 'PASS',
75
+ 'frames_checked':count,'coverage':coverage,'findings':[asdict(f) for f in findings],
76
+ 'limits':['Layout sampled at scene start/middle/end; masks and glyph shapes are not inferred.',
77
+ 'Black/flash/motion checks are pixel heuristics and may flag intentional cuts.',
78
+ 'PASS describes implemented technical checks, not artistic acceptance.']}
motionkit2d/quality.py ADDED
@@ -0,0 +1,122 @@
1
+ """Conservative quality diagnostics. Heuristics report findings, not aesthetics."""
2
+ from dataclasses import dataclass, asdict
3
+ from itertools import combinations
4
+
5
+ import numpy as np
6
+
7
+ from .composition import SafeZone, overlaps
8
+ from .layout import Rect
9
+ from .rig import sample
10
+ from .typography import AnimatedText, reading_time
11
+
12
+
13
+ @dataclass(frozen=True)
14
+ class Finding:
15
+ check: str
16
+ status: str
17
+ severity: str
18
+ subject: str
19
+ expected: str
20
+ actual: str
21
+ time: float | None = None
22
+
23
+ def as_dict(self): return asdict(self)
24
+
25
+
26
+ def validate_graph(graph,width,height,*,times=(0,),safe_zone=SafeZone()):
27
+ """AABB diagnostics; supplied bounds must enclose animated content.
28
+
29
+ These checks do not infer content hidden by masks or glyph shapes.
30
+ """
31
+ graph.validate(); findings=[]; safe=safe_zone.rect(width,height)
32
+ for t in times:
33
+ boxes={}
34
+ camera=sample(graph.camera,t)
35
+ for id,node in graph.nodes.items():
36
+ opacity=1; visible=True; current=node
37
+ while current:
38
+ visible=visible and bool(sample(current.visible,t))
39
+ opacity*=sample(current.opacity,t)
40
+ current=graph.nodes.get(current.parent)
41
+ if not visible or opacity<=0: continue
42
+ b=graph.world_bounds(id,t)
43
+ if b is None:
44
+ if node.content is not None: findings.append(Finding('bounds','NOT TESTED','info',id,'Declared bounds','No bounds',t))
45
+ continue
46
+ root=node
47
+ while root.parent: root=graph.nodes[root.parent]
48
+ if camera and not root.screen_space:
49
+ points=[camera.world_to_screen(b.anchor(u,v),width,height) for u,v in ((0,0),(1,0),(0,1),(1,1))]
50
+ xs,ys=zip(*points); b=Rect(min(xs),min(ys),max(xs)-min(xs),max(ys)-min(ys))
51
+ boxes[id]=b
52
+ inside=safe.contains(b.anchor(0,0)) and safe.contains(b.anchor(1,1))
53
+ findings.append(Finding('safe_zone','PASS' if inside else 'FAIL','warning',id,
54
+ 'Bounds inside safe zone',str(b),t))
55
+ if isinstance(node.content,AnimatedText):
56
+ text=node.content; required=reading_time(text.content)
57
+ findings.append(Finding('reading_time','PASS' if text.hold>=required else 'FAIL','warning',id,
58
+ f'Hold >= {required:.3f}s',f'{text.hold:.3f}s',t))
59
+ for a,b in combinations(boxes,2):
60
+ if 'text' in {graph.nodes[a].role,graph.nodes[b].role} and overlaps(boxes[a],boxes[b]):
61
+ # Skip a group and its descendants: these bounds intentionally overlap.
62
+ def ancestor(parent,child):
63
+ current=graph.nodes[child].parent
64
+ while current:
65
+ if current==parent: return True
66
+ current=graph.nodes[current].parent
67
+ return False
68
+ if ancestor(a,b) or ancestor(b,a): continue
69
+ findings.append(Finding('text_overlap','FAIL','warning',f'{a}/{b}','No AABB overlap','Overlapping declared bounds',t))
70
+ return findings
71
+
72
+
73
+ def validate_frames(frames,*,fps=30,black_threshold=.01,flash_threshold=.6,motion_threshold=.5):
74
+ """Inspect supplied consecutive frames; flash/motion are pixel heuristics."""
75
+ if fps<=0: raise ValueError('FPS must be positive')
76
+ findings=[]; previous=None; previous_mean=None
77
+ for i,image in enumerate(frames):
78
+ data=np.asarray(image.convert('RGB'),dtype=float)/255
79
+ mean=float(data.mean()); t=i/fps
80
+ if mean<black_threshold:
81
+ findings.append(Finding('black_frame','FAIL','warning',str(i),f'Mean >= {black_threshold}',f'{mean:.5f}',t))
82
+ if previous is not None:
83
+ if data.shape!=previous.shape: raise ValueError('Frame dimensions changed')
84
+ delta=abs(mean-previous_mean)
85
+ if delta>flash_threshold: findings.append(Finding('flash','FAIL','warning',str(i),f'Luminance delta <= {flash_threshold}',f'{delta:.5f}',t))
86
+ motion=float(np.abs(data-previous).mean())
87
+ if motion>motion_threshold: findings.append(Finding('motion_jump','FAIL','warning',str(i),f'Pixel delta <= {motion_threshold}',f'{motion:.5f}',t))
88
+ previous=data; previous_mean=mean
89
+ if previous is None: raise ValueError('No frames supplied')
90
+ return findings
91
+
92
+
93
+ def validate_attachment(attachment,*,times=(0,),tolerance=1e-6):
94
+ from math import hypot
95
+ result=[]
96
+ for t in times:
97
+ if t<attachment.start or (attachment.release is not None and t>attachment.release): continue
98
+ a=attachment.anchor(attachment.child_anchor,t); b=attachment.target.anchor(attachment.target_anchor,t)
99
+ error=hypot(a[0]-b[0],a[1]-b[1])
100
+ result.append(Finding('attachment','PASS' if error<=tolerance else 'FAIL','error',attachment.child_anchor,
101
+ f'Anchor error <= {tolerance}',str(error),t))
102
+ return result
103
+
104
+
105
+ def validate_audio(path):
106
+ from .audio_analysis import decode_audio
107
+ samples,_=decode_audio(path,rate=48000,mono=False)
108
+ if not samples.size: raise ValueError('No decoded audio samples')
109
+ peak=float(np.max(np.abs(samples))); clipped=int(np.count_nonzero(np.abs(samples)>=1))
110
+ return [Finding('audio_clipping','FAIL' if clipped else 'PASS','warning',str(path),
111
+ 'No full-scale samples in any channel',f'peak={peak:.6f}; clipped={clipped}')]
112
+
113
+
114
+ def validate_glyphs(content,font_path):
115
+ from unicodedata import normalize
116
+ try: from fontTools.ttLib import TTFont
117
+ except ImportError:
118
+ return Finding('glyphs','NOT TESTED','info',str(font_path),'Font cmap coverage','Install motionkit2d[quality]')
119
+ with TTFont(font_path) as font:
120
+ cmap=font.getBestCmap() or {}
121
+ missing=sorted({char for char in normalize('NFC',content) if not char.isspace() and ord(char) not in cmap})
122
+ return Finding('glyphs','FAIL' if missing else 'PASS','error',str(font_path),'All non-whitespace glyphs present',repr(missing))