lcode-cli 0.48.0__py3-none-any.whl → 0.49.1__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 +11 -5
- lcode/hardware.py +49 -0
- lcode/media.py +116 -23
- 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 +7 -0
- lcode/residency.py +33 -0
- {lcode_cli-0.48.0.dist-info → lcode_cli-0.49.1.dist-info}/METADATA +7 -5
- {lcode_cli-0.48.0.dist-info → lcode_cli-0.49.1.dist-info}/RECORD +17 -16
- {lcode_cli-0.48.0.dist-info → lcode_cli-0.49.1.dist-info}/WHEEL +0 -0
- {lcode_cli-0.48.0.dist-info → lcode_cli-0.49.1.dist-info}/entry_points.txt +0 -0
- {lcode_cli-0.48.0.dist-info → lcode_cli-0.49.1.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
CHANGED
|
@@ -1,8 +1,9 @@
|
|
|
1
1
|
"""Films: from one description to a short film with the same characters in every shot.
|
|
2
2
|
|
|
3
3
|
1. **A storyboard.** The prompt assistant (lcode.assistant) writes it: a title, the look of the whole film, the cast
|
|
4
|
-
(each character
|
|
5
|
-
saved as `storyboard.json` in the film's folder, so it can be
|
|
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.
|
|
6
7
|
2. **The cast.** Each character gets a reference picture (FLUX.2 klein), made once and kept in `cast/`.
|
|
7
8
|
3. **The shots.** Each shot starts as a keyframe: a picture of the shot made with the cast's pictures as references,
|
|
8
9
|
so the characters look the same from shot to shot. Video mode's model then animates the keyframe.
|
|
@@ -37,8 +38,10 @@ STORYBOARD = (
|
|
|
37
38
|
'"what happens in this shot, where, and who is in it, in one or two sentences, using the cast names", "camera": '
|
|
38
39
|
'"a shot type and camera move, like slow zoom in, tracking shot, static wide shot", "cast": ["names in this '
|
|
39
40
|
'shot"], "seconds": {seconds}}}]}}\n'
|
|
40
|
-
"
|
|
41
|
-
"
|
|
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."
|
|
42
45
|
)
|
|
43
46
|
TRANSITIONS = ("cut", "fade")
|
|
44
47
|
FADE = 0.5 # seconds a fade takes
|
|
@@ -203,7 +206,10 @@ def make(
|
|
|
203
206
|
if picture.exists():
|
|
204
207
|
continue
|
|
205
208
|
say(f"Cast: {name}")
|
|
206
|
-
prompt =
|
|
209
|
+
prompt = (
|
|
210
|
+
f"{board.look} Character reference of {name}, alone: {desc}. Full body, facing the camera, plain "
|
|
211
|
+
"background."
|
|
212
|
+
)
|
|
207
213
|
made = with_mode(agent, "image", lambda p=prompt: media.generate_image(
|
|
208
214
|
agent, p, cancelled, ask, imageopts.Options(size="3:4", quality=board.quality))) # fmt: skip
|
|
209
215
|
keep(made.files[0], picture)
|
lcode/hardware.py
CHANGED
|
@@ -5,6 +5,7 @@ from __future__ import annotations
|
|
|
5
5
|
import platform
|
|
6
6
|
import subprocess
|
|
7
7
|
from dataclasses import dataclass
|
|
8
|
+
from pathlib import Path
|
|
8
9
|
|
|
9
10
|
GIB = 1024**3
|
|
10
11
|
|
|
@@ -46,6 +47,54 @@ def _run(cmd: list[str]) -> str:
|
|
|
46
47
|
return ""
|
|
47
48
|
|
|
48
49
|
|
|
50
|
+
def gpu_used_gib() -> float | None:
|
|
51
|
+
"""GPU memory in use on the NVIDIA GPUs, in GiB; None without nvidia-smi."""
|
|
52
|
+
out = _run(["nvidia-smi", "--query-gpu=memory.used", "--format=csv,noheader,nounits"])
|
|
53
|
+
try:
|
|
54
|
+
return sum(float(v) for v in out.split()) / 1024 if out else None
|
|
55
|
+
except ValueError:
|
|
56
|
+
return None
|
|
57
|
+
|
|
58
|
+
|
|
59
|
+
def gpu_users() -> list[tuple[str, float]]:
|
|
60
|
+
"""The programs holding NVIDIA GPU memory, largest first: (a short name, GiB). Empty without nvidia-smi."""
|
|
61
|
+
out = _run(["nvidia-smi", "--query-compute-apps=pid,process_name,used_memory", "--format=csv,noheader,nounits"])
|
|
62
|
+
users: dict[str, float] = {}
|
|
63
|
+
for line in out.splitlines():
|
|
64
|
+
parts = [p.strip() for p in line.split(",")]
|
|
65
|
+
if len(parts) != 3:
|
|
66
|
+
continue
|
|
67
|
+
try:
|
|
68
|
+
gib = float(parts[2]) / 1024
|
|
69
|
+
except ValueError:
|
|
70
|
+
continue
|
|
71
|
+
name = program_name(parts[0], parts[1])
|
|
72
|
+
users[name] = users.get(name, 0.0) + gib
|
|
73
|
+
return sorted(users.items(), key=lambda item: -item[1])
|
|
74
|
+
|
|
75
|
+
|
|
76
|
+
def program_name(pid: str, process: str) -> str:
|
|
77
|
+
"""A GPU program's short name, from its command line (/proc) or else nvidia-smi's process name."""
|
|
78
|
+
try:
|
|
79
|
+
argv = [a.decode(errors="replace") for a in Path(f"/proc/{pid}/cmdline").read_bytes().split(b"\0") if a]
|
|
80
|
+
except OSError:
|
|
81
|
+
argv = []
|
|
82
|
+
return name_from(argv or [process], process)
|
|
83
|
+
|
|
84
|
+
|
|
85
|
+
def name_from(argv: list[str], process: str = "") -> str:
|
|
86
|
+
"""'render.py' for `python3 render.py`, 'ComfyUI' for its main.py, 'Ollama', else the program."""
|
|
87
|
+
program = Path(argv[0]).name if argv else process
|
|
88
|
+
if program.startswith("python") and len(argv) > 1:
|
|
89
|
+
script = next((a for a in argv[1:] if not a.startswith("-")), argv[1])
|
|
90
|
+
if Path(script).name == "main.py" and "comfyui" in " ".join(argv[:2]).lower():
|
|
91
|
+
return "ComfyUI"
|
|
92
|
+
return Path(script).name
|
|
93
|
+
if program in ("llama-server", "ollama") or "/ollama/" in (argv[0] if argv else ""):
|
|
94
|
+
return "Ollama"
|
|
95
|
+
return program or process
|
|
96
|
+
|
|
97
|
+
|
|
49
98
|
def _linux_ram_gib() -> float:
|
|
50
99
|
try:
|
|
51
100
|
with open("/proc/meminfo") as f:
|
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,13 +23,18 @@ 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, hardware, imageopts, media_cloud, preview, residency
|
|
27
27
|
from lcode import media_catalog as catalog
|
|
28
28
|
|
|
29
29
|
if TYPE_CHECKING:
|
|
30
30
|
from lcode.agent import Agent
|
|
31
31
|
|
|
32
32
|
SOON: dict[str, str] = {}
|
|
33
|
+
LOAD_WAIT = 180 # seconds to wait for the coding model to finish loading before a job (it then unloads itself)
|
|
34
|
+
MIN_FREE_GB = 1.0 # disk space a job needs, where its results are saved
|
|
35
|
+
# how PyTorch and ComfyUI say the GPU is full
|
|
36
|
+
OUT_OF_MEMORY = ("out of memory", "outofmemory", "vram grow failed", "would exceed allowed memory",
|
|
37
|
+
"cudaerrormemoryallocation", "alloc_failed") # fmt: skip
|
|
33
38
|
IGNORED = "# lcode's images and videos: not part of the project unless you add them\n*\n"
|
|
34
39
|
|
|
35
40
|
|
|
@@ -112,6 +117,8 @@ def offer_install(agent: Agent, server: comfy.Server, ask: Callable[[str], bool]
|
|
|
112
117
|
|
|
113
118
|
def warm(agent: Agent) -> str | None:
|
|
114
119
|
"""Start ComfyUI in the background on entering image or video mode, so the first request waits less."""
|
|
120
|
+
if current(agent).cloud:
|
|
121
|
+
return None # it runs at its provider; ComfyUI starts when a local model is needed
|
|
115
122
|
if agent.comfy_process is not None and agent.comfy_process.poll() is None:
|
|
116
123
|
return None
|
|
117
124
|
if comfy.Server(agent.settings.comfyui_url).stats():
|
|
@@ -133,20 +140,24 @@ def stop_engine(agent: Agent) -> bool:
|
|
|
133
140
|
|
|
134
141
|
|
|
135
142
|
def free_gpu(agent: Agent) -> None:
|
|
136
|
-
"""Unload lcode's coding model if Ollama still has it: the image or video
|
|
143
|
+
"""Unload lcode's coding model if Ollama still has it, and wait until its GPU memory is free: the image or video
|
|
144
|
+
model needs the GPU, and a job sent while Ollama is still letting go of it runs out of memory."""
|
|
137
145
|
if getattr(agent.ollama, "kind", "ollama") != "ollama":
|
|
138
146
|
return
|
|
147
|
+
if agent.load_state == "loading": # started in code mode: the load gives the GPU back when it's done
|
|
148
|
+
with agent.console.status(f"Waiting for {agent.settings.model} to finish loading, to unload it…"):
|
|
149
|
+
deadline = time.monotonic() + LOAD_WAIT
|
|
150
|
+
while agent.load_state == "loading" and time.monotonic() < deadline:
|
|
151
|
+
time.sleep(0.2)
|
|
139
152
|
try:
|
|
140
|
-
|
|
153
|
+
if not residency.placement(agent.ollama, agent.settings.model):
|
|
154
|
+
return
|
|
155
|
+
with agent.console.status(f"Unloading {agent.settings.model} to free the GPU…"):
|
|
156
|
+
freed = residency.release(agent.ollama, agent.settings.model)
|
|
141
157
|
except Exception:
|
|
142
158
|
return
|
|
143
|
-
|
|
144
|
-
|
|
145
|
-
try:
|
|
146
|
-
agent.ollama.unload(model)
|
|
147
|
-
agent.say(f"Unloaded {model} to free the GPU.")
|
|
148
|
-
except Exception:
|
|
149
|
-
pass
|
|
159
|
+
if freed:
|
|
160
|
+
agent.say(f"Unloaded {agent.settings.model} to free the GPU.")
|
|
150
161
|
|
|
151
162
|
|
|
152
163
|
# ----------------------------------------------------------------------------- where the files go
|
|
@@ -335,6 +346,12 @@ def redo(
|
|
|
335
346
|
agent.last_request = job
|
|
336
347
|
if not job.get("raw") and job["kind"] in ("image", "edit", "video") and not job.get("pads"):
|
|
337
348
|
job = {**job, "expanded": expand(agent, job)}
|
|
349
|
+
if model.cloud and not media_cloud.cannot(model, job): # at its provider: all of them, asked once
|
|
350
|
+
made = media_cloud.make(agent, model, job, options, cancelled, ask)
|
|
351
|
+
if job["kind"] in ("image", "edit"):
|
|
352
|
+
for one in made:
|
|
353
|
+
check_result(agent, one, prompt)
|
|
354
|
+
return made
|
|
338
355
|
made = []
|
|
339
356
|
for i in range(options.n):
|
|
340
357
|
seed = None if options.seed is None else options.seed + i
|
|
@@ -493,8 +510,11 @@ def generate_image(
|
|
|
493
510
|
if not prompt:
|
|
494
511
|
raise MediaError("Describe the image you want.")
|
|
495
512
|
options = options or imageopts.Options()
|
|
496
|
-
server = prepare(agent, ask, cancelled)
|
|
497
513
|
model = current(agent, "image")
|
|
514
|
+
if model.cloud:
|
|
515
|
+
job = {"kind": "image", "prompt": prompt, "expanded": expanded, "sources": []}
|
|
516
|
+
return media_cloud.make(agent, model, job, replace(options, n=1), cancelled, ask)[0]
|
|
517
|
+
server = prepare(agent, ask, cancelled)
|
|
498
518
|
files = ensure_installed(agent, model, server, ask)
|
|
499
519
|
workflow = comfy.load_workflow(model.workflow)
|
|
500
520
|
seed = options.seed if options.seed is not None else random.randrange(2**32)
|
|
@@ -522,13 +542,17 @@ def edit_image(
|
|
|
522
542
|
) -> Made:
|
|
523
543
|
"""An edit of the job's source images: by instruction, through a mask (inpainting), or on a bigger canvas
|
|
524
544
|
(outpainting). The first source sets the shape unless the request gave one."""
|
|
525
|
-
server = prepare(agent, ask, cancelled)
|
|
526
545
|
chosen = current(agent, "image")
|
|
546
|
+
why = media_cloud.cannot(chosen, {**job, "kind": "edit"}) if chosen.cloud else ""
|
|
547
|
+
if chosen.cloud and not why: # films call this directly
|
|
548
|
+
return media_cloud.make(agent, chosen, {**job, "kind": "edit"}, replace(options, n=1), cancelled, ask)[0]
|
|
549
|
+
server = prepare(agent, ask, cancelled)
|
|
527
550
|
model = catalog.load().editor(chosen)
|
|
528
551
|
if model is None:
|
|
529
552
|
raise MediaError("None of lcode's image models edits pictures yet.")
|
|
530
553
|
if model.key != chosen.key:
|
|
531
|
-
|
|
554
|
+
reason = f"doesn't do {why} here" if why else "doesn't edit pictures"
|
|
555
|
+
agent.say(f"{chosen.name} {reason}: {model.name} makes this one{' on your GPU' if chosen.cloud else ''}.")
|
|
532
556
|
files = ensure_installed(agent, model, server, ask)
|
|
533
557
|
workflow = comfy.load_workflow(model.workflow)
|
|
534
558
|
sources = [Path(p) for p in job["sources"]]
|
|
@@ -600,7 +624,7 @@ def generate_video(
|
|
|
600
624
|
restyle = Path(job["restyle"]) if job.get("restyle") else None
|
|
601
625
|
task = (
|
|
602
626
|
"restyle" if restyle else "references" if refs else "first-last-frame" if end
|
|
603
|
-
else "camera" if options.camera else "
|
|
627
|
+
else "camera" if options.camera else "extend" if clip else ""
|
|
604
628
|
) # fmt: skip
|
|
605
629
|
model = video_model(agent, task)
|
|
606
630
|
files = ensure_installed(agent, model, server, ask)
|
|
@@ -678,7 +702,7 @@ VIDEO_LATENTS = ("Wan22ImageToVideoLatent", "WanFunInpaintToVideo", "WanCameraIm
|
|
|
678
702
|
WHY = {
|
|
679
703
|
"first-last-frame": "a clip between two frames",
|
|
680
704
|
"camera": "a camera move",
|
|
681
|
-
"
|
|
705
|
+
"extend": "extending a clip",
|
|
682
706
|
"references": "following reference pictures",
|
|
683
707
|
"restyle": "restyling a clip",
|
|
684
708
|
}
|
|
@@ -722,14 +746,15 @@ def control_from(graph: dict, clip_name: str, length: int) -> list:
|
|
|
722
746
|
|
|
723
747
|
|
|
724
748
|
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."""
|
|
749
|
+
"""The video model for a job: the chosen one, or the first local one that does what the job needs."""
|
|
726
750
|
chosen = current(agent, "video")
|
|
727
|
-
if not task or task in chosen.tasks:
|
|
751
|
+
if not chosen.cloud and (not task or task in chosen.tasks):
|
|
728
752
|
return chosen
|
|
729
|
-
model = catalog.load().for_task("video", task)
|
|
753
|
+
model = catalog.load().for_task("video", task or "text-to-video")
|
|
730
754
|
if model is None:
|
|
731
755
|
raise MediaError(f"None of lcode's video models does {WHY.get(task, task)} yet.")
|
|
732
|
-
|
|
756
|
+
where = f"; {chosen.name} doesn't do that here" if chosen.cloud else ""
|
|
757
|
+
agent.say(f"{model.name} makes this one ({WHY.get(task, task)}{where}).")
|
|
733
758
|
return model
|
|
734
759
|
|
|
735
760
|
|
|
@@ -786,6 +811,24 @@ def mp4_seconds(path: Path) -> float:
|
|
|
786
811
|
return duration / scale if scale else 0.0
|
|
787
812
|
|
|
788
813
|
|
|
814
|
+
def mp4_size(path: Path) -> tuple[int, int]:
|
|
815
|
+
"""An MP4's picture size from its first video track header (tkhd), or (0, 0)."""
|
|
816
|
+
try:
|
|
817
|
+
data = path.read_bytes()[: 1 << 22]
|
|
818
|
+
except OSError:
|
|
819
|
+
return 0, 0
|
|
820
|
+
i = data.find(b"tkhd")
|
|
821
|
+
while i >= 4:
|
|
822
|
+
size = 8 + (96 if data[i + 4 : i + 5] == b"\x01" else 84) # the box, with its size and type
|
|
823
|
+
end = i - 4 + size # width and height end it, as 16.16 fixed-point numbers
|
|
824
|
+
if struct.unpack(">I", data[i - 4 : i])[0] == size and end <= len(data):
|
|
825
|
+
width, height = struct.unpack(">II", data[end - 8 : end])
|
|
826
|
+
if width and height:
|
|
827
|
+
return width >> 16, height >> 16
|
|
828
|
+
i = data.find(b"tkhd", i + 4)
|
|
829
|
+
return 0, 0
|
|
830
|
+
|
|
831
|
+
|
|
789
832
|
def apply_tool(
|
|
790
833
|
agent: Agent,
|
|
791
834
|
task: str,
|
|
@@ -892,8 +935,9 @@ def describe_job(model, workflow, prompt, text, seed, values, options, files) ->
|
|
|
892
935
|
|
|
893
936
|
def run_plan(agent: Agent, server: comfy.Server, plan: Plan, cancelled, label: str) -> Made:
|
|
894
937
|
"""Queue the plan, follow it, save what it made, number it, show it."""
|
|
895
|
-
free_gpu(agent)
|
|
896
938
|
out = folder(agent)
|
|
939
|
+
check_disk(agent, out)
|
|
940
|
+
free_gpu(agent)
|
|
897
941
|
stem = plan.stem or f"{time.strftime('%Y%m%d-%H%M%S')}-{comfy.slug(plan.prompt)}"
|
|
898
942
|
hint = "Esc or Ctrl+C cancels" if agent.interactive else ""
|
|
899
943
|
line = Line(f"{plan.model.name} ({label})" if label else plan.model.name, hint)
|
|
@@ -924,7 +968,7 @@ def run_plan(agent: Agent, server: comfy.Server, plan: Plan, cancelled, label: s
|
|
|
924
968
|
except comfy.ComfyError as e:
|
|
925
969
|
if job["id"]:
|
|
926
970
|
comfy.forget(job["id"])
|
|
927
|
-
raise MediaError(str(e)) from e
|
|
971
|
+
raise MediaError(explain(agent, str(e))) from e
|
|
928
972
|
try:
|
|
929
973
|
saved = comfy.save(server, outputs, out, stem, {**plan.meta, "comfyui_prompt_id": prompt_id})
|
|
930
974
|
except (comfy.ComfyError, OSError) as e:
|
|
@@ -947,6 +991,55 @@ def run_plan(agent: Agent, server: comfy.Server, plan: Plan, cancelled, label: s
|
|
|
947
991
|
return made
|
|
948
992
|
|
|
949
993
|
|
|
994
|
+
def check_disk(agent: Agent, out: Path) -> None:
|
|
995
|
+
"""Refuse a job when the disk it saves to is nearly full: ComfyUI fails at the end of it otherwise."""
|
|
996
|
+
places = [out]
|
|
997
|
+
install = comfy.find_install(agent.settings.comfyui_path) if agent.comfy_process is not None else None
|
|
998
|
+
if install is not None:
|
|
999
|
+
places.append(install.path) # ComfyUI writes there first
|
|
1000
|
+
for place in places:
|
|
1001
|
+
try:
|
|
1002
|
+
free = shutil.disk_usage(place).free / 1e9
|
|
1003
|
+
except OSError:
|
|
1004
|
+
continue
|
|
1005
|
+
if free < MIN_FREE_GB:
|
|
1006
|
+
raise MediaError(
|
|
1007
|
+
f"The disk is nearly full ({free:.1f} GB free at {place}): images and videos need room. Free some "
|
|
1008
|
+
"space, then try again."
|
|
1009
|
+
)
|
|
1010
|
+
|
|
1011
|
+
|
|
1012
|
+
def explain(agent: Agent, error: str) -> str:
|
|
1013
|
+
"""ComfyUI's error, said so it can be acted on: running out of GPU memory or disk space, or a crash."""
|
|
1014
|
+
low = error.lower()
|
|
1015
|
+
if any(words in low for words in OUT_OF_MEMORY):
|
|
1016
|
+
step = error.split(" failed:", 1)[0] if " failed:" in error else "a step"
|
|
1017
|
+
others = [(name, gib) for name, gib in hardware.gpu_users() if name != "ComfyUI" and gib >= 0.1]
|
|
1018
|
+
held = ", ".join(f"{name} ({gib:.1f} GB)" for name, gib in others)
|
|
1019
|
+
message = f"The GPU ran out of memory ({step})."
|
|
1020
|
+
if held:
|
|
1021
|
+
message += f" Other programs hold GPU memory: {held}. Close what you can, or try"
|
|
1022
|
+
else:
|
|
1023
|
+
message += " Try"
|
|
1024
|
+
message += " --quality fast or a smaller model (/models)."
|
|
1025
|
+
if stop_engine(agent): # after running out of memory ComfyUI can crash on its next job: start it afresh
|
|
1026
|
+
message += " lcode restarts ComfyUI with your next request."
|
|
1027
|
+
else:
|
|
1028
|
+
message += " Restart your ComfyUI if it keeps failing."
|
|
1029
|
+
return message
|
|
1030
|
+
if "no space left on device" in low:
|
|
1031
|
+
return "ComfyUI couldn't save what it made: the disk is full. Free some space, then try again."
|
|
1032
|
+
if "closed the websocket" in low or "connection" in low:
|
|
1033
|
+
proc = agent.comfy_process
|
|
1034
|
+
if proc is not None and proc.poll() is not None:
|
|
1035
|
+
agent.comfy_process = None
|
|
1036
|
+
return (
|
|
1037
|
+
f"ComfyUI stopped while it worked (it crashed; its log: {comfy.log_path()}). lcode starts it again "
|
|
1038
|
+
"with your next request."
|
|
1039
|
+
)
|
|
1040
|
+
return error
|
|
1041
|
+
|
|
1042
|
+
|
|
950
1043
|
# ----------------------------------------------------------------------------- results: numbered, shown, opened
|
|
951
1044
|
|
|
952
1045
|
|
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:
|
lcode/media_cloud.py
ADDED
|
@@ -0,0 +1,461 @@
|
|
|
1
|
+
"""Image and video mode in the cloud: models that run at a provider with your API key (xAI's Grok Imagine first).
|
|
2
|
+
|
|
3
|
+
For what a laptop can't run, or when speed matters. A cloud model is chosen like any other (`/model` in image or video
|
|
4
|
+
mode; `/models` and `lcode media` mark it "cloud"), and then:
|
|
5
|
+
|
|
6
|
+
- **nothing goes without asking.** Before each request lcode shows what goes where (the prompt, any picture) and about
|
|
7
|
+
what it costs, from the prices in media.toml and the date they were checked, and waits for a yes;
|
|
8
|
+
- **the key comes from an environment variable only** (XAI_API_KEY) and goes only to the provider's API, in the
|
|
9
|
+
Authorization header. Results are downloaded from the address the API gives, without it;
|
|
10
|
+
- what it makes lands in the media folder and the gallery like anything else, with a JSON file next to it saying what
|
|
11
|
+
was sent to which model and about what it cost.
|
|
12
|
+
|
|
13
|
+
What a cloud model can't do here (masks, several pictures at once, clips between two frames, extending or restyling a
|
|
14
|
+
clip) is made by a local model instead, and lcode says which.
|
|
15
|
+
"""
|
|
16
|
+
|
|
17
|
+
from __future__ import annotations
|
|
18
|
+
|
|
19
|
+
import base64
|
|
20
|
+
import json
|
|
21
|
+
import math
|
|
22
|
+
import mimetypes
|
|
23
|
+
import os
|
|
24
|
+
import re
|
|
25
|
+
import struct
|
|
26
|
+
import time
|
|
27
|
+
from collections.abc import Callable
|
|
28
|
+
from dataclasses import dataclass, replace
|
|
29
|
+
from pathlib import Path
|
|
30
|
+
from typing import TYPE_CHECKING
|
|
31
|
+
from urllib.parse import urlsplit
|
|
32
|
+
|
|
33
|
+
import requests
|
|
34
|
+
from rich.panel import Panel
|
|
35
|
+
from rich.text import Text
|
|
36
|
+
|
|
37
|
+
from lcode import comfy, edits, imageopts, media
|
|
38
|
+
from lcode import media_catalog as catalog
|
|
39
|
+
|
|
40
|
+
if TYPE_CHECKING:
|
|
41
|
+
from lcode.agent import Agent
|
|
42
|
+
|
|
43
|
+
TIMEOUT = 180 # seconds for one API call (a picture takes a few)
|
|
44
|
+
VIDEO_WAIT = 900 # seconds to wait for a clip before giving up on it
|
|
45
|
+
POLL = 4 # seconds between asking whether a clip is done
|
|
46
|
+
IMAGE_RATIOS = ("1:1", "16:9", "9:16", "4:3", "3:4", "3:2", "2:3", "2:1", "1:2")
|
|
47
|
+
VIDEO_RATIOS = ("16:9", "9:16", "1:1", "4:3", "3:4", "3:2", "2:3")
|
|
48
|
+
RESOLUTION = {
|
|
49
|
+
"image": {"fast": "1k", "balanced": "1k", "best": "2k"},
|
|
50
|
+
"video": {"fast": "480p", "balanced": "720p", "best": "1080p"},
|
|
51
|
+
}
|
|
52
|
+
MAX_VIDEO_SECONDS = 15
|
|
53
|
+
KEPT = ("kind", "prompt", "sources", "mask", "pads", "keep_shape", "extend", "size", "refs", "restyle")
|
|
54
|
+
|
|
55
|
+
|
|
56
|
+
class CloudError(Exception):
|
|
57
|
+
pass
|
|
58
|
+
|
|
59
|
+
|
|
60
|
+
@dataclass(frozen=True)
|
|
61
|
+
class Provider:
|
|
62
|
+
key: str
|
|
63
|
+
name: str
|
|
64
|
+
api: str
|
|
65
|
+
key_env: str # the environment variable with the user's API key
|
|
66
|
+
base_env: str # another address for the API (a proxy; the tests' stand-in)
|
|
67
|
+
keys_url: str
|
|
68
|
+
prices_url: str
|
|
69
|
+
|
|
70
|
+
def api_key(self) -> str:
|
|
71
|
+
return os.environ.get(self.key_env, "").strip()
|
|
72
|
+
|
|
73
|
+
def base(self) -> str:
|
|
74
|
+
return (os.environ.get(self.base_env, "").strip() or self.api).rstrip("/")
|
|
75
|
+
|
|
76
|
+
def host(self) -> str:
|
|
77
|
+
return urlsplit(self.base()).netloc
|
|
78
|
+
|
|
79
|
+
|
|
80
|
+
PROVIDERS = {
|
|
81
|
+
"xai": Provider(
|
|
82
|
+
"xai", "xAI", "https://api.x.ai/v1", "XAI_API_KEY", "XAI_API_BASE", "https://console.x.ai",
|
|
83
|
+
"https://docs.x.ai/developers/pricing",
|
|
84
|
+
),
|
|
85
|
+
} # fmt: skip
|
|
86
|
+
|
|
87
|
+
|
|
88
|
+
def provider(model: catalog.MediaModel) -> Provider:
|
|
89
|
+
return PROVIDERS[model.cloud]
|
|
90
|
+
|
|
91
|
+
|
|
92
|
+
def describe(model: catalog.MediaModel) -> list[str]:
|
|
93
|
+
"""For lists (/models, lcode media): where it runs, what it costs, whether the key is set."""
|
|
94
|
+
p = provider(model)
|
|
95
|
+
key = f"{p.key_env} is set" if p.api_key() else f"needs {p.key_env}"
|
|
96
|
+
return [f"cloud: {p.name}", price_text(model), key]
|
|
97
|
+
|
|
98
|
+
|
|
99
|
+
def price_text(model: catalog.MediaModel) -> str:
|
|
100
|
+
if model.mode == "video":
|
|
101
|
+
rates = [(r, model.price[r]) for r in RESOLUTION["video"].values() if r in model.price]
|
|
102
|
+
if not rates:
|
|
103
|
+
return "price not listed"
|
|
104
|
+
low, high = rates[0], rates[-1]
|
|
105
|
+
return f"${low[1]:.2f}–{high[1]:.2f} per second ({low[0]}–{high[0]})"
|
|
106
|
+
return f"${model.price['image']:.2f} per image" if "image" in model.price else "price not listed"
|
|
107
|
+
|
|
108
|
+
|
|
109
|
+
def ready_note(model: catalog.MediaModel) -> str:
|
|
110
|
+
"""What to know after choosing a cloud model."""
|
|
111
|
+
p = provider(model)
|
|
112
|
+
note = (
|
|
113
|
+
f"{model.name} runs at {p.name}: each request shows what goes there and about what it costs ("
|
|
114
|
+
f"{price_text(model)}), and asks first."
|
|
115
|
+
)
|
|
116
|
+
if not p.api_key():
|
|
117
|
+
note += f" Set your key first: export {p.key_env}=… (from {p.keys_url}), then start lcode again."
|
|
118
|
+
return note
|
|
119
|
+
|
|
120
|
+
|
|
121
|
+
# ----------------------------------------------------------------------------- what it can do, and what it costs
|
|
122
|
+
|
|
123
|
+
|
|
124
|
+
def cannot(model: catalog.MediaModel, job: dict) -> str:
|
|
125
|
+
"""What in the job the cloud model can't do here (a local model makes it then), or empty."""
|
|
126
|
+
kind, sources = job["kind"], job.get("sources") or []
|
|
127
|
+
if kind == "edit":
|
|
128
|
+
if job.get("mask"):
|
|
129
|
+
return "masks"
|
|
130
|
+
if job.get("pads"):
|
|
131
|
+
return "extending a picture"
|
|
132
|
+
if len(sources) > 1:
|
|
133
|
+
return "several pictures at once"
|
|
134
|
+
elif kind == "video":
|
|
135
|
+
if job.get("extend"):
|
|
136
|
+
return "extending a clip"
|
|
137
|
+
if job.get("restyle"):
|
|
138
|
+
return "restyling a clip"
|
|
139
|
+
if job.get("refs"):
|
|
140
|
+
return "reference pictures"
|
|
141
|
+
if len(sources) > 1:
|
|
142
|
+
return "a clip between two frames"
|
|
143
|
+
elif kind != "image":
|
|
144
|
+
return kind
|
|
145
|
+
return ""
|
|
146
|
+
|
|
147
|
+
|
|
148
|
+
def ratio(size: str, choices: tuple[str, ...]) -> str:
|
|
149
|
+
"""The provider's aspect ratio closest to an option's size (a ratio, a name or pixels)."""
|
|
150
|
+
value = imageopts.SIZES.get(size, size)
|
|
151
|
+
m = re.fullmatch(r"(\d+)\s*[:x]\s*(\d+)", value)
|
|
152
|
+
if not m or not int(m.group(2)):
|
|
153
|
+
return choices[0]
|
|
154
|
+
want = math.log(int(m.group(1)) / int(m.group(2)))
|
|
155
|
+
|
|
156
|
+
def distance(r: str) -> float:
|
|
157
|
+
w, h = (int(x) for x in r.split(":"))
|
|
158
|
+
return abs(math.log(w / h) - want)
|
|
159
|
+
|
|
160
|
+
return min(choices, key=distance)
|
|
161
|
+
|
|
162
|
+
|
|
163
|
+
def video_seconds(options: imageopts.Options) -> int:
|
|
164
|
+
return max(1, min(MAX_VIDEO_SECONDS, round(options.seconds)))
|
|
165
|
+
|
|
166
|
+
|
|
167
|
+
def cost(model: catalog.MediaModel, kind: str, options: imageopts.Options, pictures: int) -> tuple[float, str]:
|
|
168
|
+
"""About what the request costs, in dollars, and how that adds up. `pictures`: how many go with it."""
|
|
169
|
+
sent_price = model.price.get("input_image", 0.0)
|
|
170
|
+
if kind == "video":
|
|
171
|
+
resolution = RESOLUTION["video"][options.quality]
|
|
172
|
+
if resolution not in model.price:
|
|
173
|
+
raise CloudError(f"{model.name} has no price for {resolution} in lcode: choose another --quality")
|
|
174
|
+
seconds, per = video_seconds(options), model.price[resolution]
|
|
175
|
+
total = options.n * seconds * per
|
|
176
|
+
parts = [f"{options.n} × " * (options.n > 1) + f"{seconds} s at {resolution} × ${per:.2f}/s"]
|
|
177
|
+
else:
|
|
178
|
+
per = model.price.get("image", 0.0)
|
|
179
|
+
total = options.n * per
|
|
180
|
+
parts = [f"{options.n} image{'s' * (options.n > 1)} × ${per:.2f}"]
|
|
181
|
+
if pictures and sent_price:
|
|
182
|
+
total += pictures * sent_price
|
|
183
|
+
parts.append(f"{pictures} picture{'s' * (pictures > 1)} sent × ${sent_price:.2f}")
|
|
184
|
+
return total, " + ".join(parts)
|
|
185
|
+
|
|
186
|
+
|
|
187
|
+
def confirm(agent: Agent, model: catalog.MediaModel, text: str, sources: list[Path], dollars: float, how: str,
|
|
188
|
+
ask: Callable[[str], bool] | None) -> None: # fmt: skip
|
|
189
|
+
"""Show what goes where and what it costs, and ask. Raises MediaError when the answer is no (or nobody's there)."""
|
|
190
|
+
p = provider(model)
|
|
191
|
+
if ask is None:
|
|
192
|
+
raise media.MediaError(
|
|
193
|
+
f"{model.name} runs at {p.name} and costs money, so lcode asks before each request, and nobody can be "
|
|
194
|
+
"asked here: run lcode in a terminal, or choose a local model (/model)."
|
|
195
|
+
)
|
|
196
|
+
pictures = ", ".join(media.shown(agent, s) for s in sources)
|
|
197
|
+
goes = "the prompt" + (f" and {len(sources)} picture{'s' * (len(sources) > 1)} ({pictures})" if sources else "")
|
|
198
|
+
shown_text = text if len(text) <= 400 else text[:399] + "…"
|
|
199
|
+
body = Text.assemble(
|
|
200
|
+
("Where: ", "bold"), f"{model.name} ({model.api_model}) at {p.name}, {p.host()}\n",
|
|
201
|
+
("What goes: ", "bold"), f"{goes}. Your {p.key_env} goes with it, to {p.host()} only.\n",
|
|
202
|
+
("Prompt: ", "bold"), f"{shown_text}\n",
|
|
203
|
+
("Cost: ", "bold"), f"about ${dollars:.2f} ({how}), billed to your {p.name} account; prices as of "
|
|
204
|
+
f"{model.priced or 'unknown'}, the real ones: {p.prices_url}",
|
|
205
|
+
) # fmt: skip
|
|
206
|
+
agent.console.print(Panel(body, title=f"Make it at {p.name}?", title_align="left", border_style="magenta"))
|
|
207
|
+
agent.waiting(f"send it to {p.name}?")
|
|
208
|
+
if not ask(f"Send it to {p.name} (about ${dollars:.2f})?"):
|
|
209
|
+
raise media.MediaError(f"Nothing was sent to {p.name}.")
|
|
210
|
+
|
|
211
|
+
|
|
212
|
+
# ----------------------------------------------------------------------------- xAI's Grok Imagine API
|
|
213
|
+
|
|
214
|
+
|
|
215
|
+
class Imagine:
|
|
216
|
+
"""xAI's image and video API, as image and video mode use it."""
|
|
217
|
+
|
|
218
|
+
def __init__(self, p: Provider, key: str):
|
|
219
|
+
self.p, self.key, self.base = p, key, p.base()
|
|
220
|
+
self.session = requests.Session()
|
|
221
|
+
self.session.headers.update({"Authorization": f"Bearer {key}", "Content-Type": "application/json"})
|
|
222
|
+
|
|
223
|
+
def call(self, method: str, path: str, body: dict | None = None) -> dict:
|
|
224
|
+
try:
|
|
225
|
+
r = self.session.request(method, self.base + path, json=body, timeout=TIMEOUT)
|
|
226
|
+
except requests.RequestException as e:
|
|
227
|
+
raise CloudError(self.scrub(f"Can't reach {self.p.name} ({self.p.host()}): {e}")) from e
|
|
228
|
+
name, why = self.p.name, error_text(r)
|
|
229
|
+
if r.status_code in (401, 403):
|
|
230
|
+
check = f"Check {self.p.key_env} ({self.p.keys_url})."
|
|
231
|
+
raise CloudError(self.scrub(f"{name} refused the request ({r.status_code}: {why}). {check}"))
|
|
232
|
+
if r.status_code == 429:
|
|
233
|
+
raise CloudError(self.scrub(f"{name}'s rate limit or your credit limit was reached: {why}"))
|
|
234
|
+
if r.status_code >= 400:
|
|
235
|
+
raise CloudError(self.scrub(f"{name} didn't make it ({r.status_code}): {why}"))
|
|
236
|
+
try:
|
|
237
|
+
return r.json()
|
|
238
|
+
except ValueError:
|
|
239
|
+
raise CloudError(f"{self.p.name} answered with something that isn't JSON: {r.text[:200]}") from None
|
|
240
|
+
|
|
241
|
+
def scrub(self, message: str) -> str:
|
|
242
|
+
return message.replace(self.key, "…") if self.key else message
|
|
243
|
+
|
|
244
|
+
def images(self, model: str, prompt: str, n: int, aspect_ratio: str, resolution: str) -> list[bytes]:
|
|
245
|
+
body = {"model": model, "prompt": prompt, "n": n, "response_format": "b64_json", "aspect_ratio": aspect_ratio}
|
|
246
|
+
if resolution != "1k":
|
|
247
|
+
body["resolution"] = resolution
|
|
248
|
+
return self.pictures(self.call("POST", "/images/generations", body))
|
|
249
|
+
|
|
250
|
+
def edit(self, model: str, prompt: str, picture: Path) -> list[bytes]:
|
|
251
|
+
body = {"model": model, "prompt": prompt, "image": {"url": data_url(picture), "type": "image_url"},
|
|
252
|
+
"response_format": "b64_json"} # fmt: skip
|
|
253
|
+
return self.pictures(self.call("POST", "/images/edits", body))
|
|
254
|
+
|
|
255
|
+
def pictures(self, reply: dict) -> list[bytes]:
|
|
256
|
+
items = reply.get("data") or []
|
|
257
|
+
if not items:
|
|
258
|
+
raise CloudError(f"{self.p.name} returned no image: {str(reply)[:300]}")
|
|
259
|
+
return [base64.b64decode(i["b64_json"]) if i.get("b64_json") else download(i["url"], self.p) for i in items]
|
|
260
|
+
|
|
261
|
+
def start_video(self, model: str, prompt: str, seconds: int, aspect_ratio: str, resolution: str,
|
|
262
|
+
start: Path | None) -> str: # fmt: skip
|
|
263
|
+
body: dict = {"model": model, "prompt": prompt, "duration": seconds, "aspect_ratio": aspect_ratio,
|
|
264
|
+
"resolution": resolution} # fmt: skip
|
|
265
|
+
if start is not None:
|
|
266
|
+
body["image"] = {"url": data_url(start)}
|
|
267
|
+
request_id = self.call("POST", "/videos/generations", body).get("request_id")
|
|
268
|
+
if not request_id:
|
|
269
|
+
raise CloudError(f"{self.p.name} didn't start the video")
|
|
270
|
+
return str(request_id)
|
|
271
|
+
|
|
272
|
+
def video(self, request_id: str) -> dict:
|
|
273
|
+
return self.call("GET", f"/videos/{request_id}")
|
|
274
|
+
|
|
275
|
+
|
|
276
|
+
def error_text(r: requests.Response) -> str:
|
|
277
|
+
try:
|
|
278
|
+
data = r.json()
|
|
279
|
+
except ValueError:
|
|
280
|
+
return r.text[:300] or r.reason
|
|
281
|
+
error = data.get("error") if isinstance(data, dict) else None
|
|
282
|
+
if isinstance(error, dict):
|
|
283
|
+
return str(error.get("message") or error)[:300]
|
|
284
|
+
return str(error or data)[:300]
|
|
285
|
+
|
|
286
|
+
|
|
287
|
+
def download(url: str, p: Provider) -> bytes:
|
|
288
|
+
"""A result from the address the API gave: without the key, which goes to the API only."""
|
|
289
|
+
try:
|
|
290
|
+
r = requests.get(url, timeout=TIMEOUT)
|
|
291
|
+
r.raise_for_status()
|
|
292
|
+
except requests.RequestException as e:
|
|
293
|
+
raise CloudError(f"{p.name} made it, but lcode couldn't download it: {e}") from e
|
|
294
|
+
return r.content
|
|
295
|
+
|
|
296
|
+
|
|
297
|
+
def data_url(path: Path) -> str:
|
|
298
|
+
mime = mimetypes.guess_type(path.name)[0] or "image/png"
|
|
299
|
+
if mime not in ("image/png", "image/jpeg", "image/webp"):
|
|
300
|
+
raise CloudError(f"{path.name} isn't a PNG, JPEG or WebP picture, which is what the provider takes")
|
|
301
|
+
return f"data:{mime};base64,{base64.b64encode(path.read_bytes()).decode()}"
|
|
302
|
+
|
|
303
|
+
|
|
304
|
+
def image_suffix(data: bytes) -> str:
|
|
305
|
+
if data[:3] == b"\xff\xd8\xff":
|
|
306
|
+
return ".jpg"
|
|
307
|
+
if data[:4] == b"RIFF" and data[8:12] == b"WEBP":
|
|
308
|
+
return ".webp"
|
|
309
|
+
return ".png"
|
|
310
|
+
|
|
311
|
+
|
|
312
|
+
# ----------------------------------------------------------------------------- a request, made in the cloud
|
|
313
|
+
|
|
314
|
+
|
|
315
|
+
def make(
|
|
316
|
+
agent: Agent,
|
|
317
|
+
model: catalog.MediaModel,
|
|
318
|
+
job: dict,
|
|
319
|
+
options: imageopts.Options,
|
|
320
|
+
cancelled: Callable[[], bool] = lambda: False,
|
|
321
|
+
ask: Callable[[str], bool] | None = None,
|
|
322
|
+
) -> list[media.Made]:
|
|
323
|
+
"""The job's `options.n` images, edits or clips, made at the model's provider once the user says yes to the
|
|
324
|
+
cost; saved, numbered and shown like local results."""
|
|
325
|
+
p = provider(model)
|
|
326
|
+
key = p.api_key()
|
|
327
|
+
if not key:
|
|
328
|
+
raise media.MediaError(
|
|
329
|
+
f"{model.name} runs at {p.name} with your API key: export {p.key_env}=… (from {p.keys_url}) and start "
|
|
330
|
+
"lcode again, or choose a local model with /model."
|
|
331
|
+
)
|
|
332
|
+
kind = job["kind"]
|
|
333
|
+
sources = [Path(s) for s in job.get("sources") or []]
|
|
334
|
+
text = imageopts.styled(job.get("expanded") or job["prompt"], options.style)
|
|
335
|
+
if kind == "video" and options.camera and options.camera != "static":
|
|
336
|
+
text = f"{text} Camera: {options.camera.replace('-', ' ')}."
|
|
337
|
+
try:
|
|
338
|
+
dollars, how = cost(model, kind, options, options.n * len(sources))
|
|
339
|
+
except CloudError as e:
|
|
340
|
+
raise media.MediaError(str(e)) from e
|
|
341
|
+
confirm(agent, model, text, sources, dollars, how, ask)
|
|
342
|
+
api = Imagine(p, key)
|
|
343
|
+
out = media.folder(agent)
|
|
344
|
+
stem = f"{time.strftime('%Y%m%d-%H%M%S')}-{comfy.slug(job['prompt'] or kind)}"
|
|
345
|
+
resolution = RESOLUTION["video" if kind == "video" else "image"][options.quality]
|
|
346
|
+
meta = {"prompt": job["prompt"], "model": model.name, "model_key": model.key, "provider": p.name,
|
|
347
|
+
"api_model": model.api_model, "full_prompt": text, "quality": options.quality, "style": options.style,
|
|
348
|
+
"resolution": resolution, "cost_usd": round(dollars / options.n, 4), "cost_is": "an estimate",
|
|
349
|
+
"created": time.strftime("%Y-%m-%dT%H:%M:%S%z")} # fmt: skip
|
|
350
|
+
if sources:
|
|
351
|
+
meta["edit_of" if kind == "edit" else "start_image"] = [media.shown(agent, s) for s in sources]
|
|
352
|
+
line = media.Line(model.name, "Esc or Ctrl+C stops waiting" if agent.interactive else "")
|
|
353
|
+
line.doing = f"waiting for {p.name}"
|
|
354
|
+
made: list[media.Made] = []
|
|
355
|
+
try:
|
|
356
|
+
with agent.console.status(line, spinner="dots"):
|
|
357
|
+
if kind == "image":
|
|
358
|
+
shape = ratio(options.size, IMAGE_RATIOS)
|
|
359
|
+
pictures = api.images(model.api_model, text, options.n, shape, resolution)
|
|
360
|
+
for i, data in enumerate(pictures, 1):
|
|
361
|
+
made.append(keep(agent, model, job, options, {**meta, "aspect_ratio": shape}, data, out,
|
|
362
|
+
stem if len(pictures) == 1 else f"{stem}-{i}", line)) # fmt: skip
|
|
363
|
+
elif kind == "edit":
|
|
364
|
+
for i in range(options.n):
|
|
365
|
+
data = api.edit(model.api_model, text, sources[0])[0]
|
|
366
|
+
made.append(keep(agent, model, job, options, meta, data, out,
|
|
367
|
+
stem if options.n == 1 else f"{stem}-{i + 1}", line)) # fmt: skip
|
|
368
|
+
else:
|
|
369
|
+
shape = video_shape(job, options, sources[0] if sources else None)
|
|
370
|
+
seconds = video_seconds(options)
|
|
371
|
+
for i in range(options.n):
|
|
372
|
+
request_id = api.start_video(model.api_model, text, seconds, shape, resolution,
|
|
373
|
+
sources[0] if sources else None) # fmt: skip
|
|
374
|
+
state = wait(api, line, request_id, cancelled)
|
|
375
|
+
video = state.get("video") or {}
|
|
376
|
+
if not video.get("url"):
|
|
377
|
+
raise CloudError(f"{p.name} finished the video but gave no address for it: {str(state)[:200]}")
|
|
378
|
+
data = download(video["url"], p)
|
|
379
|
+
clip_meta = {**meta, "aspect_ratio": shape, "seconds": video.get("duration") or seconds,
|
|
380
|
+
"request_id": request_id} # fmt: skip
|
|
381
|
+
made.append(keep(agent, model, job, options, clip_meta, data, out,
|
|
382
|
+
stem if options.n == 1 else f"{stem}-{i + 1}", line)) # fmt: skip
|
|
383
|
+
except CloudError as e:
|
|
384
|
+
raise media.MediaError(str(e)) from e
|
|
385
|
+
finally:
|
|
386
|
+
spent = dollars * len(made) / options.n
|
|
387
|
+
agent.cloud_spent += spent
|
|
388
|
+
for one in made:
|
|
389
|
+
media.show(agent, one)
|
|
390
|
+
agent.console.print(Text(f" about ${spent:.2f} at {p.name} (this session: about ${agent.cloud_spent:.2f})",
|
|
391
|
+
style="dim")) # fmt: skip
|
|
392
|
+
return made
|
|
393
|
+
|
|
394
|
+
|
|
395
|
+
def video_shape(job: dict, options: imageopts.Options, start: Path | None) -> str:
|
|
396
|
+
"""16:9, or 9:16 from an upright start picture, unless the request gave a shape (as local video does)."""
|
|
397
|
+
if job.get("keep_shape", True) and options.size == imageopts.Options().size:
|
|
398
|
+
if start is not None:
|
|
399
|
+
try:
|
|
400
|
+
w, h = edits.image_size(start)
|
|
401
|
+
return "9:16" if h > w else "16:9"
|
|
402
|
+
except (OSError, edits.EditError):
|
|
403
|
+
pass
|
|
404
|
+
return "16:9"
|
|
405
|
+
return ratio(options.size, VIDEO_RATIOS)
|
|
406
|
+
|
|
407
|
+
|
|
408
|
+
def wait(api: Imagine, line: media.Line, request_id: str, cancelled: Callable[[], bool]) -> dict:
|
|
409
|
+
"""The clip's state once it's done. Esc or Ctrl+C stops waiting (the provider may still make it, and bill it)."""
|
|
410
|
+
stopped = media.MediaError(
|
|
411
|
+
f"Stopped waiting: {api.p.name} may still make the video and bill it (request {request_id})."
|
|
412
|
+
)
|
|
413
|
+
deadline, next_poll = time.monotonic() + VIDEO_WAIT, 0.0
|
|
414
|
+
try:
|
|
415
|
+
while True:
|
|
416
|
+
if cancelled():
|
|
417
|
+
raise stopped
|
|
418
|
+
if time.monotonic() >= next_poll:
|
|
419
|
+
state = api.video(request_id)
|
|
420
|
+
status = state.get("status")
|
|
421
|
+
if status == "done":
|
|
422
|
+
return state
|
|
423
|
+
if status in ("failed", "expired"):
|
|
424
|
+
reason = state.get("error") or ""
|
|
425
|
+
reason = reason.get("message", reason) if isinstance(reason, dict) else reason
|
|
426
|
+
because = f": {reason}" if reason else ""
|
|
427
|
+
raise CloudError(f"{api.p.name} couldn't make the video ({status}){because}")
|
|
428
|
+
line.doing = f"{api.p.name} is making it ({status or 'queued'})"
|
|
429
|
+
next_poll = time.monotonic() + POLL
|
|
430
|
+
if time.monotonic() > deadline:
|
|
431
|
+
raise CloudError(
|
|
432
|
+
f"{api.p.name} hasn't finished the video after {VIDEO_WAIT // 60} minutes (request {request_id}); "
|
|
433
|
+
"it may still finish it, and bill it."
|
|
434
|
+
)
|
|
435
|
+
time.sleep(0.2)
|
|
436
|
+
except KeyboardInterrupt:
|
|
437
|
+
raise stopped from None
|
|
438
|
+
|
|
439
|
+
|
|
440
|
+
def keep(agent: Agent, model: catalog.MediaModel, job: dict, options: imageopts.Options, meta: dict, data: bytes,
|
|
441
|
+
out: Path, stem: str, line: media.Line) -> media.Made: # fmt: skip
|
|
442
|
+
"""Save one result with its JSON, number it in the gallery."""
|
|
443
|
+
video = job["kind"] == "video"
|
|
444
|
+
path = comfy.unique(out / f"{stem}{'.mp4' if video else image_suffix(data)}")
|
|
445
|
+
if path.suffix == ".png":
|
|
446
|
+
data = comfy.with_text(data, "lcode", json.dumps(meta, ensure_ascii=False))
|
|
447
|
+
path.write_bytes(data)
|
|
448
|
+
width = height = 0
|
|
449
|
+
try:
|
|
450
|
+
width, height = media.mp4_size(path) if video else edits.image_size(path)
|
|
451
|
+
except (OSError, edits.EditError, ValueError, struct.error):
|
|
452
|
+
pass # the gallery shows no size
|
|
453
|
+
meta = {**meta, "width": width, "height": height}
|
|
454
|
+
path.with_suffix(".json").write_text(json.dumps({**meta, "file": path.name}, indent=2, ensure_ascii=False) + "\n")
|
|
455
|
+
sources = [str(s) for s in job.get("sources") or []]
|
|
456
|
+
remembered = {k: job.get(k) for k in KEPT} # for /again and /vary
|
|
457
|
+
one = replace(options, n=1)
|
|
458
|
+
plan = media.Plan(model, None, {}, meta, job["prompt"], 0, one, job["kind"], sources, remembered) # type: ignore[arg-type]
|
|
459
|
+
made = media.Made([path], model.name, 0, width, height, time.monotonic() - line.started, job["prompt"])
|
|
460
|
+
made.numbers = media.record(agent, made, plan)
|
|
461
|
+
return made
|
lcode/modes.py
CHANGED
|
@@ -32,18 +32,19 @@ COMING: dict[str, str] = {}
|
|
|
32
32
|
|
|
33
33
|
def ready(agent: Agent) -> str:
|
|
34
34
|
"""What to do in the agent's mode, said on entering it."""
|
|
35
|
-
from lcode import media
|
|
36
|
-
|
|
37
|
-
if agent.settings.mode
|
|
35
|
+
from lcode import media, media_cloud
|
|
36
|
+
|
|
37
|
+
if agent.settings.mode in ("image", "video"):
|
|
38
|
+
model = media.current(agent)
|
|
39
|
+
where = "on your GPU"
|
|
40
|
+
if model.cloud:
|
|
41
|
+
where = f"at {media_cloud.provider(model).name} (you see the cost and say yes first)"
|
|
42
|
+
what = "an image" if agent.settings.mode == "image" else "a video"
|
|
43
|
+
start = " (@photo.png starts it from a picture)" if agent.settings.mode == "video" else ""
|
|
38
44
|
return (
|
|
39
|
-
f"Describe
|
|
45
|
+
f"Describe {what} and press Enter{start}: {model.name} makes it {where}, into "
|
|
40
46
|
f"{agent.settings.media_dir}. /mode code switches back."
|
|
41
47
|
)
|
|
42
|
-
if agent.settings.mode == "video":
|
|
43
|
-
return (
|
|
44
|
-
f"Describe a video and press Enter (@photo.png starts it from a picture): {media.current(agent).name} "
|
|
45
|
-
f"makes it on your GPU, into {agent.settings.media_dir}. /mode code switches back."
|
|
46
|
-
)
|
|
47
48
|
return COMING.get(agent.settings.mode, "")
|
|
48
49
|
|
|
49
50
|
|
lcode/repl.py
CHANGED
|
@@ -939,6 +939,11 @@ def media_model_command(agent: Agent, arg: str, hardware: Hardware) -> None:
|
|
|
939
939
|
return
|
|
940
940
|
setattr(s, f"{s.mode}_model", model.key)
|
|
941
941
|
c.print(f"[green]{s.mode.capitalize()} model: {escape(model.name)}.[/]")
|
|
942
|
+
if model.cloud:
|
|
943
|
+
from lcode import media_cloud
|
|
944
|
+
|
|
945
|
+
agent.say(media_cloud.ready_note(model))
|
|
946
|
+
return
|
|
942
947
|
if installed is not None:
|
|
943
948
|
_, missing = catalog.chosen_files(model, installed)
|
|
944
949
|
if missing:
|
|
@@ -1732,6 +1737,8 @@ def preload(agent: Agent, session: PromptSession | None = None) -> None:
|
|
|
1732
1737
|
refresh()
|
|
1733
1738
|
try:
|
|
1734
1739
|
agent.ollama.load(agent.settings.model, agent.options(), agent.settings.keep_alive)
|
|
1740
|
+
if agent.settings.mode != "code": # switched to image or video mode while it loaded: give the GPU back
|
|
1741
|
+
residency.release(agent.ollama, agent.settings.model)
|
|
1735
1742
|
except OllamaError:
|
|
1736
1743
|
pass
|
|
1737
1744
|
finally:
|
lcode/residency.py
CHANGED
|
@@ -19,6 +19,7 @@ from lcode.cloud import is_cloud
|
|
|
19
19
|
from lcode.ollama import OllamaError
|
|
20
20
|
|
|
21
21
|
GB = 1e9
|
|
22
|
+
RELEASE_WAIT = 15.0 # seconds to wait for Ollama to give an unloaded model's GPU memory back
|
|
22
23
|
SPLIT_WARNING = 0.95 # a dense model with less than this on the GPU runs much slower
|
|
23
24
|
SHORTFALL = 0.25 # this much less on the GPU than expected: something else is using GPU memory
|
|
24
25
|
|
|
@@ -69,6 +70,38 @@ def loaded(ollama, model: str | None = None) -> list[Placement]:
|
|
|
69
70
|
return found
|
|
70
71
|
|
|
71
72
|
|
|
73
|
+
def release(ollama, model: str, wait: float | None = None) -> bool:
|
|
74
|
+
"""Unload a model and wait until its GPU memory is free again; whether it was loaded.
|
|
75
|
+
|
|
76
|
+
Ollama answers the unload at once and frees the memory a moment later: a program that starts on the GPU in
|
|
77
|
+
that moment finds it still full. So this waits until Ollama no longer lists the model and, on NVIDIA GPUs, until
|
|
78
|
+
most of what it held shows as free.
|
|
79
|
+
"""
|
|
80
|
+
from lcode import hardware
|
|
81
|
+
|
|
82
|
+
held = loaded(ollama, model)
|
|
83
|
+
if not held:
|
|
84
|
+
return False
|
|
85
|
+
before = hardware.gpu_used_gib()
|
|
86
|
+
ollama.unload(model)
|
|
87
|
+
deadline = time.monotonic() + (RELEASE_WAIT if wait is None else wait)
|
|
88
|
+
while loaded(ollama, model) and time.monotonic() < deadline:
|
|
89
|
+
time.sleep(0.2)
|
|
90
|
+
if before is not None: # NVIDIA: until most of it is free, or the memory stops going down for a second
|
|
91
|
+
target = before - 0.75 * sum(p.vram for p in held) / 2**30
|
|
92
|
+
last, steady = before, time.monotonic()
|
|
93
|
+
while time.monotonic() < deadline:
|
|
94
|
+
used = hardware.gpu_used_gib()
|
|
95
|
+
if used is None or used <= target:
|
|
96
|
+
break
|
|
97
|
+
if abs(used - last) > 0.1:
|
|
98
|
+
last, steady = used, time.monotonic()
|
|
99
|
+
elif time.monotonic() - steady >= 1.0 and used < before - 0.1:
|
|
100
|
+
break
|
|
101
|
+
time.sleep(0.2)
|
|
102
|
+
return True
|
|
103
|
+
|
|
104
|
+
|
|
72
105
|
def placement(ollama, model: str) -> Placement | None:
|
|
73
106
|
found = loaded(ollama, model)
|
|
74
107
|
return found[0] if found else None
|
|
@@ -1,6 +1,6 @@
|
|
|
1
1
|
Metadata-Version: 2.5
|
|
2
2
|
Name: lcode-cli
|
|
3
|
-
Version: 0.
|
|
3
|
+
Version: 0.49.1
|
|
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/
|
|
@@ -118,11 +118,13 @@ through [Ollama](https://ollama.com), and when it needs current information it c
|
|
|
118
118
|
with tool calling. Or use LM Studio, llama.cpp, vLLM or MLX instead of Ollama.
|
|
119
119
|
- **MCP servers, ready to go.** Connect Jira and Confluence, GitHub, AWS, Google Drive, Grafana,
|
|
120
120
|
Google Cloud, Sentry, Linear, Notion, Postgres, Kubernetes, Metabase, Encord, Valohai and more with one command
|
|
121
|
-
(`lcode mcp add atlassian`),
|
|
121
|
+
(`lcode mcp add atlassian`), or any other MCP server. Browser sign-in (OAuth) is built in.
|
|
122
122
|
- **Sees images.** Attach a screenshot or mockup with `@path` and lcode looks at it, using the
|
|
123
|
-
vision part of your model.
|
|
124
|
-
|
|
125
|
-
and
|
|
123
|
+
vision part of your model.
|
|
124
|
+
- **Images, videos and films.** Image and video [modes](https://nasser1941.github.io/lcode/modes/)
|
|
125
|
+
(`/mode image`) make pictures, edits, clips and short films with local models run by ComfyUI
|
|
126
|
+
(FLUX.2 klein, Wan 2.2, installed on demand), or with xAI's Grok Imagine and your own key, after
|
|
127
|
+
showing what it costs.
|
|
126
128
|
- **Web search when needed.** Looks up the latest versions, docs and error messages with Ollama web
|
|
127
129
|
search, Brave, Tavily or your own SearXNG, and reads pages as clean text.
|
|
128
130
|
- **Private.** The model runs on your machine, lcode never uploads your files and has no telemetry.
|
|
@@ -1,8 +1,8 @@
|
|
|
1
|
-
lcode/__init__.py,sha256=
|
|
1
|
+
lcode/__init__.py,sha256=E_r27bB43mx6yBYRfgRUKLFIF-vd3VyGvpgQw_5IEUs,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=
|
|
5
|
+
lcode/agent.py,sha256=jmPZLr4V1wobMXtkphX_YzOWikcHgj0J88EVbs0-BFw,89279
|
|
6
6
|
lcode/api.py,sha256=R6vwHhZcWqKNf_ygOfij6Il9hpjVJvClVBmxzaKA434,17798
|
|
7
7
|
lcode/assistant.py,sha256=BXdg3pAM6NVNNYVmht6oqVLfihaLVf87A6gcoZqXv34,7769
|
|
8
8
|
lcode/backends.py,sha256=343alwyDZin-bEhb5-Es4f8ek1oBQUzEvV6RFWR1VZo,21160
|
|
@@ -12,7 +12,7 @@ lcode/bench_runtime.py,sha256=EjzNgIvUkdbT8cbSy1TpmlyeIk6e-ipjlDFpM7Dnqx0,6835
|
|
|
12
12
|
lcode/catalog.py,sha256=pZ1azX9OH2r4JE2c6E5OfwywpgS39-W2oXzoCHJhmtM,4141
|
|
13
13
|
lcode/checkpoints.py,sha256=eqPtmPe44-aweWqc2H21ROogwzIt3NpvcUobsaCHoGY,18354
|
|
14
14
|
lcode/checks.py,sha256=haYYIPhadKavGYEhh8YWAaWrPMcfzrpT2i6638f4xjQ,12933
|
|
15
|
-
lcode/cli.py,sha256=
|
|
15
|
+
lcode/cli.py,sha256=VqUOvosm4NzI6DzbdjfcHyFEJK1ju7J6sO_w-pWrCng,51718
|
|
16
16
|
lcode/clipboard.py,sha256=nTSdJyCXPdtjH947RjvB3QvRqnL5HZsS9KB8EkC42cc,5138
|
|
17
17
|
lcode/cloud.py,sha256=q5Dl5GuqWvKzBCIso-eh6yomvEOsnQ0LW8ZgaAGwBxc,2131
|
|
18
18
|
lcode/codesearch.py,sha256=Io8leN1nb_Y-Dvlm9xaGtwUWYXX-ooswuznJV6dGU1s,10766
|
|
@@ -22,22 +22,23 @@ lcode/context.py,sha256=wgK16ZcNNnq4ngHx0EmtyKHDFTImciGEmtC5NP8tKJQ,20435
|
|
|
22
22
|
lcode/edits.py,sha256=iYXSbKv4ZfxP12B1ov6-CLEWvR_tWFUdHRQbER3O8d0,13340
|
|
23
23
|
lcode/escalate.py,sha256=f-_6_moPaHi2kLuJw2JtkzvTkCl6DoBQgYBOCYLhunM,15120
|
|
24
24
|
lcode/extensions.py,sha256=W0HFDl0BvROzr7i_qtabHdIbacBgP5o5qIJLzoM2oNE,16806
|
|
25
|
-
lcode/film.py,sha256=
|
|
25
|
+
lcode/film.py,sha256=nfffI6oMWeherp8AOU_yM7-Cok0JKoQMVeuVtVHKXo0,14455
|
|
26
26
|
lcode/frontmatter.py,sha256=Bx0n4vLPhp7ZCWx-g7xqzqNy5VoKBxyeeikh5UFB_gA,2441
|
|
27
27
|
lcode/gitflow.py,sha256=6j_nnCBZXkX1qhTI7K4CyZ5D0NAZLpH96weFEo64AkQ,27913
|
|
28
|
-
lcode/hardware.py,sha256=
|
|
28
|
+
lcode/hardware.py,sha256=9j_gxSUYLAVtnSLIEL8FVU2q-jEEjHtMs2SVAax7yU8,5154
|
|
29
29
|
lcode/hooks.py,sha256=K0itOiAuH4rxndJ9gne_uCrqby6oWAzFPRrfB3tCq-E,9324
|
|
30
30
|
lcode/imageopts.py,sha256=fSVWOiYVeKXfYCdfoBedT2DB_UnZnh66xzp-uFh7N1M,9587
|
|
31
31
|
lcode/jobs.py,sha256=P1P3FqI6EqL4LgdMX9YGZwCW0Bh5BRXFA_FnQxpHNjE,5618
|
|
32
32
|
lcode/limits.py,sha256=oJzVQoMyTZ0_Fkpu5t3qxrf9v7Hv9S8U8BRQR5M1aKA,1237
|
|
33
33
|
lcode/lsp.py,sha256=NtSW7xapv7fg2HAQLuYK1nwIqT7nG0LK1hiTpOmla_4,26086
|
|
34
34
|
lcode/matching.py,sha256=2N3_qwKJ5gd8el2m_y_egKkFM9rsF1eUhYJcRCVIp98,14015
|
|
35
|
-
lcode/media.py,sha256=
|
|
36
|
-
lcode/media.toml,sha256=
|
|
37
|
-
lcode/media_catalog.py,sha256=
|
|
35
|
+
lcode/media.py,sha256=IKLNDzY3fjjtdUz5NJP0XXzqXxLIoV1Zvy5Nbf4ISi0,53097
|
|
36
|
+
lcode/media.toml,sha256=cvXxmTEmdwQokadYRVCjmTNIXwk3EoV82XGVj_oCFB8,11297
|
|
37
|
+
lcode/media_catalog.py,sha256=hp68dG6MtS8rqgcp3coeA5tS1EAA6ATXZEMbsJhWvsk,15730
|
|
38
|
+
lcode/media_cloud.py,sha256=lu9WccP7QmT6FodZaob8ZUtt0-mdKIcZrNI_vanqb7o,21237
|
|
38
39
|
lcode/memory.py,sha256=WZEHTp-lVxAwS-yyLQR2xB3TMZ9sejmX2Ivg7T-tl3w,21949
|
|
39
40
|
lcode/models.toml,sha256=lt2G64zzo_Ryxv2ISRSNZoVD_JqCqYqsM01n8WoXGs8,4098
|
|
40
|
-
lcode/modes.py,sha256=
|
|
41
|
+
lcode/modes.py,sha256=Ybn9Pe2JJjOCIsixZpg-AHvB1nUMckNEiDKGHBLFXjA,5190
|
|
41
42
|
lcode/notify.py,sha256=uieDeXe7XwuVHjOk4tqVyZEW_85XWkoWQmFOWEf77oc,1538
|
|
42
43
|
lcode/ollama.py,sha256=xFHU2XW47ANJ34-1aeSMQVj28GhqcWiFi6zASH9FiYY,8053
|
|
43
44
|
lcode/permissions.py,sha256=q7CjDsc_Xrblw7t3_BbxA5LUjxFSswGs1RiJmtMi0po,12288
|
|
@@ -45,9 +46,9 @@ lcode/planning.py,sha256=Q2upaoZPnXDMQT2F-ETxX1lk_wDntTzhSKNVYIQSoQA,6540
|
|
|
45
46
|
lcode/preview.py,sha256=ATzEs6yaI1__bfo2_juWznrTDXUD4QTc_aQMPRCytgA,6253
|
|
46
47
|
lcode/render.py,sha256=gMvf4W3qkLUJ4Vot3az_hP_zRDAItJC9pP-68dHFkfA,1375
|
|
47
48
|
lcode/repeats.py,sha256=OTrPdb6BKArDLQEgHaXmJZ-tIFsY_1bk4P0wzzANKLY,5964
|
|
48
|
-
lcode/repl.py,sha256=
|
|
49
|
+
lcode/repl.py,sha256=rjd16rqZLyxA3Eor-k2_L5eu9ABb7dhVwyr7k2124VU,79399
|
|
49
50
|
lcode/repomap.py,sha256=1GRJgEUjBl9XHSXsF7tSGXBCEgsY-3CzwMohaTudZ_M,13969
|
|
50
|
-
lcode/residency.py,sha256=
|
|
51
|
+
lcode/residency.py,sha256=7a2NYGyHpTm8y4yrcCrDkrtn43vOnE_wg79k9e8dNqY,8484
|
|
51
52
|
lcode/review.py,sha256=0QBIS-R1B2b3zqx5TcC1qZptpKBbrDhYvMKSNCaDAUo,4686
|
|
52
53
|
lcode/sandbox.py,sha256=u_pkrVRXhCGhh-wFDPwuZ3jGG7UeXxXRAeBNsm37ZvE,8608
|
|
53
54
|
lcode/screenshots.py,sha256=pmrw_tp8eXzNyCZa5uot5rTgsxqsi3AdmkGn-XF9saY,57056
|
|
@@ -88,8 +89,8 @@ lcode/workflows/wan21-vace.json,sha256=vJsiRvLCXCjKIibOO0SGM3fT6bedAGxF8N2sN2vcP
|
|
|
88
89
|
lcode/workflows/wan22-fun-inp-5b.json,sha256=4HbKEezik8MHvxTMP6PjQUPQPfCeSu10U9FrC-DHKYw,3327
|
|
89
90
|
lcode/workflows/wan22-ti2v-5b.json,sha256=RcTehoC2pNizzlb7Ed3keJ56DiE7V5lhXmsvR2Y0smQ,3371
|
|
90
91
|
lcode/workflows/z-image-turbo-t2i.json,sha256=sHsL7xnnuULOuWGYlQrDl4jOTySdAmb2T82c_cChv0s,1585
|
|
91
|
-
lcode_cli-0.
|
|
92
|
-
lcode_cli-0.
|
|
93
|
-
lcode_cli-0.
|
|
94
|
-
lcode_cli-0.
|
|
95
|
-
lcode_cli-0.
|
|
92
|
+
lcode_cli-0.49.1.dist-info/METADATA,sha256=mRkBbVyZpm8aBXzgPxONy-DJlivb1iaJE0VAN9ZUgHs,13532
|
|
93
|
+
lcode_cli-0.49.1.dist-info/WHEEL,sha256=W3fkpkm7-wf9vBI5Z-7s0eWkeM-spu78I8Neb98DeEg,87
|
|
94
|
+
lcode_cli-0.49.1.dist-info/entry_points.txt,sha256=Hxsn_itbnbgft3U0FwxWdmEt0yoAV2LB-nJDnL9WT20,172
|
|
95
|
+
lcode_cli-0.49.1.dist-info/licenses/LICENSE,sha256=JWjmoL7nNIC1XUa-dZm2hwLUgjUQMFo6k8APb0idNzs,1074
|
|
96
|
+
lcode_cli-0.49.1.dist-info/RECORD,,
|
|
File without changes
|
|
File without changes
|
|
File without changes
|