amisima commited on
Commit
37efa91
·
verified ·
1 Parent(s): 65527a1

Upload 2 files

Browse files
Files changed (2) hide show
  1. app.py +38 -2
  2. lora_library.py +130 -1
app.py CHANGED
@@ -2277,10 +2277,46 @@ with gr.Blocks(delete_cache=(3600, 86400)) as demo:
2277
 
2278
  with gr.Accordion("💡 Tips", open=False):
2279
  gr.Markdown(
 
2280
  "- Pause the video on any frame, then hit **Use current frame** to continue the shot from there.\n"
 
 
 
 
2281
  "- 6 steps + UniPC is the sweet spot; more steps rarely helps this model.\n"
2282
- "- Higher fluidity only interpolates — it adds smoothness, not new content.\n"
2283
- "- Keep **Randomize seed** on while exploring, then lock a seed you like."
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
2284
  )
2285
 
2286
  ui_inputs = [
 
2277
 
2278
  with gr.Accordion("💡 Tips", open=False):
2279
  gr.Markdown(
2280
+ "**Workflow**\n"
2281
  "- Pause the video on any frame, then hit **Use current frame** to continue the shot from there.\n"
2282
+ "- Keep **Randomize seed** on while exploring, then lock a seed you like.\n"
2283
+ "- **Loop the clip** and **Stitch clips** both run on the CPU and cost nothing "
2284
+ "from your ZeroGPU allowance — use them freely.\n\n"
2285
+ "**Steps & speed**\n"
2286
  "- 6 steps + UniPC is the sweet spot; more steps rarely helps this model.\n"
2287
+ "- A **Speed preset** sets steps, flow shift and scheduler together. Pick one "
2288
+ "first, then adjust individual sliders only if something looks off.\n"
2289
+ "- **Guidance** above 1 turns on classifier-free guidance: it uses roughly "
2290
+ "twice the GPU per step and takes proportionally longer. Leave both at 1 "
2291
+ "unless the prompt is being ignored.\n"
2292
+ "- The **Negative prompt** is only read when a Guidance slider is above 1. "
2293
+ "At guidance 1 it does nothing.\n\n"
2294
+ "**Duration & fluidity**\n"
2295
+ "- Duration is clamped to the model's frame range, so the slider may not land "
2296
+ "exactly where you put it. 3–3.5 s is the comfortable range.\n"
2297
+ "- **Fluidity** interpolates extra frames after generation — it adds smoothness, "
2298
+ "not new content. Motion that stutters at the base rate will still stutter, "
2299
+ "just more smoothly. It also makes the file bigger.\n"
2300
+ "- For anything longer than one clip, generate short clips and stitch them "
2301
+ "rather than pushing duration up.\n\n"
2302
+ "**Stitching**\n"
2303
+ "- Clips are concatenated end to end, everything scaled to the first clip's "
2304
+ "frame. There is no crossfade, so keep the same aspect and fluidity across a "
2305
+ "chain or the joins will be visible.\n"
2306
+ "- **⚡ Add every new generation automatically** also catches "
2307
+ "**➕ Continue the scene**, so a chain builds itself as you go.\n"
2308
+ "- Generate the whole chain first, then stitch once at the end.\n\n"
2309
+ "**Images & aspect**\n"
2310
+ "- The checkpoint accepts 480–832 px per side, so anything past about 1.73:1 "
2311
+ "has to give: **Crop to fit** cuts the middle out, **Keep it all** adds black "
2312
+ "bars. Crop looks better unless something important sits near an edge.\n"
2313
+ "- Cropping happens after upload, so pre-cropping your image to roughly the "
2314
+ "render aspect is the only way to control exactly what survives.\n\n"
2315
+ "**Loras**\n"
2316
+ "- Custom loras download on first use, which happens inside GPU time — run one "
2317
+ "throwaway generation after adding a new lora so the next takes are clean.\n"
2318
+ "- **High** and **Low** strength apply to the two noise stages. If a lora is "
2319
+ "overpowering the composition, drop High first and leave Low alone."
2320
  )
2321
 
2322
  ui_inputs = [
lora_library.py CHANGED
@@ -52,6 +52,98 @@ _OWNER_JS = """
52
  """
53
 
54
  _CIVITAI_DOWNLOAD_RE = re.compile(r"/api/download/models/(\d+)")
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
55
  _HF_URL_RE = re.compile(r"^https?://(?:www\.)?huggingface\.co/(?:datasets/)?([^/\s]+)/([^/\s?#]+)")
56
 
57
 
@@ -218,6 +310,7 @@ def _clean(data) -> dict:
218
  out[section].append({
219
  "name": str(item.get("name") or "").strip() or url.split("/")[-1][:60],
220
  "url": url,
 
221
  "trigger": str(item.get("trigger") or "").strip(),
222
  "strength": strength,
223
  "high": str(item.get("high") or "").strip(),
@@ -514,6 +607,12 @@ def lookup_link(url: str):
514
  model_name = (data.get("model") or {}).get("name") or ""
515
  version_name = data.get("name") or ""
516
  label = f"{model_name} · {version_name}".strip(" ·")
 
 
 
 
 
 
517
  words = [w for w in (data.get("trainedWords") or []) if w]
518
  return label, ", ".join(words[:8])
519
  return "", ""
@@ -628,10 +727,12 @@ def library_tab(lora_box=None, prompt_box=None, lora_slots=None, scale_slots=Non
628
  choices=_labels(library["normal"]), value=[],
629
  label="ordinary", interactive=True,
630
  )
 
631
  nsfw_pick = gr.CheckboxGroup(
632
  choices=_labels(library["nsfw"]), value=[],
633
  label="nsfw", interactive=True,
634
  )
 
635
 
636
  with gr.Row():
637
  add_button = gr.Button(
@@ -640,6 +741,7 @@ def library_tab(lora_box=None, prompt_box=None, lora_slots=None, scale_slots=Non
640
  variant="primary",
641
  )
642
  refresh_button = gr.Button("🔄 refresh")
 
643
 
644
  use_triggers = gr.Checkbox(
645
  value=True, label="append the trigger words to the prompt",
@@ -694,6 +796,8 @@ def library_tab(lora_box=None, prompt_box=None, lora_slots=None, scale_slots=Non
694
  gr.update(choices=nsfw, value=[]),
695
  message,
696
  storage_note(),
 
 
697
  )
698
 
699
  def _refresh(owner=""):
@@ -702,10 +806,34 @@ def library_tab(lora_box=None, prompt_box=None, lora_slots=None, scale_slots=Non
702
  f"{len(data['nsfw'])} nsfw", owner)
703
 
704
  refresh_targets = [state, normal_labels, nsfw_labels, normal_pick, nsfw_pick,
705
- status, storage_line]
706
  refresh_button.click(_refresh, [owner_box], refresh_targets)
707
  owner_box.change(_refresh, [owner_box], refresh_targets)
708
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
709
  lookup_button.click(lambda url: lookup_link(url), new_url, [new_name, new_trigger])
710
 
711
  def _save(data, url, name, trigger, strength, nsfw, high="", low="",
@@ -733,6 +861,7 @@ def library_tab(lora_box=None, prompt_box=None, lora_slots=None, scale_slots=Non
733
  data["nsfw" if nsfw else "normal"].append({
734
  "name": name.strip(),
735
  "url": url,
 
736
  "trigger": (trigger or "").strip(),
737
  "strength": strength,
738
  "high": (high or "").strip(),
 
52
  """
53
 
54
  _CIVITAI_DOWNLOAD_RE = re.compile(r"/api/download/models/(\d+)")
55
+ _CIVITAI_PAGE_RE = re.compile(r"civitai\.(?:com|red)/models/(\d+)")
56
+ _CIVITAI_HOST_RE = re.compile(r"https?://(?:www\.)?(civitai\.(?:com|red))")
57
+
58
+ # version id -> model page url. Filled in as entries are looked at so a library
59
+ # of 50 loras does not hit the API 50 times on every refresh.
60
+ _CIVITAI_PAGE_CACHE: dict[str, str] = {}
61
+
62
+
63
+ def civitai_page_url(url: str, resolve: bool = True) -> str:
64
+ """Model page for a civitai link.
65
+
66
+ A download link (`/api/download/models/<versionId>`) says nothing about
67
+ which model it belongs to, so the version has to be resolved through the
68
+ API to get `modelId`. With `resolve=False` only links that are already a
69
+ model page, or that were resolved earlier, come back — so redrawing a big
70
+ library never blocks on the network. Returns "" when unknown.
71
+ """
72
+ url = (url or "").strip().strip('"').strip("'")
73
+ if not url:
74
+ return ""
75
+
76
+ host_match = _CIVITAI_HOST_RE.match(url)
77
+ if not host_match:
78
+ return ""
79
+ host = host_match.group(1)
80
+
81
+ # Already a model page.
82
+ if _CIVITAI_PAGE_RE.search(url):
83
+ return url
84
+
85
+ match = _CIVITAI_DOWNLOAD_RE.search(url)
86
+ if not match:
87
+ return ""
88
+ version_id = match.group(1)
89
+ if version_id in _CIVITAI_PAGE_CACHE:
90
+ return _CIVITAI_PAGE_CACHE[version_id]
91
+ if not resolve:
92
+ return ""
93
+
94
+ headers = {"User-Agent": "Mozilla/5.0"}
95
+ token = os.environ.get("CIVITAI_TOKEN", "").strip()
96
+ if token:
97
+ headers["Authorization"] = f"Bearer {token}"
98
+ for api_host in (host, "civitai.com", "civitai.red"):
99
+ try:
100
+ response = requests.get(
101
+ f"https://{api_host}/api/v1/model-versions/{version_id}",
102
+ headers=headers, timeout=15,
103
+ )
104
+ response.raise_for_status()
105
+ data = response.json()
106
+ except Exception: # noqa: BLE001
107
+ continue
108
+ model_id = data.get("modelId") or (data.get("model") or {}).get("id")
109
+ if not model_id:
110
+ continue
111
+ page = f"https://{host}/models/{model_id}?modelVersionId={version_id}"
112
+ _CIVITAI_PAGE_CACHE[version_id] = page
113
+ return page
114
+
115
+ _CIVITAI_PAGE_CACHE[version_id] = ""
116
+ return ""
117
+
118
+
119
+ def _entry_page_url(item: dict, resolve: bool = False) -> str:
120
+ """Model page for a library entry, preferring the one saved with it."""
121
+ saved = (item.get("page") or "").strip()
122
+ if saved:
123
+ return saved
124
+ return civitai_page_url(item.get("url") or "", resolve=resolve)
125
+
126
+
127
+ def _links_markdown(entries: list[dict], heading: str, resolve: bool = False) -> str:
128
+ """A numbered list of 🔗 links matching the tick boxes above it."""
129
+ rows, missing = [], 0
130
+ for index, item in enumerate(entries, start=1):
131
+ page = _entry_page_url(item, resolve=resolve)
132
+ name = str(item.get("name") or "").strip() or f"lora {index}"
133
+ if page:
134
+ rows.append(f"{index}. [🔗 {name}]({page})")
135
+ else:
136
+ rows.append(f"{index}. {name}")
137
+ missing += 1
138
+ if not rows:
139
+ return ""
140
+ text = f"**{heading} — open the model page on civitai** \n" + " \n".join(rows)
141
+ if missing:
142
+ text += (
143
+ f" \n<sub>{missing} without a model page yet — press "
144
+ "**🔗 fetch model links**.</sub>"
145
+ )
146
+ return text
147
  _HF_URL_RE = re.compile(r"^https?://(?:www\.)?huggingface\.co/(?:datasets/)?([^/\s]+)/([^/\s?#]+)")
148
 
149
 
 
310
  out[section].append({
311
  "name": str(item.get("name") or "").strip() or url.split("/")[-1][:60],
312
  "url": url,
313
+ "page": str(item.get("page") or "").strip(),
314
  "trigger": str(item.get("trigger") or "").strip(),
315
  "strength": strength,
316
  "high": str(item.get("high") or "").strip(),
 
607
  model_name = (data.get("model") or {}).get("name") or ""
608
  version_name = data.get("name") or ""
609
  label = f"{model_name} · {version_name}".strip(" ·")
610
+ model_id = data.get("modelId") or (data.get("model") or {}).get("id")
611
+ if model_id:
612
+ page_host = "civitai.red" if "civitai.red" in url else "civitai.com"
613
+ _CIVITAI_PAGE_CACHE[match.group(1)] = (
614
+ f"https://{page_host}/models/{model_id}?modelVersionId={match.group(1)}"
615
+ )
616
  words = [w for w in (data.get("trainedWords") or []) if w]
617
  return label, ", ".join(words[:8])
618
  return "", ""
 
727
  choices=_labels(library["normal"]), value=[],
728
  label="ordinary", interactive=True,
729
  )
730
+ normal_links = gr.Markdown(_links_markdown(library["normal"], "ordinary"))
731
  nsfw_pick = gr.CheckboxGroup(
732
  choices=_labels(library["nsfw"]), value=[],
733
  label="nsfw", interactive=True,
734
  )
735
+ nsfw_links = gr.Markdown(_links_markdown(library["nsfw"], "nsfw"))
736
 
737
  with gr.Row():
738
  add_button = gr.Button(
 
741
  variant="primary",
742
  )
743
  refresh_button = gr.Button("🔄 refresh")
744
+ links_button = gr.Button("🔗 fetch model links")
745
 
746
  use_triggers = gr.Checkbox(
747
  value=True, label="append the trigger words to the prompt",
 
796
  gr.update(choices=nsfw, value=[]),
797
  message,
798
  storage_note(),
799
+ _links_markdown(data["normal"], "ordinary"),
800
+ _links_markdown(data["nsfw"], "nsfw"),
801
  )
802
 
803
  def _refresh(owner=""):
 
806
  f"{len(data['nsfw'])} nsfw", owner)
807
 
808
  refresh_targets = [state, normal_labels, nsfw_labels, normal_pick, nsfw_pick,
809
+ status, storage_line, normal_links, nsfw_links]
810
  refresh_button.click(_refresh, [owner_box], refresh_targets)
811
  owner_box.change(_refresh, [owner_box], refresh_targets)
812
 
813
+ def _fetch_links(owner=""):
814
+ """Resolve every download link to its model page and write the
815
+ result back, so it is looked up once and then kept."""
816
+ data = load_library()
817
+ resolved = 0
818
+ for section in ("normal", "nsfw"):
819
+ for item in data[section]:
820
+ if (item.get("page") or "").strip():
821
+ continue
822
+ page = civitai_page_url(item.get("url") or "", resolve=True)
823
+ if page:
824
+ item["page"] = page
825
+ resolved += 1
826
+ message = f"model links found: {resolved}" if resolved else "nothing new to look up."
827
+ if resolved:
828
+ error = save_library(data)
829
+ if error:
830
+ message = f"{message} (not saved — {error})"
831
+ else:
832
+ data = load_library()
833
+ return _pack(data, message, owner)
834
+
835
+ links_button.click(_fetch_links, [owner_box], refresh_targets)
836
+
837
  lookup_button.click(lambda url: lookup_link(url), new_url, [new_name, new_trigger])
838
 
839
  def _save(data, url, name, trigger, strength, nsfw, high="", low="",
 
861
  data["nsfw" if nsfw else "normal"].append({
862
  "name": name.strip(),
863
  "url": url,
864
+ "page": civitai_page_url(url),
865
  "trigger": (trigger or "").strip(),
866
  "strength": strength,
867
  "high": (high or "").strip(),