This commit is contained in:
4DBug committed 2026-10-25 10:08:15 -05:00
1 parent c86ee98def
commit a3163cdd43
29 files changed
+693 -231

No files matched your search

+1 -1
View File
@@ -8,7 +8,7 @@
wine64
wineWow64Packages.full
appimage-run
inputs.nix-alien.packages.${pkgs.stdenv.hostPlatform.system}.nix-alien
#inputs.nix-alien.packages.${pkgs.stdenv.hostPlatform.system}.nix-alien
];
programs.appimage = {
+7 -4
View File
@@ -311,6 +311,9 @@ time_format = "{:%-I:%M %p}"
[shell.window_switcher]
style = "compact"
[shell.screenshot]
directory = "/home/bug/media/images/screenshots"
[theme]
builtin = "Catppuccin"
community_palette = "Catppuccin Mocha Mauve-Lavender"
@@ -319,16 +322,16 @@ source = "community"
wallpaper_scheme = "m3-fruit-salad"
[wallpaper.default]
path = "/home/bug/Pictures/Wallpapers/nix.png"
path = "/home/bug/media/images/wallpapers/nix.png"
[wallpaper.last]
path = "/home/bug/Pictures/Wallpapers/nix.png"
path = "/home/bug/media/images/wallpapers/nix.png"
[wallpaper.monitors.eDP-2]
path = "/home/bug/Pictures/Wallpapers/nix.png"
path = "/home/bug/media/images/wallpapers/nix.png"
[wallpaper.monitors.winit]
path = "/home/bug/Pictures/Wallpapers/nix.png"
path = "/home/bug/media/images/wallpapers/nix.png"
[weather]
unit = "imperial"
+19
View File
@@ -1,5 +1,24 @@
{
den.aspects.system.desktop.xdg = {
homeManager = { config, ... }: let home = config.home.homeDirectory; in {
xdg.userDirs = {
enable = true;
createDirectories = true;
download = "${home}/down";
documents = "${home}/library/documents";
pictures = "${home}/media/images";
music = "${home}/media/music";
videos = "${home}/media/video";
projects = "${home}/dev";
# set to ~ to disable them, per the xdg-user-dirs convention
desktop = home;
templates = home;
publicShare = home;
};
};
nixos = { pkgs, ... }: {
xdg = {
portal = {
+32 -28
View File
@@ -6,37 +6,41 @@
user = host.owner;
interval = "10min";
gracePeriod = 60;
watchedDirs = [ "~/Downloads" ];
watchedDirs = [ "~/down" ];
# destinations are relative to ~ (the watched dir's parent)
rules = {
"Pictures/Downloads" = [ "jpg" "jpeg" "png" "gif" "webp" "svg" "heic" "avif" "ico" ];
"Videos/Downloads" = [ "mp4" "mkv" "mov" "webm" "avi" "flv" ];
"Music/Downloads" = [ "mp3" "flac" "wav" "ogg" "m4a" "opus" ];
"Documents/Downloads" = [ "pdf" "doc" "docx" "odt" "txt" "md" "epub" "ppt" "pptx" "xls" "xlsx" "csv" ];
"Archives/Downloads" = [ "iso" "zip" "tar" "gz" "bz2" "xz" "rar" "7z" "wsz" ];
"Fonts/Downloads" = [ "ttf" "otf" "woff" "woff2" ];
"3D/Downloads" = [ "blend" "obj" "fbx" "stl" "dae" "3ds" "3mf" ];
"Software/Downloads" = [ "deb" "rpm" "appimage" "jar" "exe" "msi" "flatpak" ];
"Scripts/Downloads" = [ "sh" "py" "lua" ];
"inbox/images" = [ "jpg" "jpeg" "png" "gif" "webp" "svg" "heic" "avif" "ico" "bmp" "tif" "tiff" ];
"inbox/video" = [ "mp4" "mkv" "mov" "webm" "avi" "flv" ];
"inbox/audio" = [ "mp3" "flac" "wav" "ogg" "m4a" "opus" "it" "xm" "mod" "s3m" ];
"inbox/documents" = [ "pdf" "doc" "docx" "odt" "txt" "md" "epub" "ppt" "pptx" "xls" "xlsx" "csv" "ics" ];
"media/cad" = [ "step" "stp" "iges" "igs" "sldasm" "sldprt" "dxf" "dwg" "f3d" "3dm" ];
"media/3d" = [ "blend" "obj" "fbx" "stl" "dae" "3ds" "3mf" ];
"inbox/roblox" = [ "rbxm" "rbxmx" "rbxl" "rbxlx" ];
"inbox/code" = [ "luau" "lua" "js" "ts" "py" "sh" ];
"archive" = [ "iso" "zip" "tar" "gz" "bz2" "xz" "zst" "rar" "7z" ];
"inbox/software" = [ "deb" "rpm" "appimage" "jar" "exe" "msi" "flatpak" ];
"media/fonts" = [ "ttf" "otf" "woff" "woff2" ];
"inbox/misc" = [ "ovpn" "hideout" "wsz" ];
"Games/Doom" = [ "wad" "pk3" ];
"Games/Switch" = [ "nsp" "xci" ];
"Games/3DS" = [ "3ds" "cia" ];
"Games/WiiU" = [ "wux" "wud" ];
"Games/Wii" = [ "wbfs" ];
"Games/GameCube" = [ "gcm" ];
"Games/N64" = [ "n64" "z64" ];
"Games/SNES" = [ "sfc" "smc" ];
"Games/NES" = [ "nes" ];
"Games/DS" = [ "nds" "dsi" ];
"Games/GBA" = [ "gba" ];
"Games/GBC" = [ "gbc" ];
"Games/GB" = [ "gb" ];
"Games/PS1" = [ "cue" "bin" ];
"Games/Xbox" = [ "xiso" ];
"Games/Genesis" = [ "gen" ];
"Games/Dreamcast" = [ "gdi" "cdi" ];
"Games/Saturn" = [ "sat" ];
"media/games/roms/Doom" = [ "wad" "pk3" ];
"media/games/roms/Switch" = [ "nsp" "xci" ];
"media/games/roms/3DS" = [ "cia" ]; # .3ds goes to media/3d (3D Studio mesh)
"media/games/roms/WiiU" = [ "wux" "wud" ];
"media/games/roms/Wii" = [ "wbfs" ];
"media/games/roms/GameCube" = [ "gcm" ];
"media/games/roms/N64" = [ "n64" "z64" ];
"media/games/roms/SNES" = [ "sfc" "smc" ];
"media/games/roms/NES" = [ "nes" ];
"media/games/roms/DS" = [ "nds" "dsi" ];
"media/games/roms/GBA" = [ "gba" ];
"media/games/roms/GBC" = [ "gbc" ];
"media/games/roms/GB" = [ "gb" ];
"media/games/roms/PS1" = [ "cue" "bin" ];
"media/games/roms/Xbox" = [ "xiso" ];
"media/games/roms/Genesis" = [ "gen" ];
"media/games/roms/Dreamcast" = [ "gdi" "cdi" ];
"media/games/roms/Saturn" = [ "sat" ];
};
};
};
+2 -1
View File
@@ -6,8 +6,9 @@
ingress = lib.foldl' (a: t: a // t.ingress) { }
(lib.attrValues inputs.self.nixosConfigurations.box.config.services.cloudflared.tunnels);
noProbe = [ "music" "monitor" "metrics" ];
external = [ host.domain "tv.${host.domain}" "tv5.${host.domain}" "cad.${host.domain}" "llama.${host.domain}" ];
targets = map (h: "https://${h}") (lib.attrNames (lib.filterAttrs
(n: v: lib.hasPrefix "http" v && !lib.elem (lib.head (lib.splitString "." n)) noProbe) ingress));
(n: v: lib.hasPrefix "http" v && !lib.elem (lib.head (lib.splitString "." n)) noProbe) ingress) ++ external);
nvidia = lib.elem "nvidia" config.services.xserver.videoDrivers;
exp = config.services.prometheus.exporters;
local = job: port: {
+14 -9
View File
@@ -25,15 +25,20 @@
};
folders = {
"Archives" = mkFolder "${config.home.homeDirectory}/Archives";
"Software" = mkFolder "${config.home.homeDirectory}/Software";
"Scripts" = mkFolder "${config.home.homeDirectory}/Scripts";
"Projects" = mkFolder "${config.home.homeDirectory}/Projects";
"Documents" = mkFolder "${config.home.homeDirectory}/Documents";
"Downloads" = mkFolder "${config.home.homeDirectory}/Downloads";
"Pictures" = mkFolder "${config.home.homeDirectory}/Pictures";
"Videos" = mkFolder "${config.home.homeDirectory}/Videos";
# "Music" = mkFolder "${config.home.homeDirectory}/Music";
"inbox" = mkFolder "${config.home.homeDirectory}/inbox";
"down" = mkFolder "${config.home.homeDirectory}/down";
"dev" = mkFolder "${config.home.homeDirectory}/dev";
# music stays per-host (box's copy feeds MPD), as does game data that isn't safe to sync live
"media" = mkFolder "${config.home.homeDirectory}/media" // {
ignorePatterns = [ "/music" "/games/steam" "/games/minecraft" ];
};
"library" = mkFolder "${config.home.homeDirectory}/library";
# dotfiles holds this host's own retired app data
"archive" = mkFolder "${config.home.homeDirectory}/archive" // {
ignorePatterns = [ "/dotfiles" ];
};
# written only by the tagger on box; relative links resolve on every host
"tags" = mkFolder "${config.home.homeDirectory}/tags";
"nix" = mkFolder "${config.home.homeDirectory}/nix";
"hytale" = mkFolder "${config.home.homeDirectory}/.local/share/Hytale/UserData/Saves";
"ssh" = mkFolder "${config.home.homeDirectory}/.ssh";
+293
View File
@@ -0,0 +1,293 @@
"""Tag images and audio, then mirror the tags as a tree of relative symlinks.
The symlink tree is fully derived from the files on disk: links for files that
moved or were deleted disappear on the next run. Only symlinks and empty
directories inside the tag output are ever removed; real files are never touched.
"""
import hashlib
import json
import logging
import os
import sqlite3
import sys
import time
from datetime import datetime
from pathlib import Path
logging.basicConfig(level=logging.INFO, format="[tagger] %(message)s", stream=sys.stdout)
log = logging.getLogger("tagger")
IMAGE_EXT = {"jpg", "jpeg", "png", "gif", "webp", "bmp", "tif", "tiff", "avif", "heic"}
AUDIO_EXT = {"mp3", "flac", "wav", "ogg", "opus", "m4a", "aac", "wma", "aiff", "it", "xm", "mod", "s3m"}
TRACKER_EXT = {"it", "xm", "mod", "s3m"}
CATEGORIES = {"images": IMAGE_EXT, "audio": AUDIO_EXT}
def clean(value):
"""Make a tag value safe to use as a single directory name."""
value = str(value).replace("/", "-").replace("\0", "").strip().strip(".")
return value[:120] or "unknown"
def file_hash(path):
h = hashlib.blake2b(digest_size=16)
with open(path, "rb") as f:
for chunk in iter(lambda: f.read(1 << 20), b""):
h.update(chunk)
return h.hexdigest()
class Cache:
"""Tags keyed by content hash, so moved/renamed files keep their tags without re-running the model."""
def __init__(self, path, version):
self.db = sqlite3.connect(path)
self.version = version
self.db.execute("CREATE TABLE IF NOT EXISTS files (path TEXT PRIMARY KEY, size INT, mtime REAL, hash TEXT)")
self.db.execute("CREATE TABLE IF NOT EXISTS tags (hash TEXT PRIMARY KEY, version TEXT, data TEXT)")
def hash_for(self, path, st):
row = self.db.execute("SELECT size, mtime, hash FROM files WHERE path = ?", (str(path),)).fetchone()
if row and row[0] == st.st_size and row[1] == st.st_mtime:
return row[2]
digest = file_hash(path)
self.db.execute("INSERT OR REPLACE INTO files VALUES (?, ?, ?, ?)", (str(path), st.st_size, st.st_mtime, digest))
return digest
def get(self, digest):
row = self.db.execute("SELECT version, data FROM tags WHERE hash = ?", (digest,)).fetchone()
return json.loads(row[1]) if row and row[0] == self.version else None
def put(self, digest, tags):
self.db.execute("INSERT OR REPLACE INTO tags VALUES (?, ?, ?)", (digest, self.version, json.dumps(tags)))
def forget_missing(self, seen):
known = [r[0] for r in self.db.execute("SELECT path FROM files")]
self.db.executemany("DELETE FROM files WHERE path = ?", [(p,) for p in known if p not in seen])
self.db.execute("DELETE FROM tags WHERE hash NOT IN (SELECT hash FROM files)")
self.db.commit()
class Clip:
"""Zero-shot CLIP: score each image against a fixed label list."""
MEAN = (0.48145466, 0.4578275, 0.40821073)
STD = (0.26862954, 0.26130258, 0.27577711)
def __init__(self, cfg):
import numpy as np
import onnxruntime as ort
from tokenizers import Tokenizer
self.np = np
opts = ort.SessionOptions()
opts.intra_op_num_threads = cfg["threads"]
opts.inter_op_num_threads = 1
cpu = ["CPUExecutionProvider"]
self.vision = ort.InferenceSession(cfg["model"]["vision"], opts, providers=cpu)
text = ort.InferenceSession(cfg["model"]["text"], opts, providers=cpu)
tok = Tokenizer.from_file(cfg["model"]["tokenizer"])
self.labels = cfg["labels"]
self.threshold = cfg["threshold"]
self.top_k = cfg["top_k"]
embeds = []
for label in self.labels:
ids = np.array([tok.encode(cfg["prompt"].format(label)).ids], dtype=np.int64)
embeds.append(text.run(None, {"input_ids": ids})[0][0])
self.text = self._norm(np.stack(embeds))
def _norm(self, x):
return x / self.np.linalg.norm(x, axis=-1, keepdims=True)
def _pixels(self, img):
np = self.np
from PIL import Image
img = img.convert("RGB")
w, h = img.size
scale = 224 / min(w, h)
img = img.resize((max(224, round(w * scale)), max(224, round(h * scale))), Image.BICUBIC)
w, h = img.size
left, top = (w - 224) // 2, (h - 224) // 2
img = img.crop((left, top, left + 224, top + 224))
x = np.asarray(img, dtype=np.float32) / 255.0
x = (x - np.array(self.MEAN, dtype=np.float32)) / np.array(self.STD, dtype=np.float32)
return x.transpose(2, 0, 1)[None]
def tags(self, img):
np = self.np
emb = self._norm(self.vision.run(None, {"pixel_values": self._pixels(img)})[0])
logits = 100.0 * emb @ self.text.T
probs = np.exp(logits - logits.max())
probs = (probs / probs.sum())[0]
best = np.argsort(-probs)[: self.top_k]
return [self.labels[i] for i in best if probs[i] >= self.threshold]
def date_tags(when):
return [f"year/{when:%Y}", f"month/{when:%Y-%m}"]
def image_tags(path, clip):
from PIL import Image
tags = []
with Image.open(path) as img:
img.seek(0)
exif = img.getexif()
stamp = exif.get_ifd(0x8769).get(36867) or exif.get(306)
try:
tags += date_tags(datetime.strptime(str(stamp).strip("\0 "), "%Y:%m:%d %H:%M:%S"))
except ValueError:
tags += date_tags(datetime.fromtimestamp(path.stat().st_mtime))
tags += clip().tags(img)
return tags
def audio_tags(path):
ext = path.suffix.lower().lstrip(".")
if ext in TRACKER_EXT:
return ["format/tracker"]
import mutagen
tags = [f"format/{ext}"]
meta = mutagen.File(path, easy=True) or {}
def first(*keys):
for key in keys:
values = meta.get(key) or []
if values and str(values[0]).strip():
return str(values[0]).strip()
return None
for tag, keys in (("artist", ("albumartist", "artist")), ("album", ("album",)), ("genre", ("genre",))):
value = first(*keys)
if value:
tags.append(f"{tag}/{clean(value)}")
year = first("date", "originaldate")
if year and year[:4].isdigit():
tags.append(f"year/{year[:4]}")
return tags
def walk(root, exts):
for dirpath, dirnames, filenames in os.walk(root):
dirnames[:] = sorted(d for d in dirnames if not d.startswith("."))
for name in sorted(filenames):
path = Path(dirpath) / name
if name.startswith(".") or path.is_symlink():
continue
if path.suffix.lower().lstrip(".") in exts:
yield path
def sync_links(out, desired):
"""Make the symlinks under out/<category> exactly match `desired` (link -> target)."""
removed = created = 0
for category in CATEGORIES:
base = out / category
if not base.exists():
continue
for dirpath, _, filenames in os.walk(base):
for name in filenames:
link = Path(dirpath) / name
if not link.is_symlink():
continue
want = desired.get(link)
if want is None or os.readlink(link) != os.path.relpath(want, link.parent):
link.unlink()
removed += 1
for link, target in desired.items():
if link.is_symlink():
continue
if link.exists():
log.warning("Not replacing real file in tag tree: %s", link)
continue
link.parent.mkdir(parents=True, exist_ok=True)
link.symlink_to(os.path.relpath(target, link.parent))
created += 1
for category in CATEGORIES:
base = out / category
if not base.exists():
continue
for dirpath, _, _ in os.walk(base, topdown=False):
if Path(dirpath) != base and not os.listdir(dirpath):
os.rmdir(dirpath)
return created, removed
def main():
cfg = json.load(open(os.environ["TAGGER_CONFIG"]))
home = Path(os.environ.get("TAGGER_HOME", Path.home()))
out = home / cfg["output"]
state = Path(os.environ.get("STATE_DIRECTORY", home / ".cache" / "tagger"))
state.mkdir(parents=True, exist_ok=True)
version = hashlib.sha1(json.dumps([cfg["labels"], cfg["prompt"], cfg["threshold"], cfg["top_k"], cfg["model"]]).encode()).hexdigest()
cache = Cache(state / "cache.db", version)
model = {}
def clip():
if "clip" not in model:
log.info("Loading model")
model["clip"] = Clip(cfg)
return model["clip"]
desired, seen = {}, set()
tagged = failed = 0
start = time.time()
for root_cfg in cfg["roots"]:
root = home / root_cfg["path"]
category = root_cfg["type"]
if not root.is_dir():
log.warning("Root missing, skipping: %s", root)
continue
for path in walk(root, CATEGORIES[category]):
seen.add(str(path))
try:
digest = cache.hash_for(path, path.stat())
tags = cache.get(digest)
if tags is None:
tags = image_tags(path, clip) if category == "images" else audio_tags(path)
cache.put(digest, tags)
tagged += 1
if tagged % 50 == 0:
cache.db.commit()
log.info("Tagged %d new files", tagged)
except Exception as e:
failed += 1
log.warning("Skipping %s: %s", path, e)
continue
tags = list(tags)
if category == "images":
tags.append(f"type/{path.suffix.lower().lstrip('.')}")
if root_cfg.get("kind"):
tags.append(f"kind/{root_cfg['kind']}")
elif root_cfg.get("kindFromSubdir"):
rel = path.relative_to(root).parts
if len(rel) > 1:
tags.append(f"kind/{clean(rel[0])}")
for tag in tags:
folder = out / category / Path(*[clean(p) for p in tag.split("/")])
link = folder / path.name
if desired.get(link, path) != path:
link = folder / f"{path.stem}~{digest[:6]}{path.suffix}"
desired[link] = path
cache.forget_missing(seen)
created, removed = sync_links(out, desired)
log.info(
"Done in %.0fs: %d files, %d newly tagged, %d failed, %d links added, %d removed",
time.time() - start, len(seen), tagged, failed, created, removed,
)
if __name__ == "__main__":
main()
+125
View File
@@ -0,0 +1,125 @@
{
den.aspects.system.tags = {
nixos = { pkgs, lib, config, ... }:
let
cfg = config.services.tagger;
hf = file: hash: pkgs.fetchurl {
url = "https://huggingface.co/Xenova/clip-vit-base-patch32/resolve/main/${file}";
inherit hash;
};
# quantized CLIP ViT-B/32 via onnxruntime: ~150MB of weights, no torch
model = {
vision = hf "onnx/vision_model_quantized.onnx" "sha256-WD/REQpRRmeBL+59aElSqvgqmblZdgyNfcp+CrmDkpk=";
text = hf "onnx/text_model_quantized.onnx" "sha256-c7qrhV1AYZDan6pJjP7fZfFc8wn0zHOFt7Ay5tCOXDo=";
tokenizer = hf "tokenizer.json" "sha256-9/O3rxF9RntYN0eXaRpkONPmuenO+ADf1dztf2l6kM0=";
};
python = pkgs.python3.withPackages (p: [ p.onnxruntime p.tokenizers p.pillow p.numpy p.mutagen ]);
taggerConfig = pkgs.writeText "tagger_config.json" (builtins.toJSON {
inherit (cfg) output roots labels prompt threshold threads;
top_k = cfg.topK;
model = lib.mapAttrs (_: toString) model;
});
in {
options.services.tagger = {
enable = lib.mkEnableOption "image/audio tagger that builds a symlink tag tree";
user = lib.mkOption {
type = lib.types.str;
description = "User account the tagger runs as (paths are relative to its home).";
};
interval = lib.mkOption {
type = lib.types.str;
default = "15min";
description = "How often to run (systemd time span).";
};
output = lib.mkOption {
type = lib.types.str;
default = "tags";
description = "Tag tree directory, relative to home. Only symlinks and empty dirs in it are ever removed.";
};
roots = lib.mkOption {
type = lib.types.listOf (lib.types.submodule {
options = {
path = lib.mkOption { type = lib.types.str; description = "Directory to scan, relative to home."; };
type = lib.mkOption { type = lib.types.enum [ "images" "audio" ]; };
kind = lib.mkOption { type = lib.types.nullOr lib.types.str; default = null; description = "Fixed kind/<x> tag for everything in this root."; };
kindFromSubdir = lib.mkOption { type = lib.types.bool; default = false; description = "Tag kind/<first subdirectory name>."; };
};
});
default = [ ];
};
labels = lib.mkOption {
type = lib.types.listOf lib.types.str;
default = [ ];
description = "Content labels the image model chooses from. Each becomes a tag directory.";
};
prompt = lib.mkOption {
type = lib.types.str;
default = "a picture of {}";
description = "Text template each label is scored with.";
};
threshold = lib.mkOption {
type = lib.types.float;
default = 0.1;
description = "Minimum label probability (0-1) for a content tag.";
};
topK = lib.mkOption {
type = lib.types.int;
default = 3;
description = "Maximum content tags per image.";
};
threads = lib.mkOption {
type = lib.types.int;
default = 1;
description = "CPU threads the model may use.";
};
};
config = lib.mkIf cfg.enable {
systemd.services.tagger = {
description = "Image/audio tagger";
environment = {
TAGGER_CONFIG = "${taggerConfig}";
TAGGER_HOME = config.users.users.${cfg.user}.home;
};
serviceConfig = {
Type = "oneshot";
User = cfg.user;
StateDirectory = "tagger";
ExecStart = "${python}/bin/python3 ${./_tagger.py}";
# stay out of the way of everything else on the box
Nice = 19;
CPUSchedulingPolicy = "idle";
IOSchedulingClass = "idle";
CPUQuota = "${toString (cfg.threads * 100)}%";
MemoryMax = "1G";
};
};
systemd.timers.tagger = {
wantedBy = [ "timers.target" ];
timerConfig = {
OnBootSec = "15m";
OnUnitActiveSec = cfg.interval;
};
};
};
};
};
}
+37
View File
@@ -0,0 +1,37 @@
{
den.aspects.system.tags = {
nixos = { host, ... }: {
services.tagger = {
enable = true;
user = host.owner;
roots = [
{ path = "media/images"; type = "images"; kindFromSubdir = true; }
{ path = "inbox/images"; type = "images"; kind = "inbox"; }
{ path = "media/music"; type = "audio"; }
{ path = "inbox/audio"; type = "audio"; }
];
labels = [
"cat" "dog" "animal" "bird"
"person" "selfie" "group of people" "face"
"car" "motorcycle" "vehicle"
"landscape" "nature" "forest" "mountain" "beach" "ocean" "sky" "sunset" "night" "snow"
"city" "building" "interior" "room"
"food"
"space" "planet"
"anime" "cartoon" "drawing" "painting" "sketch" "pixel art"
"abstract" "pattern" "gradient" "minimal"
"meme" "text" "document" "chart" "diagram"
"screenshot" "user interface" "code" "terminal" "website"
"video game" "minecraft" "roblox"
"3d render" "cad model" "mechanical part" "wireframe"
"logo" "icon" "emoji"
"wallpaper"
"music album cover"
"electronics" "computer hardware"
];
};
};
};
}