"""Independent, MOSS-only LoRA catalogue with owner-authenticated shared writes. Reads and exports never mutate the bucket. Explicit Add/Delete/Import operations authenticate the caller's own token, re-read the remote file, and merge only that operation. No anonymous caller can spend the Space owner's token on a write. """ from contextlib import contextmanager from datetime import datetime, timezone import copy import hashlib import json import math import os from pathlib import Path import re import tempfile import threading import time from urllib.parse import quote, unquote, urlparse, urlunparse import gradio as gr import requests MODEL = "moss-image" MAX_JSON_BYTES = 4 * 1024 * 1024 MAX_ENTRIES = 2000 _COLLECTIONS = ("normal", "nsfw", "items", "loras", "entries", "library") _METADATA = {"version", "schema_version", "model", "base_model", "exported_at", "metadata"} _SOURCES = ("source", "reference", "url", "download_url", "repo", "repo_id") def _now(): return datetime.now(timezone.utc).isoformat(timespec="microseconds").replace("+00:00", "Z") def _model(value): value = str(value or MODEL).strip().casefold().replace("_", "-") compact = re.sub(r"[\s-]+", "", value.rsplit("/", 1)[-1]) if compact not in {"moss", "mossimage", "mossi2i", "mossimagei2i", "mossimageedit", "mossimagebase", "mossimagesft"}: raise gr.Error("This catalogue accepts MOSS Image LoRAs only. Select moss-image.") return MODEL def _source(value): source = str(value or "").strip().strip("\"'") if not source or len(source) > 4096 or any(ord(char) < 32 for char in source): raise gr.Error("Provide a LoRA URL or a Hugging Face model/bucket file reference.") if source.startswith(("hf://buckets/", "buckets/")): parts = source.removeprefix("hf://").split("/") if len(parts) < 4 or any(p in ("", ".", "..") for p in parts): raise gr.Error("Use hf://buckets/owner/bucket/file.safetensors for bucket files.") source = "https://huggingface.co/buckets/" + "/".join(parts[1:3]) + "/resolve/" + quote("/".join(parts[3:]), safe="/") parsed = urlparse(source) if parsed.scheme: if parsed.scheme not in ("https", "http") or not parsed.hostname or parsed.username or parsed.password: raise gr.Error("Use an HTTP(S) URL without embedded credentials or a Hugging Face reference.") if parsed.hostname.casefold() in {"huggingface.co", "www.huggingface.co", "hf.co"}: path = parsed.path.replace("/blob/", "/resolve/", 1) source = urlunparse(("https", "huggingface.co", path, "", parsed.query, "")) return source parts = source.split("/") if (len(parts) < 2 or "\\" in source or any(p in ("", ".", "..") for p in parts) or any(not re.fullmatch(r"[A-Za-z0-9_.-]+", p) for p in parts[:2]) or (len(parts) > 2 and not source.casefold().endswith(".safetensors"))): raise gr.Error("Use owner/repo[/file.safetensors], a download URL, or a HF bucket file reference.") return source def _source_key(source): """Collapse equivalent HF blob/resolve/ref spellings for deduplication.""" parsed = urlparse(source) if parsed.hostname == "huggingface.co": parts = unquote(parsed.path).strip("/").split("/") if len(parts) >= 5 and parts[2:4] == ["resolve", "main"]: return "/".join(parts[:2] + parts[4:]) if parts and parts[0] == "buckets": return "https://huggingface.co/" + "/".join(parts) return source def _stamp(value, *, missing=None): if value in (None, ""): return missing or _now() try: if isinstance(value, (int, float)) and not isinstance(value, bool): # Older exports sometimes use Date.now() milliseconds. value = value / 1000 if abs(value) >= 100_000_000_000 else value stamp = datetime.fromtimestamp(value, timezone.utc) else: stamp = datetime.fromisoformat(str(value).replace("Z", "+00:00")) if stamp.tzinfo is None: stamp = stamp.replace(tzinfo=timezone.utc) return stamp.astimezone(timezone.utc).isoformat(timespec="microseconds").replace("+00:00", "Z") except (TypeError, ValueError, OverflowError, OSError) as error: raise gr.Error("LoRA dates must be ISO dates or Unix timestamps.") from error def _clean(raw, default_model=MODEL, fallback_name="", *, old=False): if isinstance(raw, str): raw = {"source": raw, "name": fallback_name} if not isinstance(raw, dict) or raw.get("high") or raw.get("low"): raise gr.Error("Import individual MOSS image LoRAs, not paired video adapters.") model = _model(raw.get("model") or raw.get("base_model") or raw.get("baseModel") or default_model) source = next((raw.get(key) for key in _SOURCES[:4] if raw.get(key)), None) if not source: source = raw.get("repo") or raw.get("repo_id") weight = raw.get("weights") or raw.get("weight_name") or raw.get("filename") if source and weight: source = str(source).rstrip("/") + "/" + str(weight).lstrip("/") source = _source(source) name = str(raw.get("name") or raw.get("title") or fallback_name or "").strip() if not name: name = unquote(urlparse(source).path.rstrip("/").split("/")[-1]).removesuffix(".safetensors") if not name or len(name) > 160: raise gr.Error("Give the LoRA a name of 1-160 characters.") try: strength = float(raw.get("strength", raw.get("scale", raw.get("default_strength", raw.get("weight", 1.0))))) if not math.isfinite(strength) or not 0 <= strength <= 4: raise ValueError except (ValueError, TypeError): raise gr.Error("Default LoRA strength must be between 0 and 4.") trigger = raw.get("trigger", raw.get("trigger_words", raw.get("triggerWords", raw.get("trainedWords", "")))) if isinstance(trigger, (tuple, list)): trigger = ", ".join(str(word).strip() for word in trigger if str(word).strip()) trigger = str(trigger or "").strip() author = str(raw.get("author") or raw.get("creator") or "").strip() collector_url = urlparse(str(raw.get("url") or source)) if (not author and collector_url.hostname == "civitai.red" and re.fullmatch(r"/api/download/models/[0-9]+/?", collector_url.path) and urlparse(str(raw.get("page") or "")).hostname == "civitai.red" and all(key in raw for key in ("high", "low", "added"))): author = str(raw.get("owner") or "").strip() if len(trigger) > 8192 or len(author) > 160: raise gr.Error("Use at most 8,192 characters for triggers and 160 for the author.") timestamp = raw.get("added_at", raw.get("added", raw.get("created_at", raw.get("createdAt")))) digest = hashlib.sha256((model + "\n" + _source_key(source)).encode()).hexdigest()[:24] result = dict(raw) # Only the known collector schema uses owner for creator attribution; # browser ownership in other legacy JSON is not authorship or authorization. result.update(id="moss-" + digest, name=name, source=source, model=model, trigger=trigger, strength=strength, author=author, modes=["i2i"], kind="adapter", added_at=_stamp(timestamp, missing="1970-01-01T00:00:00.000000Z" if old else None)) result.pop("remote", None) result.pop("builtin", None) result.pop("style_name", None) return result def _container(payload): """Return collection key and list/mapping, retaining the original envelope.""" if isinstance(payload, list): return None, payload if isinstance(payload, dict): for key in _COLLECTIONS: if key in payload: if not isinstance(payload[key], (list, dict)): raise gr.Error("The library collection must be a list or name-to-entry mapping.") return key, payload[key] if any(key in payload for key in _SOURCES): return "__single__", [payload] if not payload or any(key not in _METADATA for key in payload): return None, payload raise gr.Error("Import a normal/items/loras catalogue, a list, or a name-to-entry mapping.") def _records(payload): # The collector deliberately exports normal=[] and all selected entries in # nsfw. Read both groups, retaining provenance so imports keep that grouping. if isinstance(payload, dict) and "nsfw" in payload: records = [] for group in ("normal", "nsfw"): if group not in payload: continue for name, raw in _records({"items": payload[group]}): if isinstance(raw, dict): raw = {**raw, "_catalog_group": group} if group == "nsfw": raw.setdefault("nsfw", True) elif isinstance(raw, str): raw = {"source": raw, "name": name, "_catalog_group": group, "nsfw": group == "nsfw"} records.append((name, raw)) if len(records) > MAX_ENTRIES: raise gr.Error("The catalogue must contain at most 2,000 entries.") return records _, rows = _container(payload) records = list(rows.items()) if isinstance(rows, dict) else [("", row) for row in rows] records = [(str(name), row) for name, row in records if name not in _METADATA] if len(records) > MAX_ENTRIES: raise gr.Error("The catalogue must contain at most 2,000 entries.") return records def _parsed(payload, default_model=MODEL): result = {} for name, raw in _records(payload): try: entry = _clean(raw, default_model, name, old=True) except (gr.Error, ValueError, TypeError): continue # Other model rows and unknown metadata remain untouched remotely. previous = result.get(entry["id"]) if previous is None or entry["added_at"] > previous["added_at"]: result[entry["id"]] = entry return list(result.values()) def _merge(payload, upserts=(), deleted=()): """Preserve unrelated metadata/records and deduplicate changed source IDs.""" result = copy.deepcopy(payload) if isinstance(result, dict) and "nsfw" in result: incoming = list(upserts) old_nsfw = {row["id"] for row in _parsed({"items": result["nsfw"]})} groups = {"normal": [], "nsfw": []} for entry in incoming: group = "nsfw" if (entry["id"] in old_nsfw or entry.get("_catalog_group") == "nsfw" or entry.get("nsfw") is True) else "normal" groups[group].append(entry) for group in ("normal", "nsfw"): if group in result or groups[group]: result[group] = _merge({"items": result.get(group, [])}, groups[group], deleted)["items"] _records(result) # Enforce the total limit across both collections. return result if isinstance(result, dict) and "normal" in result and any(entry.get("_catalog_group") == "nsfw" or entry.get("nsfw") is True for entry in upserts): result["nsfw"] = [] return _merge(result, upserts, deleted) key, rows = _container(result) additions = {entry["id"]: dict(entry) for entry in upserts} removed = set(deleted) changed = set(additions) output = [] emitted = set() for fallback, raw in _records(result): try: entry = _clean(raw, MODEL, fallback, old=True) except (gr.Error, ValueError, TypeError): output.append((fallback, raw)) continue item_id = entry["id"] if item_id in removed or (item_id in changed and item_id in emitted): continue if item_id in additions: update = additions.pop(item_id) update["added_at"] = entry["added_at"] raw = {**(raw if isinstance(raw, dict) else {}), **update, "url": update["source"], "added": update["added_at"]} emitted.add(item_id) output.append((fallback, raw)) for entry in additions.values(): output.append((entry["name"], {**entry, "url": entry["source"], "added": entry["added_at"]})) if len(output) > MAX_ENTRIES: raise gr.Error("The catalogue would exceed 2,000 entries; nothing was written.") if isinstance(rows, dict): restored = {name: value for name, value in rows.items() if name in _METADATA} for fallback, raw in output: name = fallback or str(raw.get("name", "LoRA")) base, suffix = name, 2 while name in restored: name = f"{base} ({suffix})" suffix += 1 restored[name] = raw else: restored = [raw for _, raw in output] if key == "__single__": return restored[0] if len(restored) == 1 else {"version": 1, "items": restored} if key is None: return restored result[key] = restored return result class MossCatalog: def __init__(self, cache_dir=None, bucket=None, filename="library.json", write_token_provider=None): self.bucket = (bucket or os.getenv("MOSS_LORA_LIBRARY_BUCKET", "amisima/moss-lora")).strip().strip("/") self.filename = os.getenv("MOSS_LORA_LIBRARY_FILE", filename).strip().strip("/") if (not re.fullmatch(r"[A-Za-z0-9_.-]+/[A-Za-z0-9_.-]+", self.bucket) or "\\" in self.filename or any(p in ("", ".", "..") for p in self.filename.split("/"))): raise ValueError("Invalid MOSS LoRA bucket or catalogue filename.") self.owner = self.bucket.split("/")[0] self.cache_dir = Path(cache_dir or os.path.join(tempfile.gettempdir(), "moss-lora-catalog")) cache_key = hashlib.sha256((self.bucket + "/" + self.filename).encode()).hexdigest()[:16] self.cache_file = self.cache_dir / ("moss-" + cache_key + ".json") self.lock_file = self.cache_dir / ("moss-" + cache_key + ".lock") self.write_token_provider = write_token_provider self._lock = threading.RLock() self._notice = "Sync the MOSS library to load its shared entries." @contextmanager def _transaction(self): with self._lock: self.cache_dir.mkdir(parents=True, exist_ok=True) with self.lock_file.open("a", encoding="utf-8") as handle: try: import fcntl except ImportError: fcntl = None if fcntl: fcntl.flock(handle.fileno(), fcntl.LOCK_EX) try: yield finally: if fcntl: fcntl.flock(handle.fileno(), fcntl.LOCK_UN) def _cached(self): if not self.cache_file.exists(): return {"version": 1, "model": MODEL, "normal": []} try: with self.cache_file.open(encoding="utf-8") as handle: payload = json.load(handle) _container(payload) return payload except (OSError, ValueError, gr.Error) as error: raise gr.Error("The MOSS library cache could not be read. Sync to reload it; no shared changes were made.") from error def _save_cache(self, payload): self.cache_dir.mkdir(parents=True, exist_ok=True) temporary = None try: with tempfile.NamedTemporaryFile(mode="w", encoding="utf-8", dir=self.cache_dir, prefix="moss-cache-", suffix=".tmp", delete=False) as handle: temporary = handle.name json.dump(payload, handle, ensure_ascii=False, indent=2, allow_nan=False) handle.flush() os.fsync(handle.fileno()) os.replace(temporary, self.cache_file) finally: if temporary and os.path.exists(temporary): os.remove(temporary) @staticmethod def _get_json(url, read_token=None): headers = {"Accept": "application/json"} response = requests.get(url, headers=headers, params={"cb": time.time_ns()}, timeout=(10, 30), stream=True) if response.status_code in (401, 403) and read_token: response.close() headers["Authorization"] = "Bearer " + read_token response = requests.get(url, headers=headers, params={"cb": time.time_ns()}, timeout=(10, 30), stream=True) try: if response.status_code == 404: return None if response.status_code != 200: raise RuntimeError(f"Hugging Face catalogue read returned HTTP {response.status_code}.") data = bytearray() for chunk in response.iter_content(65536): data.extend(chunk) if len(data) > MAX_JSON_BYTES: raise ValueError("The MOSS catalogue exceeds the 4 MB limit.") return json.loads(data) finally: response.close() def _read_remote(self, token=None): token = token or os.getenv("HF_TOKEN") or os.getenv("HUGGINGFACE_HUB_TOKEN") url = f"https://huggingface.co/buckets/{self.bucket}/resolve/{quote(self.filename, safe='/')}" payload = self._get_json(url, token) if payload is None: metadata = self._get_json(f"https://huggingface.co/api/buckets/{self.bucket}", token) if not isinstance(metadata, dict) or metadata.get("repoType") != "bucket": raise RuntimeError("The MOSS bucket could not be read; no write is safe.") payload = {"version": 1, "model": MODEL, "normal": []} _records(payload) return payload def _authorize(self, write_token=None): token = write_token or (self.write_token_provider() if self.write_token_provider else None) if not isinstance(token, str) or not token.strip(): raise gr.Error("To change the shared MOSS library, enter its owner's Hugging Face write token. Browsing and using LoRAs require no token.") token = token.strip() try: from huggingface_hub import HfApi identity = HfApi(token=token).whoami() except Exception: raise gr.Error("The Hugging Face token could not be verified. The catalogue was not changed.") from None if str(identity.get("name", "")).casefold() != self.owner.casefold(): raise gr.Error(f"Only the owner of {self.bucket} can change this shared catalogue.") return token def _write_remote(self, payload, token): from huggingface_hub import HfFileSystem data = json.dumps(payload, ensure_ascii=False, indent=2, allow_nan=False).encode("utf-8") if len(data) > MAX_JSON_BYTES: raise gr.Error("The MOSS catalogue would exceed 4 MB; nothing was written.") with HfFileSystem(token=token).open(f"buckets/{self.bucket}/{self.filename}", "wb") as handle: handle.write(data) def _commit(self, upserts=(), deleted=(), write_token=None): token = self._authorize(write_token) with self._transaction(): # Never push the cached catalogue or unrelated local records. fresh = self._read_remote(token) merged = _merge(fresh, upserts, deleted) if merged != fresh: # A second read detects edits during preparation. HF buckets do # not provide compare-and-swap here; independent writers still # must be serialized by their owner. Do not retry on conflict. if self._read_remote(token) != fresh: raise gr.Error("The shared MOSS library changed during this edit. Sync and try again; nothing was written.") self._write_remote(merged, token) verified = self._read_remote(token) if verified != merged: raise gr.Error("The shared save could not be verified. Sync before trying again; no automatic retry was made.") else: verified = fresh self._save_cache(verified) self._notice = f"Saved to {self.bucket}/{self.filename}." def entries(self, query=""): with self._transaction(): entries = _parsed(self._cached()) terms = str(query or "").casefold().split() entries = [entry for entry in entries if all(term in " ".join(str(entry.get(key, "")) for key in ("name", "source", "model", "trigger", "author", "description")).casefold() for term in terms)] return sorted(entries, key=lambda item: (item["added_at"], item["name"].casefold(), item["id"]), reverse=True) def find(self, entry_id): entry = next((entry for entry in self.entries() if entry["id"] == entry_id), None) if entry is None: raise gr.Error("Select a MOSS LoRA from its library. Sync if the shared catalogue changed.") return entry def refresh(self, query="", selected_id=None): entries = self.entries(query) selected = selected_id if any(item["id"] == selected_id for item in entries) else (entries[0]["id"] if entries else None) choices = [(entry["name"] + (" — " + entry["author"] if entry["author"] else "") + " · MOSS", entry["id"]) for entry in entries] return gr.update(choices=choices, value=selected), f"{len(entries)} MOSS LoRAs · newest added first. {self._notice}" def sync(self, query="", selected_id=None): try: with self._transaction(): fresh = self._read_remote() self._save_cache(fresh) self._notice = f"Synced {len(_parsed(fresh))} MOSS LoRAs from {self.bucket}." except Exception as error: self._notice = f"MOSS sync failed ({type(error).__name__}); keeping the last saved catalogue." return self.refresh(query, selected_id) def add(self, name, source, model=MODEL, trigger="", strength=1.0, author="", query="", *, write_token=None): entry = _clean(dict(name=name, source=source, model=model, trigger=trigger, strength=strength, author=author)) self._commit([entry], write_token=write_token) return self.refresh(query, entry["id"]) def delete(self, entry_id, query="", *, write_token=None): entry = self.find(entry_id) self._commit(deleted=[entry["id"]], write_token=write_token) return self.refresh(query) def import_file(self, path, default_model=MODEL, query="", *, write_token=None): _model(default_model) path = path if isinstance(path, (str, os.PathLike)) else getattr(path, "name", "") if not path or not os.path.isfile(path) or os.path.getsize(path) > MAX_JSON_BYTES: raise gr.Error("Choose a library JSON file smaller than 4 MB.") try: with open(path, encoding="utf-8-sig") as handle: payload = json.load(handle) except (OSError, ValueError): raise gr.Error("The selected file is not readable library JSON.") from None incoming = {} skipped = 0 for name, raw in _records(payload): try: item = _clean(raw, default_model, name) except (gr.Error, ValueError, TypeError): skipped += 1 continue incoming[item["id"]] = item if not incoming: raise gr.Error("The file contains no valid MOSS LoRAs. Check its model tags and sources.") self._commit(list(incoming.values()), write_token=write_token) self._notice += f" Imported {len(incoming)} MOSS LoRAs" + (f"; skipped {skipped} incompatible or invalid rows." if skipped else ".") return self.refresh(query) def export(self): # Export only MOSS entries, including their additional original metadata. payload = {"version": 1, "model": MODEL, "exported_at": _now(), "items": self.entries()} with tempfile.NamedTemporaryFile(mode="w", encoding="utf-8", prefix="moss-lora-library-", suffix=".json", delete=False) as handle: json.dump(payload, handle, ensure_ascii=False, indent=2, allow_nan=False) path = handle.name return gr.update(value=path, visible=True)