waveshaker commited on
Commit
b16fda7
·
verified ·
1 Parent(s): e26010c

Update app.py

Browse files
Files changed (1) hide show
  1. app.py +435 -401
app.py CHANGED
@@ -1,6 +1,5 @@
1
  """Universal Lora Studio: Comfy Render Backend + FastAPI Data Backend + Native Static Frontend + ZeroGPU Token Passthrough + Config Driven"""
2
  """Comfy Version: c1eece62cbf1805d4f64286d7f5592e6a215e6ba"""
3
- "6e66328f68617e66298cb7018923759756466f8d@test"
4
  import base64
5
  import asyncio
6
  import glob
@@ -32,14 +31,15 @@ import uvicorn
32
  import threading
33
 
34
  from model_config import MODEL_CONFIG
 
 
35
  # ⚠️ 必须在 load_char_loras_from_repo() 之前定义 —— 它内部要读这个常量。
36
  # 放在文件后面的"静态挂载"段里会导致启动首次扫描 NameError,触发词全空且被 300s 缓存锁住。
37
  LORA_META_URL = "https://huggingface.co/spaces/waveshaker/loras_gallery/resolve/main/models.json"
38
 
39
 
40
-
41
  # ==========================================================================
42
- # 🛠️ Environment Patches & Global Paths
43
  # ==========================================================================
44
 
45
  import builtins
@@ -85,7 +85,7 @@ OUTPUT = COMFY / "output"
85
  COMFY_COMMIT = "c1eece62cbf1805d4f64286d7f5592e6a215e6ba"
86
 
87
  # ==========================================================================
88
- # 🔥 Warmup 常量
89
  # ==========================================================================
90
  WARMUP_BOOT_FULL = True
91
  WARMUP_BOOT_DELAY = 1.0 # 让第一个 health 先过
@@ -103,6 +103,9 @@ WARMUP_LAST_FILE = str(ROOT / ".warmup_last.json")
103
  WARMUP_PRE_GPU_BUDGET = 8.0 # 申请 GPU 前最多等多久(覆盖"已经很接近完成")
104
  WARMUP_RESIDUAL_WAIT = 5.0 # GPU 内残余等待上限(烧 GPU 预算,务必小)
105
  SYNC_ON_BOOT = False # 启动时是否 os.sync(默认关:只刷脏页,不预热)
 
 
 
106
  # ==========================================================================
107
 
108
  _comfy_ready = False
@@ -247,6 +250,13 @@ def load_char_loras_from_repo():
247
  total = sum(len(eng) for eng in CHAR_LORA_CHOICES.values())
248
  matched = sum(1 for eng in CHAR_LORA_CHOICES.values() for v in eng.values() if v.get("trigger"))
249
  print(f"✅ 成功刷新角色 LoRA: {[f'{k}: {len(v)}个' for k, v in CHAR_LORA_CHOICES.items()]} | trigger 覆盖 {matched}/{total}")
 
 
 
 
 
 
 
250
  except Exception as e:
251
  print(f"⚠️ 动态刷新失败: {e}")
252
 
@@ -271,6 +281,17 @@ def _install_filtered_requirements(path: pathlib.Path) -> None:
271
  if requirements:
272
  _run([sys.executable, "-m", "pip", "install", "--no-cache-dir", *requirements], check=False)
273
 
 
 
 
 
 
 
 
 
 
 
 
274
  def _ensure_comfy() -> None:
275
  global _comfy_ready
276
  if _comfy_ready: return
@@ -302,6 +323,35 @@ def _ensure_comfy() -> None:
302
 
303
  _comfy_ready = True
304
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
305
  def _init_comfy_nodes() -> None:
306
  global _nodes_ready
307
  if _nodes_ready: return
@@ -334,78 +384,38 @@ def _init_comfy_nodes() -> None:
334
  print("✅ ComfyUI 节点初始化完成!", flush=True)
335
 
336
  # ==========================================================================
337
- # ⚡ Comfy optimization
338
  # ==========================================================================
339
-
340
 
341
-
342
- def _download_if_needed(repo: str, subfolder: str, filename: str, dest_root: pathlib.Path) -> None:
343
- dest_path = dest_root / filename
344
- if dest_path.exists(): return
345
- print(f"⏳ Downloading: {filename} ...")
346
- dest_root.mkdir(parents=True, exist_ok=True)
347
- hf_hub_download(repo_id=repo, subfolder=subfolder if subfolder else None, filename=filename, local_dir=str(dest_root))
348
- src = dest_root / subfolder / filename if subfolder else dest_root / filename
349
- if src.exists() and src != dest_path:
350
- shutil.move(str(src), str(dest_path))
351
-
352
- # 主动把大文件拉到本地 Page Cache,避免 ZeroGPU worker 跨网络 mmap 缺页
353
- def _warmup_page_cache(file_path: pathlib.Path):
354
- if not file_path.exists():
355
- return
356
- # 只预热大于 500MB 的大文件(量化大模型、大 TE),小文件(如 VAE)没必要
357
- if file_path.stat().st_size < 500 * 1024 * 1024:
358
- return
359
-
360
- print(f"[预热] 🔥 正在拉取文件到本地缓存: {file_path.name} ({file_path.stat().st_size / 1024 / 1024:.1f} MB)...", flush=True)
361
- _t0 = time.time()
362
-
363
  try:
364
- # 顺序读取整个文件。这里不要用 mmap,直接 f.read() 才能最快触发底层网络拉取和本地缓存
365
- with open(file_path, "rb") as f:
366
- # 每次读 32MB,避免瞬间吃掉几十 GB 内存导致 OOM
367
- chunk_size = 32 * 1024 * 1024
368
- while True:
369
- chunk = f.read(chunk_size)
370
- if not chunk:
371
- break
372
- _elapsed = round(time.time() - _t0, 2)
373
- print(f"[预热] ✅ {file_path.name} 已载入本地缓存,耗时: {_elapsed}s", flush=True)
374
  except Exception as e:
375
- print(f"[预热] ⚠️ {file_path.name} 预热失败: {e}", flush=True)
376
 
377
 
378
- def _ensure_models() -> None:
379
- print("开始全量下载基础模型...")
380
- for engine_cfg in MODEL_CONFIG["models"].values():
381
- for repo, file_path in engine_cfg.get("companion_downloads", []):
382
- path = pathlib.Path(file_path)
383
- if "text_encoders" in str(path): dest_root = MODELS / "text_encoders"
384
- elif "vae" in str(path): dest_root = MODELS / "vae"
385
- else: dest_root = MODELS / path.parent
386
- _download_if_needed(repo, str(path.parent), path.name, dest_root)
387
- for name, cfg in UNET_CHOICES.items():
388
- _download_if_needed(cfg["repo"], cfg["subfolder"], cfg["filename"], MODELS / "diffusion_models")
389
- lora_root = MODELS / "loras"
390
- for name, cfg in BASE_LORAS_CHOICES.items():
391
- _download_if_needed(cfg["repo"], cfg["subfolder"], cfg["filename"], lora_root)
392
 
393
- # ❌ 不再在这里 os.sync + 全量预热:
394
- # ① 同步跑在 import 阶段 → uvicorn 还没 listen,/api/health 打不进来
395
- # ② 会阻塞启动几十秒,且和后面的 sweep 重复
396
- # ✅ 预热统一交给 WarmupManager,在 @app.on_event("startup") 的后台线程里做
397
- if SYNC_ON_BOOT:
398
- try:
399
- _t0 = time.time()
400
- os.sync()
401
- print(f"✅ 脏页已刷盘 (os.sync 耗时: {round(time.time() - _t0, 2)}s)", flush=True)
402
- except Exception as e:
403
- print(f"⚠️ os.sync 失败: {e}", flush=True)
404
 
405
- # --------------------------------------------------------------------------
406
- # ♻️ Reusable Executor Singleton (preserves Comfy model cache across tasks)
407
- # --------------------------------------------------------------------------
408
- import threading
409
 
410
  _exec_lock = threading.Lock() # 串行化执行,GPU 一次一个任务
411
 
@@ -471,9 +481,9 @@ def _get_executor():
471
  except Exception:
472
  pass
473
  return loop, executor
474
- # --------------------------------------------------------------------------
475
- # 🧩 Loader Chain Cache (stable node ids => Comfy node-cache hits, no re-patch
476
- # --------------------------------------------------------------------------
477
 
