lcode-cli 0.46.0__py3-none-any.whl → 0.48.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/film.py +316 -0
- lcode/media.py +103 -8
- lcode/repl.py +67 -0
- {lcode_cli-0.46.0.dist-info → lcode_cli-0.48.0.dist-info}/METADATA +1 -1
- {lcode_cli-0.46.0.dist-info → lcode_cli-0.48.0.dist-info}/RECORD +13 -11
- {lcode_cli-0.46.0.dist-info → lcode_cli-0.48.0.dist-info}/WHEEL +0 -0
- {lcode_cli-0.46.0.dist-info → lcode_cli-0.48.0.dist-info}/entry_points.txt +0 -0
- {lcode_cli-0.46.0.dist-info → lcode_cli-0.48.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/film.py
ADDED
|
@@ -0,0 +1,316 @@
|
|
|
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 character or place described once), and the shots (what happens, how long, the camera, who's in it). It's
|
|
5
|
+
saved as `storyboard.json` in the film's folder, so it can be edited and made again.
|
|
6
|
+
2. **The cast.** Each character gets a reference picture (FLUX.2 klein), made once and kept in `cast/`.
|
|
7
|
+
3. **The shots.** Each shot starts as a keyframe: a picture of the shot made with the cast's pictures as references,
|
|
8
|
+
so the characters look the same from shot to shot. Video mode's model then animates the keyframe.
|
|
9
|
+
4. **The film.** The shots are joined with cuts or fades (ffmpeg) into `film.mp4`, and a sound track can be added.
|
|
10
|
+
|
|
11
|
+
Any shot can be made again alone (`/film shot 2`), and the film joined again (`/film stitch`).
|
|
12
|
+
"""
|
|
13
|
+
|
|
14
|
+
from __future__ import annotations
|
|
15
|
+
|
|
16
|
+
import json
|
|
17
|
+
import re
|
|
18
|
+
import shutil
|
|
19
|
+
import subprocess
|
|
20
|
+
from collections.abc import Callable
|
|
21
|
+
from dataclasses import asdict, dataclass, field, replace
|
|
22
|
+
from pathlib import Path
|
|
23
|
+
from typing import TYPE_CHECKING
|
|
24
|
+
|
|
25
|
+
from lcode import assistant, comfy, imageopts, media
|
|
26
|
+
|
|
27
|
+
if TYPE_CHECKING:
|
|
28
|
+
from lcode.agent import Agent
|
|
29
|
+
|
|
30
|
+
MAX_SHOTS = 8
|
|
31
|
+
STORYBOARD = (
|
|
32
|
+
"You write storyboards for short AI-generated films. From the user's idea, write a film of {shots} shots, each "
|
|
33
|
+
"about {seconds} seconds. Answer with JSON only, in English:\n"
|
|
34
|
+
'{{"title": "a short title", "look": "the visual style of the whole film in one sentence (medium, light, '
|
|
35
|
+
'colour, lens)", "cast": [{{"name": "a one-word name", "description": "what the character looks like: '
|
|
36
|
+
'species or age, build, clothes, colours, distinctive features, in one sentence"}}], "shots": [{{"description": '
|
|
37
|
+
'"what happens in this shot, where, and who is in it, in one or two sentences, using the cast names", "camera": '
|
|
38
|
+
'"a shot type and camera move, like slow zoom in, tracking shot, static wide shot", "cast": ["names in this '
|
|
39
|
+
'shot"], "seconds": {seconds}}}]}}\n'
|
|
40
|
+
"Use one to three cast members, the same names in every shot. Each shot is one continuous moment; the film "
|
|
41
|
+
"tells a small story from the first shot to the last. Describe what is seen, never what is felt or heard."
|
|
42
|
+
)
|
|
43
|
+
TRANSITIONS = ("cut", "fade")
|
|
44
|
+
FADE = 0.5 # seconds a fade takes
|
|
45
|
+
|
|
46
|
+
|
|
47
|
+
class FilmError(Exception):
|
|
48
|
+
pass
|
|
49
|
+
|
|
50
|
+
|
|
51
|
+
@dataclass
|
|
52
|
+
class Shot:
|
|
53
|
+
description: str
|
|
54
|
+
camera: str = "static shot"
|
|
55
|
+
cast: list[str] = field(default_factory=list)
|
|
56
|
+
seconds: float = 4.0
|
|
57
|
+
|
|
58
|
+
|
|
59
|
+
@dataclass
|
|
60
|
+
class Board:
|
|
61
|
+
title: str
|
|
62
|
+
look: str
|
|
63
|
+
cast: dict[str, str] # name -> description
|
|
64
|
+
shots: list[Shot]
|
|
65
|
+
idea: str = ""
|
|
66
|
+
transition: str = "cut"
|
|
67
|
+
sound: str = "" # a sound track for the whole film, made after it's joined
|
|
68
|
+
quality: str = "fast"
|
|
69
|
+
|
|
70
|
+
def to_json(self) -> dict:
|
|
71
|
+
data = asdict(self)
|
|
72
|
+
data["cast"] = [{"name": n, "description": d} for n, d in self.cast.items()]
|
|
73
|
+
return data
|
|
74
|
+
|
|
75
|
+
@classmethod
|
|
76
|
+
def from_json(cls, data: dict) -> Board:
|
|
77
|
+
cast = {}
|
|
78
|
+
for member in data.get("cast") or []:
|
|
79
|
+
if isinstance(member, dict) and str(member.get("name") or "").strip():
|
|
80
|
+
cast[str(member["name"]).strip()] = str(member.get("description") or "").strip()
|
|
81
|
+
shots = []
|
|
82
|
+
for raw in data.get("shots") or []:
|
|
83
|
+
if not isinstance(raw, dict) or not str(raw.get("description") or "").strip():
|
|
84
|
+
continue
|
|
85
|
+
seconds = raw.get("seconds")
|
|
86
|
+
shots.append(
|
|
87
|
+
Shot(
|
|
88
|
+
str(raw["description"]).strip(),
|
|
89
|
+
str(raw.get("camera") or "static shot").strip(),
|
|
90
|
+
[str(n).strip() for n in raw.get("cast") or [] if str(n).strip() in cast],
|
|
91
|
+
float(seconds) if isinstance(seconds, (int, float)) and 1 <= seconds <= 8 else 4.0,
|
|
92
|
+
)
|
|
93
|
+
)
|
|
94
|
+
if not shots:
|
|
95
|
+
raise FilmError("the storyboard has no shots")
|
|
96
|
+
return cls(
|
|
97
|
+
str(data.get("title") or "Untitled").strip(),
|
|
98
|
+
str(data.get("look") or "").strip(),
|
|
99
|
+
cast,
|
|
100
|
+
shots[:MAX_SHOTS],
|
|
101
|
+
str(data.get("idea") or ""),
|
|
102
|
+
data.get("transition") if data.get("transition") in TRANSITIONS else "cut",
|
|
103
|
+
str(data.get("sound") or ""),
|
|
104
|
+
data.get("quality") if data.get("quality") in imageopts.QUALITIES else "fast",
|
|
105
|
+
)
|
|
106
|
+
|
|
107
|
+
|
|
108
|
+
# ----------------------------------------------------------------------------- the storyboard
|
|
109
|
+
|
|
110
|
+
|
|
111
|
+
def films_folder(agent: Agent) -> Path:
|
|
112
|
+
return media.folder(agent) / "films"
|
|
113
|
+
|
|
114
|
+
|
|
115
|
+
def plan(agent: Agent, idea: str, shots: int = 3, seconds: float = 4.0) -> tuple[Board, Path]:
|
|
116
|
+
"""The assistant's storyboard for an idea, saved in a new film folder."""
|
|
117
|
+
model = assistant.pick(agent.ollama, agent.settings.prompt_assistant if agent.settings.prompt_assistant
|
|
118
|
+
not in assistant.SCOPES else "auto") # fmt: skip
|
|
119
|
+
if model is None:
|
|
120
|
+
raise FilmError("Films need the prompt assistant to write the storyboard: ollama pull qwen3.5:4b")
|
|
121
|
+
helper = assistant.Assistant(agent.ollama, model)
|
|
122
|
+
system = STORYBOARD.format(shots=shots, seconds=f"{seconds:g}")
|
|
123
|
+
with agent.console.status(f"The prompt assistant ({model}) is writing the storyboard…", spinner="dots"):
|
|
124
|
+
try:
|
|
125
|
+
data = assistant.parse_json(helper.write(system, idea, json_answer=True))
|
|
126
|
+
except assistant.AssistantError as e:
|
|
127
|
+
raise FilmError(str(e)) from e
|
|
128
|
+
data["idea"] = idea
|
|
129
|
+
board = Board.from_json(data)
|
|
130
|
+
folder = new_folder(agent, board.title)
|
|
131
|
+
save(board, folder)
|
|
132
|
+
return board, folder
|
|
133
|
+
|
|
134
|
+
|
|
135
|
+
def new_folder(agent: Agent, title: str) -> Path:
|
|
136
|
+
base = films_folder(agent) / comfy.slug(title, 30)
|
|
137
|
+
folder, n = base, 2
|
|
138
|
+
while folder.exists():
|
|
139
|
+
folder, n = base.with_name(f"{base.name}-{n}"), n + 1
|
|
140
|
+
folder.mkdir(parents=True)
|
|
141
|
+
return folder
|
|
142
|
+
|
|
143
|
+
|
|
144
|
+
def save(board: Board, folder: Path) -> None:
|
|
145
|
+
(folder / "storyboard.json").write_text(json.dumps(board.to_json(), indent=2, ensure_ascii=False) + "\n")
|
|
146
|
+
lines = [f"# {board.title}", "", f"*{board.look}*", "", "## Cast", ""]
|
|
147
|
+
lines += [f"- **{name}:** {desc}" for name, desc in board.cast.items()]
|
|
148
|
+
lines += ["", "## Shots", ""]
|
|
149
|
+
for n, shot in enumerate(board.shots, 1):
|
|
150
|
+
who = f" ({', '.join(shot.cast)})" if shot.cast else ""
|
|
151
|
+
lines.append(f"{n}. {shot.description}{who} — {shot.camera}, {shot.seconds:g} s")
|
|
152
|
+
(folder / "storyboard.md").write_text("\n".join(lines) + "\n")
|
|
153
|
+
|
|
154
|
+
|
|
155
|
+
def load(folder: Path) -> Board:
|
|
156
|
+
try:
|
|
157
|
+
return Board.from_json(json.loads((folder / "storyboard.json").read_text()))
|
|
158
|
+
except (OSError, ValueError) as e:
|
|
159
|
+
raise FilmError(f"can't read {folder / 'storyboard.json'}: {e}") from e
|
|
160
|
+
|
|
161
|
+
|
|
162
|
+
def latest(agent: Agent) -> Path:
|
|
163
|
+
folders = sorted((p for p in films_folder(agent).glob("*") if (p / "storyboard.json").exists()),
|
|
164
|
+
key=lambda p: p.stat().st_mtime) # fmt: skip
|
|
165
|
+
if not folders:
|
|
166
|
+
raise FilmError("No film here yet: /film <your idea>")
|
|
167
|
+
return folders[-1]
|
|
168
|
+
|
|
169
|
+
|
|
170
|
+
def find(agent: Agent, name: str) -> Path:
|
|
171
|
+
if not name:
|
|
172
|
+
return latest(agent)
|
|
173
|
+
folder = films_folder(agent) / name
|
|
174
|
+
if not (folder / "storyboard.json").exists():
|
|
175
|
+
raise FilmError(f"There's no film {name!r}: /film list")
|
|
176
|
+
return folder
|
|
177
|
+
|
|
178
|
+
|
|
179
|
+
def describe(board: Board, folder: Path, agent: Agent) -> str:
|
|
180
|
+
lines = [f"{board.title} ({media.shown(agent, folder)})", f" look: {board.look}"]
|
|
181
|
+
lines += [f" cast: {name} — {desc}" for name, desc in board.cast.items()]
|
|
182
|
+
for n, shot in enumerate(board.shots, 1):
|
|
183
|
+
who = f" [{', '.join(shot.cast)}]" if shot.cast else ""
|
|
184
|
+
lines.append(f" {n}. {shot.description}{who} — {shot.camera}, {shot.seconds:g} s")
|
|
185
|
+
return "\n".join(lines)
|
|
186
|
+
|
|
187
|
+
|
|
188
|
+
# ----------------------------------------------------------------------------- making it
|
|
189
|
+
|
|
190
|
+
|
|
191
|
+
def make(
|
|
192
|
+
agent: Agent,
|
|
193
|
+
board: Board,
|
|
194
|
+
folder: Path,
|
|
195
|
+
only: list[int] | None = None,
|
|
196
|
+
cancelled: Callable[[], bool] = lambda: False,
|
|
197
|
+
ask: Callable[[str], bool] | None = None,
|
|
198
|
+
) -> Path:
|
|
199
|
+
"""Make the cast's pictures (once), the shots (all, or `only` those numbers), and join the film."""
|
|
200
|
+
say = agent.say
|
|
201
|
+
for name, desc in board.cast.items():
|
|
202
|
+
picture = folder / "cast" / f"{comfy.slug(name, 20)}.png"
|
|
203
|
+
if picture.exists():
|
|
204
|
+
continue
|
|
205
|
+
say(f"Cast: {name}")
|
|
206
|
+
prompt = f"{board.look} Character reference of {name}: {desc}. Full body, facing the camera, plain background."
|
|
207
|
+
made = with_mode(agent, "image", lambda p=prompt: media.generate_image(
|
|
208
|
+
agent, p, cancelled, ask, imageopts.Options(size="3:4", quality=board.quality))) # fmt: skip
|
|
209
|
+
keep(made.files[0], picture)
|
|
210
|
+
for n, shot in enumerate(board.shots, 1):
|
|
211
|
+
if only and n not in only:
|
|
212
|
+
continue
|
|
213
|
+
say(f"Shot {n} of {len(board.shots)}: {shot.description}")
|
|
214
|
+
keyframe = folder / "keyframes" / f"{n:02d}.png"
|
|
215
|
+
refs = [folder / "cast" / f"{comfy.slug(name, 20)}.png" for name in shot.cast]
|
|
216
|
+
if refs:
|
|
217
|
+
names = "; ".join(f"image {k} is {name}" for k, name in enumerate(shot.cast, 1))
|
|
218
|
+
prompt = f"{board.look} {shot.description} ({names}). A film still, wide 16:9 frame."
|
|
219
|
+
options = imageopts.Options(size="16:9", quality=board.quality)
|
|
220
|
+
job = {"kind": "edit", "prompt": prompt, "options": options, "sources": [str(p) for p in refs],
|
|
221
|
+
"mask": None, "pads": None, "keep_shape": False, "raw": True} # fmt: skip
|
|
222
|
+
made = with_mode(agent, "image", lambda j=job: media.edit_image(agent, j, j["options"], cancelled, ask))
|
|
223
|
+
else:
|
|
224
|
+
prompt = f"{board.look} {shot.description}. A film still, wide 16:9 frame."
|
|
225
|
+
made = with_mode(agent, "image", lambda p=prompt: media.generate_image(
|
|
226
|
+
agent, p, cancelled, ask, imageopts.Options(size="16:9", quality=board.quality))) # fmt: skip
|
|
227
|
+
keep(made.files[0], keyframe)
|
|
228
|
+
options = imageopts.Options(seconds=shot.seconds, quality=board.quality)
|
|
229
|
+
job = {"kind": "video", "prompt": f"{shot.description} {shot.camera}. {board.look}", "options": options,
|
|
230
|
+
"sources": [str(keyframe)], "mask": None, "pads": None, "keep_shape": True} # fmt: skip
|
|
231
|
+
[clip] = with_mode(agent, "video", lambda j=job: media.redo(agent, j, cancelled, ask))
|
|
232
|
+
keep(clip.files[0], folder / "shots" / f"{n:02d}.mp4")
|
|
233
|
+
return stitch(agent, board, folder, cancelled, ask)
|
|
234
|
+
|
|
235
|
+
|
|
236
|
+
def with_mode(agent: Agent, mode: str, run):
|
|
237
|
+
"""Run one step in image or video mode (the right model for it), then go back."""
|
|
238
|
+
before = agent.settings.mode
|
|
239
|
+
agent.settings.mode = mode
|
|
240
|
+
try:
|
|
241
|
+
return run()
|
|
242
|
+
finally:
|
|
243
|
+
agent.settings.mode = before
|
|
244
|
+
|
|
245
|
+
|
|
246
|
+
def keep(made: Path, where: Path) -> None:
|
|
247
|
+
where.parent.mkdir(parents=True, exist_ok=True)
|
|
248
|
+
shutil.copyfile(made, where)
|
|
249
|
+
|
|
250
|
+
|
|
251
|
+
def stitch(
|
|
252
|
+
agent: Agent,
|
|
253
|
+
board: Board,
|
|
254
|
+
folder: Path,
|
|
255
|
+
cancelled: Callable[[], bool] = lambda: False,
|
|
256
|
+
ask: Callable[[str], bool] | None = None,
|
|
257
|
+
) -> Path:
|
|
258
|
+
"""Join the shots into film.mp4 (cuts or fades), and add the sound track when the storyboard has one."""
|
|
259
|
+
shots = [folder / "shots" / f"{n:02d}.mp4" for n in range(1, len(board.shots) + 1)]
|
|
260
|
+
missing = [p.name for p in shots if not p.exists()]
|
|
261
|
+
if missing:
|
|
262
|
+
raise FilmError(f"Shots not made yet: {', '.join(missing)} (/film make)")
|
|
263
|
+
ffmpeg = shutil.which("ffmpeg")
|
|
264
|
+
if not ffmpeg:
|
|
265
|
+
raise FilmError("Joining the shots needs ffmpeg: install it (apt install ffmpeg, brew install ffmpeg)")
|
|
266
|
+
film = folder / "film.mp4"
|
|
267
|
+
command = join_command(ffmpeg, shots, film, board.transition, [media.clip_info(p)["seconds"] for p in shots])
|
|
268
|
+
with agent.console.status("Joining the shots…", spinner="dots"):
|
|
269
|
+
done = subprocess.run(command, capture_output=True, text=True, stdin=subprocess.DEVNULL)
|
|
270
|
+
if done.returncode != 0:
|
|
271
|
+
raise FilmError(f"ffmpeg couldn't join the shots: {done.stderr.strip()[-400:]}")
|
|
272
|
+
if board.sound:
|
|
273
|
+
made = with_mode(agent, "video", lambda: media.apply_tool(agent, "sound", film, 1, cancelled, ask, board.sound))
|
|
274
|
+
keep(made.files[0], folder / "film-sound.mp4")
|
|
275
|
+
film = folder / "film-sound.mp4"
|
|
276
|
+
agent.console.print(f"[green]◆ {board.title}:[/] {media.shown(agent, film)}")
|
|
277
|
+
return film
|
|
278
|
+
|
|
279
|
+
|
|
280
|
+
def join_command(ffmpeg: str, shots: list[Path], out: Path, transition: str, lengths: list[float]) -> list[str]:
|
|
281
|
+
"""ffmpeg's command for the shots one after another: cut, or each fading into the next (xfade)."""
|
|
282
|
+
command = [ffmpeg, "-y", "-v", "error"]
|
|
283
|
+
for shot in shots:
|
|
284
|
+
command += ["-i", str(shot)]
|
|
285
|
+
count = len(shots)
|
|
286
|
+
if transition == "fade" and count > 1:
|
|
287
|
+
chain, last = [], "[0:v]"
|
|
288
|
+
for k in range(1, count):
|
|
289
|
+
joined = sum(lengths[:k]) - (k - 1) * FADE # how long the film is so far
|
|
290
|
+
label = f"[v{k}]"
|
|
291
|
+
start = max(0.0, joined - FADE)
|
|
292
|
+
chain.append(f"{last}[{k}:v]xfade=transition=fade:duration={FADE}:offset={start:.3f}{label}")
|
|
293
|
+
last = label
|
|
294
|
+
graph = ";".join(chain)
|
|
295
|
+
else:
|
|
296
|
+
last = "[out]"
|
|
297
|
+
graph = "".join(f"[{k}:v]" for k in range(count)) + f"concat=n={count}:v=1:a=0{last}"
|
|
298
|
+
return [*command, "-filter_complex", graph, "-map", last, "-c:v", "libx264", "-pix_fmt", "yuv420p",
|
|
299
|
+
"-movflags", "+faststart", str(out)] # fmt: skip
|
|
300
|
+
|
|
301
|
+
|
|
302
|
+
def shot_numbers(text: str, count: int) -> list[int]:
|
|
303
|
+
numbers = [int(n) for n in re.findall(r"\d+", text)]
|
|
304
|
+
bad = [n for n in numbers if not 1 <= n <= count]
|
|
305
|
+
if not numbers or bad:
|
|
306
|
+
raise FilmError(f"Say which shot: 1 to {count} (/film shot 2)")
|
|
307
|
+
return numbers
|
|
308
|
+
|
|
309
|
+
|
|
310
|
+
def with_options(board: Board, transition: str = "", sound: str = "", quality: str = "") -> Board:
|
|
311
|
+
return replace(
|
|
312
|
+
board,
|
|
313
|
+
transition=transition if transition in TRANSITIONS else board.transition,
|
|
314
|
+
sound=sound or board.sound,
|
|
315
|
+
quality=quality if quality in imageopts.QUALITIES else board.quality,
|
|
316
|
+
)
|
lcode/media.py
CHANGED
|
@@ -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 comfy, edits, imageopts, preview
|
|
26
|
+
from lcode import assistant, comfy, edits, imageopts, preview
|
|
27
27
|
from lcode import media_catalog as catalog
|
|
28
28
|
|
|
29
29
|
if TYPE_CHECKING:
|
|
@@ -270,6 +270,7 @@ def thumbnail(server: comfy.Server, outputs: dict, node: str = THUMB_NODES[1]) -
|
|
|
270
270
|
|
|
271
271
|
|
|
272
272
|
SIZE_FLAG = re.compile(r"(?:^|\s)--?(ar|aspect|size)\b")
|
|
273
|
+
RAW_FLAG = re.compile(r"(?:^|\s)--raw\b")
|
|
273
274
|
MASK_FLAG = re.compile(r'(?:^|\s)--mask\s+("[^"]+"|\S+)')
|
|
274
275
|
REF_FLAG = re.compile(r"(?:^|\s)--refs?\b")
|
|
275
276
|
|
|
@@ -281,6 +282,8 @@ def request(
|
|
|
281
282
|
the session's /options), then the images."""
|
|
282
283
|
as_references = bool(REF_FLAG.search(text))
|
|
283
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)
|
|
284
287
|
mask = None
|
|
285
288
|
m = MASK_FLAG.search(text)
|
|
286
289
|
if m:
|
|
@@ -302,11 +305,19 @@ def request(
|
|
|
302
305
|
frames = [] if as_references else [str(p) for p in sources[:2]]
|
|
303
306
|
refs = [str(p) for p in sources] if as_references else []
|
|
304
307
|
job = {"kind": "video", "prompt": prompt, "options": options, "sources": frames, "mask": None, "pads": None,
|
|
305
|
-
"keep_shape": not SIZE_FLAG.search(text), "refs": refs} # fmt: skip
|
|
308
|
+
"keep_shape": not SIZE_FLAG.search(text), "refs": refs, "raw": raw} # fmt: skip
|
|
306
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)
|
|
307
318
|
job = {"kind": "edit" if sources else "image", "prompt": prompt, "options": options,
|
|
308
319
|
"sources": [str(p) for p in sources], "mask": str(mask) if mask else None, "pads": None,
|
|
309
|
-
"keep_shape": not SIZE_FLAG.search(text)} # fmt: skip
|
|
320
|
+
"keep_shape": not SIZE_FLAG.search(text), "raw": raw} # fmt: skip
|
|
310
321
|
return redo(agent, job, cancelled, ask)
|
|
311
322
|
|
|
312
323
|
|
|
@@ -322,20 +333,102 @@ def redo(
|
|
|
322
333
|
if options.negative and not model.negative:
|
|
323
334
|
agent.say(f"{model.name} doesn't use a negative prompt: describe what you want instead (--no is ignored).")
|
|
324
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)}
|
|
325
338
|
made = []
|
|
326
339
|
for i in range(options.n):
|
|
327
340
|
seed = None if options.seed is None else options.seed + i
|
|
328
341
|
label = f"{i + 1} of {options.n}" if options.n > 1 else ""
|
|
329
342
|
one = replace(options, seed=seed, n=1)
|
|
330
343
|
if job["kind"] == "image":
|
|
331
|
-
made.append(generate_image(agent, prompt, cancelled, ask, one, label))
|
|
344
|
+
made.append(generate_image(agent, prompt, cancelled, ask, one, label, job.get("expanded", "")))
|
|
332
345
|
elif job["kind"] == "video":
|
|
333
346
|
made.append(generate_video(agent, job, one, cancelled, ask, label))
|
|
334
347
|
else:
|
|
335
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)
|
|
336
351
|
return made
|
|
337
352
|
|
|
338
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
|
+
|
|
339
432
|
def make(
|
|
340
433
|
agent: Agent,
|
|
341
434
|
prompt: str,
|
|
@@ -393,8 +486,9 @@ def generate_image(
|
|
|
393
486
|
ask: Callable[[str], bool] | None = None,
|
|
394
487
|
options: imageopts.Options | None = None,
|
|
395
488
|
label: str = "",
|
|
489
|
+
expanded: str = "",
|
|
396
490
|
) -> Made:
|
|
397
|
-
"""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."""
|
|
398
492
|
prompt = prompt.strip()
|
|
399
493
|
if not prompt:
|
|
400
494
|
raise MediaError("Describe the image you want.")
|
|
@@ -406,7 +500,7 @@ def generate_image(
|
|
|
406
500
|
seed = options.seed if options.seed is not None else random.randrange(2**32)
|
|
407
501
|
steps, megapixels = model.preset(options.quality)
|
|
408
502
|
width, height = imageopts.dimensions(options.size, megapixels)
|
|
409
|
-
text = imageopts.styled(prompt, options.style)
|
|
503
|
+
text = imageopts.styled(expanded or prompt, options.style)
|
|
410
504
|
values = {**workflow.defaults, **files, "prompt": text, "seed": seed, "width": width, "height": height}
|
|
411
505
|
if steps:
|
|
412
506
|
values["steps"] = steps
|
|
@@ -452,7 +546,8 @@ def edit_image(
|
|
|
452
546
|
keep_shape = bool(job.get("keep_shape", True) or job.get("mask") or pads)
|
|
453
547
|
ratio = f"{first_w}x{first_h}" if keep_shape else options.size
|
|
454
548
|
width, height = shape(ratio, megapixels)
|
|
455
|
-
instruction = job
|
|
549
|
+
instruction = job.get("expanded") or job["prompt"]
|
|
550
|
+
instruction = instruction if not pads else f"{edits.EXTEND_HINT} {job['prompt']}".strip()
|
|
456
551
|
text = imageopts.styled(instruction, options.style)
|
|
457
552
|
values = {**workflow.defaults, **files, "prompt": text, "seed": seed, "width": width, "height": height}
|
|
458
553
|
if steps:
|
|
@@ -533,7 +628,7 @@ def generate_video(
|
|
|
533
628
|
fps = int(info["fps"] or fps)
|
|
534
629
|
options = replace(options, seconds=min(options.seconds if job.get("seconds_given") else 99,
|
|
535
630
|
(min(info["frames"] or 81, 81) - 1) / fps)) # fmt: skip
|
|
536
|
-
text = imageopts.styled(prompt, options.style)
|
|
631
|
+
text = imageopts.styled(job.get("expanded") or prompt, options.style)
|
|
537
632
|
values = {**workflow.defaults, **files, "prompt": text, "seed": seed, "width": width, "height": height,
|
|
538
633
|
"length": imageopts.frames(options.seconds, fps), "fps": fps} # fmt: skip
|
|
539
634
|
if steps:
|
lcode/repl.py
CHANGED
|
@@ -94,6 +94,7 @@ COMMANDS = {
|
|
|
94
94
|
"/sound": "Video mode: add sound to a clip, e.g. /sound 4 waves and seagulls",
|
|
95
95
|
"/restyle": "Video mode: the same clip in a new look, e.g. /restyle 4 as a watercolor painting",
|
|
96
96
|
"/play": "Play a video in your player, e.g. /play 4 (default: the last)",
|
|
97
|
+
"/film": "A short film from an idea: /film a fox finds a lost kitten --shots 3 (plan, make, shot N, stitch, list)",
|
|
97
98
|
"/cd": "Change the working directory",
|
|
98
99
|
"/todos": "Show the current todo list",
|
|
99
100
|
"/status": "The task sheet: your requests, the plan and notes, files changed, the last check",
|
|
@@ -1198,6 +1199,8 @@ def handle_command(agent: Agent, line: str, hardware: Hardware) -> bool:
|
|
|
1198
1199
|
mode_command(agent, arg.strip().lower())
|
|
1199
1200
|
elif cmd in IMAGE_COMMANDS:
|
|
1200
1201
|
image_command(agent, cmd, arg)
|
|
1202
|
+
elif cmd == "/film":
|
|
1203
|
+
film_command(agent, arg)
|
|
1201
1204
|
elif cmd == "/permissions":
|
|
1202
1205
|
if arg in PERMISSION_MODES:
|
|
1203
1206
|
agent.perms.mode = arg
|
|
@@ -1583,6 +1586,70 @@ def use_references(agent: Agent, arg: str) -> None:
|
|
|
1583
1586
|
c.print(f"References for the next requests: [bold]{escape(shown)}[/] [dim](/use off stops)[/]")
|
|
1584
1587
|
|
|
1585
1588
|
|
|
1589
|
+
FILM_FLAGS = re.compile(r'--(shots|seconds|quality|transition|sound)\s+("[^"]*"|\S+)')
|
|
1590
|
+
|
|
1591
|
+
|
|
1592
|
+
def film_command(agent: Agent, arg: str) -> None:
|
|
1593
|
+
"""/film: a storyboard from an idea, the film made from it, a shot made again, the shots joined again."""
|
|
1594
|
+
from lcode import film
|
|
1595
|
+
|
|
1596
|
+
c = agent.console
|
|
1597
|
+
flags = {k: v.strip('"') for k, v in FILM_FLAGS.findall(arg)}
|
|
1598
|
+
text = " ".join(FILM_FLAGS.sub(" ", arg).split())
|
|
1599
|
+
word, _, rest = text.partition(" ")
|
|
1600
|
+
try:
|
|
1601
|
+
if word == "list":
|
|
1602
|
+
folders = sorted(p for p in film.films_folder(agent).glob("*") if (p / "storyboard.json").exists())
|
|
1603
|
+
if not folders:
|
|
1604
|
+
c.print("[dim]No films here yet: /film <your idea>[/]")
|
|
1605
|
+
for folder in folders:
|
|
1606
|
+
board = film.load(folder)
|
|
1607
|
+
made = "made" if (folder / "film.mp4").exists() else "storyboard only"
|
|
1608
|
+
about = f"{len(board.shots)} shots · {made}"
|
|
1609
|
+
c.print(f" [bold]{escape(folder.name)}[/] {escape(board.title)} [dim]· {about}[/]")
|
|
1610
|
+
return
|
|
1611
|
+
if word in ("make", "stitch", "shot", "show"):
|
|
1612
|
+
if word == "shot":
|
|
1613
|
+
numbers_text, _, name = rest.partition(" ")
|
|
1614
|
+
folder = film.find(agent, name.strip())
|
|
1615
|
+
else:
|
|
1616
|
+
folder = film.find(agent, rest.strip())
|
|
1617
|
+
board = film.with_options(film.load(folder), flags.get("transition", ""), flags.get("sound", ""),
|
|
1618
|
+
flags.get("quality", "")) # fmt: skip
|
|
1619
|
+
if word == "show":
|
|
1620
|
+
c.print(escape(film.describe(board, folder, agent)))
|
|
1621
|
+
return
|
|
1622
|
+
film.save(board, folder)
|
|
1623
|
+
if word == "stitch":
|
|
1624
|
+
film.stitch(agent, board, folder)
|
|
1625
|
+
return
|
|
1626
|
+
only = film.shot_numbers(numbers_text, len(board.shots)) if word == "shot" else None
|
|
1627
|
+
make_image(agent, run=lambda cancel, ask: film.make(agent, board, folder, only, cancel, ask))
|
|
1628
|
+
return
|
|
1629
|
+
just_plan = word == "plan"
|
|
1630
|
+
idea = rest if just_plan else text
|
|
1631
|
+
if not idea.strip():
|
|
1632
|
+
c.print("[yellow]Say what the film is about: /film a fox finds a lost kitten in the snow --shots 3[/]")
|
|
1633
|
+
return
|
|
1634
|
+
shots = int(flags.get("shots", "3"))
|
|
1635
|
+
if not 1 <= shots <= film.MAX_SHOTS:
|
|
1636
|
+
c.print(f"[yellow]A film has 1 to {film.MAX_SHOTS} shots.[/]")
|
|
1637
|
+
return
|
|
1638
|
+
seconds = float(flags.get("seconds", "4"))
|
|
1639
|
+
board, folder = film.plan(agent, idea, shots, min(max(seconds, 1.0), 8.0))
|
|
1640
|
+
board = film.with_options(board, flags.get("transition", ""), flags.get("sound", ""), flags.get("quality", ""))
|
|
1641
|
+
film.save(board, folder)
|
|
1642
|
+
c.print(escape(film.describe(board, folder, agent)))
|
|
1643
|
+
if just_plan:
|
|
1644
|
+
c.print(
|
|
1645
|
+
f"[dim]Edit {escape(media.shown(agent, folder / 'storyboard.json'))} if you like, then /film make.[/]"
|
|
1646
|
+
)
|
|
1647
|
+
return
|
|
1648
|
+
make_image(agent, run=lambda cancel, ask: film.make(agent, board, folder, None, cancel, ask))
|
|
1649
|
+
except (film.FilmError, ValueError) as e:
|
|
1650
|
+
c.print(f"[yellow]{escape(str(e))}[/]")
|
|
1651
|
+
|
|
1652
|
+
|
|
1586
1653
|
def gallery(agent: Agent, everything: bool = False) -> None:
|
|
1587
1654
|
"""The session's images (or every image in the media folder), with what made them."""
|
|
1588
1655
|
import json as json_module
|
|
@@ -1,6 +1,6 @@
|
|
|
1
1
|
Metadata-Version: 2.5
|
|
2
2
|
Name: lcode-cli
|
|
3
|
-
Version: 0.
|
|
3
|
+
Version: 0.48.0
|
|
4
4
|
Summary: A local-first terminal coding agent powered by open-weight models on your own GPU or Mac, via Ollama.
|
|
5
5
|
Project-URL: Homepage, https://nasser1941.github.io/lcode/
|
|
6
6
|
Project-URL: Documentation, https://nasser1941.github.io/lcode/
|
|
@@ -1,9 +1,10 @@
|
|
|
1
|
-
lcode/__init__.py,sha256=
|
|
1
|
+
lcode/__init__.py,sha256=LiyarI3HWyGeHECknUw5S4wvds02vAJzv6Eh0hcg3vI,473
|
|
2
2
|
lcode/__main__.py,sha256=s5N5pryX2FAu93GGZ3FxUrIXHWGzxz66lKUoaV_h8Ws,35
|
|
3
3
|
lcode/acp.py,sha256=d97VV3sbqXdWKhPQQNbYRaDTm8WrUk0mGbDLiOyX7jE,29058
|
|
4
4
|
lcode/action.py,sha256=wuT5F9EJCdEligPeytzmEi8FpahWBhXer528tpuTj_k,16711
|
|
5
|
-
lcode/agent.py,sha256=
|
|
6
|
-
lcode/api.py,sha256=
|
|
5
|
+
lcode/agent.py,sha256=FbDhUhkUa5WfWQDk6DKcY4InNYOKV2kYEAkHfePJH0Q,89164
|
|
6
|
+
lcode/api.py,sha256=R6vwHhZcWqKNf_ygOfij6Il9hpjVJvClVBmxzaKA434,17798
|
|
7
|
+
lcode/assistant.py,sha256=BXdg3pAM6NVNNYVmht6oqVLfihaLVf87A6gcoZqXv34,7769
|
|
7
8
|
lcode/backends.py,sha256=343alwyDZin-bEhb5-Es4f8ek1oBQUzEvV6RFWR1VZo,21160
|
|
8
9
|
lcode/bench.py,sha256=HxeUfy9Kv_0Rug1HAlDLyHYfYd9dw2bMgbXsvUy9nd4,43096
|
|
9
10
|
lcode/bench_backend.py,sha256=X2fo-zRX92Xp3KMxSsFlWioc2vRupBTtowj5kLME8mw,14287
|
|
@@ -16,11 +17,12 @@ lcode/clipboard.py,sha256=nTSdJyCXPdtjH947RjvB3QvRqnL5HZsS9KB8EkC42cc,5138
|
|
|
16
17
|
lcode/cloud.py,sha256=q5Dl5GuqWvKzBCIso-eh6yomvEOsnQ0LW8ZgaAGwBxc,2131
|
|
17
18
|
lcode/codesearch.py,sha256=Io8leN1nb_Y-Dvlm9xaGtwUWYXX-ooswuznJV6dGU1s,10766
|
|
18
19
|
lcode/comfy.py,sha256=_pbLVQS_1clsa7awPrxQ7xIOwp5XzyMHPDAagomEswc,26614
|
|
19
|
-
lcode/config.py,sha256=
|
|
20
|
+
lcode/config.py,sha256=wUiyshqnD9o7YyMmD0iEM4LLRsOCtvHN0QZLQtkU9vs,14203
|
|
20
21
|
lcode/context.py,sha256=wgK16ZcNNnq4ngHx0EmtyKHDFTImciGEmtC5NP8tKJQ,20435
|
|
21
22
|
lcode/edits.py,sha256=iYXSbKv4ZfxP12B1ov6-CLEWvR_tWFUdHRQbER3O8d0,13340
|
|
22
23
|
lcode/escalate.py,sha256=f-_6_moPaHi2kLuJw2JtkzvTkCl6DoBQgYBOCYLhunM,15120
|
|
23
24
|
lcode/extensions.py,sha256=W0HFDl0BvROzr7i_qtabHdIbacBgP5o5qIJLzoM2oNE,16806
|
|
25
|
+
lcode/film.py,sha256=LJs0vRCFozEx2ZCEJE-bJtvbIbvJ6iOPEE6rlUxPXko,14197
|
|
24
26
|
lcode/frontmatter.py,sha256=Bx0n4vLPhp7ZCWx-g7xqzqNy5VoKBxyeeikh5UFB_gA,2441
|
|
25
27
|
lcode/gitflow.py,sha256=6j_nnCBZXkX1qhTI7K4CyZ5D0NAZLpH96weFEo64AkQ,27913
|
|
26
28
|
lcode/hardware.py,sha256=2VbknZCxTZJwJUD8YWdQ7ryEQo_LcjtoOBOHOU9Y0fw,3085
|
|
@@ -30,7 +32,7 @@ lcode/jobs.py,sha256=P1P3FqI6EqL4LgdMX9YGZwCW0Bh5BRXFA_FnQxpHNjE,5618
|
|
|
30
32
|
lcode/limits.py,sha256=oJzVQoMyTZ0_Fkpu5t3qxrf9v7Hv9S8U8BRQR5M1aKA,1237
|
|
31
33
|
lcode/lsp.py,sha256=NtSW7xapv7fg2HAQLuYK1nwIqT7nG0LK1hiTpOmla_4,26086
|
|
32
34
|
lcode/matching.py,sha256=2N3_qwKJ5gd8el2m_y_egKkFM9rsF1eUhYJcRCVIp98,14015
|
|
33
|
-
lcode/media.py,sha256=
|
|
35
|
+
lcode/media.py,sha256=LvALoDc956plrKTMGeDNnWoiT18NeoPoHgdv_psHDBA,47853
|
|
34
36
|
lcode/media.toml,sha256=fzBbk4NigNzZnBzRkuQxFLtdVmuXPHM0KkxknOUxaKA,10022
|
|
35
37
|
lcode/media_catalog.py,sha256=nYgJtgWmVwtgV_rBA2rWC21HBM9yYL70DrTkkRrhqDg,14754
|
|
36
38
|
lcode/memory.py,sha256=WZEHTp-lVxAwS-yyLQR2xB3TMZ9sejmX2Ivg7T-tl3w,21949
|
|
@@ -43,7 +45,7 @@ lcode/planning.py,sha256=Q2upaoZPnXDMQT2F-ETxX1lk_wDntTzhSKNVYIQSoQA,6540
|
|
|
43
45
|
lcode/preview.py,sha256=ATzEs6yaI1__bfo2_juWznrTDXUD4QTc_aQMPRCytgA,6253
|
|
44
46
|
lcode/render.py,sha256=gMvf4W3qkLUJ4Vot3az_hP_zRDAItJC9pP-68dHFkfA,1375
|
|
45
47
|
lcode/repeats.py,sha256=OTrPdb6BKArDLQEgHaXmJZ-tIFsY_1bk4P0wzzANKLY,5964
|
|
46
|
-
lcode/repl.py,sha256=
|
|
48
|
+
lcode/repl.py,sha256=rmiONSTEaB5V9WrFqLxQz1NWCpyuv-sAXNcdUxdsZGw,79090
|
|
47
49
|
lcode/repomap.py,sha256=1GRJgEUjBl9XHSXsF7tSGXBCEgsY-3CzwMohaTudZ_M,13969
|
|
48
50
|
lcode/residency.py,sha256=B9pwqG6yx5aQD2M5xyQ-bMnYmhD7fv3wCVw_X6VIeAo,7012
|
|
49
51
|
lcode/review.py,sha256=0QBIS-R1B2b3zqx5TcC1qZptpKBbrDhYvMKSNCaDAUo,4686
|
|
@@ -86,8 +88,8 @@ lcode/workflows/wan21-vace.json,sha256=vJsiRvLCXCjKIibOO0SGM3fT6bedAGxF8N2sN2vcP
|
|
|
86
88
|
lcode/workflows/wan22-fun-inp-5b.json,sha256=4HbKEezik8MHvxTMP6PjQUPQPfCeSu10U9FrC-DHKYw,3327
|
|
87
89
|
lcode/workflows/wan22-ti2v-5b.json,sha256=RcTehoC2pNizzlb7Ed3keJ56DiE7V5lhXmsvR2Y0smQ,3371
|
|
88
90
|
lcode/workflows/z-image-turbo-t2i.json,sha256=sHsL7xnnuULOuWGYlQrDl4jOTySdAmb2T82c_cChv0s,1585
|
|
89
|
-
lcode_cli-0.
|
|
90
|
-
lcode_cli-0.
|
|
91
|
-
lcode_cli-0.
|
|
92
|
-
lcode_cli-0.
|
|
93
|
-
lcode_cli-0.
|
|
91
|
+
lcode_cli-0.48.0.dist-info/METADATA,sha256=eVNF2au-B6fcqb3MoXTTymle8LALCtEKCyfhJEBF5E8,13469
|
|
92
|
+
lcode_cli-0.48.0.dist-info/WHEEL,sha256=W3fkpkm7-wf9vBI5Z-7s0eWkeM-spu78I8Neb98DeEg,87
|
|
93
|
+
lcode_cli-0.48.0.dist-info/entry_points.txt,sha256=Hxsn_itbnbgft3U0FwxWdmEt0yoAV2LB-nJDnL9WT20,172
|
|
94
|
+
lcode_cli-0.48.0.dist-info/licenses/LICENSE,sha256=JWjmoL7nNIC1XUa-dZm2hwLUgjUQMFo6k8APb0idNzs,1074
|
|
95
|
+
lcode_cli-0.48.0.dist-info/RECORD,,
|
|
File without changes
|
|
File without changes
|
|
File without changes
|