lcode-cli 0.45.0__py3-none-any.whl → 0.47.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 +2 -0
- lcode/api.py +2 -0
- lcode/assistant.py +166 -0
- lcode/config.py +2 -0
- lcode/media.py +256 -25
- lcode/media.toml +58 -0
- lcode/media_catalog.py +2 -0
- lcode/repl.py +35 -4
- lcode/workflows/smooth-film.json +78 -0
- lcode/workflows/sound-stable-audio.json +144 -0
- lcode/workflows/upscale-video-esrgan.json +89 -0
- lcode/workflows/wan21-vace.json +173 -0
- {lcode_cli-0.45.0.dist-info → lcode_cli-0.47.0.dist-info}/METADATA +1 -1
- {lcode_cli-0.45.0.dist-info → lcode_cli-0.47.0.dist-info}/RECORD +18 -13
- {lcode_cli-0.45.0.dist-info → lcode_cli-0.47.0.dist-info}/WHEEL +0 -0
- {lcode_cli-0.45.0.dist-info → lcode_cli-0.47.0.dist-info}/entry_points.txt +0 -0
- {lcode_cli-0.45.0.dist-info → lcode_cli-0.47.0.dist-info}/licenses/LICENSE +0 -0
lcode/__init__.py
CHANGED
lcode/agent.py
CHANGED
|
@@ -310,6 +310,8 @@ class Settings:
|
|
|
310
310
|
media_dir: str = ".lcode/media" # where image and video mode save their files (lcode.media)
|
|
311
311
|
image_model: str = "flux2-klein-4b" # the media catalog's model image mode uses (lcode.media_catalog)
|
|
312
312
|
video_model: str = "wan22-ti2v-5b" # and video mode's
|
|
313
|
+
prompt_assistant: str = "video" # video, all, off or an Ollama model: writes fuller prompts (lcode.assistant)
|
|
314
|
+
check_results: bool = False # the prompt assistant checks each image against the request
|
|
313
315
|
preview: str = "auto" # images in the terminal: auto, kitty, iterm, blocks or off (lcode.preview)
|
|
314
316
|
num_batch: int | None = None
|
|
315
317
|
keep_alive: str = "30m"
|
lcode/api.py
CHANGED
|
@@ -202,6 +202,8 @@ def open_agent(cwd: Path, options: Options, console: Console, hw: Hardware | Non
|
|
|
202
202
|
media_dir=cfg["media_dir"],
|
|
203
203
|
image_model=cfg["image_model"],
|
|
204
204
|
video_model=cfg["video_model"],
|
|
205
|
+
prompt_assistant=cfg["prompt_assistant"],
|
|
206
|
+
check_results=cfg["check_results"],
|
|
205
207
|
preview=cfg["preview"],
|
|
206
208
|
web=switch(options.web, cfg["web"], "on"),
|
|
207
209
|
search_backend=cfg["search_backend"],
|
lcode/assistant.py
ADDED
|
@@ -0,0 +1,166 @@
|
|
|
1
|
+
"""The prompt assistant: a small local language model that helps image and video mode with words.
|
|
2
|
+
|
|
3
|
+
Image and video models do better with detailed prompts in English, written the way each expects (a picture's subject,
|
|
4
|
+
light and composition; a clip's motion and camera). The assistant:
|
|
5
|
+
|
|
6
|
+
- **expands** a short request into such a prompt, from any language;
|
|
7
|
+
- **looks at a start picture** (it can see) and writes the video prompt around it;
|
|
8
|
+
- **reads follow-ups** ("darker", "add a hat") as changes to the last image;
|
|
9
|
+
- **checks a result** against the request and suggests a better prompt when it misses;
|
|
10
|
+
- **writes storyboards** for films (lcode.film).
|
|
11
|
+
|
|
12
|
+
It runs in Ollama, loaded for each job and unloaded right after (keep_alive 0), so the image or video model has the GPU
|
|
13
|
+
to itself while it works. The `prompt_assistant` setting says where it helps: `video` (the default: measured, video
|
|
14
|
+
models make much better clips from fuller prompts, while FLUX.2 klein didn't make better pictures), `all` (pictures
|
|
15
|
+
too, and follow-ups), `off`, or an Ollama model's name (everywhere, with that model).
|
|
16
|
+
"""
|
|
17
|
+
|
|
18
|
+
from __future__ import annotations
|
|
19
|
+
|
|
20
|
+
import base64
|
|
21
|
+
import json
|
|
22
|
+
import re
|
|
23
|
+
from dataclasses import dataclass
|
|
24
|
+
from pathlib import Path
|
|
25
|
+
|
|
26
|
+
PREFERRED = ("qwen3.5:4b", "qwen3.5:9b", "qwen3:4b", "gemma3:4b", "llama3.2:3b")
|
|
27
|
+
MAX_PROMPT = 900 # characters: image and video models read only so much
|
|
28
|
+
|
|
29
|
+
STYLE_GUIDE = {
|
|
30
|
+
"image": (
|
|
31
|
+
"You write prompts for an image generation model. Rewrite the user's request as one detailed prompt in "
|
|
32
|
+
"English: the subject, what it looks like, the setting, the light, the composition and the medium (photo, "
|
|
33
|
+
"painting…). Keep everything the user asked for, add no new subjects or text, and keep any words in quotes "
|
|
34
|
+
"exactly as written (they are text to show in the picture). 40 to 80 words, one paragraph, no lists."
|
|
35
|
+
),
|
|
36
|
+
"edit": (
|
|
37
|
+
"You write instructions for an image editing model. Rewrite the user's request as one short, clear "
|
|
38
|
+
"instruction in English that says exactly what to change in the picture and what to keep. 10 to 30 words."
|
|
39
|
+
),
|
|
40
|
+
"video": (
|
|
41
|
+
"You write prompts for a video generation model. Rewrite the user's request as one prompt in English: the "
|
|
42
|
+
"subject and the setting, the motion over time, the camera (a shot: slow zoom in, pan left, tracking shot, "
|
|
43
|
+
"static), and the light and mood. Describe movement, not a single picture. Never mention a camera as an "
|
|
44
|
+
"object in the scene. 50 to 90 words, one paragraph."
|
|
45
|
+
),
|
|
46
|
+
}
|
|
47
|
+
START_IMAGE = (
|
|
48
|
+
"The video starts from the attached picture. Begin the prompt by describing what the picture shows (subject, "
|
|
49
|
+
"setting, light, style) in one sentence, then the motion the user asked for."
|
|
50
|
+
)
|
|
51
|
+
FOLLOW_UP = (
|
|
52
|
+
"The user made a picture from this request: {last!r}. Now they wrote: {text!r}.\n"
|
|
53
|
+
"Is the new text a change to that picture (like 'darker', 'add a hat', 'make it night', 'without the car'), or "
|
|
54
|
+
"a description of a new, different picture?\n"
|
|
55
|
+
'Answer with JSON only: {{"change": true or false, "instruction": "the change as one clear editing '
|
|
56
|
+
'instruction in English, or empty"}}'
|
|
57
|
+
)
|
|
58
|
+
CHECK = (
|
|
59
|
+
"The user asked for: {request!r}.\nLook at the picture. Does it show what was asked? Answer with JSON only: "
|
|
60
|
+
'{{"matches": true or false, "missing": "what is missing or wrong, or empty", '
|
|
61
|
+
'"better_prompt": "a clearer prompt for the request when it does not match, or empty"}}'
|
|
62
|
+
)
|
|
63
|
+
|
|
64
|
+
|
|
65
|
+
class AssistantError(Exception):
|
|
66
|
+
pass
|
|
67
|
+
|
|
68
|
+
|
|
69
|
+
@dataclass
|
|
70
|
+
class Check:
|
|
71
|
+
matches: bool
|
|
72
|
+
missing: str = ""
|
|
73
|
+
better_prompt: str = ""
|
|
74
|
+
|
|
75
|
+
|
|
76
|
+
SCOPES = ("off", "video", "all", "auto")
|
|
77
|
+
|
|
78
|
+
|
|
79
|
+
def pick(ollama, setting: str) -> str | None:
|
|
80
|
+
"""The assistant's model for a setting: off, or a small installed model (video, all, auto), or a model's name."""
|
|
81
|
+
if setting in ("off", "", None):
|
|
82
|
+
return None
|
|
83
|
+
try:
|
|
84
|
+
installed = set(ollama.installed_names())
|
|
85
|
+
except Exception:
|
|
86
|
+
return None
|
|
87
|
+
if setting not in SCOPES:
|
|
88
|
+
return setting if setting in installed or f"{setting}:latest" in installed else None
|
|
89
|
+
return next((m for m in PREFERRED if m in installed), None)
|
|
90
|
+
|
|
91
|
+
|
|
92
|
+
class Assistant:
|
|
93
|
+
def __init__(self, ollama, model: str):
|
|
94
|
+
self.ollama, self.model = ollama, model
|
|
95
|
+
|
|
96
|
+
def _ask(self, system: str, user: str, images: list[Path] = (), json_answer: bool = False) -> str:
|
|
97
|
+
message: dict = {"role": "user", "content": user}
|
|
98
|
+
if images:
|
|
99
|
+
message["images"] = [base64.b64encode(p.read_bytes()).decode() for p in images]
|
|
100
|
+
payload = {
|
|
101
|
+
"model": self.model,
|
|
102
|
+
"messages": [{"role": "system", "content": system}, message],
|
|
103
|
+
"think": False,
|
|
104
|
+
"keep_alive": 0, # unloaded right after: the image or video model needs the GPU
|
|
105
|
+
"options": {"temperature": 0.4, "num_ctx": 4096},
|
|
106
|
+
}
|
|
107
|
+
if json_answer:
|
|
108
|
+
payload["format"] = "json"
|
|
109
|
+
try:
|
|
110
|
+
reply = self.ollama.chat(payload, timeout=180)
|
|
111
|
+
except Exception as e:
|
|
112
|
+
raise AssistantError(f"the prompt assistant ({self.model}) didn't answer: {e}") from e
|
|
113
|
+
return ((reply.get("message") or {}).get("content") or "").strip()
|
|
114
|
+
|
|
115
|
+
def expand(self, request: str, kind: str = "image", start: Path | None = None) -> str:
|
|
116
|
+
"""A detailed prompt for the model, in English, from the user's request (and a start picture)."""
|
|
117
|
+
system = STYLE_GUIDE.get(kind, STYLE_GUIDE["image"])
|
|
118
|
+
if start is not None and kind == "video":
|
|
119
|
+
system += " " + START_IMAGE
|
|
120
|
+
text = clean(self._ask(system, request, [start] if start is not None else []))
|
|
121
|
+
return text[:MAX_PROMPT] if text else request
|
|
122
|
+
|
|
123
|
+
def follow_up(self, text: str, last: str) -> str | None:
|
|
124
|
+
"""When `text` is a change to the last picture, the change as an editing instruction; else None."""
|
|
125
|
+
answer = parse_json(
|
|
126
|
+
self._ask("You answer with JSON only.", FOLLOW_UP.format(last=last, text=text), json_answer=True)
|
|
127
|
+
)
|
|
128
|
+
if answer.get("change") is True and str(answer.get("instruction") or "").strip():
|
|
129
|
+
return str(answer["instruction"]).strip()
|
|
130
|
+
return None
|
|
131
|
+
|
|
132
|
+
def check(self, picture: Path, request: str) -> Check:
|
|
133
|
+
"""Whether the picture shows what was asked, and a better prompt when it doesn't."""
|
|
134
|
+
answer = parse_json(
|
|
135
|
+
self._ask(
|
|
136
|
+
"You check pictures. You answer with JSON only.",
|
|
137
|
+
CHECK.format(request=request),
|
|
138
|
+
[picture],
|
|
139
|
+
json_answer=True,
|
|
140
|
+
)
|
|
141
|
+
)
|
|
142
|
+
matches = answer.get("matches")
|
|
143
|
+
if not isinstance(matches, bool):
|
|
144
|
+
raise AssistantError("the prompt assistant's check had no answer")
|
|
145
|
+
return Check(matches, str(answer.get("missing") or "").strip(), str(answer.get("better_prompt") or "").strip())
|
|
146
|
+
|
|
147
|
+
def write(self, system: str, request: str, json_answer: bool = False) -> str:
|
|
148
|
+
"""Any other writing job (storyboards)."""
|
|
149
|
+
return self._ask(system, request, json_answer=json_answer)
|
|
150
|
+
|
|
151
|
+
|
|
152
|
+
def clean(text: str) -> str:
|
|
153
|
+
"""The prompt alone: without quotes around it, a 'Prompt:' label, or reasoning tags."""
|
|
154
|
+
text = re.sub(r"<think>.*?</think>", "", text, flags=re.S).strip()
|
|
155
|
+
text = re.sub(r"^(here is|here's)[^:\n]*:\s*", "", text, flags=re.I)
|
|
156
|
+
text = re.sub(r"^\**\s*(prompt|rewritten prompt|instruction)\s*\**\s*:\s*\**\s*", "", text, flags=re.I)
|
|
157
|
+
return " ".join(text.strip().strip('"').strip("“”").split())
|
|
158
|
+
|
|
159
|
+
|
|
160
|
+
def parse_json(text: str) -> dict:
|
|
161
|
+
m = re.search(r"\{.*\}", text, flags=re.S)
|
|
162
|
+
try:
|
|
163
|
+
value = json.loads(m.group(0) if m else text)
|
|
164
|
+
except ValueError:
|
|
165
|
+
return {}
|
|
166
|
+
return value if isinstance(value, dict) else {}
|
lcode/config.py
CHANGED
|
@@ -47,6 +47,8 @@ SETTINGS: dict[str, tuple[object, type, str]] = {
|
|
|
47
47
|
"media_dir": (".lcode/media", str, "where images and videos go: a folder in the project, or an absolute path"),
|
|
48
48
|
"image_model": ("flux2-klein-4b", str, "the model image mode uses: a key from `lcode media`"),
|
|
49
49
|
"video_model": ("wan22-ti2v-5b", str, "the model video mode uses: a key from `lcode media`"),
|
|
50
|
+
"prompt_assistant": ("video", str, "a small model writes fuller prompts: video | all | off | an Ollama model"),
|
|
51
|
+
"check_results": (False, bool, "the prompt assistant checks each image against the request"),
|
|
50
52
|
"preview": ("auto", str, "images in the terminal: auto | kitty | iterm | blocks (colour text) | off"),
|
|
51
53
|
"think": (True, bool, "let the model reason before answering (slower, better)"),
|
|
52
54
|
"web": ("on", str, "web search and page fetching for the model: on | ask | off"),
|
lcode/media.py
CHANGED
|
@@ -6,10 +6,12 @@ sizes, variations and a gallery come with #151, video with #153.
|
|
|
6
6
|
|
|
7
7
|
from __future__ import annotations
|
|
8
8
|
|
|
9
|
+
import json
|
|
9
10
|
import os
|
|
10
11
|
import random
|
|
11
12
|
import re
|
|
12
13
|
import shutil
|
|
14
|
+
import struct
|
|
13
15
|
import subprocess
|
|
14
16
|
import sys
|
|
15
17
|
import time
|
|
@@ -21,7 +23,7 @@ from typing import TYPE_CHECKING
|
|
|
21
23
|
import requests
|
|
22
24
|
from rich.text import Text
|
|
23
25
|
|
|
24
|
-
from lcode import comfy, edits, imageopts, preview
|
|
26
|
+
from lcode import assistant, comfy, edits, imageopts, preview
|
|
25
27
|
from lcode import media_catalog as catalog
|
|
26
28
|
|
|
27
29
|
if TYPE_CHECKING:
|
|
@@ -268,7 +270,9 @@ def thumbnail(server: comfy.Server, outputs: dict, node: str = THUMB_NODES[1]) -
|
|
|
268
270
|
|
|
269
271
|
|
|
270
272
|
SIZE_FLAG = re.compile(r"(?:^|\s)--?(ar|aspect|size)\b")
|
|
273
|
+
RAW_FLAG = re.compile(r"(?:^|\s)--raw\b")
|
|
271
274
|
MASK_FLAG = re.compile(r'(?:^|\s)--mask\s+("[^"]+"|\S+)')
|
|
275
|
+
REF_FLAG = re.compile(r"(?:^|\s)--refs?\b")
|
|
272
276
|
|
|
273
277
|
|
|
274
278
|
def request(
|
|
@@ -276,6 +280,10 @@ def request(
|
|
|
276
280
|
) -> list[Made]:
|
|
277
281
|
"""A typed request: its @references (images to edit or follow), --mask, and flags (--n 4 --ar 16:9 …, over
|
|
278
282
|
the session's /options), then the images."""
|
|
283
|
+
as_references = bool(REF_FLAG.search(text))
|
|
284
|
+
text = REF_FLAG.sub(" ", text)
|
|
285
|
+
raw = bool(RAW_FLAG.search(text)) # the prompt exactly as typed: no assistant
|
|
286
|
+
text = RAW_FLAG.sub(" ", text)
|
|
279
287
|
mask = None
|
|
280
288
|
m = MASK_FLAG.search(text)
|
|
281
289
|
if m:
|
|
@@ -292,12 +300,24 @@ def request(
|
|
|
292
300
|
if agent.settings.mode == "video":
|
|
293
301
|
if mask:
|
|
294
302
|
raise MediaError("Video mode doesn't take a mask: @photo.png starts a video from a picture.")
|
|
295
|
-
|
|
296
|
-
|
|
303
|
+
if as_references and not sources:
|
|
304
|
+
raise MediaError("--ref makes the @pictures references: @cat.png @hat.png --ref the cat wears the hat")
|
|
305
|
+
frames = [] if as_references else [str(p) for p in sources[:2]]
|
|
306
|
+
refs = [str(p) for p in sources] if as_references else []
|
|
307
|
+
job = {"kind": "video", "prompt": prompt, "options": options, "sources": frames, "mask": None, "pads": None,
|
|
308
|
+
"keep_shape": not SIZE_FLAG.search(text), "refs": refs, "raw": raw} # fmt: skip
|
|
297
309
|
return redo(agent, job, cancelled, ask)
|
|
310
|
+
if not sources and not mask and not raw:
|
|
311
|
+
change = follow_up(agent, prompt)
|
|
312
|
+
if change: # "darker", "add a hat": the last picture, changed
|
|
313
|
+
last = agent.media_results[-1]
|
|
314
|
+
agent.console.print(Text(f"✎ A change to #{last['n']}: {change}", style="dim italic"))
|
|
315
|
+
job = {"kind": "edit", "prompt": change, "options": options, "sources": [last["path"]], "mask": None,
|
|
316
|
+
"pads": None, "keep_shape": not SIZE_FLAG.search(text), "raw": True} # fmt: skip
|
|
317
|
+
return redo(agent, job, cancelled, ask)
|
|
298
318
|
job = {"kind": "edit" if sources else "image", "prompt": prompt, "options": options,
|
|
299
319
|
"sources": [str(p) for p in sources], "mask": str(mask) if mask else None, "pads": None,
|
|
300
|
-
"keep_shape": not SIZE_FLAG.search(text)} # fmt: skip
|
|
320
|
+
"keep_shape": not SIZE_FLAG.search(text), "raw": raw} # fmt: skip
|
|
301
321
|
return redo(agent, job, cancelled, ask)
|
|
302
322
|
|
|
303
323
|
|
|
@@ -313,20 +333,102 @@ def redo(
|
|
|
313
333
|
if options.negative and not model.negative:
|
|
314
334
|
agent.say(f"{model.name} doesn't use a negative prompt: describe what you want instead (--no is ignored).")
|
|
315
335
|
agent.last_request = job
|
|
336
|
+
if not job.get("raw") and job["kind"] in ("image", "edit", "video") and not job.get("pads"):
|
|
337
|
+
job = {**job, "expanded": expand(agent, job)}
|
|
316
338
|
made = []
|
|
317
339
|
for i in range(options.n):
|
|
318
340
|
seed = None if options.seed is None else options.seed + i
|
|
319
341
|
label = f"{i + 1} of {options.n}" if options.n > 1 else ""
|
|
320
342
|
one = replace(options, seed=seed, n=1)
|
|
321
343
|
if job["kind"] == "image":
|
|
322
|
-
made.append(generate_image(agent, prompt, cancelled, ask, one, label))
|
|
344
|
+
made.append(generate_image(agent, prompt, cancelled, ask, one, label, job.get("expanded", "")))
|
|
323
345
|
elif job["kind"] == "video":
|
|
324
346
|
made.append(generate_video(agent, job, one, cancelled, ask, label))
|
|
325
347
|
else:
|
|
326
348
|
made.append(edit_image(agent, job, one, cancelled, ask, label))
|
|
349
|
+
if job["kind"] in ("image", "edit"):
|
|
350
|
+
check_result(agent, made[-1], prompt)
|
|
327
351
|
return made
|
|
328
352
|
|
|
329
353
|
|
|
354
|
+
# ----------------------------------------------------------------------------- the prompt assistant
|
|
355
|
+
|
|
356
|
+
|
|
357
|
+
def helps(agent: Agent, kind: str) -> bool:
|
|
358
|
+
"""Whether the prompt assistant writes this kind of prompt: video only by default, or everything (all)."""
|
|
359
|
+
setting = agent.settings.prompt_assistant
|
|
360
|
+
return setting != "off" and (setting != "video" or kind == "video")
|
|
361
|
+
|
|
362
|
+
|
|
363
|
+
def helper(agent: Agent) -> assistant.Assistant | None:
|
|
364
|
+
"""The prompt assistant (lcode.assistant): the prompt_assistant setting's model, or a small installed one."""
|
|
365
|
+
if getattr(agent, "_assistant_model", None) is None:
|
|
366
|
+
setting = agent.settings.prompt_assistant
|
|
367
|
+
model = assistant.pick(agent.ollama, "auto" if setting == "off" else setting) # check_results may want one
|
|
368
|
+
agent._assistant_model = model or ""
|
|
369
|
+
if setting not in assistant.SCOPES and not model:
|
|
370
|
+
agent.say(f"The prompt assistant {agent.settings.prompt_assistant} isn't installed in Ollama: ollama pull "
|
|
371
|
+
f"{agent.settings.prompt_assistant}. Prompts go as typed.", warning=True) # fmt: skip
|
|
372
|
+
return assistant.Assistant(agent.ollama, agent._assistant_model) if agent._assistant_model else None
|
|
373
|
+
|
|
374
|
+
|
|
375
|
+
def expand(agent: Agent, job: dict) -> str:
|
|
376
|
+
"""The assistant's fuller prompt for the job, shown before it's used; empty when it's off or fails."""
|
|
377
|
+
kind = job["kind"]
|
|
378
|
+
helper_model = helper(agent) if helps(agent, kind) else None
|
|
379
|
+
if helper_model is None:
|
|
380
|
+
return ""
|
|
381
|
+
start = Path(job["sources"][0]) if kind == "video" and job.get("sources") else None
|
|
382
|
+
try:
|
|
383
|
+
with agent.console.status(
|
|
384
|
+
f"The prompt assistant ({helper_model.model}) is writing the prompt…", spinner="dots"
|
|
385
|
+
):
|
|
386
|
+
text = helper_model.expand(job["prompt"], kind, start if start and edits.is_image(start) else None)
|
|
387
|
+
except assistant.AssistantError as e:
|
|
388
|
+
agent.say(f"{e}: the prompt goes as typed.", warning=True)
|
|
389
|
+
return ""
|
|
390
|
+
if text and text != job["prompt"]:
|
|
391
|
+
agent.console.print(Text(f"✎ {text}", style="dim italic"))
|
|
392
|
+
return text
|
|
393
|
+
return ""
|
|
394
|
+
|
|
395
|
+
|
|
396
|
+
def follow_up(agent: Agent, text: str) -> str | None:
|
|
397
|
+
"""A short request after an image: the assistant decides whether it's a change to it, and words it."""
|
|
398
|
+
last = agent.media_results[-1] if agent.media_results else None
|
|
399
|
+
if last is None or not edits.is_image(Path(last["path"])) or len(text.split()) > 10:
|
|
400
|
+
return None
|
|
401
|
+
if agent.settings.prompt_assistant in ("off", "video"): # follow-ups come with prompts for pictures (all)
|
|
402
|
+
return None
|
|
403
|
+
helper_model = helper(agent)
|
|
404
|
+
if helper_model is None:
|
|
405
|
+
return None
|
|
406
|
+
try:
|
|
407
|
+
return helper_model.follow_up(text, last["prompt"])
|
|
408
|
+
except assistant.AssistantError:
|
|
409
|
+
return None
|
|
410
|
+
|
|
411
|
+
|
|
412
|
+
def check_result(agent: Agent, made: Made, request: str) -> None:
|
|
413
|
+
"""With check_results on: the assistant looks at the picture and says whether it shows what was asked."""
|
|
414
|
+
if not agent.settings.check_results or not made.files or not edits.is_image(made.files[0]):
|
|
415
|
+
return
|
|
416
|
+
helper_model = helper(agent)
|
|
417
|
+
if helper_model is None:
|
|
418
|
+
return
|
|
419
|
+
try:
|
|
420
|
+
with agent.console.status("The prompt assistant is checking the picture…", spinner="dots"):
|
|
421
|
+
result = helper_model.check(made.files[0], request)
|
|
422
|
+
except assistant.AssistantError as e:
|
|
423
|
+
agent.say(f"Couldn't check the picture: {e}", warning=True)
|
|
424
|
+
return
|
|
425
|
+
if result.matches:
|
|
426
|
+
agent.console.print(Text("✓ It shows what you asked for.", style="green"))
|
|
427
|
+
else:
|
|
428
|
+
tip = f" Try: {result.better_prompt}" if result.better_prompt else ""
|
|
429
|
+
agent.console.print(Text(f"⚠ {result.missing or 'It misses part of the request.'}{tip}", style="yellow"))
|
|
430
|
+
|
|
431
|
+
|
|
330
432
|
def make(
|
|
331
433
|
agent: Agent,
|
|
332
434
|
prompt: str,
|
|
@@ -384,8 +486,9 @@ def generate_image(
|
|
|
384
486
|
ask: Callable[[str], bool] | None = None,
|
|
385
487
|
options: imageopts.Options | None = None,
|
|
386
488
|
label: str = "",
|
|
489
|
+
expanded: str = "",
|
|
387
490
|
) -> Made:
|
|
388
|
-
"""One image from the prompt, saved in the media folder and numbered.
|
|
491
|
+
"""One image from the prompt (or the assistant's fuller prompt), saved in the media folder and numbered."""
|
|
389
492
|
prompt = prompt.strip()
|
|
390
493
|
if not prompt:
|
|
391
494
|
raise MediaError("Describe the image you want.")
|
|
@@ -397,7 +500,7 @@ def generate_image(
|
|
|
397
500
|
seed = options.seed if options.seed is not None else random.randrange(2**32)
|
|
398
501
|
steps, megapixels = model.preset(options.quality)
|
|
399
502
|
width, height = imageopts.dimensions(options.size, megapixels)
|
|
400
|
-
text = imageopts.styled(prompt, options.style)
|
|
503
|
+
text = imageopts.styled(expanded or prompt, options.style)
|
|
401
504
|
values = {**workflow.defaults, **files, "prompt": text, "seed": seed, "width": width, "height": height}
|
|
402
505
|
if steps:
|
|
403
506
|
values["steps"] = steps
|
|
@@ -443,7 +546,8 @@ def edit_image(
|
|
|
443
546
|
keep_shape = bool(job.get("keep_shape", True) or job.get("mask") or pads)
|
|
444
547
|
ratio = f"{first_w}x{first_h}" if keep_shape else options.size
|
|
445
548
|
width, height = shape(ratio, megapixels)
|
|
446
|
-
instruction = job
|
|
549
|
+
instruction = job.get("expanded") or job["prompt"]
|
|
550
|
+
instruction = instruction if not pads else f"{edits.EXTEND_HINT} {job['prompt']}".strip()
|
|
447
551
|
text = imageopts.styled(instruction, options.style)
|
|
448
552
|
values = {**workflow.defaults, **files, "prompt": text, "seed": seed, "width": width, "height": height}
|
|
449
553
|
if steps:
|
|
@@ -492,8 +596,13 @@ def generate_video(
|
|
|
492
596
|
start = sources[0] if sources else None
|
|
493
597
|
end = sources[1] if len(sources) > 1 else None
|
|
494
598
|
clip = Path(job["extend"]) if job.get("extend") else None
|
|
495
|
-
|
|
496
|
-
|
|
599
|
+
refs = [Path(p) for p in job.get("refs") or []]
|
|
600
|
+
restyle = Path(job["restyle"]) if job.get("restyle") else None
|
|
601
|
+
task = (
|
|
602
|
+
"restyle" if restyle else "references" if refs else "first-last-frame" if end
|
|
603
|
+
else "camera" if options.camera else "image-to-video" if clip else ""
|
|
604
|
+
) # fmt: skip
|
|
605
|
+
model = video_model(agent, task)
|
|
497
606
|
files = ensure_installed(agent, model, server, ask)
|
|
498
607
|
workflow = comfy.load_workflow(model.workflow)
|
|
499
608
|
seed = options.seed if options.seed is not None else random.randrange(2**32)
|
|
@@ -511,7 +620,15 @@ def generate_video(
|
|
|
511
620
|
if clip is not None: # the new part continues the clip, so it has its size
|
|
512
621
|
width, height = job["size"]
|
|
513
622
|
fps = int(workflow.defaults.get("fps", 24))
|
|
514
|
-
|
|
623
|
+
if clip is not None: # one clip, one pace: the new part plays at the clip's fps
|
|
624
|
+
fps = int(clip_info(clip)["fps"] or fps)
|
|
625
|
+
if restyle is not None: # the restyled clip has the clip's size and pace (up to the model's length)
|
|
626
|
+
info = clip_info(restyle)
|
|
627
|
+
width, height = (info["width"] // 16 * 16 or 832), (info["height"] // 16 * 16 or 480)
|
|
628
|
+
fps = int(info["fps"] or fps)
|
|
629
|
+
options = replace(options, seconds=min(options.seconds if job.get("seconds_given") else 99,
|
|
630
|
+
(min(info["frames"] or 81, 81) - 1) / fps)) # fmt: skip
|
|
631
|
+
text = imageopts.styled(job.get("expanded") or prompt, options.style)
|
|
515
632
|
values = {**workflow.defaults, **files, "prompt": text, "seed": seed, "width": width, "height": height,
|
|
516
633
|
"length": imageopts.frames(options.seconds, fps), "fps": fps} # fmt: skip
|
|
517
634
|
if steps:
|
|
@@ -535,28 +652,75 @@ def generate_video(
|
|
|
535
652
|
graph[latent]["inputs"]["end_image"] = ["8101", 0]
|
|
536
653
|
if clip is not None:
|
|
537
654
|
continue_clip(graph, latent, server.upload(clip), values["length"])
|
|
655
|
+
vace = edits.node_of(graph, "WanVaceToVideo")
|
|
656
|
+
if refs and vace is not None:
|
|
657
|
+
graph[vace]["inputs"]["reference_image"] = reference_strip(graph, [server.upload(p) for p in refs])
|
|
658
|
+
if restyle is not None and vace is not None:
|
|
659
|
+
graph[vace]["inputs"]["control_video"] = control_from(graph, server.upload(restyle), values["length"])
|
|
538
660
|
except (comfy.ComfyError, OSError) as e:
|
|
539
661
|
raise MediaError(f"Couldn't hand the files to ComfyUI: {e}") from e
|
|
540
662
|
add_thumbnail(graph, width, height)
|
|
541
663
|
meta = describe_job(model, workflow, prompt, text, seed, values, options, files)
|
|
542
664
|
meta.update({"seconds": round((values["length"] - 1) / fps, 2), "fps": fps, "frames": values["length"],
|
|
543
665
|
"start_image": shown(agent, start) if start else "", "end_image": shown(agent, end) if end else "",
|
|
544
|
-
"camera": options.camera, "extends": shown(agent, clip) if clip else ""
|
|
545
|
-
|
|
546
|
-
|
|
666
|
+
"camera": options.camera, "extends": shown(agent, clip) if clip else "",
|
|
667
|
+
"references": [shown(agent, p) for p in refs],
|
|
668
|
+
"restyles": shown(agent, restyle) if restyle else ""}) # fmt: skip
|
|
669
|
+
keys = ("kind", "prompt", "sources", "mask", "pads", "keep_shape", "extend", "size", "refs", "restyle")
|
|
670
|
+
remembered = {k: job.get(k) for k in keys}
|
|
671
|
+
stem = f"{clip.stem}-extended" if clip else (f"{restyle.stem}-restyled" if restyle else "")
|
|
547
672
|
plan = Plan(model, workflow, graph, meta, prompt, seed, options, "video", job.get("sources") or [], remembered,
|
|
548
673
|
stem) # fmt: skip
|
|
549
674
|
return run_plan(agent, server, plan, cancelled, label)
|
|
550
675
|
|
|
551
676
|
|
|
552
|
-
VIDEO_LATENTS = ("Wan22ImageToVideoLatent", "WanFunInpaintToVideo", "WanCameraImageToVideo")
|
|
677
|
+
VIDEO_LATENTS = ("Wan22ImageToVideoLatent", "WanFunInpaintToVideo", "WanCameraImageToVideo", "WanVaceToVideo")
|
|
553
678
|
WHY = {
|
|
554
679
|
"first-last-frame": "a clip between two frames",
|
|
555
680
|
"camera": "a camera move",
|
|
556
681
|
"image-to-video": "continuing a clip",
|
|
682
|
+
"references": "following reference pictures",
|
|
683
|
+
"restyle": "restyling a clip",
|
|
557
684
|
}
|
|
558
685
|
|
|
559
686
|
|
|
687
|
+
def reference_strip(graph: dict, names: list[str]) -> list:
|
|
688
|
+
"""The reference pictures side by side in one image, as VACE takes them."""
|
|
689
|
+
graph["8300"] = {"class_type": "LoadImage", "inputs": {"image": names[0]}}
|
|
690
|
+
strip = ["8300", 0]
|
|
691
|
+
for k, name in enumerate(names[1:], 1):
|
|
692
|
+
load, stitch = str(8300 + 2 * k - 1), str(8300 + 2 * k)
|
|
693
|
+
graph[load] = {"class_type": "LoadImage", "inputs": {"image": name}}
|
|
694
|
+
graph[stitch] = {
|
|
695
|
+
"class_type": "ImageStitch",
|
|
696
|
+
"inputs": {"image1": strip, "direction": "right", "match_image_size": True, "spacing_width": 0,
|
|
697
|
+
"spacing_color": "white", "image2": [load, 0]},
|
|
698
|
+
} # fmt: skip
|
|
699
|
+
strip = [stitch, 0]
|
|
700
|
+
return strip
|
|
701
|
+
|
|
702
|
+
|
|
703
|
+
def control_from(graph: dict, clip_name: str, length: int) -> list:
|
|
704
|
+
"""Restyling: the clip's outlines (Canny edges), frame by frame, for VACE to follow."""
|
|
705
|
+
graph["8400"] = {"class_type": "LoadVideo", "inputs": {"file": clip_name}}
|
|
706
|
+
graph["8401"] = {"class_type": "GetVideoComponents", "inputs": {"video": ["8400", 0]}}
|
|
707
|
+
graph["8402"] = {
|
|
708
|
+
"class_type": "ImageFromBatch",
|
|
709
|
+
"inputs": {"image": ["8401", 0], "batch_index": 0, "length": length},
|
|
710
|
+
}
|
|
711
|
+
latent = edits.node_of(graph, "WanVaceToVideo")
|
|
712
|
+
w, h = graph[latent]["inputs"]["width"], graph[latent]["inputs"]["height"]
|
|
713
|
+
graph["8403"] = {
|
|
714
|
+
"class_type": "ImageScale",
|
|
715
|
+
"inputs": {"image": ["8402", 0], "upscale_method": "bilinear", "width": w, "height": h, "crop": "center"},
|
|
716
|
+
}
|
|
717
|
+
graph["8404"] = {
|
|
718
|
+
"class_type": "Canny",
|
|
719
|
+
"inputs": {"image": ["8403", 0], "low_threshold": 0.3, "high_threshold": 0.6},
|
|
720
|
+
}
|
|
721
|
+
return ["8404", 0]
|
|
722
|
+
|
|
723
|
+
|
|
560
724
|
def video_model(agent: Agent, task: str) -> catalog.MediaModel:
|
|
561
725
|
"""The video model for a job: the chosen one, or the first that does what the job needs."""
|
|
562
726
|
chosen = current(agent, "video")
|
|
@@ -582,6 +746,46 @@ def continue_clip(graph: dict, latent: str, clip_name: str, length: int) -> None
|
|
|
582
746
|
graph[video]["inputs"]["images"] = ["8204", 0]
|
|
583
747
|
|
|
584
748
|
|
|
749
|
+
VIDEO_TYPES = (".mp4", ".webm", ".mkv", ".mov")
|
|
750
|
+
TOOL_NAMES = {"upscale": "upscaled", "remove-background": "nobg", "interpolate": "smooth", "sound": "sound"}
|
|
751
|
+
|
|
752
|
+
|
|
753
|
+
def is_video(path: Path) -> bool:
|
|
754
|
+
return path.suffix.lower() in VIDEO_TYPES
|
|
755
|
+
|
|
756
|
+
|
|
757
|
+
def clip_info(path: Path) -> dict:
|
|
758
|
+
"""A clip's fps, seconds, frames, width and height: from lcode's JSON next to it, else its MP4 header."""
|
|
759
|
+
info = {"fps": 24.0, "seconds": 0.0, "frames": 0, "width": 0, "height": 0}
|
|
760
|
+
try:
|
|
761
|
+
meta = json.loads(path.with_suffix(".json").read_text())
|
|
762
|
+
info.update({k: meta[k] for k in info if isinstance(meta.get(k), (int, float))})
|
|
763
|
+
except (OSError, ValueError):
|
|
764
|
+
pass
|
|
765
|
+
if not info["seconds"]:
|
|
766
|
+
info["seconds"] = mp4_seconds(path)
|
|
767
|
+
if not info["frames"] and info["seconds"]:
|
|
768
|
+
info["frames"] = round(info["seconds"] * info["fps"]) + 1
|
|
769
|
+
return info
|
|
770
|
+
|
|
771
|
+
|
|
772
|
+
def mp4_seconds(path: Path) -> float:
|
|
773
|
+
"""An MP4's length from its movie header (mvhd), or 0."""
|
|
774
|
+
try:
|
|
775
|
+
data = path.read_bytes()
|
|
776
|
+
except OSError:
|
|
777
|
+
return 0.0
|
|
778
|
+
i = data.find(b"mvhd")
|
|
779
|
+
if i < 4:
|
|
780
|
+
return 0.0
|
|
781
|
+
version = data[i + 4]
|
|
782
|
+
if version == 1:
|
|
783
|
+
scale, duration = struct.unpack(">IQ", data[i + 24 : i + 36])
|
|
784
|
+
else:
|
|
785
|
+
scale, duration = struct.unpack(">II", data[i + 16 : i + 24])
|
|
786
|
+
return duration / scale if scale else 0.0
|
|
787
|
+
|
|
788
|
+
|
|
585
789
|
def apply_tool(
|
|
586
790
|
agent: Agent,
|
|
587
791
|
task: str,
|
|
@@ -589,27 +793,52 @@ def apply_tool(
|
|
|
589
793
|
scale: int = 2,
|
|
590
794
|
cancelled: Callable[[], bool] = lambda: False,
|
|
591
795
|
ask: Callable[[str], bool] | None = None,
|
|
796
|
+
prompt: str = "",
|
|
592
797
|
) -> Made:
|
|
593
|
-
"""
|
|
798
|
+
"""A tool model on one image or clip: /upscale (both), /nobg (pictures), /smooth and /sound (clips)."""
|
|
799
|
+
video = is_video(source)
|
|
800
|
+
if task == "remove-background" and video:
|
|
801
|
+
raise MediaError("/nobg works on pictures.")
|
|
802
|
+
if task in ("interpolate", "sound") and not video:
|
|
803
|
+
raise MediaError(f"/{'smooth' if task == 'interpolate' else 'sound'} works on clips.")
|
|
804
|
+
if task == "sound" and not prompt.strip():
|
|
805
|
+
raise MediaError("Say what it should sound like: /sound 4 waves and seagulls")
|
|
594
806
|
server = prepare(agent, ask, cancelled)
|
|
595
807
|
model = catalog.load().tool(task)
|
|
596
808
|
files = ensure_installed(agent, model, server, ask)
|
|
597
|
-
workflow = comfy.load_workflow(model.workflow)
|
|
809
|
+
workflow = comfy.load_workflow(model.video_workflow if video and model.video_workflow else model.workflow)
|
|
598
810
|
try:
|
|
599
811
|
name = server.upload(source)
|
|
600
|
-
|
|
812
|
+
if video:
|
|
813
|
+
info = clip_info(source)
|
|
814
|
+
width, height = info["width"] or 864, info["height"] or 480
|
|
815
|
+
else:
|
|
816
|
+
width, height = edits.image_size(source)
|
|
601
817
|
except (comfy.ComfyError, OSError, edits.EditError) as e:
|
|
602
|
-
raise MediaError(f"Couldn't hand the
|
|
603
|
-
values = {**workflow.defaults, **files, "image": name}
|
|
818
|
+
raise MediaError(f"Couldn't hand the file to ComfyUI: {e}") from e
|
|
819
|
+
values = {**workflow.defaults, **files, ("video" if video else "image"): name}
|
|
820
|
+
seed = 0
|
|
821
|
+
if video:
|
|
822
|
+
values["fps"] = info["fps"]
|
|
604
823
|
if task == "upscale":
|
|
605
824
|
values["scale_by"] = scale / 4 # Real-ESRGAN makes 4 times the size; scaled back for 2
|
|
606
825
|
width, height = width * scale, height * scale
|
|
826
|
+
elif task == "interpolate":
|
|
827
|
+
values["multiplier"], values["fps"] = scale, info["fps"] * scale
|
|
828
|
+
elif task == "sound":
|
|
829
|
+
seed = random.randrange(2**32)
|
|
830
|
+
values.update({"prompt": prompt.strip(), "seed": seed, "seconds": max(1.0, info["seconds"])})
|
|
607
831
|
graph = comfy.fill(workflow.graph, values)
|
|
608
832
|
add_thumbnail(graph, width, height)
|
|
609
|
-
what =
|
|
610
|
-
|
|
833
|
+
what = {
|
|
834
|
+
"upscale": f"upscaled {scale}×",
|
|
835
|
+
"remove-background": "background removed",
|
|
836
|
+
"interpolate": f"{scale}× the frames",
|
|
837
|
+
"sound": f"sound: {prompt.strip()}",
|
|
838
|
+
}[task]
|
|
839
|
+
label = f"{what} ({shown(agent, source)})"
|
|
611
840
|
meta = {
|
|
612
|
-
"prompt":
|
|
841
|
+
"prompt": label,
|
|
613
842
|
"model": model.name,
|
|
614
843
|
"model_key": model.key,
|
|
615
844
|
"workflow": workflow.key,
|
|
@@ -617,8 +846,10 @@ def apply_tool(
|
|
|
617
846
|
"files": files,
|
|
618
847
|
"created": time.strftime("%Y-%m-%dT%H:%M:%S%z"),
|
|
619
848
|
}
|
|
620
|
-
|
|
621
|
-
|
|
849
|
+
if video:
|
|
850
|
+
meta.update({"fps": values["fps"], "seconds": info["seconds"], "width": width, "height": height})
|
|
851
|
+
suffix = {"upscale": f"upscaled-{scale}x", "interpolate": f"smooth-{scale}x"}.get(task, TOOL_NAMES[task])
|
|
852
|
+
plan = Plan(model, workflow, graph, meta, label, seed, imageopts.Options(), task, [str(source)], {},
|
|
622
853
|
f"{source.stem}-{suffix}") # fmt: skip
|
|
623
854
|
return run_plan(agent, server, plan, cancelled, "")
|
|
624
855
|
|