478
  _loader_chain_cache: dict[str, tuple[dict, str]] = {}
479
 
@@ -482,6 +492,26 @@ def _combo_key(engine: str, unet_name: str,
482
  base = tuple((f, round(float(s), 3)) for f, s in base_loras)
483
  return f"{engine}|{unet_name}|{base}|{char_lora or ''}|{round(float(char_strength), 3)}"
484
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
485
  def _build_loader_chain(engine, unet_name, base_loras, char_lora, char_strength):
486
  """
487
  只构建 1..N 的 loader 链(unet/clip/vae + lora 叠加),
@@ -510,36 +540,6 @@ def _build_loader_chain(engine, unet_name, base_loras, char_lora, char_strength)
510
  cur = str(idx); idx += 1
511
  return chain, cur
512
 
513
- # ==========================================================================
514
- # 💻 Prepare runtime
515
- # ==========================================================================
516
-
517
- def _warmup_node_imports() -> None:
518
- """预热 Comfy 节点类导入,消除首次 execute 的 import 开销"""
519
- try:
520
- import nodes as comfy_nodes
521
- for class_name in ["UNETLoader", "CLIPLoader", "DualCLIPLoader", "VAELoader",
522
- "LoraLoaderModelOnly", "KSampler", "VAEDecode", "SaveImage",
523
- "CLIPTextEncode", "ConditioningZeroOut", "EmptyLatentImage"]:
524
- if hasattr(comfy_nodes, class_name):
525
- getattr(comfy_nodes, class_name)
526
- print("[预热] ✅ 节点类导入完成", flush=True)
527
- except Exception as e:
528
- print(f"[预热] ⚠️ {e}", flush=True)
529
-
530
-
531
- def _prepare_runtime() -> None:
532
- _ensure_comfy()
533
- _ensure_models()
534
- _init_comfy_nodes()
535
- _warmup_node_imports() # 🌟 P1: 预热节点类
536
-
537
- try:
538
- print("⬇️ Starting up...")
539
- _prepare_runtime()
540
- except Exception as e:
541
- print(f"⚠️ Startup failed: {e}")
542
-
543
 
544
  # ==========================================================================
545
  # 🔄 Progress Interceptor
@@ -605,6 +605,36 @@ class UnifiedProgressTqdm(tqdm):
605
  if has_steps:
606
  tasks_status[gen_task_id]["message"] = step_msg
607
  print(f"[进度拦截] Task {gen_task_id[:8]} | {self.n}/{self.total} steps ({int(self.n / self.total * 100)}%)")
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
608
 
609
  # ==========================================================================
610
  # ⚛️ Comfy Backend & Workflow
@@ -642,8 +672,51 @@ def print_ram_status(stage: str):
642
  print(f"[RAM监控 - {stage}] 宿主机总内存: {total_gb:.2f} GB | 宿主机可用: {avail_gb:.2f} GB | 本进程占用: {proc_mem_gb:.2f} GB | 系统已用: {mem.percent}%{cgroup_str}")
643
 
644
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
645
  # --------------------------------------------------------------------------
646
- # 📊 Metric 文件:原子写入 + 统一读改写(/tmp/metrics_<task_id>.json)
647
  # --------------------------------------------------------------------------
648
  _metric_lock = threading.RLock()
649
 
@@ -691,40 +764,83 @@ def _write_metric(task_id: str, **updates) -> None:
691
  d.update(updates)
692
  return True
693
  _update_metric(task_id, _m)
694
-
695
- # --------------------------------------------------------------------------
696
- # 🔁 tqdm Patch:可重入引用计数,杜绝并发 save/restore 泄漏
697
- # --------------------------------------------------------------------------
698
- _tqdm_patch_lock = threading.RLock()
699
- _tqdm_patch_depth = 0
700
- _tqdm_patch_originals: dict[str, Any] = {}
701
-
702
- def _tqdm_patch_enter() -> None:
703
- global _tqdm_patch_depth
704
- import tqdm as tqdm_lib
705
- import tqdm.auto as tqdm_auto
706
- with _tqdm_patch_lock:
707
- if _tqdm_patch_depth == 0:
708
- _tqdm_patch_originals["lib"] = tqdm_lib.tqdm
709
- _tqdm_patch_originals["auto"] = tqdm_auto.tqdm
710
- tqdm_lib.tqdm = UnifiedProgressTqdm
711
- tqdm_auto.tqdm = UnifiedProgressTqdm
712
- _tqdm_patch_depth += 1
713
-
714
- def _tqdm_patch_exit() -> None:
715
- global _tqdm_patch_depth
716
- import tqdm as tqdm_lib
717
- import tqdm.auto as tqdm_auto
718
- with _tqdm_patch_lock:
719
- if _tqdm_patch_depth > 0:
720
- _tqdm_patch_depth -= 1
721
- if _tqdm_patch_depth == 0 and "lib" in _tqdm_patch_originals:
722
- tqdm_lib.tqdm = _tqdm_patch_originals.pop("lib")
723
- tqdm_auto.tqdm = _tqdm_patch_originals.pop("auto")
724
  # --------------------------------------------------------------------------
725
  def _ref(node: str, output: int = 0) -> list[Any]:
726
  return [node, output]
727
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
728
  def _log_workflow_summary(workflow: dict[str, Any], task_id: str, load_time_val: float, wf_time: float, image: str = None):
729
  """独立提取并打印单行 JSON 摘要日志(不影响主流程逻辑)"""
730
  try:
@@ -799,49 +915,6 @@ def _log_workflow_summary(workflow: dict[str, Any], task_id: str, load_time_val:
799
 
800
  except Exception as e:
801
  print(f"[Log Format Error]: {e}", flush=True)
802
-
803
-
804
- def _io_probe():
805
- try:
806
- c = psutil.Process().io_counters()
807
- return {"read_chars": c.read_chars, "read_bytes": c.read_bytes}
808
- except Exception:
809
- return {"read_chars": 0, "read_bytes": 0}
810
-
811
- def _mem_probe():
812
- """返回 (host_Cached_MB, host_Avail_MB, cg_current_GB, cg_file_GB, cg_inactive_file_GB)"""
813
- cached = avail = -1
814
- try:
815
- with open("/proc/meminfo") as f:
816
- m = {l.split(":")[0]: int(l.split()[1]) // 1024 for l in f if len(l.split()) >= 2}
817
- cached, avail = m.get("Cached", -1), m.get("MemAvailable", -1)
818
- except Exception:
819
- pass
820
-
821
- cur = file_gb = inact_gb = -1.0
822
- try:
823
- with open("/sys/fs/cgroup/memory.current") as f:
824
- cur = int(f.read().strip()) / 1024**3
825
- with open("/sys/fs/cgroup/memory.stat") as f:
826
- for line in f:
827
- p = line.split()
828
- if len(p) != 2:
829
- continue
830
- if p[0] == "file":
831
- file_gb = int(p[1]) / 1024**3
832
- elif p[0] == "inactive_file":
833
- inact_gb = int(p[1]) / 1024**3
834
- except Exception:
835
- pass
836
- return cached, avail, cur, file_gb, inact_gb
837
-
838
- def _gpu_id():
839
- try:
840
- dev = torch.cuda.current_device()
841
- p = torch.cuda.get_device_properties(dev)
842
- return f"dev{dev}/uuid={getattr(p, 'uuid', 'n/a')}"
843
- except Exception as e:
844
- return f"n/a({e})"
845
 
846
  def _execute_workflow(workflow: dict[str, Any], task_id: str = None) -> list[str]:
847
  print_ram_status("任务开始前")
@@ -976,103 +1049,9 @@ def prepare_env(char_enable: bool, char_lora: str, unet_choice: str, task_id: st
976
  _tqdm_patch_exit()
977
  _current_download_task_id.set(None)
978
 
979
- def select_base_loras(engine: str, lora_states: tuple) -> list[tuple[str, float]]:
980
- selected = []
981
-
982
- # 找出当前引擎专属的 Base LoRA 列表,保持顺序
983
- valid_loras = []
984
- for name, cfg in BASE_LORAS_CHOICES.items():
985
- if cfg["engine"] == engine:
986
- valid_loras.append((name, cfg))
987
-
988
- # 解析前端传来的勾选状态
989
- for i in range(0, len(lora_states), 2):
990
- enable = lora_states[i]
991
- try:
992
- strength = float(lora_states[i + 1])
993
- except (ValueError, TypeError):
994
- strength = 1.0
995
-
996
- if enable and strength > 0:
997
- # 如果前端的数组长度和当前引擎实际可用的 LoRA 列表长度一致
998
- idx = i // 2
999
- if idx < len(valid_loras):
1000
- lora_name, lora_cfg = valid_loras[idx]
1001
- selected.append((lora_cfg["filename"], strength))
1002
-
1003
- # 你的探针(保留观察)
1004
- print(f"[LoRA选择探针] ✅ 成功匹配并加载: {lora_name} ({strength})")
1005
-
1006
- return selected
1007
-
1008
- def _build_clip_inputs(engine_cfg: dict, clip_loader_node: str) -> dict:
1009
- clip_type = engine_cfg.get("clip_type", "moss_image")
1010
- clip_inputs = {"type": clip_type}
1011
- te_filenames = engine_cfg.get("local_te_filename", [])
1012
- if clip_loader_node == "DualCLIPLoader":
1013
- if len(te_filenames) >= 2:
1014
- if "clip_l" in te_filenames[0].lower():
1015
- clip_inputs["clip_name1"] = te_filenames[0]
1016
- clip_inputs["clip_name2"] = te_filenames[1]
1017
- else:
1018
- clip_inputs["clip_name1"] = te_filenames[1]
1019
- clip_inputs["clip_name2"] = te_filenames[0]
1020
- elif len(te_filenames) == 1:
1021
- clip_inputs["clip_name1"] = te_filenames[0]
1022
- else:
1023
- if te_filenames: clip_inputs["clip_name"] = te_filenames[0]
1024
- if "clip_device" in MODEL_CONFIG.get("loader_args", {}):
1025
- clip_inputs["device"] = MODEL_CONFIG["loader_args"]["clip_device"]
1026
- return clip_inputs
1027
-
1028
- def build_workflow(
1029
- prompt: str,
1030
- unet_name: str,
1031
- engine: str,
1032
- width: int,
1033
- height: int,
1034
- steps: int,
1035
- cfg: float,
1036
- seed: int,
1037
- sampler: str,
1038
- scheduler: str,
1039
- base_loras: list[tuple[str, float]],
1040
- char_lora: str | None,
1041
- char_strength: float,
1042
- ) -> dict[str, Any]:
1043
- # --- loader 链:命中缓存则复用(节点 id / inputs 完全一致) ---
1044
- key = _combo_key(engine, unet_name, base_loras, char_lora, char_strength)
1045
- cached = _loader_chain_cache.get(key)
1046
- if cached is not None:
1047
- chain, current_model_node = cached
1048
- workflow = dict(chain) # 浅拷贝,下游不改 loader 链
1049
- else:
1050
- chain, current_model_node = _build_loader_chain(
1051
- engine, unet_name, base_loras, char_lora, char_strength)
1052
- _loader_chain_cache[key] = (chain, current_model_node)
1053
- # 只保留最近 8 个组合,避免内存无限增长
1054
- if len(_loader_chain_cache) > 8:
1055
- _loader_chain_cache.pop(next(iter(_loader_chain_cache)))
1056
- workflow = dict(chain)
1057
-
1058
- # --- 下游节点:id 从链末端续接,与原逻辑完全一致 ---
1059
- nodes = MODEL_CONFIG["node_types"]
1060
- node_idx = max(int(k) for k in chain.keys()) + 1
1061
-
1062
- final_prompt = prompt.strip()
1063
- workflow[str(node_idx)] = {"class_type": "CLIPTextEncode", "inputs": {"clip": _ref("2"), "text": final_prompt}}
1064
- workflow[str(node_idx+1)] = {"class_type": "ConditioningZeroOut", "inputs": {"conditioning": _ref(str(node_idx))}}
1065
- workflow[str(node_idx+2)] = {"class_type": "EmptyLatentImage", "inputs": {"width": width, "height": height, "batch_size": 1}}
1066
-
1067
- workflow[str(node_idx+3)] = {"class_type": "KSampler", "inputs": {"model": _ref(current_model_node), "positive": _ref(str(node_idx)), "negative": _ref(str(node_idx+1)), "latent_image": _ref(str(node_idx+2)), "seed": seed, "steps": steps, "cfg": cfg, "sampler_name": sampler, "scheduler": scheduler, "denoise": 1.0}}
1068
- workflow[str(node_idx+4)] = {"class_type": "VAEDecode", "inputs": {"samples": _ref(str(node_idx+3)), "vae": _ref("3")}}
1069
- workflow[str(node_idx+5)] = {"class_type": "SaveImage", "inputs": {"images": _ref(str(node_idx+4)), "filename_prefix": MODEL_CONFIG["name"].lower()}}
1070
- return workflow
1071
-
1072
- # 🌟 增加全局变量用于追踪 GPU 域内的架构切换
1073
 
1074
  # ==========================================================================
1075
- # 🔥 GPU 内残余预热等待(跨进程读 /tmp 状态文件,与 _read_metric 同一机制)
1076
  # ==========================================================================
1077
  def _read_warm_state():
1078
  try:
@@ -1084,17 +1063,40 @@ def _read_warm_state():
1084
 
1085
  def _warm_wait_in_gpu(unet_choice: str, budget: float = WARMUP_RESIDUAL_WAIT) -> bool:
1086
  """只在"已经非常接近完成"时等,最多 budget 秒。
1087
- 注意:这段是在 GPU 切片内执行,等待即烧配额,所以上限必须小。"""
1088
  t0 = time.time()
1089
  while time.time() - t0 < budget:
1090
  st = _read_warm_state()
1091
- if st and st.get("target") == unet_choice and st.get("state") == "ready":
1092
- return True
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1093
  time.sleep(0.25)
 
1094
  print(f"[预热] ⏳ GPU 内残余等待超时({budget}s),转冷加载", flush=True)
1095
  return False
1096
 
1097
 
 
 
 
 
1098
  def _generate_impl(
1099
  prompt: str, unet_choice: str, custom_w: int, custom_h: int,
1100
  steps: int, cfg: float, seed: int, sampler: str, scheduler: str,
@@ -1175,16 +1177,15 @@ demo.queue()
1175
 
1176
 
1177
  # ==========================================================================
1178
- # 🧹 Clean
1179
  # ==========================================================================
1180
 
1181
 
1182
- import threading
1183
  # 专门用于保护 tasks_status 字典的状态锁
1184
  _status_lock = threading.RLock()
1185
  _model_switch_lock = threading.Lock()
1186
 
1187
- # ---- 清理策略 ----
1188
  _STATUS_TTL = 3600 # 终态任务内存保留 60 分钟
1189
  _STATUS_MAX_ENTRIES = 200 # 兜底:最多保留 200 条终态
1190
  _OUTPUT_TTL = 24 * 3600 # 输出图片保留 24 小时
@@ -1243,9 +1244,16 @@ def _cleanup_stale(force: bool = False) -> None:
1243
  if deleted:
1244
  print(f"[清理] 🧹 删除 {deleted} 个过期输出,释放 {freed / 1024 / 1024:.1f} MB", flush=True)
1245
 
 
 
 
 
 
 
 
1246
 
1247
  # ==========================================================================
1248
- # 🔥 WarmupManager:文件级 page-cache 预热状态机
1249
  # ==========================================================================
1250
  class WarmupManager:
1251
  def __init__(self):
@@ -1661,6 +1669,32 @@ class WarmupManager:
1661
  print(f"[预热] 🔥 start target={target} reason={plan.get('reason')} "
1662
  f"files={len(files)} big={big_total:.0f}MB lite={lite}", flush=True)
1663
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1664
  for rec in files:
1665
  if self._superseded(seq):
1666
  print(f"[预热] ⏹️ 被新目标抢占 (seq={seq})", flush=True)
@@ -1679,6 +1713,13 @@ class WarmupManager:
1679
  self._flush(plan, records)
1680
  continue
1681
 
 
 
 
 
 
 
 
1682
  old = self._files.get(rec["owner"], {}).get(rec["file_key"])
1683
  if (old and old["state"] == "warm" and old["size_mb"] == rec["size_mb"]
1684
  and (time.time() - old.get("verified_at", 0)) < WARMUP_TTL):
@@ -1772,6 +1813,40 @@ class WarmupManager:
1772
 
1773
 
1774
  warmup = WarmupManager()
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1775
 
1776
  # ==========================================================================
1777
  # 🌐 FastAPI & API Routes
@@ -1791,6 +1866,17 @@ class GenerateRequest(BaseModel):
1791
  char_strength: float = 1.0
1792
  base_lora_states: list = []
1793
 
 
 
 
 
 
 
 
 
 
 
 
1794
 
1795
  def background_generate_task(task_id: str, req: GenerateRequest, ip_token: str = None, request: Request = None):
1796
  global _last_used_architecture, _last_used_unet
@@ -1987,49 +2073,6 @@ def background_generate_task(task_id: str, req: GenerateRequest, ip_token: str =
1987
  _gen_leave()
1988
  _current_generation_task_id.set(None)
1989
 
1990
- app = FastAPI()
1991
-
1992
- def _read_last_unet():
1993
- try:
1994
- with open(WARMUP_LAST_FILE) as f:
1995
- return json.load(f).get("unet_choice")
1996
- except Exception:
1997
- return None
1998
-
1999
- def _boot_warmup():
2000
- """两段式:
2001
- ① 阶梯一级(<1s):上次模型的 UNET 头部 → 用户第一眼就有"部分热"
2002
- ② 全量 sweep(P1,可被抢占):等 ① 跑完再启动,否则会把 ① 顶掉
2003
- """
2004
- last = _read_last_unet()
2005
- target = last if last in UNET_CHOICES else next(iter(UNET_CHOICES), None)
2006
-
2007
- lite_requested = False
2008
- if target:
2009
- rec = warmup._rec(MODELS / "diffusion_models" / UNET_CHOICES[target]["filename"],
2010
- "unet", "unet")
2011
- mbps = warmup.probe(rec)
2012
- if mbps is not None and mbps >= WARMUP_WARM_MBPS:
2013
- print(f"[预热] ⚡ boot: UNET 已在 cache 中 ({mbps:.0f}MB/s),跳过 lite", flush=True)
2014
- else:
2015
- print(f"[预热] 🥾 boot: UNET 探测 {mbps} MB/s → 做阶梯一级", flush=True)
2016
- warmup.request(target, lite=True, reason="boot", priority=1)
2017
- lite_requested = True # ← 新增
2018
-
2019
- if not WARMUP_BOOT_FULL:
2020
- return
2021
-
2022
- if lite_requested: # ← 只在发起了才等
2023
- t0 = time.time()
2024
- while time.time() - t0 < 20:
2025
- with warmup._lock:
2026
- r = warmup._files.get(target, {}).get("unet")
2027
- if r and r.get("state") in ("partial", "warm", "failed", "stale"):
2028
- break
2029
- time.sleep(0.2)
2030
-
2031
- warmup.request_sweep(reason="boot_sweep")
2032
-
2033
 
2034
  @app.on_event("startup")
2035
  async def _on_startup():
@@ -2040,17 +2083,75 @@ async def _on_startup():
2040
  except Exception as e:
2041
  print(f"[预热] ⚠️ boot 异常: {e}", flush=True)
2042
  threading.Thread(target=_delayed, daemon=True).start()
2043
-
2044
 
2045
- app.add_middleware(
2046
- CORSMiddleware,
2047
- allow_origins=["*"],
2048
- allow_credentials=True,
2049
- allow_methods=["*"],
2050
- allow_headers=["*"],
2051
- )
2052
 
2053
- from fastapi import HTTPException, Depends, Header, Query
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
2054
 
2055
  @app.post("/api/generate")
2056
  async def handle_generate(req: GenerateRequest, background_tasks: BackgroundTasks, request: Request):
@@ -2089,7 +2190,6 @@ async def handle_generate(req: GenerateRequest, background_tasks: BackgroundTask
2089
  tasks_status[task_id] = {"status": "queued", "message": "⏳ 任务已进入队列..."}
2090
 
2091
  # 👇 抛弃 BackgroundTasks,使用原生守护线程,直接与 HTTP 返回脱钩
2092
- import threading
2093
  t = threading.Thread(
2094
  target=background_generate_task,
2095
  args=(task_id, req, ip_token, request),
@@ -2120,70 +2220,10 @@ async def check_status(task_id: str):
2120
  status_data["message"] = file_data["phase"]
2121
  return status_data
2122
 
2123
- @app.get("/api/models")
2124
- async def get_models():
2125
- models_data = {}
2126
- global_default_prompt = MODEL_CONFIG.get("default_prompt", "")
2127
-
2128
- for unet_name, unet_info in UNET_CHOICES.items():
2129
- engine = unet_info["engine"]
2130
- engine_name = MODEL_CONFIG["models"].get(engine, {}).get("name", engine)
2131
-
2132
- if " | " in unet_name:
2133
- model_specific_name = unet_name.split(" | ", 1)[1]
2134
- else:
2135
- model_specific_name = unet_name
2136
-
2137
- display_unet_name = f"{engine_name} | {model_specific_name}"
2138
-
2139
- base_loras_for_engine = []
2140
- for name, cfg in BASE_LORAS_CHOICES.items():
2141
- if cfg["engine"] == engine:
2142
- base_loras_for_engine.append({
2143
- "name": name,
2144
- "filename": cfg["filename"],
2145
- "defaultEnable": cfg.get("defaultEnable", False)
2146
- })
2147
-
2148
- engine_cfg = MODEL_CONFIG["models"].get(engine, {})
2149
- final_prompt = engine_cfg.get("default_prompt_override", global_default_prompt)
2150
-
2151
- # 🌟 核心新增:提取 TE 和 VAE 信息
2152
- # TE 可能是列表,用 " + " 连接起来展示
2153
- te_list = engine_cfg.get("local_te_filename", [])
2154
- te_display = " + ".join([f.replace(".safetensors", "") for f in te_list]) if te_list else "Unknown"
2155
-
2156
- # VAE 通常是字符串
2157
- vae_display = engine_cfg.get("local_vae_filename", "Unknown").replace(".safetensors", "")
2158
-
2159
- models_data[display_unet_name] = {
2160
- "engine": engine,
2161
- "defaults": engine_cfg.get("defaults", {}),
2162
- "base_loras": base_loras_for_engine,
2163
- "default_prompt": final_prompt,
2164
- "te_name": te_display, # 👈 传给前端
2165
- "vae_name": vae_display # 👈 传给前端
2166
- }
2167
-
2168
- return {"models": models_data}
2169
-
2170
- @app.get("/api/loras")
2171
- async def get_loras():
2172
- # ⚠️ load_char_loras_from_repo 里有同步 requests.get + list_repo_files(网络 IO)。
2173
- # 直接在 async 路由里调用会阻塞 event loop,期间所有请求(含 /api/config)
2174
- # 都无法处理,HF 代理超时后会 reset 连接 → 前端表现为 "Failed to fetch"。
2175
- # 扔进线程池执行,event loop 保持畅通。
2176
- await asyncio.to_thread(load_char_loras_from_repo)
2177
- return {"loras": CHAR_LORA_CHOICES}
2178
 
2179
- @app.get("/api/config")
2180
- async def get_sampler_config():
2181
- return {
2182
- "samplers": SAMPLERS,
2183
- "schedulers": SCHEDULERS,
2184
- "root_mapping": MODEL_CONFIG.get("json_keys", {}).get("root_mapping", {}),
2185
- "default_prompt": MODEL_CONFIG.get("default_prompt", ""),
2186
- }
2187
 
2188
  class WarmupRequest(BaseModel):
2189
  unet_choice: str
@@ -2237,8 +2277,8 @@ async def api_warmup_status():
2237
  return warmup.snapshot()
2238
 
2239
  # ==========================================================================
2240
- # 🔧 预热调试端点(默认完全关闭;开启需在 Space Settings → Secrets 配置
2241
- # WARMUP_DEBUG_TOKEN,之后请求必须带 X-Debug-Token 头或 ?token= 参数)
2242
  # ==========================================================================
2243
  import hmac
2244
 
@@ -2405,10 +2445,6 @@ async def debug_warmup(
2405
 
2406
  raise HTTPException(400, f"unknown action: {action}")
2407
 
2408
- @app.get("/api/health")
2409
- async def health_check():
2410
- return {"status": "ok"}
2411
-
2412
  # ==========================================================================
2413
  # 📁 Static Files Sync & Mount
2414
  # ==========================================================================
@@ -2444,9 +2480,7 @@ def sync_ui_assets():
2444
  # 1. 启动时执行同步
2445
  sync_ui_assets()
2446
 
2447
- # ==========================================================
2448
  # 🌟 核心修改:必须在挂载根路径 "/" 之前,先挂载 /output 目录
2449
- # ==========================================================
2450
  app.mount("/output", StaticFiles(directory=str(OUTPUT)), name="output")
2451
 
2452
  # 2. 挂载静态文件夹 (前端)
 
1
  """Universal Lora Studio: Comfy Render Backend + FastAPI Data Backend + Native Static Frontend + ZeroGPU Token Passthrough + Config Driven"""
2
  """Comfy Version: c1eece62cbf1805d4f64286d7f5592e6a215e6ba"""
 
3
  import base64
4
  import asyncio
5
  import glob
 
31
  import threading
32
 
33
  from model_config import MODEL_CONFIG
34
+
35
+ from fastapi import HTTPException, Depends, Header, Query
36
  # ⚠️ 必须在 load_char_loras_from_repo() 之前定义 —— 它内部要读这个常量。
37
  # 放在文件后面的"静态挂载"段里会导致启动首次扫描 NameError,触发词全空且被 300s 缓存锁住。
38
  LORA_META_URL = "https://huggingface.co/spaces/waveshaker/loras_gallery/resolve/main/models.json"
39
 
40
 
 
41
  # ==========================================================================
42
+ # 🛠️ Environment Patches & Global Paths
43
  # ==========================================================================
44
 
45
  import builtins
 
85
  COMFY_COMMIT = "c1eece62cbf1805d4f64286d7f5592e6a215e6ba"
86
 
87
  # ==========================================================================
88
+ # 🔥 Warmup Constants
89
  # ==========================================================================
90
  WARMUP_BOOT_FULL = True
91
  WARMUP_BOOT_DELAY = 1.0 # 让第一个 health 先过
 
103
  WARMUP_PRE_GPU_BUDGET = 8.0 # 申请 GPU 前最多等多久(覆盖"已经很接近完成")
104
  WARMUP_RESIDUAL_WAIT = 5.0 # GPU 内残余等待上限(烧 GPU 预算,务必小)
105
  SYNC_ON_BOOT = False # 启动时是否 os.sync(默认关:只刷脏页,不预热)
106
+
107
+ # ==========================================================================
108
+ # 🧠 Global Runtime State
109
  # ==========================================================================
110
 
111
  _comfy_ready = False
 
250
  total = sum(len(eng) for eng in CHAR_LORA_CHOICES.values())
251
  matched = sum(1 for eng in CHAR_LORA_CHOICES.values() for v in eng.values() if v.get("trigger"))
252
  print(f"✅ 成功刷新角色 LoRA: {[f'{k}: {len(v)}个' for k, v in CHAR_LORA_CHOICES.items()]} | trigger 覆盖 {matched}/{total}")
253
+
254
+ # ✅ 新增:分架构覆盖率,数据缺口一眼可见
255
+ per = " | ".join(
256
+ f"{eng}:{sum(1 for v in m.values() if v.get('trigger'))}/{len(m)}"
257
+ for eng, m in CHAR_LORA_CHOICES.items()
258
+ )
259
+ print(f" └ trigger 分架构: {per}")
260
  except Exception as e:
261
  print(f"⚠️ 动态刷新失败: {e}")
262
 
 
281
  if requirements:
282
  _run([sys.executable, "-m", "pip", "install", "--no-cache-dir", *requirements], check=False)
283
 
284
+
285
+ def _download_if_needed(repo: str, subfolder: str, filename: str, dest_root: pathlib.Path) -> None:
286
+ dest_path = dest_root / filename
287
+ if dest_path.exists(): return
288
+ print(f"⏳ Downloading: {filename} ...")
289
+ dest_root.mkdir(parents=True, exist_ok=True)
290
+ hf_hub_download(repo_id=repo, subfolder=subfolder if subfolder else None, filename=filename, local_dir=str(dest_root))
291
+ src = dest_root / subfolder / filename if subfolder else dest_root / filename
292
+ if src.exists() and src != dest_path:
293
+ shutil.move(str(src), str(dest_path))
294
+
295
  def _ensure_comfy() -> None:
296
  global _comfy_ready
297
  if _comfy_ready: return
 
323
 
324
  _comfy_ready = True
325
 
326
+
327
+ def _ensure_models() -> None:
328
+ print("开始全量下载基础模型...")
329
+ for engine_cfg in MODEL_CONFIG["models"].values():
330
+ for repo, file_path in engine_cfg.get("companion_downloads", []):
331
+ path = pathlib.Path(file_path)
332
+ if "text_encoders" in str(path): dest_root = MODELS / "text_encoders"
333
+ elif "vae" in str(path): dest_root = MODELS / "vae"
334
+ else: dest_root = MODELS / path.parent
335
+ _download_if_needed(repo, str(path.parent), path.name, dest_root)
336
+ for name, cfg in UNET_CHOICES.items():
337
+ _download_if_needed(cfg["repo"], cfg["subfolder"], cfg["filename"], MODELS / "diffusion_models")
338
+ lora_root = MODELS / "loras"
339
+ for name, cfg in BASE_LORAS_CHOICES.items():
340
+ _download_if_needed(cfg["repo"], cfg["subfolder"], cfg["filename"], lora_root)
341
+
342
+ # ❌ 不再在这里 os.sync + 全量预热:
343
+ # ① 同步跑在 import 阶段 → uvicorn 还没 listen,/api/health 打不进来
344
+ # ② 会阻塞启动几十秒,且和后面的 sweep 重复
345
+ # ✅ 预热统一交给 WarmupManager,在 @app.on_event("startup") 的后台线程里做
346
+ if SYNC_ON_BOOT:
347
+ try:
348
+ _t0 = time.time()
349
+ os.sync()
350
+ print(f"✅ 脏页已刷盘 (os.sync 耗时: {round(time.time() - _t0, 2)}s)", flush=True)
351
+ except Exception as e:
352
+ print(f"⚠️ os.sync 失败: {e}", flush=True)
353
+
354
+
355
  def _init_comfy_nodes() -> None:
356
  global _nodes_ready
357
  if _nodes_ready: return
 
384
  print("✅ ComfyUI 节点初始化完成!", flush=True)
385
 
386
  # ==========================================================================
387
+ # 💻 Prepare Runtime
388
  # ==========================================================================
 
389
 
390
+ def _warmup_node_imports() -> None:
391
+ """预热 Comfy 节点类导入,消除首次 execute 的 import 开销"""
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
392
  try:
393
+ import nodes as comfy_nodes
394
+ for class_name in ["UNETLoader", "CLIPLoader", "DualCLIPLoader", "VAELoader",
395
+ "LoraLoaderModelOnly", "KSampler", "VAEDecode", "SaveImage",
396
+ "CLIPTextEncode", "ConditioningZeroOut", "EmptyLatentImage"]:
397
+ if hasattr(comfy_nodes, class_name):
398
+ getattr(comfy_nodes, class_name)
399
+ print("[预热] ✅ 节点类导入完成", flush=True)
 
 
 
400
  except Exception as e:
401
+ print(f"[预热] ⚠️ {e}", flush=True)
402
 
403
 
404
+ def _prepare_runtime() -> None:
405
+ _ensure_comfy()
406
+ _ensure_models()
407
+ _init_comfy_nodes()
408
+ _warmup_node_imports() # 🌟 P1: 预热节点类
 
 
 
 
 
 
 
 
 
409
 
410
+ try:
411
+ print("⬇️ Starting up...")
412
+ _prepare_runtime()
413
+ except Exception as e:
414
+ print(f"⚠️ Startup failed: {e}")
 
 
 
 
 
 
415
 
416
+ # ==========================================================================
417
+ # ♻️ Reusable Executor Singleton (preserves Comfy model cache across tasks)
418
+ # ==========================================================================
 
419
 
420
  _exec_lock = threading.Lock() # 串行化执行,GPU 一次一个任务
421
 
 
481
  except Exception:
482
  pass
483
  return loop, executor
484
+ # ==========================================================================
485
+ # 🧩 Loader Chain Cache (stable node ids => Comfy node-cache hits, no re-patch)
486
+ # ==========================================================================
487
 
488
  _loader_chain_cache: dict[str, tuple[dict, str]] = {}
489
 
 
492
  base = tuple((f, round(float(s), 3)) for f, s in base_loras)
493
  return f"{engine}|{unet_name}|{base}|{char_lora or ''}|{round(float(char_strength), 3)}"
494
 
495
+ def _build_clip_inputs(engine_cfg: dict, clip_loader_node: str) -> dict:
496
+ clip_type = engine_cfg.get("clip_type", "moss_image")
497
+ clip_inputs = {"type": clip_type}
498
+ te_filenames = engine_cfg.get("local_te_filename", [])
499
+ if clip_loader_node == "DualCLIPLoader":
500
+ if len(te_filenames) >= 2:
501
+ if "clip_l" in te_filenames[0].lower():
502
+ clip_inputs["clip_name1"] = te_filenames[0]
503
+ clip_inputs["clip_name2"] = te_filenames[1]
504
+ else:
505
+ clip_inputs["clip_name1"] = te_filenames[1]
506
+ clip_inputs["clip_name2"] = te_filenames[0]
507
+ elif len(te_filenames) == 1:
508
+ clip_inputs["clip_name1"] = te_filenames[0]
509
+ else:
510
+ if te_filenames: clip_inputs["clip_name"] = te_filenames[0]
511
+ if "clip_device" in MODEL_CONFIG.get("loader_args", {}):
512
+ clip_inputs["device"] = MODEL_CONFIG["loader_args"]["clip_device"]
513
+ return clip_inputs
514
+
515
  def _build_loader_chain(engine, unet_name, base_loras, char_lora, char_strength):
516
  """
517
  只构建 1..N 的 loader 链(unet/clip/vae + lora 叠加),
 
540
  cur = str(idx); idx += 1
541
  return chain, cur
542
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
543
 
544
  # ==========================================================================
545
  # 🔄 Progress Interceptor
 
605
  if has_steps:
606
  tasks_status[gen_task_id]["message"] = step_msg
607
  print(f"[进度拦截] Task {gen_task_id[:8]} | {self.n}/{self.total} steps ({int(self.n / self.total * 100)}%)")
608
+
609
+ # ==========================================================================
610
+ # 🔁 tqdm Patch: Re-entrant Ref-counting (no save/restore leak)
611
+ # ==========================================================================
612
+ _tqdm_patch_lock = threading.RLock()
613
+ _tqdm_patch_depth = 0
614
+ _tqdm_patch_originals: dict[str, Any] = {}
615
+
616
+ def _tqdm_patch_enter() -> None:
617
+ global _tqdm_patch_depth
618
+ import tqdm as tqdm_lib
619
+ import tqdm.auto as tqdm_auto
620
+ with _tqdm_patch_lock:
621
+ if _tqdm_patch_depth == 0:
622
+ _tqdm_patch_originals["lib"] = tqdm_lib.tqdm
623
+ _tqdm_patch_originals["auto"] = tqdm_auto.tqdm
624
+ tqdm_lib.tqdm = UnifiedProgressTqdm
625
+ tqdm_auto.tqdm = UnifiedProgressTqdm
626
+ _tqdm_patch_depth += 1
627
+
628
+ def _tqdm_patch_exit() -> None:
629
+ global _tqdm_patch_depth
630
+ import tqdm as tqdm_lib
631
+ import tqdm.auto as tqdm_auto
632
+ with _tqdm_patch_lock:
633
+ if _tqdm_patch_depth > 0:
634
+ _tqdm_patch_depth -= 1
635
+ if _tqdm_patch_depth == 0 and "lib" in _tqdm_patch_originals:
636
+ tqdm_lib.tqdm = _tqdm_patch_originals.pop("lib")
637
+ tqdm_auto.tqdm = _tqdm_patch_originals.pop("auto")
638
 
639
  # ==========================================================================
640
  # ⚛️ Comfy Backend & Workflow
 
672
  print(f"[RAM监控 - {stage}] 宿主机总内存: {total_gb:.2f} GB | 宿主机可用: {avail_gb:.2f} GB | 本进程占用: {proc_mem_gb:.2f} GB | 系统已用: {mem.percent}%{cgroup_str}")
673
 
674
 
675
+ def _io_probe():
676
+ try:
677
+ c = psutil.Process().io_counters()
678
+ return {"read_chars": c.read_chars, "read_bytes": c.read_bytes}
679
+ except Exception:
680
+ return {"read_chars": 0, "read_bytes": 0}
681
+
682
+ def _mem_probe():
683
+ """返回 (host_Cached_MB, host_Avail_MB, cg_current_GB, cg_file_GB, cg_inactive_file_GB)"""
684
+ cached = avail = -1
685
+ try:
686
+ with open("/proc/meminfo") as f:
687
+ m = {l.split(":")[0]: int(l.split()[1]) // 1024 for l in f if len(l.split()) >= 2}
688
+ cached, avail = m.get("Cached", -1), m.get("MemAvailable", -1)
689
+ except Exception:
690
+ pass
691
+
692
+ cur = file_gb = inact_gb = -1.0
693
+ try:
694
+ with open("/sys/fs/cgroup/memory.current") as f:
695
+ cur = int(f.read().strip()) / 1024**3
696
+ with open("/sys/fs/cgroup/memory.stat") as f:
697
+ for line in f:
698
+ p = line.split()
699
+ if len(p) != 2:
700
+ continue
701
+ if p[0] == "file":
702
+ file_gb = int(p[1]) / 1024**3
703
+ elif p[0] == "inactive_file":
704
+ inact_gb = int(p[1]) / 1024**3
705
+ except Exception:
706
+ pass
707
+ return cached, avail, cur, file_gb, inact_gb
708
+
709
+ def _gpu_id():
710
+ try:
711
+ dev = torch.cuda.current_device()
712
+ p = torch.cuda.get_device_properties(dev)
713
+ return f"dev{dev}/uuid={getattr(p, 'uuid', 'n/a')}"
714
+ except Exception as e:
715
+ return f"n/a({e})"
716
+
717
+
718
  # --------------------------------------------------------------------------
719
+ # 📊 Metric Files: Atomic Write + Read-Modify-Write (/tmp/metrics_<task_id>.json)
720
  # --------------------------------------------------------------------------
721
  _metric_lock = threading.RLock()
722
 
 
764
  d.update(updates)
765
  return True
766
  _update_metric(task_id, _m)
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
767
  # --------------------------------------------------------------------------
768
  def _ref(node: str, output: int = 0) -> list[Any]:
769
  return [node, output]
770
 
771
+ def select_base_loras(engine: str, lora_states: tuple) -> list[tuple[str, float]]:
772
+ selected = []
773
+
774
+ # 找出当前引擎专属的 Base LoRA 列表,保持顺序
775
+ valid_loras = []
776
+ for name, cfg in BASE_LORAS_CHOICES.items():
777
+ if cfg["engine"] == engine:
778
+ valid_loras.append((name, cfg))
779
+
780
+ # 解析前端传来的勾选状态
781
+ for i in range(0, len(lora_states), 2):
782
+ enable = lora_states[i]
783
+ try:
784
+ strength = float(lora_states[i + 1])
785
+ except (ValueError, TypeError):
786
+ strength = 1.0
787
+
788
+ if enable and strength > 0:
789
+ # 如果前端的数组长度和当前引擎实际可用的 LoRA 列表长度一致
790
+ idx = i // 2
791
+ if idx < len(valid_loras):
792
+ lora_name, lora_cfg = valid_loras[idx]
793
+ selected.append((lora_cfg["filename"], strength))
794
+
795
+ # 你的探针(保留观察)
796
+ print(f"[LoRA选择探针] ✅ 成功匹配并加载: {lora_name} ({strength})")
797
+
798
+ return selected
799
+
800
+ def build_workflow(
801
+ prompt: str,
802
+ unet_name: str,
803
+ engine: str,
804
+ width: int,
805
+ height: int,
806
+ steps: int,
807
+ cfg: float,
808
+ seed: int,
809
+ sampler: str,
810
+ scheduler: str,
811
+ base_loras: list[tuple[str, float]],
812
+ char_lora: str | None,
813
+ char_strength: float,
814
+ ) -> dict[str, Any]:
815
+ # --- loader 链:命中缓存则复用(节点 id / inputs 完全一致) ---
816
+ key = _combo_key(engine, unet_name, base_loras, char_lora, char_strength)
817
+ cached = _loader_chain_cache.get(key)
818
+ if cached is not None:
819
+ chain, current_model_node = cached
820
+ workflow = dict(chain) # 浅拷贝,下游不改 loader 链
821
+ else:
822
+ chain, current_model_node = _build_loader_chain(
823
+ engine, unet_name, base_loras, char_lora, char_strength)
824
+ _loader_chain_cache[key] = (chain, current_model_node)
825
+ # 只保留最近 8 个组合,避免内存无限增长
826
+ if len(_loader_chain_cache) > 8:
827
+ _loader_chain_cache.pop(next(iter(_loader_chain_cache)))
828
+ workflow = dict(chain)
829
+
830
+ # --- 下游节点:id 从链末端续接,与原逻辑完全一致 ---
831
+ nodes = MODEL_CONFIG["node_types"]
832
+ node_idx = max(int(k) for k in chain.keys()) + 1
833
+
834
+ final_prompt = prompt.strip()
835
+ workflow[str(node_idx)] = {"class_type": "CLIPTextEncode", "inputs": {"clip": _ref("2"), "text": final_prompt}}
836
+ workflow[str(node_idx+1)] = {"class_type": "ConditioningZeroOut", "inputs": {"conditioning": _ref(str(node_idx))}}
837
+ workflow[str(node_idx+2)] = {"class_type": "EmptyLatentImage", "inputs": {"width": width, "height": height, "batch_size": 1}}
838
+
839
+ workflow[str(node_idx+3)] = {"class_type": "KSampler", "inputs": {"model": _ref(current_model_node), "positive": _ref(str(node_idx)), "negative": _ref(str(node_idx+1)), "latent_image": _ref(str(node_idx+2)), "seed": seed, "steps": steps, "cfg": cfg, "sampler_name": sampler, "scheduler": scheduler, "denoise": 1.0}}
840
+ workflow[str(node_idx+4)] = {"class_type": "VAEDecode", "inputs": {"samples": _ref(str(node_idx+3)), "vae": _ref("3")}}
841
+ workflow[str(node_idx+5)] = {"class_type": "SaveImage", "inputs": {"images": _ref(str(node_idx+4)), "filename_prefix": MODEL_CONFIG["name"].lower()}}
842
+ return workflow
843
+
844
  def _log_workflow_summary(workflow: dict[str, Any], task_id: str, load_time_val: float, wf_time: float, image: str = None):
845
  """独立提取并打印单行 JSON 摘要日志(不影响主流程逻辑)"""
846
  try:
 
915
 
916
  except Exception as e:
917
  print(f"[Log Format Error]: {e}", flush=True)
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
918
 
919
  def _execute_workflow(workflow: dict[str, Any], task_id: str = None) -> list[str]:
920
  print_ram_status("任务开始前")
 
1049
  _tqdm_patch_exit()
1050
  _current_download_task_id.set(None)
1051
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1052
 
1053
  # ==========================================================================
1054
+ # 🔥 GPU-side Residual Warmup Wait (same /tmp channel as _read_metric)
1055
  # ==========================================================================
1056
  def _read_warm_state():
1057
  try:
 
1063
 
1064
  def _warm_wait_in_gpu(unet_choice: str, budget: float = WARMUP_RESIDUAL_WAIT) -> bool:
1065
  """只在"已经非常接近完成"时等,最多 budget 秒。
1066
+ 注意:这段是在 GPU 切片内执行,等待即烧配额,所以必须能提前放弃。"""
1067
  t0 = time.time()
1068
  while time.time() - t0 < budget:
1069
  st = _read_warm_state()
1070
+
1071
+ if st and st.get("target") == unet_choice:
1072
+ if st.get("state") == "ready":
1073
+ print(f"[预热] ✅ GPU 内等到 ready({time.time() - t0:.2f}s)", flush=True)
1074
+ return True
1075
+ # ⚠️ 进度太低 = 还在冷读,等满 budget 也等不到。立刻放行,省下配额。
1076
+ p = float(st.get("progress") or 0.0)
1077
+ if p < 0.9:
1078
+ saved = budget - (time.time() - t0)
1079
+ print(f"[预热] ⏭️ 进度仅 {p:.2f},放弃残余等待(省 {saved:.1f}s GPU)", flush=True)
1080
+ return False
1081
+
1082
+ elif time.time() - t0 > 0.5:
1083
+ # 0.5 秒内 target 还没轮到本模型(比如 sweep 占着),也别等
1084
+ print(
1085
+ f"[预热] ⏭️ target={st.get('target') if st else None} ≠ 本模型,放弃残余等待",
1086
+ flush=True,
1087
+ )
1088
+ return False
1089
+
1090
  time.sleep(0.25)
1091
+
1092
  print(f"[预热] ⏳ GPU 内残余等待超时({budget}s),转冷加载", flush=True)
1093
  return False
1094
 
1095
 
1096
+ # ==========================================================================
1097
+ # 🎬 Generation
1098
+ # ==========================================================================
1099
+
1100
  def _generate_impl(
1101
  prompt: str, unet_choice: str, custom_w: int, custom_h: int,
1102
  steps: int, cfg: float, seed: int, sampler: str, scheduler: str,
 
1177
 
1178
 
1179
  # ==========================================================================
1180
+ # 🧹 Cleanup
1181
  # ==========================================================================
1182
 
1183
 
 
1184
  # 专门用于保护 tasks_status 字典的状态锁
1185
  _status_lock = threading.RLock()
1186
  _model_switch_lock = threading.Lock()
1187
 
1188
+ # ---- Cleanup Policy ----
1189
  _STATUS_TTL = 3600 # 终态任务内存保留 60 分钟
1190
  _STATUS_MAX_ENTRIES = 200 # 兜底:最多保留 200 条终态
1191
  _OUTPUT_TTL = 24 * 3600 # 输出图片保留 24 小时
 
1244
  if deleted:
1245
  print(f"[清理] 🧹 删除 {deleted} 个过期输出,释放 {freed / 1024 / 1024:.1f} MB", flush=True)
1246
 
1247
+ def _read_last_unet():
1248
+ try:
1249
+ with open(WARMUP_LAST_FILE) as f:
1250
+ return json.load(f).get("unet_choice")
1251
+ except Exception:
1252
+ return None
1253
+
1254
 
1255
  # ==========================================================================
1256
+ # 🔥 WarmupManager: File-level Page-cache Warmup State Machine
1257
  # ==========================================================================
1258
  class WarmupManager:
1259
  def __init__(self):
 
1669
  print(f"[预热] 🔥 start target={target} reason={plan.get('reason')} "
1670
  f"files={len(files)} big={big_total:.0f}MB lite={lite}", flush=True)
1671
 
1672
+ # for rec in files:
1673
+ # if self._superseded(seq):
1674
+ # done_mb = sum(
1675
+ # r.get("size_mb", 0) for r in records.values()
1676
+ # if r.get("state") in ("warm", "skipped")
1677
+ # )
1678
+ # pct = (done_mb / big_total * 100) if big_total else 0.0
1679
+ # print(
1680
+ # f"[预热] ⏹️ 被新目标抢占 (seq={seq}),"
1681
+ # f"已完成 {done_mb:.0f}MB/{big_total:.0f}MB ({pct:.0f}%),"
1682
+ # f"用时 {time.time() - t0:.1f}s",
1683
+ # flush=True,
1684
+ # )
1685
+ # break
1686
+ # records[f"{rec['owner']}::{rec['file_key']}"] = rec
1687
+
1688
+ # # ✅ 预算裁剪:request_sweep() 已判定超预算的记录,直接跳过,别再读
1689
+ # if rec.get("state") == "skipped":
1690
+ # self._flush(plan, records)
1691
+ # continue
1692
+
1693
+ # if rec["size_mb"] < WARMUP_MIN_MB:
1694
+ # rec.update(state="skipped", progress=1.0)
1695
+ # self._flush(plan, records)
1696
+ # continue
1697
+
1698
  for rec in files:
1699
  if self._superseded(seq):
1700
  print(f"[预热] ⏹️ 被新目标抢占 (seq={seq})", flush=True)
 
1713
  self._flush(plan, records)
1714
  continue
1715
 
1716
+ old = self._files.get(rec["owner"], {}).get(rec["file_key"])
1717
+ if (old and old["state"] == "warm" and old["size_mb"] == rec["size_mb"]
1718
+ and (time.time() - old.get("verified_at", 0)) < WARMUP_TTL):
1719
+ rec.update({**old, "state": "warm"}) # 直接复用,不重读
1720
+ self._flush(plan, records)
1721
+ continue
1722
+
1723
  old = self._files.get(rec["owner"], {}).get(rec["file_key"])
1724
  if (old and old["state"] == "warm" and old["size_mb"] == rec["size_mb"]
1725
  and (time.time() - old.get("verified_at", 0)) < WARMUP_TTL):
 
1813
 
1814
 
1815
  warmup = WarmupManager()
1816
+
1817
+ def _boot_warmup():
1818
+ """两段式:
1819
+ ① 阶梯一级(<1s):上次模型的 UNET 头部 → 用户第一眼就有"部分热"
1820
+ ② 全量 sweep(P1,可被抢占):等 ① 跑完再启动,否则会把 ① 顶掉
1821
+ """
1822
+ last = _read_last_unet()
1823
+ target = last if last in UNET_CHOICES else next(iter(UNET_CHOICES), None)
1824
+
1825
+ lite_requested = False
1826
+ if target:
1827
+ rec = warmup._rec(MODELS / "diffusion_models" / UNET_CHOICES[target]["filename"],
1828
+ "unet", "unet")
1829
+ mbps = warmup.probe(rec)
1830
+ if mbps is not None and mbps >= WARMUP_WARM_MBPS:
1831
+ print(f"[预热] ⚡ boot: UNET 已在 cache 中 ({mbps:.0f}MB/s),跳过 lite", flush=True)
1832
+ else:
1833
+ print(f"[预热] 🥾 boot: UNET 探测 {mbps} MB/s → 做阶梯一级", flush=True)
1834
+ warmup.request(target, lite=True, reason="boot", priority=1)
1835
+ lite_requested = True # ← 新增
1836
+
1837
+ if not WARMUP_BOOT_FULL:
1838
+ return
1839
+
1840
+ if lite_requested: # ← 只在发起了才等
1841
+ t0 = time.time()
1842
+ while time.time() - t0 < 20:
1843
+ with warmup._lock:
1844
+ r = warmup._files.get(target, {}).get("unet")
1845
+ if r and r.get("state") in ("partial", "warm", "failed", "stale"):
1846
+ break
1847
+ time.sleep(0.2)
1848
+
1849
+ warmup.request_sweep(reason="boot_sweep")
1850
 
1851
  # ==========================================================================
1852
  # 🌐 FastAPI & API Routes
 
1866
  char_strength: float = 1.0
1867
  base_lora_states: list = []
1868
 
1869
+ app = FastAPI()
1870
+
1871
+
1872
+ app.add_middleware(
1873
+ CORSMiddleware,
1874
+ allow_origins=["*"],
1875
+ allow_credentials=True,
1876
+ allow_methods=["*"],
1877
+ allow_headers=["*"],
1878
+ )
1879
+
1880
 
1881
  def background_generate_task(task_id: str, req: GenerateRequest, ip_token: str = None, request: Request = None):
1882
  global _last_used_architecture, _last_used_unet
 
2073
  _gen_leave()
2074
  _current_generation_task_id.set(None)
2075
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
2076
 
2077
  @app.on_event("startup")
2078
  async def _on_startup():
 
2083
  except Exception as e:
2084
  print(f"[预热] ⚠️ boot 异常: {e}", flush=True)
2085
  threading.Thread(target=_delayed, daemon=True).start()
 
2086
 
2087
+ @app.get("/api/models")
2088
+ async def get_models():
2089
+ models_data = {}
2090
+ global_default_prompt = MODEL_CONFIG.get("default_prompt", "")
 
 
 
2091
 
2092
+ for unet_name, unet_info in UNET_CHOICES.items():
2093
+ engine = unet_info["engine"]
2094
+ engine_name = MODEL_CONFIG["models"].get(engine, {}).get("name", engine)
2095
+
2096
+ if " | " in unet_name:
2097
+ model_specific_name = unet_name.split(" | ", 1)[1]
2098
+ else:
2099
+ model_specific_name = unet_name
2100
+
2101
+ display_unet_name = f"{engine_name} | {model_specific_name}"
2102
+
2103
+ base_loras_for_engine = []
2104
+ for name, cfg in BASE_LORAS_CHOICES.items():
2105
+ if cfg["engine"] == engine:
2106
+ base_loras_for_engine.append({
2107
+ "name": name,
2108
+ "filename": cfg["filename"],
2109
+ "defaultEnable": cfg.get("defaultEnable", False)
2110
+ })
2111
+
2112
+ engine_cfg = MODEL_CONFIG["models"].get(engine, {})
2113
+ final_prompt = engine_cfg.get("default_prompt_override", global_default_prompt)
2114
+
2115
+ # 🌟 核心新增:提取 TE 和 VAE 信息
2116
+ # TE 可能是列表,用 " + " 连接起来展示
2117
+ te_list = engine_cfg.get("local_te_filename", [])
2118
+ te_display = " + ".join([f.replace(".safetensors", "") for f in te_list]) if te_list else "Unknown"
2119
+
2120
+ # VAE 通常是字符串
2121
+ vae_display = engine_cfg.get("local_vae_filename", "Unknown").replace(".safetensors", "")
2122
+
2123
+ models_data[display_unet_name] = {
2124
+ "engine": engine,
2125
+ "defaults": engine_cfg.get("defaults", {}),
2126
+ "base_loras": base_loras_for_engine,
2127
+ "default_prompt": final_prompt,
2128
+ "te_name": te_display, # 👈 传给前端
2129
+ "vae_name": vae_display # 👈 传给前端
2130
+ }
2131
+
2132
+ return {"models": models_data}
2133
+
2134
+ @app.get("/api/loras")
2135
+ async def get_loras():
2136
+ # ⚠️ load_char_loras_from_repo 里有同步 requests.get + list_repo_files(网络 IO)。
2137
+ # 直接在 async 路由里调用会阻塞 event loop,期间所有请求(含 /api/config)
2138
+ # 都无法处理,HF 代理超时后会 reset 连接 → 前端表现为 "Failed to fetch"。
2139
+ # 扔进线程池执行,event loop 保持畅通。
2140
+ await asyncio.to_thread(load_char_loras_from_repo)
2141
+ return {"loras": CHAR_LORA_CHOICES}
2142
+
2143
+ @app.get("/api/config")
2144
+ async def get_sampler_config():
2145
+ return {
2146
+ "samplers": SAMPLERS,
2147
+ "schedulers": SCHEDULERS,
2148
+ "root_mapping": MODEL_CONFIG.get("json_keys", {}).get("root_mapping", {}),
2149
+ "default_prompt": MODEL_CONFIG.get("default_prompt", ""),
2150
+ }
2151
+
2152
+ @app.get("/api/health")
2153
+ async def health_check():
2154
+ return {"status": "ok"}
2155
 
2156
  @app.post("/api/generate")
2157
  async def handle_generate(req: GenerateRequest, background_tasks: BackgroundTasks, request: Request):
 
2190
  tasks_status[task_id] = {"status": "queued", "message": "⏳ 任务已进入队列..."}
2191
 
2192
  # 👇 抛弃 BackgroundTasks,使用原生守护线程,直接与 HTTP 返回脱钩
 
2193
  t = threading.Thread(
2194
  target=background_generate_task,
2195
  args=(task_id, req, ip_token, request),
 
2220
  status_data["message"] = file_data["phase"]
2221
  return status_data
2222
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
2223
 
2224
+ # ==========================================================================
2225
+ # 🔥 Warmup Endpoints
2226
+ # ==========================================================================
 
 
 
 
 
2227
 
2228
  class WarmupRequest(BaseModel):
2229
  unet_choice: str
 
2277
  return warmup.snapshot()
2278
 
2279
  # ==========================================================================
2280
+ # 🔧 Warmup Debug Endpoint (disabled by default)
2281
+ # Set WARMUP_DEBUG_TOKEN in Space Secrets; send X-Debug-Token header or ?token=
2282
  # ==========================================================================
2283
  import hmac
2284
 
 
2445
 
2446
  raise HTTPException(400, f"unknown action: {action}")
2447
 
 
 
 
 
2448
  # ==========================================================================
2449
  # 📁 Static Files Sync & Mount
2450
  # ==========================================================================
 
2480
  # 1. 启动时执行同步
2481
  sync_ui_assets()
2482
 
 
2483
  # 🌟 核心修改:必须在挂载根路径 "/" 之前,先挂载 /output 目录
 
2484
  app.mount("/output", StaticFiles(directory=str(OUTPUT)), name="output")
2485
 
2486
  # 2. 挂载静态文件夹 (前端)