Skip to content

Make videos on the computer you already own. FreeVideo runs MiniMax H3 in as little as 8 GB of VRAM and 16 GB of RAM, and adapts its acceleration path to your hardware.

Agent cast: start from six pictures only for measured card classes (tier, people, precision)...

Bowen Xue911fe6499ae0
diff --git a/freevideo_engine/agent/comfy.py b/freevideo_engine/agent/comfy.py
index 96deda1..4d7f320 100644
--- a/freevideo_engine/agent/comfy.py
+++ b/freevideo_engine/agent/comfy.py
@@ -101,6 +101,13 @@ class ComfyPort:
cache = getattr(self.server, '_freevideo_capabilities', None)
return cache.get(_query(query)) if hasattr(cache, 'get') else dict(UNAVAILABLE)
+ def prepared_precision(self):
+ """'int8' or 'fp8', the family of the model setup prepared for this machine; None while unknown."""
+ cache = getattr(self.server, '_freevideo_capabilities', None)
+ snapshot = getattr(cache, 'snapshot', None)
+ saved = snapshot[0].get('prepared_format', 'int8') if snapshot else None
+ return next((p for p in ('int8', 'fp8') if isinstance(saved, str) and saved.startswith(p)), None)
+
def output_summary(self, relative):
from .jobs import library_id
from ..comfy_library import _report
diff --git a/freevideo_engine/agent/drama.py b/freevideo_engine/agent/drama.py
index 877c5d1..e8c425f 100644
--- a/freevideo_engine/agent/drama.py
+++ b/freevideo_engine/agent/drama.py
@@ -62,7 +62,16 @@ CAPTIONED = 3 # the score of a take with unwanted captions
CARD = re.compile(r'c[0-9a-f]{12}') # characters.<key>.card names a cast library card
# How a shot carries its cast cards. Change these after the reference tests; nothing else needs to.
PICTURE_ORDER = ('sheet', 'front', 'three_quarter', 'face') # then any other label, in card order
-PICTURES_EACH = 3
+PICTURES_EACH = 6
+PICTURES_LEAST = 3 # What a person carried before six: a device that cannot hold more still shoots with these.
+# Six pictures cost extra time on every step. A class of machine starts from six only when it was measured at 25%
+# extra or less on every step, cold and warm: (card memory tier in GiB, people in the shot, weight precision).
+# Everything else, and everything unmeasured, starts from three. Only Linux is measured. Two people went 45-79% over
+# at 8 to 24 GiB, so only one-person classes can ever be listed. No class has passed yet.
+SIX_PICTURES_CLASSES = frozenset()
+SIX_PICTURES_TIERS_GIB = (8, 10, 12, 16, 20, 24, 32) # measured card sizes; a card takes the largest one it reaches
+SIX_PICTURES_SYSTEMS = ('Linux',)
+TIER_SLACK_GIB = .5 # A "24 GB" card reports a little under 24 GiB.
MAX_VOICES = 3 # voice clips per shot, the model limit
MAX_REFERENCES = 32
@@ -289,17 +298,18 @@ def subject_definitions(subjects):
return 'subject_definitions: ' + ' '.join(parts)
-def _pictures(card):
+def _pictures(card, each=PICTURES_EACH):
rank = {label: i for i, label in enumerate(PICTURE_ORDER)}
rows = sorted(enumerate(card.get('images') or []), key=lambda r: (rank.get(r[1]['label'], len(rank)), r[0]))
- return [row['media'] for _, row in rows[:PICTURES_EACH]]
+ return [row['media'] for _, row in rows[:each]]
-def cast_references(play, shot, cards, *, continues=False):
+def cast_references(play, shot, cards, *, continues=False, each=PICTURES_EACH):
"""Which cast cards a shot carries, as references and a prompt prefix.
cards maps a card ID to the current card, or None once it is gone. The same
- function serves plan previews and the moment a take is submitted.
+ function serves plan previews and the moment a take is submitted. each is
+ the most pictures one person carries; pictures_each says what was used.
cast_reference: None (no character in the shot has a card), 'own' (the shot
names its own first frame or references), 'missing' (a card was deleted),
'partial' (not everyone fit) or 'cards'. 'omitted' lists people left out
@@ -310,7 +320,7 @@ def cast_references(play, shot, cards, *, continues=False):
characters = play.get('characters', {})
keys = [k for k in cast(play, shot) if isinstance(characters[k].get('card'), str)]
result = dict(cast_reference=None, people=[], omitted=[], voice_omitted=[], missing=[], references=[],
- prefix=None, subjects=[], cards={})
+ prefix=None, subjects=[], cards={}, pictures_each=each, clip_seconds=[])
if not keys:
return result
if shot.get('first') is not None or shot.get('references'):
@@ -327,7 +337,7 @@ def cast_references(play, shot, cards, *, continues=False):
if card is None:
result['missing'].append(key)
continue
- images = _pictures(card)
+ images = _pictures(card, each)
if continues:
if images and len(chosen) < specs.CONTINUED_PICTURES:
chosen.append((key, card, images[:1], False))
@@ -349,6 +359,7 @@ def cast_references(play, shot, cards, *, continues=False):
result['references'].extend(dict(item) for item in images)
if voice:
clips.append(dict(card['voice']['clip']))
+ result['clip_seconds'].append(card['voice'].get('end', 15.) - card['voice'].get('start', 0.))
person = characters[key]
subject = dict(name=person.get('name') or key, description=card.get('description'),
pictures=(picture + 1, picture + len(images)) if images else None,
@@ -367,6 +378,27 @@ def cast_references(play, shot, cards, *, continues=False):
return result
+def pictures_start(machine, people=1):
+ """Pictures a person carries before the length check: six for a measured class, else three.
+ machine is a capability table's `machine` row; a missing or unreadable one is unmeasured."""
+ try:
+ if machine['system'] in SIX_PICTURES_SYSTEMS:
+ vram = float(machine['vram_gib']) + TIER_SLACK_GIB
+ tier = max((t for t in SIX_PICTURES_TIERS_GIB if t <= vram), default=None)
+ if tier is not None and (tier, people, machine['precision']) in SIX_PICTURES_CLASSES:
+ return PICTURES_EACH
+ except (KeyError, TypeError, ValueError):
+ pass
+ return PICTURES_LEAST
+
+
+def pictures_note(each, cut=True):
+ """One sentence when the length check carried fewer pictures than this device started from; otherwise None."""
+ if each is None or each >= PICTURES_EACH or not cut:
+ return None
+ return 'Each person carries %d pictures in this shot; this device cannot hold more at this length.' % each
+
+
PROMPT_LIMIT = 20000
DESCRIPTION_CUTS = (500, 250, 120, 0)
diff --git a/freevideo_engine/agent/length.py b/freevideo_engine/agent/length.py
index eb4a492..adacee8 100644
--- a/freevideo_engine/agent/length.py
+++ b/freevideo_engine/agent/length.py
@@ -1,4 +1,5 @@
"""Studio capability limits for Agent generation plans, without hardware probing."""
+import json
import time
# A size asked for the first time is worked out in the background in about 0.1 s. The plan that asks first
@@ -6,9 +7,12 @@ import time
WAIT_SECONDS = 3.
-def capability_table(port, spec, *, wait=0.):
+def capability_table(port, spec, *, wait=0., references=None, task=None):
+ """references: panel metadata rows (see capabilities.normalize_references) for a layout other than the default."""
query = dict(width=str(spec['width']), height=str(spec['height']),
- task=spec['task'], adapters='1' if spec['loras'] else '0')
+ task=task or spec['task'], adapters='1' if spec['loras'] else '0')
+ if references is not None:
+ query['references'] = json.dumps(references, separators=(',', ':'))
deadline = time.monotonic() + wait
try:
while True:
diff --git a/freevideo_engine/agent/production.py b/freevideo_engine/agent/production.py
index 4c0a515..d172622 100644
--- a/freevideo_engine/agent/production.py
+++ b/freevideo_engine/agent/production.py
@@ -721,7 +721,9 @@ def view(state):
latest = next((t for t in reversed(shot['takes']) if 'cast_reference' in t), {})
row.update(cast_reference=latest.get('cast_reference'), cast_omitted=deepcopy(latest.get('cast_omitted', [])),
cast_voice_omitted=deepcopy(latest.get('cast_voice_omitted', [])),
- cast_missing=deepcopy(latest.get('cast_missing', [])))
+ cast_missing=deepcopy(latest.get('cast_missing', [])),
+ cast_pictures_each=latest.get('cast_pictures_each'),
+ cast_note=drama.pictures_note(latest.get('cast_pictures_each'), latest.get('cast_pictures_cut', True)))
row['takes'] = []
for take in shot['takes']:
item = {key: deepcopy(take[key]) for key in ('take', 'job', 'generation', 'seed', 'state', 'stale',
diff --git a/freevideo_engine/agent/productions.py b/freevideo_engine/agent/productions.py
index fab1b08..df88866 100644
--- a/freevideo_engine/agent/productions.py
+++ b/freevideo_engine/agent/productions.py
@@ -65,6 +65,16 @@ def _rows(error):
return rows
+def pictures_each(resolved):
+ """Pictures per person a shot used; None when no card was carried."""
+ return resolved['pictures_each'] if resolved['people'] else None
+
+
+def pictures_cut(resolved):
+ """True when the length check took pictures away from what this device starts with."""
+ return bool(resolved['people'] and resolved.get('pictures_cut'))
+
+
class MaterialRejected(JobError):
"""External callers named material the content-only boundary does not admit: the job validation error."""
status = 422
@@ -161,6 +171,7 @@ def failure(view):
class Productions:
def __init__(self, jobs):
self.jobs = jobs
+ self._machine = None # the capability table's machine row, once known
self.directory = jobs.directory / 'productions'
self.records = {}
self.changed = threading.Condition(jobs.lock)
@@ -358,11 +369,13 @@ class Productions:
problems = []
for i, (row, source, shot) in enumerate(zip(result['preview']['shots'], play['shots'], state['shots'])):
# The same resolution a take gets when it is submitted, with the cards as they are now.
- resolved = drama.cast_references(play, source, cards, continues=shot['continues'])
+ first = next((t for s, t in self._takes(state) if s is shot), None)
+ resolved = self._carry(play, source, cards, first and first['spec'], continues=shot['continues'])
row['prompt'] = drama.with_cast(row['prompt'], resolved)
row.update(cast_reference=resolved['cast_reference'], cast=resolved['people'],
cast_omitted=resolved['omitted'], cast_voice_omitted=resolved['voice_omitted'],
- cast_missing=resolved['missing'],
+ cast_missing=resolved['missing'], cast_pictures_each=pictures_each(resolved),
+ cast_note=drama.pictures_note(pictures_each(resolved), pictures_cut(resolved)),
references=len(resolved['references']))
try:
spec._text(row['prompt'], '/screenplay/shots/%d/prompt' % i, 20000)
@@ -389,9 +402,8 @@ class Productions:
item['continue_from'] = dict(from_job='j000000000000')
if item.get('continue_from', {}).get('ref'):
item['continue_from'] = dict(from_job='j000000000000')
- resolved = drama.cast_references(state['screenplay'],
- state['screenplay']['shots'][shot['index'] - 1], self._current(state['screenplay']),
- continues=shot['continues'])
+ resolved = self._carry(state['screenplay'], state['screenplay']['shots'][shot['index'] - 1],
+ self._current(state['screenplay']), item, continues=shot['continues'])
if resolved['references']:
item['media'] = dict(references=deepcopy(resolved['references']))
estimate, revision = generation_estimate(self.jobs.port, spec.normalize(item, port=self.jobs.port))
@@ -908,7 +920,9 @@ class Productions:
saved.update(cast=dict(resolved['cards']), cast_reference=resolved['cast_reference'],
cast_omitted=list(resolved['omitted']),
cast_voice_omitted=list(resolved['voice_omitted']),
- cast_missing=list(resolved['missing']))
+ cast_missing=list(resolved['missing']),
+ cast_pictures_each=pictures_each(resolved),
+ cast_pictures_cut=pictures_cut(resolved))
self._save(marker) # Durable before Jobs may accept it.
self.jobs.submit(item, client='production:' + identity, parent=dict(production=identity, ref=ref))
except spec.SpecError as error:
@@ -931,8 +945,8 @@ class Productions:
"""Read the cast cards now, at submission: later takes and reshoots use the cards as they are then."""
play = state['screenplay']
shot = next(s for s in state['shots'] if any(t['job'] == take['job'] for t in s['takes']))
- resolved = drama.cast_references(play, play['shots'][shot['index'] - 1], self._current(play),
- continues=shot['continues'])
+ resolved = self._carry(play, play['shots'][shot['index'] - 1], self._current(play), item,
+ continues=shot['continues'])
if resolved['cast_reference'] is None:
return resolved
if resolved['references']:
@@ -942,6 +956,79 @@ class Productions:
cast_reference=resolved['cast_reference'])
return resolved
+ def _carry(self, play, shot, cards, item, *, continues):
+ """The cast a shot carries: this device's starting number of pictures a person (six for a measured
+ class of card, people and precision, else three), fewer where it cannot hold them, down to three. Plan
+ previews and submissions both come here, so they agree."""
+ if continues:
+ # A continuing shot carries one picture a person whatever the device holds.
+ resolved = drama.cast_references(play, shot, cards, continues=True, each=drama.PICTURES_LEAST)
+ resolved.update(pictures_each=None, pictures_cut=False)
+ return resolved
+ people = len(drama.cast_references(play, shot, cards, continues=continues, each=drama.PICTURES_LEAST)['people'])
+ start = each = self._pictures_start(item, people)
+ while True:
+ resolved = drama.cast_references(play, shot, cards, continues=continues, each=each)
+ if each <= drama.PICTURES_LEAST or item is None or not self._too_long(item, resolved):
+ resolved['pictures_cut'] = each < start
+ return resolved
+ each -= 1
+
+ def _pictures_start(self, item, people):
+ """Where the picture count starts for this many people on this machine, from the capability table's
+ graphics card, system and precision. Any canvas names the same machine, so a shot without a take asks
+ about the default canvas."""
+ if self._machine is None:
+ from .length import capability_table
+ width, height = spec.canvas_size(item or {})
+ table = capability_table(self.jobs.port, dict(width=width, height=height, task='ref2va', loras=False), wait=3.)
+ if table.get('status') != 'ready':
+ return drama.pictures_start(None) # Not worked out yet: three, and the next ask looks again.
+ precision = getattr(self.jobs.port, 'prepared_precision', lambda: None)()
+ # The machine does not change while this server runs.
+ self._machine = dict(table.get('machine') or {}, precision=precision if isinstance(precision, str) else None)
+ return drama.pictures_start(self._machine, people)
+
+ def _too_long(self, item, resolved):
+ """True when this device cannot generate the shot with these references. A table that is not ready
+ (still computing, unavailable) or lacks this canvas says False and keeps the pictures; a ready table
+ that admits no length at this canvas, or a limit this shot's length cannot be planned under, says True."""
+ pictures = sum(p['pictures'] for p in resolved['people'])
+ if not pictures:
+ return False
+ try:
+ from ..chain_plan import PlanError, plan as chain_plan
+ from .length import capability_table
+ media = dict(references=deepcopy(resolved['references']))
+ normalized = spec.normalize(dict(deepcopy(item), media=media))
+ rows = ([dict(kind='image', width=normalized['width'], height=normalized['height'])] * pictures
+ + [dict(kind='audio', seconds=seconds) for seconds in resolved['clip_seconds']])
+ table = capability_table(self.jobs.port, normalized, wait=3., references=rows,
+ task='ref2va_av' if resolved['clip_seconds'] else 'ref2va')
+ if table.get('status') != 'ready':
+ return False
+ index = next((i for i, row in enumerate(table.get('sizes', []))
+ if (row['width'], row['height']) == (normalized['width'], normalized['height'])), None)
+ tiers = table.get('tiers', {})
+ tier = tiers.get(normalized['quality'])
+ if tier is None:
+ tier = next((row for row in tiers.values()
+ if row.get('steps') == normalized['base_steps'] and row.get('two_pass') == normalized['two_pass']
+ and (not normalized['two_pass'] or normalized['refine_steps'] == 3)), None)
+ maxima = tier.get('max_frames') if tier else None
+ if index is None or not isinstance(maxima, list) or index >= len(maxima):
+ return False
+ limit = maxima[index]
+ if limit is None:
+ return True # no length at all fits at this canvas with these pictures
+ try:
+ chain_plan(normalized['seconds'], max_frames=limit, continued=bool(normalized.get('continue_from')))
+ except PlanError:
+ return True
+ return False
+ except Exception: # The limit is advisory: a failure here keeps the pictures and lets the job decide.
+ return False
+
def _current(self, play):
"""Cards as they are now; a card deleted since the film started is None (the shot uses text)."""
cast = getattr(self.jobs, 'cast', None)
diff --git a/freevideo_engine/agent/schema.py b/freevideo_engine/agent/schema.py
index 79f7376..303b8ee 100644
--- a/freevideo_engine/agent/schema.py
+++ b/freevideo_engine/agent/schema.py
@@ -892,6 +892,8 @@ def production_response():
cast_reference=CAST_REFERENCE, cast_omitted=dict(type='array', items=string()),
cast_voice_omitted=dict(type='array', items=string()),
cast_missing=dict(type='array', items=string()),
+ cast_pictures_each=dict(type=['integer', 'null'], description='Pictures each person carries in this shot: six or three by graphics card class, fewer (down to three) when this device cannot hold the starting number at the shot length.'),
+ cast_note=dict(type=['string', 'null'], description='One sentence saying so, only when it was reduced from the starting number.'),
takes=dict(type='array', items=dict(type='object', properties=dict(take=number(1, integer=True), job=REF,
task={'oneOf': [JOB, {'type': 'null'}]}, generation=number(0, integer=True), seed=number(0, integer=True),
stale={'type': 'boolean'}, error={'type': ['object', 'null']},