lcode-cli 0.47.0__py3-none-any.whl → 0.49.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.
- lcode/__init__.py +1 -1
- lcode/agent.py +1 -0
- lcode/cli.py +12 -0
- lcode/film.py +322 -0
- lcode/media.py +46 -12
- lcode/media.toml +33 -1
- lcode/media_catalog.py +27 -11
- lcode/media_cloud.py +461 -0
- lcode/modes.py +10 -9
- lcode/repl.py +72 -0
- {lcode_cli-0.47.0.dist-info → lcode_cli-0.49.0.dist-info}/METADATA +7 -5
- {lcode_cli-0.47.0.dist-info → lcode_cli-0.49.0.dist-info}/RECORD +15 -13
- {lcode_cli-0.47.0.dist-info → lcode_cli-0.49.0.dist-info}/WHEEL +0 -0
- {lcode_cli-0.47.0.dist-info → lcode_cli-0.49.0.dist-info}/entry_points.txt +0 -0
- {lcode_cli-0.47.0.dist-info → lcode_cli-0.49.0.dist-info}/licenses/LICENSE +0 -0
lcode/__init__.py
CHANGED
lcode/agent.py
CHANGED
|
@@ -385,6 +385,7 @@ class Agent:
|
|
|
385
385
|
self.media_results: list[dict] = [] # the session's images, numbered (/gallery, /vary, /open)
|
|
386
386
|
self.last_request: dict | None = None # what /again repeats (lcode.media.redo)
|
|
387
387
|
self.image_refs: list[str] = [] # images every next request follows (/use)
|
|
388
|
+
self.cloud_spent = 0.0 # dollars, about, spent at cloud image and video models this session (media_cloud)
|
|
388
389
|
self.reflected = 0 # messages before this index were already checked for notes to remember
|
|
389
390
|
self._memory: memory_notes.Memory | None = None
|
|
390
391
|
self._agent_types: tuple[Path, dict[str, subagents.AgentType], list[str]] | None = None
|
lcode/cli.py
CHANGED
|
@@ -781,6 +781,13 @@ def comfyui_status(cfg: dict) -> tuple[str, bool | None]:
|
|
|
781
781
|
from lcode import media_catalog as catalog
|
|
782
782
|
|
|
783
783
|
model = catalog.load().find(cfg.get("image_model") or "") or catalog.load().models[catalog.DEFAULT_IMAGE]
|
|
784
|
+
if model.cloud:
|
|
785
|
+
from lcode import media_cloud
|
|
786
|
+
|
|
787
|
+
p = media_cloud.provider(model)
|
|
788
|
+
if not p.api_key():
|
|
789
|
+
return f"image model: {model.name}, at {p.name}, but {p.key_env} isn't set ({p.keys_url})", None
|
|
790
|
+
return f"image model: {model.name}, at {p.name} ({p.key_env} is set)", True
|
|
784
791
|
server = comfy.Server(cfg["comfyui_url"])
|
|
785
792
|
stats = server.stats()
|
|
786
793
|
install = None if stats else comfy.find_install(cfg["comfyui_path"])
|
|
@@ -1085,6 +1092,11 @@ def cmd_media(args) -> None:
|
|
|
1085
1092
|
model = cat.find(args.model or "")
|
|
1086
1093
|
if model is None:
|
|
1087
1094
|
fail(f"no media model {args.model!r}: lcode media lists them")
|
|
1095
|
+
if model.cloud:
|
|
1096
|
+
from lcode import media_cloud
|
|
1097
|
+
|
|
1098
|
+
console.print(f"Nothing to install: {media_cloud.ready_note(model)}")
|
|
1099
|
+
return
|
|
1088
1100
|
if not running and install is None:
|
|
1089
1101
|
fail(f"lcode needs ComfyUI to install models into. {comfy.install_hint()}")
|
|
1090
1102
|
ask = None if args.yes else (lambda q: Confirm.ask(q, default=True, console=console))
|
lcode/film.py
ADDED
|
@@ -0,0 +1,322 @@
|
|
|
1
|
+
"""Films: from one description to a short film with the same characters in every shot.
|
|
2
|
+
|
|
3
|
+
1. **A storyboard.** The prompt assistant (lcode.assistant) writes it: a title, the look of the whole film, the cast
|
|
4
|
+
(each living character described once; things and places are described in the shots), and the shots (what
|
|
5
|
+
happens, how long, the camera, who's in it). It's saved as `storyboard.json` in the film's folder, so it can be
|
|
6
|
+
edited and made again.
|
|
7
|
+
2. **The cast.** Each character gets a reference picture (FLUX.2 klein), made once and kept in `cast/`.
|
|
8
|
+
3. **The shots.** Each shot starts as a keyframe: a picture of the shot made with the cast's pictures as references,
|
|
9
|
+
so the characters look the same from shot to shot. Video mode's model then animates the keyframe.
|
|
10
|
+
4. **The film.** The shots are joined with cuts or fades (ffmpeg) into `film.mp4`, and a sound track can be added.
|
|
11
|
+
|
|
12
|
+
Any shot can be made again alone (`/film shot 2`), and the film joined again (`/film stitch`).
|
|
13
|
+
"""
|
|
14
|
+
|
|
15
|
+
from __future__ import annotations
|
|
16
|
+
|
|
17
|
+
import json
|
|
18
|
+
import re
|
|
19
|
+
import shutil
|
|
20
|
+
import subprocess
|
|
21
|
+
from collections.abc import Callable
|
|
22
|
+
from dataclasses import asdict, dataclass, field, replace
|
|
23
|
+
from pathlib import Path
|
|
24
|
+
from typing import TYPE_CHECKING
|
|
25
|
+
|
|
26
|
+
from lcode import assistant, comfy, imageopts, media
|
|
27
|
+
|
|
28
|
+
if TYPE_CHECKING:
|
|
29
|
+
from lcode.agent import Agent
|
|
30
|
+
|
|
31
|
+
MAX_SHOTS = 8
|
|
32
|
+
STORYBOARD = (
|
|
33
|
+
"You write storyboards for short AI-generated films. From the user's idea, write a film of {shots} shots, each "
|
|
34
|
+
"about {seconds} seconds. Answer with JSON only, in English:\n"
|
|
35
|
+
'{{"title": "a short title", "look": "the visual style of the whole film in one sentence (medium, light, '
|
|
36
|
+
'colour, lens)", "cast": [{{"name": "a one-word name", "description": "what the character looks like: '
|
|
37
|
+
'species or age, build, clothes, colours, distinctive features, in one sentence"}}], "shots": [{{"description": '
|
|
38
|
+
'"what happens in this shot, where, and who is in it, in one or two sentences, using the cast names", "camera": '
|
|
39
|
+
'"a shot type and camera move, like slow zoom in, tracking shot, static wide shot", "cast": ["names in this '
|
|
40
|
+
'shot"], "seconds": {seconds}}}]}}\n'
|
|
41
|
+
"The cast is one to three living characters (people, animals, creatures), with the same names in every shot. "
|
|
42
|
+
"Things and places are never cast members: a kite, a car, a house or a forest is described in the shots. Each "
|
|
43
|
+
"shot is one continuous moment; the film tells a small story from the first shot to the last. Describe what is "
|
|
44
|
+
"seen, never what is felt or heard."
|
|
45
|
+
)
|
|
46
|
+
TRANSITIONS = ("cut", "fade")
|
|
47
|
+
FADE = 0.5 # seconds a fade takes
|
|
48
|
+
|
|
49
|
+
|
|
50
|
+
class FilmError(Exception):
|
|
51
|
+
pass
|
|
52
|
+
|
|
53
|
+
|
|
54
|
+
@dataclass
|
|
55
|
+
class Shot:
|
|
56
|
+
description: str
|
|
57
|
+
camera: str = "static shot"
|
|
58
|
+
cast: list[str] = field(default_factory=list)
|
|
59
|
+
seconds: float = 4.0
|
|
60
|
+
|
|
61
|
+
|
|
62
|
+
@dataclass
|
|
63
|
+
class Board:
|
|
64
|
+
title: str
|
|
65
|
+
look: str
|
|
66
|
+
cast: dict[str, str] # name -> description
|
|
67
|
+
shots: list[Shot]
|
|
68
|
+
idea: str = ""
|
|
69
|
+
transition: str = "cut"
|
|
70
|
+
sound: str = "" # a sound track for the whole film, made after it's joined
|
|
71
|
+
quality: str = "fast"
|
|
72
|
+
|
|
73
|
+
def to_json(self) -> dict:
|
|
74
|
+
data = asdict(self)
|
|
75
|
+
data["cast"] = [{"name": n, "description": d} for n, d in self.cast.items()]
|
|
76
|
+
return data
|
|
77
|
+
|
|
78
|
+
@classmethod
|
|
79
|
+
def from_json(cls, data: dict) -> Board:
|
|
80
|
+
cast = {}
|
|
81
|
+
for member in data.get("cast") or []:
|
|
82
|
+
if isinstance(member, dict) and str(member.get("name") or "").strip():
|
|
83
|
+
cast[str(member["name"]).strip()] = str(member.get("description") or "").strip()
|
|
84
|
+
shots = []
|
|
85
|
+
for raw in data.get("shots") or []:
|
|
86
|
+
if not isinstance(raw, dict) or not str(raw.get("description") or "").strip():
|
|
87
|
+
continue
|
|
88
|
+
seconds = raw.get("seconds")
|
|
89
|
+
shots.append(
|
|
90
|
+
Shot(
|
|
91
|
+
str(raw["description"]).strip(),
|
|
92
|
+
str(raw.get("camera") or "static shot").strip(),
|
|
93
|
+
[str(n).strip() for n in raw.get("cast") or [] if str(n).strip() in cast],
|
|
94
|
+
float(seconds) if isinstance(seconds, (int, float)) and 1 <= seconds <= 8 else 4.0,
|
|
95
|
+
)
|
|
96
|
+
)
|
|
97
|
+
if not shots:
|
|
98
|
+
raise FilmError("the storyboard has no shots")
|
|
99
|
+
return cls(
|
|
100
|
+
str(data.get("title") or "Untitled").strip(),
|
|
101
|
+
str(data.get("look") or "").strip(),
|
|
102
|
+
cast,
|
|
103
|
+
shots[:MAX_SHOTS],
|
|
104
|
+
str(data.get("idea") or ""),
|
|
105
|
+
data.get("transition") if data.get("transition") in TRANSITIONS else "cut",
|
|
106
|
+
str(data.get("sound") or ""),
|
|
107
|
+
data.get("quality") if data.get("quality") in imageopts.QUALITIES else "fast",
|
|
108
|
+
)
|
|
109
|
+
|
|
110
|
+
|
|
111
|
+
# ----------------------------------------------------------------------------- the storyboard
|
|
112
|
+
|
|
113
|
+
|
|
114
|
+
def films_folder(agent: Agent) -> Path:
|
|
115
|
+
return media.folder(agent) / "films"
|
|
116
|
+
|
|
117
|
+
|
|
118
|
+
def plan(agent: Agent, idea: str, shots: int = 3, seconds: float = 4.0) -> tuple[Board, Path]:
|
|
119
|
+
"""The assistant's storyboard for an idea, saved in a new film folder."""
|
|
120
|
+
model = assistant.pick(agent.ollama, agent.settings.prompt_assistant if agent.settings.prompt_assistant
|
|
121
|
+
not in assistant.SCOPES else "auto") # fmt: skip
|
|
122
|
+
if model is None:
|
|
123
|
+
raise FilmError("Films need the prompt assistant to write the storyboard: ollama pull qwen3.5:4b")
|
|
124
|
+
helper = assistant.Assistant(agent.ollama, model)
|
|
125
|
+
system = STORYBOARD.format(shots=shots, seconds=f"{seconds:g}")
|
|
126
|
+
with agent.console.status(f"The prompt assistant ({model}) is writing the storyboard…", spinner="dots"):
|
|
127
|
+
try:
|
|
128
|
+
data = assistant.parse_json(helper.write(system, idea, json_answer=True))
|
|
129
|
+
except assistant.AssistantError as e:
|
|
130
|
+
raise FilmError(str(e)) from e
|
|
131
|
+
data["idea"] = idea
|
|
132
|
+
board = Board.from_json(data)
|
|
133
|
+
folder = new_folder(agent, board.title)
|
|
134
|
+
save(board, folder)
|
|
135
|
+
return board, folder
|
|
136
|
+
|
|
137
|
+
|
|
138
|
+
def new_folder(agent: Agent, title: str) -> Path:
|
|
139
|
+
base = films_folder(agent) / comfy.slug(title, 30)
|
|
140
|
+
folder, n = base, 2
|
|
141
|
+
while folder.exists():
|
|
142
|
+
folder, n = base.with_name(f"{base.name}-{n}"), n + 1
|
|
143
|
+
folder.mkdir(parents=True)
|
|
144
|
+
return folder
|
|
145
|
+
|
|
146
|
+
|
|
147
|
+
def save(board: Board, folder: Path) -> None:
|
|
148
|
+
(folder / "storyboard.json").write_text(json.dumps(board.to_json(), indent=2, ensure_ascii=False) + "\n")
|
|
149
|
+
lines = [f"# {board.title}", "", f"*{board.look}*", "", "## Cast", ""]
|
|
150
|
+
lines += [f"- **{name}:** {desc}" for name, desc in board.cast.items()]
|
|
151
|
+
lines += ["", "## Shots", ""]
|
|
152
|
+
for n, shot in enumerate(board.shots, 1):
|
|
153
|
+
who = f" ({', '.join(shot.cast)})" if shot.cast else ""
|
|
154
|
+
lines.append(f"{n}. {shot.description}{who} — {shot.camera}, {shot.seconds:g} s")
|
|
155
|
+
(folder / "storyboard.md").write_text("\n".join(lines) + "\n")
|
|
156
|
+
|
|
157
|
+
|
|
158
|
+
def load(folder: Path) -> Board:
|
|
159
|
+
try:
|
|
160
|
+
return Board.from_json(json.loads((folder / "storyboard.json").read_text()))
|
|
161
|
+
except (OSError, ValueError) as e:
|
|
162
|
+
raise FilmError(f"can't read {folder / 'storyboard.json'}: {e}") from e
|
|
163
|
+
|
|
164
|
+
|
|
165
|
+
def latest(agent: Agent) -> Path:
|
|
166
|
+
folders = sorted((p for p in films_folder(agent).glob("*") if (p / "storyboard.json").exists()),
|
|
167
|
+
key=lambda p: p.stat().st_mtime) # fmt: skip
|
|
168
|
+
if not folders:
|
|
169
|
+
raise FilmError("No film here yet: /film <your idea>")
|
|
170
|
+
return folders[-1]
|
|
171
|
+
|
|
172
|
+
|
|
173
|
+
def find(agent: Agent, name: str) -> Path:
|
|
174
|
+
if not name:
|
|
175
|
+
return latest(agent)
|
|
176
|
+
folder = films_folder(agent) / name
|
|
177
|
+
if not (folder / "storyboard.json").exists():
|
|
178
|
+
raise FilmError(f"There's no film {name!r}: /film list")
|
|
179
|
+
return folder
|
|
180
|
+
|
|
181
|
+
|
|
182
|
+
def describe(board: Board, folder: Path, agent: Agent) -> str:
|
|
183
|
+
lines = [f"{board.title} ({media.shown(agent, folder)})", f" look: {board.look}"]
|
|
184
|
+
lines += [f" cast: {name} — {desc}" for name, desc in board.cast.items()]
|
|
185
|
+
for n, shot in enumerate(board.shots, 1):
|
|
186
|
+
who = f" [{', '.join(shot.cast)}]" if shot.cast else ""
|
|
187
|
+
lines.append(f" {n}. {shot.description}{who} — {shot.camera}, {shot.seconds:g} s")
|
|
188
|
+
return "\n".join(lines)
|
|
189
|
+
|
|
190
|
+
|
|
191
|
+
# ----------------------------------------------------------------------------- making it
|
|
192
|
+
|
|
193
|
+
|
|
194
|
+
def make(
|
|
195
|
+
agent: Agent,
|
|
196
|
+
board: Board,
|
|
197
|
+
folder: Path,
|
|
198
|
+
only: list[int] | None = None,
|
|
199
|
+
cancelled: Callable[[], bool] = lambda: False,
|
|
200
|
+
ask: Callable[[str], bool] | None = None,
|
|
201
|
+
) -> Path:
|
|
202
|
+
"""Make the cast's pictures (once), the shots (all, or `only` those numbers), and join the film."""
|
|
203
|
+
say = agent.say
|
|
204
|
+
for name, desc in board.cast.items():
|
|
205
|
+
picture = folder / "cast" / f"{comfy.slug(name, 20)}.png"
|
|
206
|
+
if picture.exists():
|
|
207
|
+
continue
|
|
208
|
+
say(f"Cast: {name}")
|
|
209
|
+
prompt = (
|
|
210
|
+
f"{board.look} Character reference of {name}, alone: {desc}. Full body, facing the camera, plain "
|
|
211
|
+
"background."
|
|
212
|
+
)
|
|
213
|
+
made = with_mode(agent, "image", lambda p=prompt: media.generate_image(
|
|
214
|
+
agent, p, cancelled, ask, imageopts.Options(size="3:4", quality=board.quality))) # fmt: skip
|
|
215
|
+
keep(made.files[0], picture)
|
|
216
|
+
for n, shot in enumerate(board.shots, 1):
|
|
217
|
+
if only and n not in only:
|
|
218
|
+
continue
|
|
219
|
+
say(f"Shot {n} of {len(board.shots)}: {shot.description}")
|
|
220
|
+
keyframe = folder / "keyframes" / f"{n:02d}.png"
|
|
221
|
+
refs = [folder / "cast" / f"{comfy.slug(name, 20)}.png" for name in shot.cast]
|
|
222
|
+
if refs:
|
|
223
|
+
names = "; ".join(f"image {k} is {name}" for k, name in enumerate(shot.cast, 1))
|
|
224
|
+
prompt = f"{board.look} {shot.description} ({names}). A film still, wide 16:9 frame."
|
|
225
|
+
options = imageopts.Options(size="16:9", quality=board.quality)
|
|
226
|
+
job = {"kind": "edit", "prompt": prompt, "options": options, "sources": [str(p) for p in refs],
|
|
227
|
+
"mask": None, "pads": None, "keep_shape": False, "raw": True} # fmt: skip
|
|
228
|
+
made = with_mode(agent, "image", lambda j=job: media.edit_image(agent, j, j["options"], cancelled, ask))
|
|
229
|
+
else:
|
|
230
|
+
prompt = f"{board.look} {shot.description}. A film still, wide 16:9 frame."
|
|
231
|
+
made = with_mode(agent, "image", lambda p=prompt: media.generate_image(
|
|
232
|
+
agent, p, cancelled, ask, imageopts.Options(size="16:9", quality=board.quality))) # fmt: skip
|
|
233
|
+
keep(made.files[0], keyframe)
|
|
234
|
+
options = imageopts.Options(seconds=shot.seconds, quality=board.quality)
|
|
235
|
+
job = {"kind": "video", "prompt": f"{shot.description} {shot.camera}. {board.look}", "options": options,
|
|
236
|
+
"sources": [str(keyframe)], "mask": None, "pads": None, "keep_shape": True} # fmt: skip
|
|
237
|
+
[clip] = with_mode(agent, "video", lambda j=job: media.redo(agent, j, cancelled, ask))
|
|
238
|
+
keep(clip.files[0], folder / "shots" / f"{n:02d}.mp4")
|
|
239
|
+
return stitch(agent, board, folder, cancelled, ask)
|
|
240
|
+
|
|
241
|
+
|
|
242
|
+
def with_mode(agent: Agent, mode: str, run):
|
|
243
|
+
"""Run one step in image or video mode (the right model for it), then go back."""
|
|
244
|
+
before = agent.settings.mode
|
|
245
|
+
agent.settings.mode = mode
|
|
246
|
+
try:
|
|
247
|
+
return run()
|
|
248
|
+
finally:
|
|
249
|
+
agent.settings.mode = before
|
|
250
|
+
|
|
251
|
+
|
|
252
|
+
def keep(made: Path, where: Path) -> None:
|
|
253
|
+
where.parent.mkdir(parents=True, exist_ok=True)
|
|
254
|
+
shutil.copyfile(made, where)
|
|
255
|
+
|
|
256
|
+
|
|
257
|
+
def stitch(
|
|
258
|
+
agent: Agent,
|
|
259
|
+
board: Board,
|
|
260
|
+
folder: Path,
|
|
261
|
+
cancelled: Callable[[], bool] = lambda: False,
|
|
262
|
+
ask: Callable[[str], bool] | None = None,
|
|
263
|
+
) -> Path:
|
|
264
|
+
"""Join the shots into film.mp4 (cuts or fades), and add the sound track when the storyboard has one."""
|
|
265
|
+
shots = [folder / "shots" / f"{n:02d}.mp4" for n in range(1, len(board.shots) + 1)]
|
|
266
|
+
missing = [p.name for p in shots if not p.exists()]
|
|
267
|
+
if missing:
|
|
268
|
+
raise FilmError(f"Shots not made yet: {', '.join(missing)} (/film make)")
|
|
269
|
+
ffmpeg = shutil.which("ffmpeg")
|
|
270
|
+
if not ffmpeg:
|
|
271
|
+
raise FilmError("Joining the shots needs ffmpeg: install it (apt install ffmpeg, brew install ffmpeg)")
|
|
272
|
+
film = folder / "film.mp4"
|
|
273
|
+
command = join_command(ffmpeg, shots, film, board.transition, [media.clip_info(p)["seconds"] for p in shots])
|
|
274
|
+
with agent.console.status("Joining the shots…", spinner="dots"):
|
|
275
|
+
done = subprocess.run(command, capture_output=True, text=True, stdin=subprocess.DEVNULL)
|
|
276
|
+
if done.returncode != 0:
|
|
277
|
+
raise FilmError(f"ffmpeg couldn't join the shots: {done.stderr.strip()[-400:]}")
|
|
278
|
+
if board.sound:
|
|
279
|
+
made = with_mode(agent, "video", lambda: media.apply_tool(agent, "sound", film, 1, cancelled, ask, board.sound))
|
|
280
|
+
keep(made.files[0], folder / "film-sound.mp4")
|
|
281
|
+
film = folder / "film-sound.mp4"
|
|
282
|
+
agent.console.print(f"[green]◆ {board.title}:[/] {media.shown(agent, film)}")
|
|
283
|
+
return film
|
|
284
|
+
|
|
285
|
+
|
|
286
|
+
def join_command(ffmpeg: str, shots: list[Path], out: Path, transition: str, lengths: list[float]) -> list[str]:
|
|
287
|
+
"""ffmpeg's command for the shots one after another: cut, or each fading into the next (xfade)."""
|
|
288
|
+
command = [ffmpeg, "-y", "-v", "error"]
|
|
289
|
+
for shot in shots:
|
|
290
|
+
command += ["-i", str(shot)]
|
|
291
|
+
count = len(shots)
|
|
292
|
+
if transition == "fade" and count > 1:
|
|
293
|
+
chain, last = [], "[0:v]"
|
|
294
|
+
for k in range(1, count):
|
|
295
|
+
joined = sum(lengths[:k]) - (k - 1) * FADE # how long the film is so far
|
|
296
|
+
label = f"[v{k}]"
|
|
297
|
+
start = max(0.0, joined - FADE)
|
|
298
|
+
chain.append(f"{last}[{k}:v]xfade=transition=fade:duration={FADE}:offset={start:.3f}{label}")
|
|
299
|
+
last = label
|
|
300
|
+
graph = ";".join(chain)
|
|
301
|
+
else:
|
|
302
|
+
last = "[out]"
|
|
303
|
+
graph = "".join(f"[{k}:v]" for k in range(count)) + f"concat=n={count}:v=1:a=0{last}"
|
|
304
|
+
return [*command, "-filter_complex", graph, "-map", last, "-c:v", "libx264", "-pix_fmt", "yuv420p",
|
|
305
|
+
"-movflags", "+faststart", str(out)] # fmt: skip
|
|
306
|
+
|
|
307
|
+
|
|
308
|
+
def shot_numbers(text: str, count: int) -> list[int]:
|
|
309
|
+
numbers = [int(n) for n in re.findall(r"\d+", text)]
|
|
310
|
+
bad = [n for n in numbers if not 1 <= n <= count]
|
|
311
|
+
if not numbers or bad:
|
|
312
|
+
raise FilmError(f"Say which shot: 1 to {count} (/film shot 2)")
|
|
313
|
+
return numbers
|
|
314
|
+
|
|
315
|
+
|
|
316
|
+
def with_options(board: Board, transition: str = "", sound: str = "", quality: str = "") -> Board:
|
|
317
|
+
return replace(
|
|
318
|
+
board,
|
|
319
|
+
transition=transition if transition in TRANSITIONS else board.transition,
|
|
320
|
+
sound=sound or board.sound,
|
|
321
|
+
quality=quality if quality in imageopts.QUALITIES else board.quality,
|
|
322
|
+
)
|
lcode/media.py
CHANGED
|
@@ -1,7 +1,7 @@
|
|
|
1
1
|
"""Image and video mode: a request becomes media, made by ComfyUI (lcode.comfy) with no language model in between.
|
|
2
2
|
|
|
3
|
-
|
|
4
|
-
|
|
3
|
+
The image or video model is chosen from the media catalog (lcode.media_catalog). A cloud model there (Grok Imagine)
|
|
4
|
+
makes what it can at its provider instead, after showing the cost (lcode.media_cloud).
|
|
5
5
|
"""
|
|
6
6
|
|
|
7
7
|
from __future__ import annotations
|
|
@@ -23,7 +23,7 @@ from typing import TYPE_CHECKING
|
|
|
23
23
|
import requests
|
|
24
24
|
from rich.text import Text
|
|
25
25
|
|
|
26
|
-
from lcode import assistant, comfy, edits, imageopts, preview
|
|
26
|
+
from lcode import assistant, comfy, edits, imageopts, media_cloud, preview
|
|
27
27
|
from lcode import media_catalog as catalog
|
|
28
28
|
|
|
29
29
|
if TYPE_CHECKING:
|
|
@@ -112,6 +112,8 @@ def offer_install(agent: Agent, server: comfy.Server, ask: Callable[[str], bool]
|
|
|
112
112
|
|
|
113
113
|
def warm(agent: Agent) -> str | None:
|
|
114
114
|
"""Start ComfyUI in the background on entering image or video mode, so the first request waits less."""
|
|
115
|
+
if current(agent).cloud:
|
|
116
|
+
return None # it runs at its provider; ComfyUI starts when a local model is needed
|
|
115
117
|
if agent.comfy_process is not None and agent.comfy_process.poll() is None:
|
|
116
118
|
return None
|
|
117
119
|
if comfy.Server(agent.settings.comfyui_url).stats():
|
|
@@ -335,6 +337,12 @@ def redo(
|
|
|
335
337
|
agent.last_request = job
|
|
336
338
|
if not job.get("raw") and job["kind"] in ("image", "edit", "video") and not job.get("pads"):
|
|
337
339
|
job = {**job, "expanded": expand(agent, job)}
|
|
340
|
+
if model.cloud and not media_cloud.cannot(model, job): # at its provider: all of them, asked once
|
|
341
|
+
made = media_cloud.make(agent, model, job, options, cancelled, ask)
|
|
342
|
+
if job["kind"] in ("image", "edit"):
|
|
343
|
+
for one in made:
|
|
344
|
+
check_result(agent, one, prompt)
|
|
345
|
+
return made
|
|
338
346
|
made = []
|
|
339
347
|
for i in range(options.n):
|
|
340
348
|
seed = None if options.seed is None else options.seed + i
|
|
@@ -493,8 +501,11 @@ def generate_image(
|
|
|
493
501
|
if not prompt:
|
|
494
502
|
raise MediaError("Describe the image you want.")
|
|
495
503
|
options = options or imageopts.Options()
|
|
496
|
-
server = prepare(agent, ask, cancelled)
|
|
497
504
|
model = current(agent, "image")
|
|
505
|
+
if model.cloud:
|
|
506
|
+
job = {"kind": "image", "prompt": prompt, "expanded": expanded, "sources": []}
|
|
507
|
+
return media_cloud.make(agent, model, job, replace(options, n=1), cancelled, ask)[0]
|
|
508
|
+
server = prepare(agent, ask, cancelled)
|
|
498
509
|
files = ensure_installed(agent, model, server, ask)
|
|
499
510
|
workflow = comfy.load_workflow(model.workflow)
|
|
500
511
|
seed = options.seed if options.seed is not None else random.randrange(2**32)
|
|
@@ -522,13 +533,17 @@ def edit_image(
|
|
|
522
533
|
) -> Made:
|
|
523
534
|
"""An edit of the job's source images: by instruction, through a mask (inpainting), or on a bigger canvas
|
|
524
535
|
(outpainting). The first source sets the shape unless the request gave one."""
|
|
525
|
-
server = prepare(agent, ask, cancelled)
|
|
526
536
|
chosen = current(agent, "image")
|
|
537
|
+
why = media_cloud.cannot(chosen, {**job, "kind": "edit"}) if chosen.cloud else ""
|
|
538
|
+
if chosen.cloud and not why: # films call this directly
|
|
539
|
+
return media_cloud.make(agent, chosen, {**job, "kind": "edit"}, replace(options, n=1), cancelled, ask)[0]
|
|
540
|
+
server = prepare(agent, ask, cancelled)
|
|
527
541
|
model = catalog.load().editor(chosen)
|
|
528
542
|
if model is None:
|
|
529
543
|
raise MediaError("None of lcode's image models edits pictures yet.")
|
|
530
544
|
if model.key != chosen.key:
|
|
531
|
-
|
|
545
|
+
reason = f"doesn't do {why} here" if why else "doesn't edit pictures"
|
|
546
|
+
agent.say(f"{chosen.name} {reason}: {model.name} makes this one{' on your GPU' if chosen.cloud else ''}.")
|
|
532
547
|
files = ensure_installed(agent, model, server, ask)
|
|
533
548
|
workflow = comfy.load_workflow(model.workflow)
|
|
534
549
|
sources = [Path(p) for p in job["sources"]]
|
|
@@ -600,7 +615,7 @@ def generate_video(
|
|
|
600
615
|
restyle = Path(job["restyle"]) if job.get("restyle") else None
|
|
601
616
|
task = (
|
|
602
617
|
"restyle" if restyle else "references" if refs else "first-last-frame" if end
|
|
603
|
-
else "camera" if options.camera else "
|
|
618
|
+
else "camera" if options.camera else "extend" if clip else ""
|
|
604
619
|
) # fmt: skip
|
|
605
620
|
model = video_model(agent, task)
|
|
606
621
|
files = ensure_installed(agent, model, server, ask)
|
|
@@ -678,7 +693,7 @@ VIDEO_LATENTS = ("Wan22ImageToVideoLatent", "WanFunInpaintToVideo", "WanCameraIm
|
|
|
678
693
|
WHY = {
|
|
679
694
|
"first-last-frame": "a clip between two frames",
|
|
680
695
|
"camera": "a camera move",
|
|
681
|
-
"
|
|
696
|
+
"extend": "extending a clip",
|
|
682
697
|
"references": "following reference pictures",
|
|
683
698
|
"restyle": "restyling a clip",
|
|
684
699
|
}
|
|
@@ -722,14 +737,15 @@ def control_from(graph: dict, clip_name: str, length: int) -> list:
|
|
|
722
737
|
|
|
723
738
|
|
|
724
739
|
def video_model(agent: Agent, task: str) -> catalog.MediaModel:
|
|
725
|
-
"""The video model for a job: the chosen one, or the first that does what the job needs."""
|
|
740
|
+
"""The video model for a job: the chosen one, or the first local one that does what the job needs."""
|
|
726
741
|
chosen = current(agent, "video")
|
|
727
|
-
if not task or task in chosen.tasks:
|
|
742
|
+
if not chosen.cloud and (not task or task in chosen.tasks):
|
|
728
743
|
return chosen
|
|
729
|
-
model = catalog.load().for_task("video", task)
|
|
744
|
+
model = catalog.load().for_task("video", task or "text-to-video")
|
|
730
745
|
if model is None:
|
|
731
746
|
raise MediaError(f"None of lcode's video models does {WHY.get(task, task)} yet.")
|
|
732
|
-
|
|
747
|
+
where = f"; {chosen.name} doesn't do that here" if chosen.cloud else ""
|
|
748
|
+
agent.say(f"{model.name} makes this one ({WHY.get(task, task)}{where}).")
|
|
733
749
|
return model
|
|
734
750
|
|
|
735
751
|
|
|
@@ -786,6 +802,24 @@ def mp4_seconds(path: Path) -> float:
|
|
|
786
802
|
return duration / scale if scale else 0.0
|
|
787
803
|
|
|
788
804
|
|
|
805
|
+
def mp4_size(path: Path) -> tuple[int, int]:
|
|
806
|
+
"""An MP4's picture size from its first video track header (tkhd), or (0, 0)."""
|
|
807
|
+
try:
|
|
808
|
+
data = path.read_bytes()[: 1 << 22]
|
|
809
|
+
except OSError:
|
|
810
|
+
return 0, 0
|
|
811
|
+
i = data.find(b"tkhd")
|
|
812
|
+
while i >= 4:
|
|
813
|
+
size = 8 + (96 if data[i + 4 : i + 5] == b"\x01" else 84) # the box, with its size and type
|
|
814
|
+
end = i - 4 + size # width and height end it, as 16.16 fixed-point numbers
|
|
815
|
+
if struct.unpack(">I", data[i - 4 : i])[0] == size and end <= len(data):
|
|
816
|
+
width, height = struct.unpack(">II", data[end - 8 : end])
|
|
817
|
+
if width and height:
|
|
818
|
+
return width >> 16, height >> 16
|
|
819
|
+
i = data.find(b"tkhd", i + 4)
|
|
820
|
+
return 0, 0
|
|
821
|
+
|
|
822
|
+
|
|
789
823
|
def apply_tool(
|
|
790
824
|
agent: Agent,
|
|
791
825
|
task: str,
|
lcode/media.toml
CHANGED
|
@@ -19,6 +19,12 @@
|
|
|
19
19
|
# negative whether it uses a negative prompt (distilled models don't)
|
|
20
20
|
# edit how it edits images: "reference-latent" (its text-to-image workflow, given the images as
|
|
21
21
|
# reference latents on both conditionings); absent: it doesn't edit
|
|
22
|
+
#
|
|
23
|
+
# Cloud models (lcode.media_cloud) have no files or workflow; they run at a provider, with the user's API key:
|
|
24
|
+
# cloud the provider: xai
|
|
25
|
+
# api_model the provider's name for the model
|
|
26
|
+
# price dollars: image (per picture made), input_image (per picture sent), 480p / 720p / 1080p (per second)
|
|
27
|
+
# priced when the prices were checked (they change: the provider's pricing page has the real ones)
|
|
22
28
|
|
|
23
29
|
[files.flux-2-klein-4b-fp8]
|
|
24
30
|
folder = "diffusion_models"
|
|
@@ -139,7 +145,7 @@ name = "Wan 2.2 TI2V 5B"
|
|
|
139
145
|
mode = "video"
|
|
140
146
|
publisher = "Wan-AI (Alibaba)"
|
|
141
147
|
license = "Apache 2.0"
|
|
142
|
-
tasks = ["text-to-video", "image-to-video"]
|
|
148
|
+
tasks = ["text-to-video", "image-to-video", "extend"]
|
|
143
149
|
workflow = "wan22-ti2v-5b"
|
|
144
150
|
files = { model = "wan22-ti2v-5b", text_encoder = "umt5-xxl-fp8", vae = "wan22-vae" }
|
|
145
151
|
gpu_gb = 0.0
|
|
@@ -254,3 +260,29 @@ tasks = ["sound"]
|
|
|
254
260
|
workflow = "sound-stable-audio"
|
|
255
261
|
files = { model = "stable-audio-open", text_encoder = "t5-base" }
|
|
256
262
|
notes = "/sound: sound effects and ambience for a clip, up to 47 s"
|
|
263
|
+
|
|
264
|
+
# ----------------------------------------------------------------------------- in the cloud: your key, your bill
|
|
265
|
+
|
|
266
|
+
[models.grok-image]
|
|
267
|
+
name = "Grok Imagine Image 2.0"
|
|
268
|
+
mode = "image"
|
|
269
|
+
publisher = "xAI"
|
|
270
|
+
license = "xAI's terms of service"
|
|
271
|
+
tasks = ["text-to-image", "edit"]
|
|
272
|
+
cloud = "xai"
|
|
273
|
+
api_model = "grok-imagine-image-2.0"
|
|
274
|
+
price = { image = 0.04, input_image = 0.01 }
|
|
275
|
+
priced = "2026-10-24"
|
|
276
|
+
notes = "1k or 2k (--quality best); edits one picture at a time"
|
|
277
|
+
|
|
278
|
+
[models.grok-video]
|
|
279
|
+
name = "Grok Imagine Video 1.5"
|
|
280
|
+
mode = "video"
|
|
281
|
+
publisher = "xAI"
|
|
282
|
+
license = "xAI's terms of service"
|
|
283
|
+
tasks = ["text-to-video", "image-to-video"]
|
|
284
|
+
cloud = "xai"
|
|
285
|
+
api_model = "grok-imagine-video-1.5"
|
|
286
|
+
price = { "480p" = 0.08, "720p" = 0.14, "1080p" = 0.25, input_image = 0.01 }
|
|
287
|
+
priced = "2026-10-24"
|
|
288
|
+
notes = "480p fast, 720p balanced, 1080p best; text or a start image"
|
lcode/media_catalog.py
CHANGED
|
@@ -72,6 +72,10 @@ class MediaModel:
|
|
|
72
72
|
negative: bool = False # whether it uses a negative prompt
|
|
73
73
|
edit: str = "" # how it edits images ("reference-latent"), or empty: it doesn't
|
|
74
74
|
video_workflow: str = "" # a tool's workflow for clips, when it works on them too (upscaling)
|
|
75
|
+
cloud: str = "" # the provider it runs at (lcode.media_cloud.PROVIDERS), or empty: on this machine
|
|
76
|
+
api_model: str = "" # the provider's name for it
|
|
77
|
+
price: dict[str, float] = field(default_factory=dict, hash=False) # dollars: per image, per second at 720p…
|
|
78
|
+
priced: str = "" # when the prices were checked
|
|
75
79
|
|
|
76
80
|
def preset(self, quality: str) -> tuple[int | None, float]:
|
|
77
81
|
"""(steps, megapixels) for a quality preset: None steps keeps the workflow's."""
|
|
@@ -86,10 +90,12 @@ class MediaModel:
|
|
|
86
90
|
def need_gb(self) -> float:
|
|
87
91
|
"""GPU memory at the peak: measured, or estimated. ComfyUI loads the text encoder, the model and the VAE
|
|
88
92
|
one after another and moves what it doesn't need off the GPU, so the largest file sets the peak."""
|
|
89
|
-
return self.gpu_gb or max(f.gb for f in self.files.values()) + WORKING_GB
|
|
93
|
+
return self.gpu_gb or max((f.gb for f in self.files.values()), default=0.0) + WORKING_GB
|
|
90
94
|
|
|
91
95
|
def fit(self, hw: Hardware) -> tuple[str, str]:
|
|
92
|
-
"""(fits | slower | too big | cpu, a short note) on this machine."""
|
|
96
|
+
"""(fits | slower | too big | cpu | cloud, a short note) on this machine."""
|
|
97
|
+
if self.cloud:
|
|
98
|
+
return "cloud", "runs at the provider: nothing on this machine"
|
|
93
99
|
weights_gib = self.size_gb * 1e9 / GIB
|
|
94
100
|
need_gib = self.need_gb * 1e9 / GIB
|
|
95
101
|
if hw.unified:
|
|
@@ -114,18 +120,18 @@ class Catalog:
|
|
|
114
120
|
return [m for m in self.models.values() if m.mode == mode]
|
|
115
121
|
|
|
116
122
|
def for_task(self, mode: str, task: str) -> MediaModel | None:
|
|
117
|
-
"""The first model of a mode that does a task (first-last-frame, camera,
|
|
118
|
-
return next((m for m in self.for_mode(mode) if task in m.tasks), None)
|
|
123
|
+
"""The first local model of a mode that does a task (first-last-frame, camera, extend…)."""
|
|
124
|
+
return next((m for m in self.for_mode(mode) if task in m.tasks and not m.cloud), None)
|
|
119
125
|
|
|
120
126
|
def tool(self, task: str) -> MediaModel:
|
|
121
127
|
"""The tool for a task (upscale, remove-background)."""
|
|
122
128
|
return next(m for m in self.models.values() if m.mode == "tool" and task in m.tasks)
|
|
123
129
|
|
|
124
130
|
def editor(self, preferred: MediaModel) -> MediaModel | None:
|
|
125
|
-
"""A model that edits: the preferred one if it can, else the first image model that can."""
|
|
126
|
-
if preferred.edit:
|
|
131
|
+
"""A local model that edits: the preferred one if it can, else the first image model that can."""
|
|
132
|
+
if preferred.edit and not preferred.cloud:
|
|
127
133
|
return preferred
|
|
128
|
-
return next((m for m in self.for_mode("image") if m.edit), None)
|
|
134
|
+
return next((m for m in self.for_mode("image") if m.edit and not m.cloud), None)
|
|
129
135
|
|
|
130
136
|
def find(self, wanted: str, mode: str | None = None) -> MediaModel | None:
|
|
131
137
|
"""A model by key or name (any case), or by its number in the mode's list."""
|
|
@@ -146,7 +152,7 @@ def load() -> Catalog:
|
|
|
146
152
|
models = {}
|
|
147
153
|
for key, m in data.get("models", {}).items():
|
|
148
154
|
try:
|
|
149
|
-
roles = {role: files[ref] for role, ref in m
|
|
155
|
+
roles = {role: files[ref] for role, ref in m.get("files", {}).items()}
|
|
150
156
|
except KeyError as e:
|
|
151
157
|
raise CatalogError(f"media.toml: {key} uses the file {e}, which isn't listed") from e
|
|
152
158
|
models[key] = MediaModel(
|
|
@@ -156,7 +162,7 @@ def load() -> Catalog:
|
|
|
156
162
|
m.get("publisher", ""),
|
|
157
163
|
m.get("license", ""),
|
|
158
164
|
tuple(m.get("tasks", ())),
|
|
159
|
-
m
|
|
165
|
+
m.get("workflow", ""),
|
|
160
166
|
roles,
|
|
161
167
|
float(m.get("gpu_gb", 0.0)),
|
|
162
168
|
m.get("measured", ""),
|
|
@@ -165,6 +171,10 @@ def load() -> Catalog:
|
|
|
165
171
|
bool(m.get("negative", False)),
|
|
166
172
|
m.get("edit", ""),
|
|
167
173
|
m.get("video_workflow", ""),
|
|
174
|
+
m.get("cloud", ""),
|
|
175
|
+
m.get("api_model", ""),
|
|
176
|
+
{name: float(v) for name, v in (m.get("price") or {}).items()},
|
|
177
|
+
m.get("priced", ""),
|
|
168
178
|
)
|
|
169
179
|
return Catalog(files, models)
|
|
170
180
|
|
|
@@ -307,8 +317,10 @@ def file_sha256(path: Path) -> str:
|
|
|
307
317
|
def install(model: MediaModel, server=None, install=None, console=None, ask=None, get=None) -> list[Path]:
|
|
308
318
|
"""Download the model's missing files into ComfyUI's model folders. Raises CatalogError with what to do.
|
|
309
319
|
|
|
310
|
-
`ask(question) -> bool` confirms the download (None: go ahead, for `--yes`).
|
|
320
|
+
`ask(question) -> bool` confirms the download (None: go ahead, for `--yes`). A cloud model has nothing to install.
|
|
311
321
|
"""
|
|
322
|
+
if model.cloud:
|
|
323
|
+
return []
|
|
312
324
|
from rich.console import Console
|
|
313
325
|
from rich.progress import BarColumn, DownloadColumn, Progress, TextColumn, TimeRemainingColumn, TransferSpeedColumn
|
|
314
326
|
|
|
@@ -346,7 +358,11 @@ def install(model: MediaModel, server=None, install=None, console=None, ask=None
|
|
|
346
358
|
|
|
347
359
|
|
|
348
360
|
def describe(model: MediaModel, hw: Hardware, installed: Installed | None) -> str:
|
|
349
|
-
"""One line for a list: tasks, size, fit, installed."""
|
|
361
|
+
"""One line for a list: tasks, size, fit, installed; for a cloud model, where it runs, its price and the key."""
|
|
362
|
+
if model.cloud:
|
|
363
|
+
from lcode import media_cloud
|
|
364
|
+
|
|
365
|
+
return " · ".join([", ".join(model.tasks), *media_cloud.describe(model)])
|
|
350
366
|
status, note = model.fit(hw)
|
|
351
367
|
parts = [", ".join(model.tasks), f"{model.size_gb:.1f} GB"]
|
|
352
368
|
if installed is not None:
|