lcode-cli 0.44.0__py3-none-any.whl → 0.46.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 CHANGED
@@ -3,7 +3,7 @@
3
3
  From a program: `from lcode import Session` (see lcode.api).
4
4
  """
5
5
 
6
- __version__ = "0.44.0"
6
+ __version__ = "0.46.0"
7
7
 
8
8
  API = ("Session", "Result", "Options", "SetupError")
9
9
 
lcode/imageopts.py CHANGED
@@ -35,6 +35,21 @@ STYLES = {
35
35
  "comic": "comic book art, bold ink outlines, halftone shading",
36
36
  "flat": "flat vector illustration, minimal, bold shapes",
37
37
  }
38
+ CAMERA = { # video: --camera name -> the camera model's pose
39
+ "static": "Static",
40
+ "pan-left": "Pan Left",
41
+ "pan-right": "Pan Right",
42
+ "pan-up": "Pan Up",
43
+ "pan-down": "Pan Down",
44
+ "tilt-up": "Pan Up",
45
+ "tilt-down": "Pan Down",
46
+ "zoom-in": "Zoom In",
47
+ "zoom-out": "Zoom Out",
48
+ "dolly-in": "Zoom In",
49
+ "dolly-out": "Zoom Out",
50
+ "rotate-left": "Anti Clockwise (ACW)",
51
+ "rotate-right": "ClockWise (CW)",
52
+ }
38
53
  ALIASES = {
39
54
  "n": "n",
40
55
  "count": "n",
@@ -49,6 +64,7 @@ ALIASES = {
49
64
  "style": "style",
50
65
  "seconds": "seconds",
51
66
  "duration": "seconds",
67
+ "camera": "camera",
52
68
  }
53
69
  FLAG = re.compile(r"(?:^|\s)--?(" + "|".join(sorted(ALIASES, key=len, reverse=True)) + r")\b(?=[\s=]|$)")
54
70
  DIMENSIONS = re.compile(r"^(\d{2,4})\s*[x×]\s*(\d{2,4})$")
@@ -68,12 +84,15 @@ class Options:
68
84
  negative: str = ""
69
85
  style: str = ""
70
86
  seconds: float = 5.0 # video only
87
+ camera: str = "" # video only: a move from CAMERA, made by a camera-control model
71
88
 
72
89
  def describe(self, video: bool = False) -> str:
73
90
  seed = "random" if self.seed is None else str(self.seed)
74
91
  parts = [f"n={self.n}", f"size={self.size}", f"seed={seed}", f"quality={self.quality}"]
75
92
  if video:
76
93
  parts.append(f"seconds={self.seconds:g}")
94
+ if self.camera:
95
+ parts.append(f"camera={self.camera}")
77
96
  if self.style:
78
97
  parts.append(f"style={self.style}")
79
98
  if self.negative:
@@ -98,7 +117,9 @@ def set_values(options: Options, values: dict[str, object]) -> Options:
98
117
  for raw_key, raw in values.items():
99
118
  key = ALIASES.get(str(raw_key).lower().lstrip("-"))
100
119
  if key is None:
101
- raise OptionError(f"unknown option {raw_key!r}: use n, ar (or size), seed, quality, style, no or seconds")
120
+ raise OptionError(
121
+ f"unknown option {raw_key!r}: use n, ar (or size), seed, quality, style, no, seconds or camera"
122
+ )
102
123
  value = str(raw).strip() if raw is not None else ""
103
124
  if key == "n":
104
125
  if not value.isdigit() or not 1 <= int(value) <= MAX_COUNT:
@@ -126,6 +147,13 @@ def set_values(options: Options, values: dict[str, object]) -> Options:
126
147
  raise OptionError(f"style is one of {', '.join(STYLES)} (or none)")
127
148
  elif key == "negative":
128
149
  out.negative = "" if value.lower() in ("none", "off") else value
150
+ elif key == "camera":
151
+ if value.lower() in ("none", "off", ""):
152
+ out.camera = ""
153
+ elif value.lower() in CAMERA:
154
+ out.camera = value.lower()
155
+ else:
156
+ raise OptionError(f"camera is one of {', '.join(CAMERA)} (or none)")
129
157
  elif key == "seconds":
130
158
  try:
131
159
  seconds = float(value.rstrip("s"))
lcode/media.py CHANGED
@@ -6,10 +6,12 @@ sizes, variations and a gallery come with #151, video with #153.
6
6
 
7
7
  from __future__ import annotations
8
8
 
9
+ import json
9
10
  import os
10
11
  import random
11
12
  import re
12
13
  import shutil
14
+ import struct
13
15
  import subprocess
14
16
  import sys
15
17
  import time
@@ -269,6 +271,7 @@ def thumbnail(server: comfy.Server, outputs: dict, node: str = THUMB_NODES[1]) -
269
271
 
270
272
  SIZE_FLAG = re.compile(r"(?:^|\s)--?(ar|aspect|size)\b")
271
273
  MASK_FLAG = re.compile(r'(?:^|\s)--mask\s+("[^"]+"|\S+)')
274
+ REF_FLAG = re.compile(r"(?:^|\s)--refs?\b")
272
275
 
273
276
 
274
277
  def request(
@@ -276,6 +279,8 @@ def request(
276
279
  ) -> list[Made]:
277
280
  """A typed request: its @references (images to edit or follow), --mask, and flags (--n 4 --ar 16:9 …, over
278
281
  the session's /options), then the images."""
282
+ as_references = bool(REF_FLAG.search(text))
283
+ text = REF_FLAG.sub(" ", text)
279
284
  mask = None
280
285
  m = MASK_FLAG.search(text)
281
286
  if m:
@@ -292,8 +297,12 @@ def request(
292
297
  if agent.settings.mode == "video":
293
298
  if mask:
294
299
  raise MediaError("Video mode doesn't take a mask: @photo.png starts a video from a picture.")
295
- job = {"kind": "video", "prompt": prompt, "options": options, "sources": [str(p) for p in sources[:1]],
296
- "mask": None, "pads": None, "keep_shape": not SIZE_FLAG.search(text)} # fmt: skip
300
+ if as_references and not sources:
301
+ raise MediaError("--ref makes the @pictures references: @cat.png @hat.png --ref the cat wears the hat")
302
+ frames = [] if as_references else [str(p) for p in sources[:2]]
303
+ refs = [str(p) for p in sources] if as_references else []
304
+ 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
297
306
  return redo(agent, job, cancelled, ask)
298
307
  job = {"kind": "edit" if sources else "image", "prompt": prompt, "options": options,
299
308
  "sources": [str(p) for p in sources], "mask": str(mask) if mask else None, "pads": None,
@@ -488,10 +497,19 @@ def generate_video(
488
497
  image (the shapes video models know best; the image is cropped to it), unless the request gives one."""
489
498
  prompt = job["prompt"].strip()
490
499
  server = prepare(agent, ask, cancelled)
491
- model = current(agent, "video")
500
+ sources = [Path(p) for p in job.get("sources") or []]
501
+ start = sources[0] if sources else None
502
+ end = sources[1] if len(sources) > 1 else None
503
+ clip = Path(job["extend"]) if job.get("extend") else None
504
+ refs = [Path(p) for p in job.get("refs") or []]
505
+ restyle = Path(job["restyle"]) if job.get("restyle") else None
506
+ task = (
507
+ "restyle" if restyle else "references" if refs else "first-last-frame" if end
508
+ else "camera" if options.camera else "image-to-video" if clip else ""
509
+ ) # fmt: skip
510
+ model = video_model(agent, task)
492
511
  files = ensure_installed(agent, model, server, ask)
493
512
  workflow = comfy.load_workflow(model.workflow)
494
- start = Path(job["sources"][0]) if job.get("sources") else None
495
513
  seed = options.seed if options.seed is not None else random.randrange(2**32)
496
514
  steps, megapixels = model.preset(options.quality)
497
515
  ratio = options.size
@@ -504,7 +522,17 @@ def generate_video(
504
522
  except (OSError, edits.EditError):
505
523
  pass
506
524
  width, height = imageopts.dimensions(imageopts.SIZES.get(ratio, ratio), megapixels, multiple=32)
525
+ if clip is not None: # the new part continues the clip, so it has its size
526
+ width, height = job["size"]
507
527
  fps = int(workflow.defaults.get("fps", 24))
528
+ if clip is not None: # one clip, one pace: the new part plays at the clip's fps
529
+ fps = int(clip_info(clip)["fps"] or fps)
530
+ if restyle is not None: # the restyled clip has the clip's size and pace (up to the model's length)
531
+ info = clip_info(restyle)
532
+ width, height = (info["width"] // 16 * 16 or 832), (info["height"] // 16 * 16 or 480)
533
+ fps = int(info["fps"] or fps)
534
+ options = replace(options, seconds=min(options.seconds if job.get("seconds_given") else 99,
535
+ (min(info["frames"] or 81, 81) - 1) / fps)) # fmt: skip
508
536
  text = imageopts.styled(prompt, options.style)
509
537
  values = {**workflow.defaults, **files, "prompt": text, "seed": seed, "width": width, "height": height,
510
538
  "length": imageopts.frames(options.seconds, fps), "fps": fps} # fmt: skip
@@ -512,26 +540,157 @@ def generate_video(
512
540
  values["steps"] = steps
513
541
  if options.negative:
514
542
  values["negative"] = options.negative
543
+ values["camera"] = imageopts.CAMERA[options.camera or "static"]
515
544
  graph = comfy.fill(workflow.graph, values)
516
- if start is not None:
517
- try:
518
- name = server.upload(start)
519
- except (comfy.ComfyError, OSError) as e:
520
- raise MediaError(f"Couldn't hand the image to ComfyUI: {e}") from e
521
- latent = edits.node_of(graph, "Wan22ImageToVideoLatent")
522
- if latent is None:
523
- raise MediaError(f"{model.name} can't start from an image.")
524
- graph["8100"] = {"class_type": "LoadImage", "inputs": {"image": name}}
525
- graph[latent]["inputs"]["start_image"] = ["8100", 0]
545
+ latent = next((edits.node_of(graph, c) for c in VIDEO_LATENTS if edits.node_of(graph, c)), None)
546
+ try:
547
+ if start is not None:
548
+ graph["8100"] = {"class_type": "LoadImage", "inputs": {"image": server.upload(start)}}
549
+ graph[latent]["inputs"]["start_image"] = ["8100", 0]
550
+ loader = edits.node_of(graph, "CLIPVisionLoader")
551
+ if loader is not None: # the camera model also looks at the start image
552
+ look = {"clip_vision": [loader, 0], "image": ["8100", 0], "crop": "none"}
553
+ graph["8102"] = {"class_type": "CLIPVisionEncode", "inputs": look}
554
+ graph[latent]["inputs"]["clip_vision_output"] = ["8102", 0]
555
+ if end is not None:
556
+ graph["8101"] = {"class_type": "LoadImage", "inputs": {"image": server.upload(end)}}
557
+ graph[latent]["inputs"]["end_image"] = ["8101", 0]
558
+ if clip is not None:
559
+ continue_clip(graph, latent, server.upload(clip), values["length"])
560
+ vace = edits.node_of(graph, "WanVaceToVideo")
561
+ if refs and vace is not None:
562
+ graph[vace]["inputs"]["reference_image"] = reference_strip(graph, [server.upload(p) for p in refs])
563
+ if restyle is not None and vace is not None:
564
+ graph[vace]["inputs"]["control_video"] = control_from(graph, server.upload(restyle), values["length"])
565
+ except (comfy.ComfyError, OSError) as e:
566
+ raise MediaError(f"Couldn't hand the files to ComfyUI: {e}") from e
526
567
  add_thumbnail(graph, width, height)
527
568
  meta = describe_job(model, workflow, prompt, text, seed, values, options, files)
528
569
  meta.update({"seconds": round((values["length"] - 1) / fps, 2), "fps": fps, "frames": values["length"],
529
- "start_image": shown(agent, start) if start else ""}) # fmt: skip
530
- remembered = {k: job.get(k) for k in ("kind", "prompt", "sources", "mask", "pads", "keep_shape")}
531
- plan = Plan(model, workflow, graph, meta, prompt, seed, options, "video", job.get("sources") or [], remembered)
570
+ "start_image": shown(agent, start) if start else "", "end_image": shown(agent, end) if end else "",
571
+ "camera": options.camera, "extends": shown(agent, clip) if clip else "",
572
+ "references": [shown(agent, p) for p in refs],
573
+ "restyles": shown(agent, restyle) if restyle else ""}) # fmt: skip
574
+ keys = ("kind", "prompt", "sources", "mask", "pads", "keep_shape", "extend", "size", "refs", "restyle")
575
+ remembered = {k: job.get(k) for k in keys}
576
+ stem = f"{clip.stem}-extended" if clip else (f"{restyle.stem}-restyled" if restyle else "")
577
+ plan = Plan(model, workflow, graph, meta, prompt, seed, options, "video", job.get("sources") or [], remembered,
578
+ stem) # fmt: skip
532
579
  return run_plan(agent, server, plan, cancelled, label)
533
580
 
534
581
 
582
+ VIDEO_LATENTS = ("Wan22ImageToVideoLatent", "WanFunInpaintToVideo", "WanCameraImageToVideo", "WanVaceToVideo")
583
+ WHY = {
584
+ "first-last-frame": "a clip between two frames",
585
+ "camera": "a camera move",
586
+ "image-to-video": "continuing a clip",
587
+ "references": "following reference pictures",
588
+ "restyle": "restyling a clip",
589
+ }
590
+
591
+
592
+ def reference_strip(graph: dict, names: list[str]) -> list:
593
+ """The reference pictures side by side in one image, as VACE takes them."""
594
+ graph["8300"] = {"class_type": "LoadImage", "inputs": {"image": names[0]}}
595
+ strip = ["8300", 0]
596
+ for k, name in enumerate(names[1:], 1):
597
+ load, stitch = str(8300 + 2 * k - 1), str(8300 + 2 * k)
598
+ graph[load] = {"class_type": "LoadImage", "inputs": {"image": name}}
599
+ graph[stitch] = {
600
+ "class_type": "ImageStitch",
601
+ "inputs": {"image1": strip, "direction": "right", "match_image_size": True, "spacing_width": 0,
602
+ "spacing_color": "white", "image2": [load, 0]},
603
+ } # fmt: skip
604
+ strip = [stitch, 0]
605
+ return strip
606
+
607
+
608
+ def control_from(graph: dict, clip_name: str, length: int) -> list:
609
+ """Restyling: the clip's outlines (Canny edges), frame by frame, for VACE to follow."""
610
+ graph["8400"] = {"class_type": "LoadVideo", "inputs": {"file": clip_name}}
611
+ graph["8401"] = {"class_type": "GetVideoComponents", "inputs": {"video": ["8400", 0]}}
612
+ graph["8402"] = {
613
+ "class_type": "ImageFromBatch",
614
+ "inputs": {"image": ["8401", 0], "batch_index": 0, "length": length},
615
+ }
616
+ latent = edits.node_of(graph, "WanVaceToVideo")
617
+ w, h = graph[latent]["inputs"]["width"], graph[latent]["inputs"]["height"]
618
+ graph["8403"] = {
619
+ "class_type": "ImageScale",
620
+ "inputs": {"image": ["8402", 0], "upscale_method": "bilinear", "width": w, "height": h, "crop": "center"},
621
+ }
622
+ graph["8404"] = {
623
+ "class_type": "Canny",
624
+ "inputs": {"image": ["8403", 0], "low_threshold": 0.3, "high_threshold": 0.6},
625
+ }
626
+ return ["8404", 0]
627
+
628
+
629
+ def video_model(agent: Agent, task: str) -> catalog.MediaModel:
630
+ """The video model for a job: the chosen one, or the first that does what the job needs."""
631
+ chosen = current(agent, "video")
632
+ if not task or task in chosen.tasks:
633
+ return chosen
634
+ model = catalog.load().for_task("video", task)
635
+ if model is None:
636
+ raise MediaError(f"None of lcode's video models does {WHY.get(task, task)} yet.")
637
+ agent.say(f"{model.name} makes this one ({WHY.get(task, task)}).")
638
+ return model
639
+
640
+
641
+ def continue_clip(graph: dict, latent: str, clip_name: str, length: int) -> None:
642
+ """Extending a clip: start from its last frame, and join the new frames (without that first one) after it."""
643
+ graph["8200"] = {"class_type": "LoadVideo", "inputs": {"file": clip_name}}
644
+ graph["8201"] = {"class_type": "GetVideoComponents", "inputs": {"video": ["8200", 0]}}
645
+ graph["8202"] = {"class_type": "ImageFromBatch", "inputs": {"image": ["8201", 0], "batch_index": -1, "length": 1}}
646
+ graph[latent]["inputs"]["start_image"] = ["8202", 0]
647
+ video = edits.node_of(graph, "CreateVideo")
648
+ decoded = graph[video]["inputs"]["images"]
649
+ graph["8203"] = {"class_type": "ImageFromBatch", "inputs": {"image": decoded, "batch_index": 1, "length": length}}
650
+ graph["8204"] = {"class_type": "ImageBatch", "inputs": {"image1": ["8201", 0], "image2": ["8203", 0]}}
651
+ graph[video]["inputs"]["images"] = ["8204", 0]
652
+
653
+
654
+ VIDEO_TYPES = (".mp4", ".webm", ".mkv", ".mov")
655
+ TOOL_NAMES = {"upscale": "upscaled", "remove-background": "nobg", "interpolate": "smooth", "sound": "sound"}
656
+
657
+
658
+ def is_video(path: Path) -> bool:
659
+ return path.suffix.lower() in VIDEO_TYPES
660
+
661
+
662
+ def clip_info(path: Path) -> dict:
663
+ """A clip's fps, seconds, frames, width and height: from lcode's JSON next to it, else its MP4 header."""
664
+ info = {"fps": 24.0, "seconds": 0.0, "frames": 0, "width": 0, "height": 0}
665
+ try:
666
+ meta = json.loads(path.with_suffix(".json").read_text())
667
+ info.update({k: meta[k] for k in info if isinstance(meta.get(k), (int, float))})
668
+ except (OSError, ValueError):
669
+ pass
670
+ if not info["seconds"]:
671
+ info["seconds"] = mp4_seconds(path)
672
+ if not info["frames"] and info["seconds"]:
673
+ info["frames"] = round(info["seconds"] * info["fps"]) + 1
674
+ return info
675
+
676
+
677
+ def mp4_seconds(path: Path) -> float:
678
+ """An MP4's length from its movie header (mvhd), or 0."""
679
+ try:
680
+ data = path.read_bytes()
681
+ except OSError:
682
+ return 0.0
683
+ i = data.find(b"mvhd")
684
+ if i < 4:
685
+ return 0.0
686
+ version = data[i + 4]
687
+ if version == 1:
688
+ scale, duration = struct.unpack(">IQ", data[i + 24 : i + 36])
689
+ else:
690
+ scale, duration = struct.unpack(">II", data[i + 16 : i + 24])
691
+ return duration / scale if scale else 0.0
692
+
693
+
535
694
  def apply_tool(
536
695
  agent: Agent,
537
696
  task: str,
@@ -539,27 +698,52 @@ def apply_tool(
539
698
  scale: int = 2,
540
699
  cancelled: Callable[[], bool] = lambda: False,
541
700
  ask: Callable[[str], bool] | None = None,
701
+ prompt: str = "",
542
702
  ) -> Made:
543
- """/upscale and /nobg: a tool model on one image (no seed, no prompt)."""
703
+ """A tool model on one image or clip: /upscale (both), /nobg (pictures), /smooth and /sound (clips)."""
704
+ video = is_video(source)
705
+ if task == "remove-background" and video:
706
+ raise MediaError("/nobg works on pictures.")
707
+ if task in ("interpolate", "sound") and not video:
708
+ raise MediaError(f"/{'smooth' if task == 'interpolate' else 'sound'} works on clips.")
709
+ if task == "sound" and not prompt.strip():
710
+ raise MediaError("Say what it should sound like: /sound 4 waves and seagulls")
544
711
  server = prepare(agent, ask, cancelled)
545
712
  model = catalog.load().tool(task)
546
713
  files = ensure_installed(agent, model, server, ask)
547
- workflow = comfy.load_workflow(model.workflow)
714
+ workflow = comfy.load_workflow(model.video_workflow if video and model.video_workflow else model.workflow)
548
715
  try:
549
716
  name = server.upload(source)
550
- width, height = edits.image_size(source)
717
+ if video:
718
+ info = clip_info(source)
719
+ width, height = info["width"] or 864, info["height"] or 480
720
+ else:
721
+ width, height = edits.image_size(source)
551
722
  except (comfy.ComfyError, OSError, edits.EditError) as e:
552
- raise MediaError(f"Couldn't hand the image to ComfyUI: {e}") from e
553
- values = {**workflow.defaults, **files, "image": name}
723
+ raise MediaError(f"Couldn't hand the file to ComfyUI: {e}") from e
724
+ values = {**workflow.defaults, **files, ("video" if video else "image"): name}
725
+ seed = 0
726
+ if video:
727
+ values["fps"] = info["fps"]
554
728
  if task == "upscale":
555
729
  values["scale_by"] = scale / 4 # Real-ESRGAN makes 4 times the size; scaled back for 2
556
730
  width, height = width * scale, height * scale
731
+ elif task == "interpolate":
732
+ values["multiplier"], values["fps"] = scale, info["fps"] * scale
733
+ elif task == "sound":
734
+ seed = random.randrange(2**32)
735
+ values.update({"prompt": prompt.strip(), "seed": seed, "seconds": max(1.0, info["seconds"])})
557
736
  graph = comfy.fill(workflow.graph, values)
558
737
  add_thumbnail(graph, width, height)
559
- what = f"upscaled {scale}×" if task == "upscale" else "background removed"
560
- prompt = f"{what}: {shown(agent, source)}"
738
+ what = {
739
+ "upscale": f"upscaled {scale}×",
740
+ "remove-background": "background removed",
741
+ "interpolate": f"{scale}× the frames",
742
+ "sound": f"sound: {prompt.strip()}",
743
+ }[task]
744
+ label = f"{what} ({shown(agent, source)})"
561
745
  meta = {
562
- "prompt": prompt,
746
+ "prompt": label,
563
747
  "model": model.name,
564
748
  "model_key": model.key,
565
749
  "workflow": workflow.key,
@@ -567,8 +751,10 @@ def apply_tool(
567
751
  "files": files,
568
752
  "created": time.strftime("%Y-%m-%dT%H:%M:%S%z"),
569
753
  }
570
- suffix = f"upscaled-{scale}x" if task == "upscale" else "nobg"
571
- plan = Plan(model, workflow, graph, meta, prompt, 0, imageopts.Options(), task, [str(source)], {},
754
+ if video:
755
+ meta.update({"fps": values["fps"], "seconds": info["seconds"], "width": width, "height": height})
756
+ suffix = {"upscale": f"upscaled-{scale}x", "interpolate": f"smooth-{scale}x"}.get(task, TOOL_NAMES[task])
757
+ plan = Plan(model, workflow, graph, meta, label, seed, imageopts.Options(), task, [str(source)], {},
572
758
  f"{source.stem}-{suffix}") # fmt: skip
573
759
  return run_plan(agent, server, plan, cancelled, "")
574
760
 
lcode/media.toml CHANGED
@@ -101,6 +101,7 @@ publisher = "Xintao Wang et al."
101
101
  license = "BSD-3-Clause"
102
102
  tasks = ["upscale"]
103
103
  workflow = "upscale-esrgan"
104
+ video_workflow = "upscale-video-esrgan"
104
105
  files = { model = "realesrgan-x4" }
105
106
  notes = "/upscale: 2× or 4× the pixels"
106
107
 
@@ -146,3 +147,110 @@ measured = "5 s clip: 100 s fast, 150 s balanced (864×480), 10.5 min best (1280
146
147
  notes = "5 s at 24 fps, up to 1280×704; text or a start image"
147
148
  quality = { fast = [12, 0.4], balanced = [20, 0.4], best = [30, 0.859] }
148
149
  negative = true
150
+
151
+ [files.wan22-fun-inp-5b]
152
+ folder = "diffusion_models"
153
+ name = "wan2.2_fun_inpaint_5B_bf16.safetensors"
154
+ url = "https://huggingface.co/Comfy-Org/Wan_2.2_ComfyUI_Repackaged/resolve/main/split_files/diffusion_models/wan2.2_fun_inpaint_5B_bf16.safetensors"
155
+ gb = 10.00
156
+
157
+ [files.wan21-fun-camera-1-3b]
158
+ folder = "diffusion_models"
159
+ name = "wan2.1_fun_camera_v1.1_1.3B_bf16.safetensors"
160
+ url = "https://huggingface.co/Comfy-Org/Wan_2.1_ComfyUI_repackaged/resolve/main/split_files/diffusion_models/wan2.1_fun_camera_v1.1_1.3B_bf16.safetensors"
161
+ gb = 3.23
162
+
163
+ [files.clip-vision-h]
164
+ folder = "clip_vision"
165
+ name = "clip_vision_h.safetensors"
166
+ url = "https://huggingface.co/Comfy-Org/Wan_2.1_ComfyUI_repackaged/resolve/main/split_files/clip_vision/clip_vision_h.safetensors"
167
+ gb = 1.26
168
+
169
+ [files.wan21-vae]
170
+ folder = "vae"
171
+ name = "wan_2.1_vae.safetensors"
172
+ url = "https://huggingface.co/Comfy-Org/Wan_2.1_ComfyUI_repackaged/resolve/main/split_files/vae/wan_2.1_vae.safetensors"
173
+ gb = 0.25
174
+
175
+ [models.wan22-fun-inp-5b]
176
+ name = "Wan 2.2 Fun InP 5B"
177
+ mode = "video"
178
+ publisher = "Alibaba PAI"
179
+ license = "Apache 2.0"
180
+ tasks = ["first-last-frame"]
181
+ workflow = "wan22-fun-inp-5b"
182
+ files = { model = "wan22-fun-inp-5b", text_encoder = "umt5-xxl-fp8", vae = "wan22-vae" }
183
+ measured = "3 s clip, fast: 62 s (864×480) on an RTX 4080 Laptop, 12 GB"
184
+ notes = "a clip from a first frame to a last frame: @start.png @end.png"
185
+ quality = { fast = [12, 0.4], balanced = [20, 0.4], best = [30, 0.859] }
186
+ negative = true
187
+
188
+ [models.wan21-fun-camera-1-3b]
189
+ name = "Wan 2.1 Fun Camera 1.3B"
190
+ mode = "video"
191
+ publisher = "Alibaba PAI"
192
+ license = "Apache 2.0"
193
+ tasks = ["camera"]
194
+ workflow = "wan21-fun-camera"
195
+ files = { model = "wan21-fun-camera-1-3b", text_encoder = "umt5-xxl-fp8", vae = "wan21-vae", clip_vision = "clip-vision-h" }
196
+ measured = "3 s clip (49 frames, 832×480): 115 s on an RTX 4080 Laptop, 12 GB"
197
+ notes = "camera moves (--camera pan-left, zoom-in, …), small and fast, 16 fps"
198
+ quality = { fast = [12, 0.38], balanced = [20, 0.38], best = [30, 0.38] }
199
+ negative = true
200
+
201
+ [files.wan21-vace-1-3b]
202
+ folder = "diffusion_models"
203
+ name = "wan2.1_vace_1.3B_fp16.safetensors"
204
+ url = "https://huggingface.co/Comfy-Org/Wan_2.1_ComfyUI_repackaged/resolve/main/split_files/diffusion_models/wan2.1_vace_1.3B_fp16.safetensors"
205
+ gb = 4.31
206
+
207
+ [files.film-net]
208
+ folder = "frame_interpolation"
209
+ name = "film_net_fp16.safetensors"
210
+ url = "https://huggingface.co/Comfy-Org/frame_interpolation/resolve/main/frame_interpolation/film_net_fp16.safetensors"
211
+ gb = 0.07
212
+
213
+ [files.stable-audio-open]
214
+ folder = "checkpoints"
215
+ name = "stable-audio-open-1.0.safetensors"
216
+ url = "https://huggingface.co/Comfy-Org/stable-audio-open-1.0_repackaged/resolve/main/stable-audio-open-1.0.safetensors"
217
+ gb = 4.85
218
+
219
+ [files.t5-base]
220
+ folder = "text_encoders"
221
+ name = "t5-base.safetensors"
222
+ url = "https://huggingface.co/ComfyUI-Wiki/t5-base/resolve/main/t5-base.safetensors"
223
+ gb = 0.89
224
+
225
+ [models.wan21-vace-1-3b]
226
+ name = "Wan 2.1 VACE 1.3B"
227
+ mode = "video"
228
+ publisher = "Alibaba (Wan-AI)"
229
+ license = "Apache 2.0"
230
+ tasks = ["references", "restyle"]
231
+ workflow = "wan21-vace"
232
+ files = { model = "wan21-vace-1-3b", text_encoder = "umt5-xxl-fp8", vae = "wan21-vae" }
233
+ measured = "3 s clip from references (832×480): 190 s; restyling 3 s: 320 s, on an RTX 4080 Laptop, 12 GB"
234
+ notes = "clips that follow reference pictures (--ref), or restyle a clip (/restyle)"
235
+ quality = { fast = [12, 0.38], balanced = [20, 0.38], best = [30, 0.38] }
236
+ negative = true
237
+
238
+ [models.film]
239
+ name = "FILM"
240
+ mode = "tool"
241
+ publisher = "Google Research"
242
+ license = "Apache 2.0"
243
+ tasks = ["interpolate"]
244
+ workflow = "smooth-film"
245
+ files = { model = "film-net" }
246
+ notes = "/smooth: twice the frames per second"
247
+
248
+ [models.stable-audio-open]
249
+ name = "Stable Audio Open 1.0"
250
+ mode = "tool"
251
+ publisher = "Stability AI"
252
+ license = "Stability AI Community License"
253
+ tasks = ["sound"]
254
+ workflow = "sound-stable-audio"
255
+ files = { model = "stable-audio-open", text_encoder = "t5-base" }
256
+ notes = "/sound: sound effects and ambience for a clip, up to 47 s"
lcode/media_catalog.py CHANGED
@@ -71,6 +71,7 @@ class MediaModel:
71
71
  quality: dict[str, tuple[int, float]] = field(default_factory=dict, hash=False) # preset -> (steps, megapixels)
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
+ video_workflow: str = "" # a tool's workflow for clips, when it works on them too (upscaling)
74
75
 
75
76
  def preset(self, quality: str) -> tuple[int | None, float]:
76
77
  """(steps, megapixels) for a quality preset: None steps keeps the workflow's."""
@@ -112,6 +113,10 @@ class Catalog:
112
113
  def for_mode(self, mode: str) -> list[MediaModel]:
113
114
  return [m for m in self.models.values() if m.mode == mode]
114
115
 
116
+ 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, image-to-video…)."""
118
+ return next((m for m in self.for_mode(mode) if task in m.tasks), None)
119
+
115
120
  def tool(self, task: str) -> MediaModel:
116
121
  """The tool for a task (upscale, remove-background)."""
117
122
  return next(m for m in self.models.values() if m.mode == "tool" and task in m.tasks)
@@ -159,6 +164,7 @@ def load() -> Catalog:
159
164
  {name: (int(v[0]), float(v[1])) for name, v in (m.get("quality") or {}).items()},
160
165
  bool(m.get("negative", False)),
161
166
  m.get("edit", ""),
167
+ m.get("video_workflow", ""),
162
168
  )
163
169
  return Catalog(files, models)
164
170
 
lcode/repl.py CHANGED
@@ -86,10 +86,13 @@ COMMANDS = {
86
86
  "/open": "Open an image in your viewer, e.g. /open 3 (default: the last)",
87
87
  "/edit": "Image mode: change an image by instruction, e.g. /edit 3 make the sky purple (@photo.png: references)",
88
88
  "/use": "Image mode: images the next requests follow, e.g. /use 3 or /use photo.png (/use off)",
89
- "/extend": "Image mode: outpaint an image to a shape or by sides, e.g. /extend 3 --ar 16:9 (or --left 256)",
90
- "/upscale": "Image mode: 2 or 4 times the pixels, e.g. /upscale 3 4",
89
+ "/extend": "Outpaint an image (/extend 3 --ar 16:9), or continue a clip in video mode (/extend 4 --seconds 3)",
90
+ "/upscale": "2 or 4 times the pixels of an image or a clip, e.g. /upscale 3 4",
91
91
  "/nobg": "Image mode: remove the background (a transparent PNG), e.g. /nobg 3",
92
92
  "/animate": "Image mode: make a video starting from an image, e.g. /animate 3 the waves roll in (video mode)",
93
+ "/smooth": "Video mode: 2 or 4 times the frames (smoother motion), e.g. /smooth 4",
94
+ "/sound": "Video mode: add sound to a clip, e.g. /sound 4 waves and seagulls",
95
+ "/restyle": "Video mode: the same clip in a new look, e.g. /restyle 4 as a watercolor painting",
93
96
  "/play": "Play a video in your player, e.g. /play 4 (default: the last)",
94
97
  "/cd": "Change the working directory",
95
98
  "/todos": "Show the current todo list",
@@ -1404,9 +1407,12 @@ def respond(agent: Agent, line: str) -> None:
1404
1407
 
1405
1408
  IMAGE_COMMANDS = (
1406
1409
  "/options", "/again", "/vary", "/gallery", "/open", "/play", "/edit", "/use", "/extend", "/upscale", "/nobg",
1407
- "/animate",
1410
+ "/animate", "/smooth", "/sound", "/restyle",
1408
1411
  ) # fmt: skip
1409
- VIDEO_TOO = ("/options", "/again", "/vary", "/gallery", "/open", "/play", "/use") # what video mode shares
1412
+ VIDEO_TOO = (
1413
+ "/options", "/again", "/vary", "/gallery", "/open", "/play", "/use", "/extend", "/upscale", "/smooth", "/sound",
1414
+ "/restyle",
1415
+ ) # what video mode has # fmt: skip
1410
1416
  NUMBER = re.compile(r"^#?(\d+)$")
1411
1417
 
1412
1418
 
@@ -1464,7 +1470,8 @@ def image_command(agent: Agent, cmd: str, arg: str) -> None:
1464
1470
  return
1465
1471
  if cmd == "/vary":
1466
1472
  job = dict(entry.get("job") or {"kind": "image", "sources": [], "mask": None, "pads": None})
1467
- if entry.get("kind") in ("upscale", "remove-background") or job["kind"] not in ("image", "edit", "video"):
1473
+ tools = ("upscale", "remove-background", "interpolate", "sound")
1474
+ if entry.get("kind") in tools or job["kind"] not in ("image", "edit", "video"):
1468
1475
  c.print(f"[yellow]#{entry['n']} is {escape(entry['prompt'])}: /vary the image it came from.[/]")
1469
1476
  return
1470
1477
  job["prompt"] = entry["prompt"] if job["kind"] == "image" else job.get("prompt", entry["prompt"])
@@ -1495,6 +1502,17 @@ def image_command(agent: Agent, cmd: str, arg: str) -> None:
1495
1502
  "pads": None, "keep_shape": "--ar" not in rest and "--size" not in rest} # fmt: skip
1496
1503
  make_image(agent, run=lambda cancel, ask: media.redo(agent, job, cancel, ask))
1497
1504
  return
1505
+ if cmd == "/extend" and video:
1506
+ if edits.is_image(source):
1507
+ c.print(f"[yellow]#{entry['n']} is a picture: /animate it, or /extend a clip.[/]")
1508
+ return
1509
+ text, options = imageopts.parse(rest, imageopts.replace_seed(agent.image_options, n=1))
1510
+ job = {"kind": "video", "prompt": text or entry["prompt"], "options": options, "sources": [],
1511
+ "mask": None, "pads": None, "keep_shape": True, "extend": str(source),
1512
+ "size": [entry["width"], entry["height"]]} # fmt: skip
1513
+ c.print(f"[dim]Continuing #{entry['n']} from its last frame, {options.seconds:g} s more.[/]")
1514
+ make_image(agent, run=lambda cancel, ask: media.redo(agent, job, cancel, ask))
1515
+ return
1498
1516
  if cmd == "/extend":
1499
1517
  width, height = edits.image_size(source)
1500
1518
  pads, text = edits.parse_extend(rest, width, height)
@@ -1514,6 +1532,30 @@ def image_command(agent: Agent, cmd: str, arg: str) -> None:
1514
1532
  agent, run=lambda cancel, ask: media.apply_tool(agent, "upscale", source, int(scale), cancel, ask)
1515
1533
  )
1516
1534
  return
1535
+ if cmd == "/smooth":
1536
+ times = int(rest.strip().lower().rstrip("x×") or "2")
1537
+ if times not in (2, 4):
1538
+ c.print("[yellow]/smooth makes 2 or 4 times the frames: /smooth 4 2[/]")
1539
+ return
1540
+ make_image(
1541
+ agent, run=lambda cancel, ask: media.apply_tool(agent, "interpolate", source, times, cancel, ask)
1542
+ )
1543
+ return
1544
+ if cmd == "/sound":
1545
+ make_image(agent, run=lambda cancel, ask: media.apply_tool(agent, "sound", source, 1, cancel, ask, rest))
1546
+ return
1547
+ if cmd == "/restyle":
1548
+ if not media.is_video(source):
1549
+ c.print("[yellow]/restyle works on clips: /restyle 4 as a watercolor painting.[/]")
1550
+ return
1551
+ text, options = imageopts.parse(rest, imageopts.replace_seed(agent.image_options, n=1))
1552
+ if not text:
1553
+ c.print("[yellow]Say the new look: /restyle 4 as a watercolor painting[/]")
1554
+ return
1555
+ job = {"kind": "video", "prompt": text, "options": options, "sources": [], "mask": None, "pads": None,
1556
+ "keep_shape": True, "restyle": str(source), "seconds_given": "--seconds" in rest} # fmt: skip
1557
+ make_image(agent, run=lambda cancel, ask: media.redo(agent, job, cancel, ask))
1558
+ return
1517
1559
  if cmd == "/nobg":
1518
1560
  make_image(
1519
1561
  agent, run=lambda cancel, ask: media.apply_tool(agent, "remove-background", source, 2, cancel, ask)