diff --git a/flake.lock b/flake.lock index cd89383..c4fca2e 100644 --- a/flake.lock +++ b/flake.lock @@ -7,11 +7,11 @@ ] }, "locked": { - "lastModified": 1792080051, - "narHash": "sha256-HTSn+R0ClnJwmhQMC1iT1n5/G9sYwdGxRpGyDTZQFjU=", + "lastModified": 1792609737, + "narHash": "sha256-vfmqH26p9JjqXdtFJ2j0fbiu3X4SISezi/s6X6ak1u0=", "owner": "AdnanHodzic", "repo": "auto-cpufreq", - "rev": "aa2c5ad2d1798da1c65f81cb0eb95ea933a074c6", + "rev": "5a1683037a583785f802b5d039022127b9b154cd", "type": "github" }, "original": { @@ -125,11 +125,11 @@ "nixpkgs": "nixpkgs" }, "locked": { - "lastModified": 1791795517, - "narHash": "sha256-hmF0FVrUW6UKQ74qyGJSepMYadnIqzVe2h7TQtZdbmo=", + "lastModified": 1792238796, + "narHash": "sha256-mRsa8oJ8R7fkvR5K+uQYfuxX9Np0ai/KvzTE8FYVx7E=", "owner": "catppuccin", "repo": "nix", - "rev": "2e605f61db52a45a7ff1db414df395ef566565a3", + "rev": "30c87b95a628e81ec82a4fa0ed4db85d7c7d46d6", "type": "github" }, "original": { @@ -164,11 +164,11 @@ "nixpkgs": "nixpkgs_2" }, "locked": { - "lastModified": 1792020613, - "narHash": "sha256-31skutSMYGBAvGK5vs6wPGXAV4s0ietf1doMynL9FfI=", + "lastModified": 1792559340, + "narHash": "sha256-IRpSJIA0ijCUDndWSZk7MdbtzAjj30t9mkCQ2VspHdo=", "owner": "9001", "repo": "copyparty", - "rev": "8b4593c9a286791eb5dc40862fa24198cea4def7", + "rev": "1af7efeca858dcfa29f797d7ae93f22eb2fdecf0", "type": "github" }, "original": { @@ -194,11 +194,11 @@ }, "den": { "locked": { - "lastModified": 1792099092, - "narHash": "sha256-ITDya5NtTtmNl+XsOY5LX3asCxoAcZcaiHMl5Pz7vAM=", + "lastModified": 1792618207, + "narHash": "sha256-iBpvVBVBnynNWW9sLX5oKVigXU28oO2oiMPXgcLO1HI=", "owner": "denful", "repo": "den", - "rev": "6e5e413880e3d1f05713c617b569c2f268c4bd9c", + "rev": "0f7675b0b789eabe1a62f8a31b5323a7ad3ca5c4", "type": "github" }, "original": { @@ -646,11 +646,11 @@ ] }, "locked": { - "lastModified": 1792098797, - "narHash": "sha256-u4DIIZgznEGzByxXrxWCXK19VcMtTBmi/M9gZ7Jk9bM=", + "lastModified": 1792668857, + "narHash": "sha256-chUrnAqBhBLvXBUsLFxFYBIl8c0GWp06wdjmAMS8l+U=", "owner": "nix-community", "repo": "home-manager", - "rev": "640725978b99076e18e069f6e7d2959124584f8f", + "rev": "cb7de2c7e589afe7531d4832c71ad4df144624ea", "type": "github" }, "original": { @@ -686,11 +686,11 @@ "nixpkgs": "nixpkgs_4" }, "locked": { - "lastModified": 1792011798, - "narHash": "sha256-gLIz9KH5t8SWTkzeQPEgQQHf1L061M3tSs4IW2Xa+go=", + "lastModified": 1792638249, + "narHash": "sha256-34jxGi9m1l+rtDfT7WdRCrbIKeFJDek53T5fugb+4QQ=", "owner": "JPyke3", "repo": "hytale-launcher-nix", - "rev": "30eb0515625a7f03e1fdc61009933d83759fffde", + "rev": "dddd73423e804dade9a2312430937c1d5e1954ee", "type": "github" }, "original": { @@ -722,11 +722,11 @@ }, "locked": { "dir": "packages/nix", - "lastModified": 1792022604, - "narHash": "sha256-xyl3KTB+j4W3dAxQVSolNJCQZOasDnCLB3Dr14adBmU=", + "lastModified": 1792357572, + "narHash": "sha256-2krnWSUcN06EYtUKqFxkbSIQP6NAfhMOrgnxZXB+dcc=", "owner": "SteamClientHomebrew", "repo": "Millennium", - "rev": "22af2f453777a925fb398a3dab60a407e66aa83f", + "rev": "f7a356f6789bc7d23f44bfbcdd95c71f0385cc1a", "type": "github" }, "original": { @@ -739,17 +739,17 @@ "millennium-src": { "flake": false, "locked": { - "lastModified": 1791947497, - "narHash": "sha256-sNpoyJ+IjrTiDGfX2QiKVg4jkrJR7n9PdBeOYJSS4n8=", + "lastModified": 1792357406, + "narHash": "sha256-We8OIJP/5q0nv2RVHQYfjRaHK6ZQuSM88eKa9BezUPk=", "owner": "SteamClientHomebrew", "repo": "Millennium", - "rev": "401d532543a0fbff469653ccba802bdd7e45f861", + "rev": "88fb7c16d04d162cb3e94beedb11a51705ec03fb", "type": "github" }, "original": { "owner": "SteamClientHomebrew", "repo": "Millennium", - "rev": "401d532543a0fbff469653ccba802bdd7e45f861", + "rev": "88fb7c16d04d162cb3e94beedb11a51705ec03fb", "type": "github" } }, @@ -781,11 +781,11 @@ "nixpkgs": "nixpkgs_7" }, "locked": { - "lastModified": 1791950799, - "narHash": "sha256-I2mlSmjrgWNIbkF+kA2t1qkeRZr9RAcwW4MrOYuN+J8=", + "lastModified": 1792554814, + "narHash": "sha256-iaSuYLgQh7sZTazUC/sWXkI0s428W1A6oLeEsc646CM=", "owner": "Ninlives", "repo": "minecraft.json", - "rev": "51cccadbb83ea6d8618f8cd696d5f3e7b0934d5d", + "rev": "9c6d986ea611170ab2da0d1291d984e72c44caff", "type": "github" }, "original": { @@ -962,11 +962,11 @@ "nixpkgs": "nixpkgs_11" }, "locked": { - "lastModified": 1791951554, - "narHash": "sha256-7ZMKTSse+BxmGiQ+isxga/biFfaEpEgYSRvv2efdCWY=", + "lastModified": 1792469825, + "narHash": "sha256-yZzRSNogTrbYjLNHiRMphZGIVcTHbXWSID37oPBbrEw=", "owner": "fufexan", "repo": "nix-gaming", - "rev": "b3d035dbc65250f6990ac526b0c9e188fe853856", + "rev": "0405c59de63e8b74d11dcc420f65ead938ea6ec6", "type": "github" }, "original": { @@ -1004,11 +1004,11 @@ "proton-ge-nix": "proton-ge-nix" }, "locked": { - "lastModified": 1792398868, - "narHash": "sha256-jWMeCYb3zRIaFTq8Up39exGIBQeLbT/vKGKmY9V5aH8=", + "lastModified": 1792657371, + "narHash": "sha256-peX2Ogs54jUGAGCS+Cl2zD6wxCAjIy6WqFE3Fl3k8Xk=", "owner": "raccube", "repo": "nix-warcraft", - "rev": "be646d2446fbe918715b74c02ccda3846b0cd9d5", + "rev": "feb66d9b67198e66dee7d8c67c30f0b372bfc46c", "type": "github" }, "original": { @@ -1028,11 +1028,11 @@ "treefmt-nix": "treefmt-nix_2" }, "locked": { - "lastModified": 1792109284, - "narHash": "sha256-wM9dqRgWYFKGiJ5xne+kXcUBRQXw+mN0xO16cdAc1a4=", + "lastModified": 1792675776, + "narHash": "sha256-aWIRMe9F4mdIJyL8oA2sRDmDP4muFZoL0VQ9J8TelNQ=", "owner": "FlameFlag", "repo": "nixcord", - "rev": "3b85f32df809ab138d3071ba10bd9273c4b9f34c", + "rev": "7e7a4a6d862aa833fd829ced231a1c345dafd38b", "type": "github" }, "original": { @@ -1049,11 +1049,11 @@ "nixpkgs": "nixpkgs_13" }, "locked": { - "lastModified": 1791231530, - "narHash": "sha256-sj7RiYmHW+d7NjH2TWKozEaYp8nhdGas6/zMKjTCO5k=", + "lastModified": 1792611588, + "narHash": "sha256-K6tvVoF+DSoMpgddGk6Xhern6pcBm3KktHV4c9MWrxM=", "owner": "simple-nixos-mailserver", "repo": "nixos-mailserver", - "rev": "4a06abf89ea5e38a3e0f9bf12f3036095d4a24a2", + "rev": "9004c7d9b0986719a76ca6945a718434508d7b2e", "type": "gitlab" }, "original": { @@ -1271,11 +1271,11 @@ }, "nixpkgs_14": { "locked": { - "lastModified": 1791966044, - "narHash": "sha256-t1hT8UW97rFCWCJO7/pClvu0AhLN5V3uir2M0ic4w/Q=", + "lastModified": 1792506237, + "narHash": "sha256-Q/8KLB6jNfpaUN1HAedE/u/Et9feE/zYSsutBLKrCFk=", "owner": "nixos", "repo": "nixpkgs", - "rev": "319e4cebef10cbb636c6ea392137b52ad105336a", + "rev": "5adc50831c259f87faeb09ddf930d43597197473", "type": "github" }, "original": { @@ -1318,11 +1318,11 @@ }, "nixpkgs_4": { "locked": { - "lastModified": 1791734076, - "narHash": "sha256-i5qk1kLiit98rRbh1AXmWBNT9QXC/y4l5Wk/u5EdpDQ=", + "lastModified": 1792502884, + "narHash": "sha256-IoNisKcGbUjdd45qCqywGMCYmZ5EnkxezvLII0FWwNA=", "owner": "NixOS", "repo": "nixpkgs", - "rev": "7fd4004d0511991fff3a0524856a9be09e28c5f0", + "rev": "02c087f3fe673c9e317f206a627cb6b910336dbe", "type": "github" }, "original": { @@ -1362,11 +1362,11 @@ }, "nixpkgs_7": { "locked": { - "lastModified": 1791949574, - "narHash": "sha256-42uGgil1WK3ZtL5c7odb9ac8PkhGzB9TyIYOA0USmmc=", + "lastModified": 1792554001, + "narHash": "sha256-kl1O+PN79CnnRgVkE+NrXYRJz63//rmlUefk9aiFE34=", "owner": "NixOS", "repo": "nixpkgs", - "rev": "721672233996a50d159d2ad0ffd2233d1f2bf844", + "rev": "af9839e576da1d1d549f70e00304274acbaa6d29", "type": "github" }, "original": { @@ -1414,11 +1414,11 @@ ] }, "locked": { - "lastModified": 1792113651, - "narHash": "sha256-OAXcxtszGBk6CSHFnqT0bpH+AovFgBYsJBMHEh50UsA=", + "lastModified": 1792679383, + "narHash": "sha256-nYxj6UjePv5IQq0/dxsT3A5qU57seUE0DY5NXrMyUo8=", "owner": "noctalia-dev", "repo": "noctalia", - "rev": "eeea6ff75cd71f9dbcd3acea6035449fefe3c71a", + "rev": "2e83bf2a5cf73629c12bb58e2f3d36e36104a6cb", "type": "github" }, "original": { @@ -1523,11 +1523,11 @@ "rust-overlay": "rust-overlay" }, "locked": { - "lastModified": 1792296708, - "narHash": "sha256-R7MjgTZFMl1dUZqTwDEVpdQKnkU2Sm4py9/S+KZeZhM=", + "lastModified": 1792651959, + "narHash": "sha256-Pixx0LRFGEMwCxXya8Q2tWrOcyX0HzXkMUw8Fd48pSY=", "owner": "microlift", "repo": "rosemary", - "rev": "77c38c95a62f4d0c7cfa475d195246638bd40650", + "rev": "5b8ec93daec454c9d25e179c2e4e373ef87aea5d", "type": "github" }, "original": { @@ -1539,6 +1539,7 @@ "rust-overlay": { "inputs": { "nixpkgs": [ + "rosemary", "nixpkgs" ] }, @@ -1596,11 +1597,11 @@ "systems": "systems_3" }, "locked": { - "lastModified": 1792111133, - "narHash": "sha256-UGPRL5Lo+QTvQC1s5IPd+NIhDF48Zd6eKuzjbFIcFeI=", + "lastModified": 1792525131, + "narHash": "sha256-jdOJvBudkFKI0vY5n7xRk38RMNblvHLMyb7g31fKYNg=", "owner": "different-name", "repo": "steam-config-nix", - "rev": "ae75eb33cfd73929f519882cc8ec8294bfdc3c0d", + "rev": "64ed84993738d84cf10dfe6011bc85177414ac2d", "type": "github" }, "original": { @@ -1817,11 +1818,11 @@ "xdg-desktop-portal-umbriel": "xdg-desktop-portal-umbriel" }, "locked": { - "lastModified": 1792116298, - "narHash": "sha256-T6Ci30ZMp/E35RLaFeKhsd2egAA9Si94EwwNTiYgXFM=", + "lastModified": 1792677583, + "narHash": "sha256-yp016oAkFNDpghy8aEKnyGWVcafr47ZO7nOxhd7k6uQ=", "ref": "refs/heads/main", - "rev": "9f4af3bebbecd9d3fcb24c4cf768b77dc12570fe", - "revCount": 1252, + "rev": "5d657581e27e1a3fe604693779ca1405610f4f21", + "revCount": 1332, "type": "git", "url": "https://github.com/noctalia-dev/umbriel" }, @@ -1835,11 +1836,11 @@ "flake-parts": "flake-parts_7" }, "locked": { - "lastModified": 1784312229, - "narHash": "sha256-2uHCSUw341o3my1R0U0YCfbnMEazylxb58evWsjGL50=", + "lastModified": 1792669057, + "narHash": "sha256-3dBWR7+z35n1Rrg68MghpGEUu9RnlKRzSDrkCzKXj7Q=", "owner": "nix-community", "repo": "nixos-vscode-server", - "rev": "2f984dfbe7e5271b5c413d3e734374cc1306c921", + "rev": "442c629540ed1e85cd2aed813a65b7eaa7ff27c5", "type": "github" }, "original": { @@ -1856,11 +1857,11 @@ ] }, "locked": { - "lastModified": 1792026707, - "narHash": "sha256-4Y93egV/VYybIJ6D6tHEgbOzn2gtWxHRIyomOx5Gc/4=", + "lastModified": 1792417147, + "narHash": "sha256-uCM9pwVAG4Csf8n+IvFdhEAlXjqVWPidUNY3I1oUkzE=", "owner": "noctalia-dev", "repo": "xdg-desktop-portal-umbriel", - "rev": "5d16415264fa5ae86a110db5d172ca05edb43cf6", + "rev": "1cc6eb18ba0d6c82dd66999646d7e554f76a85b6", "type": "github" }, "original": { diff --git a/modules/hosts/box.nix b/modules/hosts/box.nix index 0805ca0..dd528b8 100644 --- a/modules/hosts/box.nix +++ b/modules/hosts/box.nix @@ -28,6 +28,10 @@ "net.ipv6.conf.all.forwarding" = 1; }; + services.journald.settings.Journal.SystemMaxUse = "500M"; + nix.settings = { min-free = 5 * 1024 * 1024 * 1024; max-free = 10 * 1024 * 1024 * 1024; }; + virtualisation.podman.autoPrune = { enable = true; flags = [ "--all" ]; }; + fileSystems."/home" = { device = "/dev/disk/by-uuid/30f357aa-fc86-4bcd-bed7-c91fc8afbdbc"; fsType = "ext4"; diff --git a/modules/roles.nix b/modules/roles.nix index 2327515..c020052 100644 --- a/modules/roles.nix +++ b/modules/roles.nix @@ -43,8 +43,8 @@ services.glances services.invidious services.mailserver - # services.matrix - services.redlib + services.matrix + # services.redlib services.bugtv services.vscode-server services.gitea @@ -54,6 +54,7 @@ services.slskd services.mpd services.monitoring + system.tags ]; }; } diff --git a/modules/services/attic.nix b/modules/services/attic.nix index f7ecaa9..6fb5ac9 100644 --- a/modules/services/attic.nix +++ b/modules/services/attic.nix @@ -1,18 +1,18 @@ { - # Private Nix binary cache. Caches are created private; pulling needs a token (netrc). den.aspects.services.attic = let port = 8090; in { tunnel = { subdomain = "cache"; inherit port; }; nixos = { config, host, ... }: { services.atticd = { enable = true; - # ATTIC_SERVER_TOKEN_RS256_SECRET_BASE64=... + environmentFile = "${config.users.users.${host.owner}.home}/.config/attic/env"; + settings = { listen = "127.0.0.1:${toString port}"; - # No api-endpoint: CI uploads stay on localhost (Cloudflare caps bodies at 100MB). + substituter-endpoint = "https://cache.${host.domain}/"; - # Big NARs (darling rootfs) dedupe better in chunks. + chunking = { nar-size-threshold = 64 * 1024; min-size = 16 * 1024; diff --git a/modules/services/cloudflared.nix b/modules/services/cloudflared.nix index 1d413ae..3e9f4c4 100644 --- a/modules/services/cloudflared.nix +++ b/modules/services/cloudflared.nix @@ -1,7 +1,6 @@ { den.quirks.tunnel.description = "cloudflared ingress: { subdomain, port, scheme ? \"http\" }"; - # per host: den.hosts...cloudflared = { uuid = "..."; protocol = "http2"; # optional }; den.aspects.services.cloudflared = { nixos = { tunnel, host, pkgs, lib, config, ... }: let inherit (host.cloudflared) uuid; diff --git a/modules/services/copyparty.nix b/modules/services/copyparty.nix index 23a0bb3..e1f8a5b 100644 --- a/modules/services/copyparty.nix +++ b/modules/services/copyparty.nix @@ -75,7 +75,7 @@ }; "/Music" = { - path = "${home}/Music/"; + path = "${home}/media/music/"; access = { r = "*"; diff --git a/modules/services/gitea-runner.nix b/modules/services/gitea-runner.nix index b1058bd..0f71977 100644 --- a/modules/services/gitea-runner.nix +++ b/modules/services/gitea-runner.nix @@ -1,16 +1,14 @@ { - # Gitea Actions runner on box itself; jobs run directly on the host (label "native"). den.aspects.services.gitea-runner.nixos = { config, host, pkgs, ... }: let home = config.users.users.${host.owner}.home; in { - # Owner's GitHub SSH key, readable by jobs at $CREDENTIALS_DIRECTORY/github; never in Gitea. systemd.services."gitea-runner-${config.networking.hostName}".serviceConfig.LoadCredential = [ "github:${home}/.ssh/id_rsa" ]; services.gitea-actions-runner.instances.${config.networking.hostName} = { enable = true; name = config.networking.hostName; url = "http://127.0.0.1:${toString config.services.gitea.settings.server.HTTP_PORT}"; - # TOKEN= + tokenFile = "${config.users.users.${host.owner}.home}/.config/gitea-runner/token"; labels = [ "native:host" ]; hostPackages = with pkgs; [ bash coreutils gnused gnugrep findutils git openssh curl jq nix nodejs attic-client ]; diff --git a/modules/services/glances.nix b/modules/services/glances.nix index d94bf0a..f0bcfdf 100644 --- a/modules/services/glances.nix +++ b/modules/services/glances.nix @@ -17,7 +17,7 @@ systemd.services.glances-web = { description = "glances web interface"; - # after = [ "network-online.target" ]; + wantedBy = [ "multi-user.target" ]; serviceConfig = { diff --git a/modules/services/invidious.nix b/modules/services/invidious.nix index aee8329..33f2b6d 100644 --- a/modules/services/invidious.nix +++ b/modules/services/invidious.nix @@ -17,41 +17,12 @@ "companioncache:/var/tmp/youtubei.js:rw" ]; environment = { - # Same as configured on invidious above. SERVER_SECRET_KEY = companionKey; }; }; }; }; - /*virtualisation.podman.enable = true; - virtualisation.oci-containers.backend = lib.mkDefault "podman"; - - virtualisation.oci-containers.containers.invidious-companion = { - image = "quay.io/invidious/invidious-companion:master-5652eda"; - extraOptions = [ "--network=host" "--pull=always" ]; - - environment = { - SERVER_SECRET_KEY = companionKey; - HOST = "127.0.0.1"; - PORT = toString companionPort; - SERVER_BASE_URL = "http://127.0.0.1:${toString companionPort}"; - - # HTTP_PROXY = "http://proxy.example:3128"; - # HTTPS_PROXY = "http://proxy.example:3128"; - # NO_PROXY = "127.0.0.1,localhost"; - - CACHE_DIRECTORY = "/var/tmp"; - NETWORKING_VIDEOPLAYBACK_UMP = "false"; - NETWORKING_FETCH_RETRY_ENABLED = "true"; - NETWORKING_FETCH_RETRY_TIMES = "3"; - NETWORKING_FETCH_RETRY_INITIAL_DEBOUNCE = "500"; # ms - NETWORKING_FETCH_RETRY_DEBOUNCE_MULTIPLIER = "2"; - #JOBS_YOUTUBE_SESSION_PO_TOKEN_ENABLED = "false"; - #YOUTUBE_SESSION_OAUTH_ENABLED = "true"; - }; - };*/ - services.invidious = { enable = true; package = pkgs.invidious; @@ -67,7 +38,7 @@ settings = { domain = "tube.${host.domain}"; #https_only = false; - external_port = 443; # public URLs go through cloudflared on https, not :3030 + external_port = 443; invidious_companion = [ { @@ -78,7 +49,7 @@ invidious_companion_key = companionKey; continue = true; - local = true; # googlevideo URLs are bound to box's IP; proxy playback via companion + local = true; check_tables = true; https_only = true; use_quic = false; @@ -90,12 +61,6 @@ statistics_enabled = true; }; }; - - /*systemd.services.invidious = let dep = "podman-invidious-companion.service"; in { - wants = [ dep ]; - after = [ dep ]; - requires = [ dep ]; - };*/ }; }; } diff --git a/modules/services/llama.nix b/modules/services/llama.nix index 1d927a6..b95e55d 100644 --- a/modules/services/llama.nix +++ b/modules/services/llama.nix @@ -6,12 +6,10 @@ nixos = { pkgs, lib, ... }: { services.llama-cpp = let - # https://github.com/ggml-org/llama.cpp/blob/master/tools/server/README.md modelsPreset = { "*" = rec { - # keep-sorted start agent = true; - cache-ram = 0; # unified memory + cache-ram = 0; cache-type-k = "q8_0"; cache-type-v = "q8_0"; ctx-size = 256 * 256 * parallel; @@ -26,28 +24,23 @@ sleep-idle-seconds = -1; spec-draft-type-k = "q8_0"; spec-draft-type-v = "q8_0"; - # keep-sorted end - }; + }; "qwen3.6-35b-a3b" = { - # keep-sorted start hf-repo = "unsloth/Qwen3.6-35B-A3B-GGUF:UD-Q4_K_XL"; min-p = 0.0; temperature = 1.0; top-k = 20; top-p = 0.95; - # keep-sorted end }; "qwen3.8-27b" = { - # keep-sorted start - ctx-size = 32768; # drop from the 65536 default to leave VRAM headroom at Q6 + ctx-size = 32768; hf-repo = "unsloth/Qwen3.8-27B-GGUF:UD-Q6_K"; min-p = 0.0; temperature = 1.0; top-k = 20; top-p = 0.95; - # keep-sorted end }; }; in { diff --git a/modules/services/matrix.nix b/modules/services/matrix.nix index bf9f6f0..4de7601 100644 --- a/modules/services/matrix.nix +++ b/modules/services/matrix.nix @@ -1,44 +1,27 @@ { - den.aspects.services.matrix = { - nixos = { - config, - pkgs, - lib, - host, - ... - }: let - port = 8008; + den.aspects.services.matrix = let port = 8008; in { + tunnel = { subdomain = "matrix"; inherit port; }; + + nixos = { lib, host, ... }: let inherit (host) domain; - matrixDomain = "matrix.${domain}"; - clientConfig = { - "m.homeserver".base_url = "https://${matrixDomain}"; - "m.identity_server" = {}; - }; - serverConfig = { - "m.server" = "${matrixDomain}:443"; - }; - mkWellKnown = data: '' - default_type application/json; - add_header Access-Control-Allow-Origin *; - return 200 '${builtins.toJSON data}'; - ''; + secret = "/var/lib/matrix-synapse/registration_secret"; in { services.matrix-synapse = { enable = true; settings = { server_name = domain; - public_baseurl = "https://${matrixDomain}"; + public_baseurl = "https://matrix.${domain}"; listeners = [ { - port = port; - bind_addresses = ["127.0.0.1"]; + inherit port; + bind_addresses = [ "127.0.0.1" ]; type = "http"; tls = false; x_forwarded = true; resources = [ { - names = ["client" "federation"]; + names = [ "client" "federation" ]; compress = true; } ]; @@ -59,7 +42,7 @@ url_preview_enabled = true; enable_registration = false; enable_metrics = false; - registration_shared_secret_path = "/var/lib/matrix-synapse/registration_secret"; + registration_shared_secret_path = secret; trusted_key_servers = [ { @@ -69,9 +52,13 @@ }; }; + systemd.services.matrix-synapse.preStart = lib.mkBefore '' + [ -s ${secret} ] || (umask 077; head -c 32 /dev/urandom | base64 | tr -d '\n' > ${secret}) + ''; + services.postgresql = { enable = true; - ensureDatabases = ["matrix-synapse"]; + ensureDatabases = [ "matrix-synapse" ]; ensureUsers = [ { name = "matrix-synapse"; @@ -79,27 +66,6 @@ } ]; }; - - services.nginx.virtualHosts.${domain} = { - enableACME = true; - forceSSL = true; - locations."= /.well-known/matrix/server".extraConfig = mkWellKnown serverConfig; - locations."= /.well-known/matrix/client".extraConfig = mkWellKnown clientConfig; - }; - - services.nginx.virtualHosts.${matrixDomain} = { - enableACME = true; - forceSSL = true; - locations."/" = { - proxyPass = "http://127.0.0.1:${toString port}"; - extraConfig = '' - proxy_set_header X-Forwarded-For $remote_addr; - proxy_set_header X-Forwarded-Proto $scheme; - proxy_set_header Host $host; - client_max_body_size 100M; - ''; - }; - }; }; }; } diff --git a/modules/services/mpd.nix b/modules/services/mpd.nix index 951a13e..3891737 100644 --- a/modules/services/mpd.nix +++ b/modules/services/mpd.nix @@ -1,5 +1,5 @@ { - # MPD on the server: plays ~/Music into an Opus HTTP stream, no local speakers. + # MPD on the server: plays ~/media/music into an Opus HTTP stream, no local speakers. # music. = audio stream, mpd. = MPD protocol (via `cloudflared access tcp` on clients). # Password: ~/.config/mpd/password (same file on every device, chmod 600). den.aspects.services.mpd = { @@ -19,7 +19,7 @@ }]; settings = { - music_directory = "${home}/Music"; + music_directory = "${home}/media/music"; decoder = [ { plugin = "ffmpeg"; enabled = "yes"; } diff --git a/modules/services/omnisearch.nix b/modules/services/omnisearch.nix index a3cbc87..f74992f 100644 --- a/modules/services/omnisearch.nix +++ b/modules/services/omnisearch.nix @@ -5,8 +5,9 @@ inputs.nixpkgs.follows = "nixpkgs"; }; */ + den.aspects.services.omnisearch = { - tunnel = { subdomain = "omnisearch"; port = 8087; }; # module default port + tunnel = { subdomain = "omnisearch"; port = 8087; }; nixos = { imports = [ inputs.omnisearch.nixosModules.default ]; diff --git a/modules/services/redlib.nix b/modules/services/redlib.nix index 11671cc..90d559c 100644 --- a/modules/services/redlib.nix +++ b/modules/services/redlib.nix @@ -6,7 +6,6 @@ services.redlib = { enable = true; - # upstream main with the wreq TLS-fingerprint fix for Reddit OAuth 401s package = pkgs.redlib.overrideAttrs (old: rec { version = "0.36.0-unstable-2026-04-24"; @@ -22,7 +21,6 @@ hash = "sha256-eO3c7rlFna3DuO31etJ6S4c7NmcvgvIWZ1KVkNIuUqQ="; }; - # BoringSSL via boring-sys2 nativeBuildInputs = (old.nativeBuildInputs or [ ]) ++ (with pkgs; [ cmake go perl git rustPlatform.bindgenHook ]); diff --git a/modules/services/slskd.nix b/modules/services/slskd.nix index e4b5ba7..bd5f42c 100644 --- a/modules/services/slskd.nix +++ b/modules/services/slskd.nix @@ -11,6 +11,7 @@ systemd.services.slskd.serviceConfig = { ReadWritePaths = [ "${home}/slskd" ]; ProtectHome = lib.mkForce false; + ReadOnlyPaths = lib.mkForce [ ]; }; services.slskd = { diff --git a/modules/software/browsers/librewolf/default.nix b/modules/software/browsers/librewolf/default.nix index 9fc2795..37f8c1f 100644 --- a/modules/software/browsers/librewolf/default.nix +++ b/modules/software/browsers/librewolf/default.nix @@ -10,7 +10,7 @@ }; den.aspects.software.browsers = { - homeManager = { host, pkgs, ... }: let + homeManager = { host, pkgs, config, ... }: let mkExtension = src: vars: extra: rec { id = (builtins.fromJSON (builtins.readFile "${src}/manifest.json")).browser_specific_settings.gecko.id; xpi = pkgs.runCommand "${lib.head (lib.splitString "@" id)}.xpi" { nativeBuildInputs = [ pkgs.zip ]; } '' @@ -70,6 +70,11 @@ "browser.search.separatePrivateDefault" = false; "browser.download.autohideButton" = true; + # save straight to ~/down (janitor sorts it) instead of asking + "browser.download.folderList" = 2; + "browser.download.dir" = "${config.home.homeDirectory}/down"; + "browser.download.useDownloadDir" = true; + "browser.download.always_ask_before_handling_new_types" = false; "browser.quitShortcut.disabled" = true; "browser.sessionstore.resume_session_once" = true; diff --git a/modules/software/cad/magica.nix b/modules/software/cad/magica.nix index 3f55d72..4ca9961 100644 --- a/modules/software/cad/magica.nix +++ b/modules/software/cad/magica.nix @@ -37,7 +37,7 @@ in { home.packages = lib.mapAttrsToList launcher present; - # Register .vox/.mcsg; our desktop entries are the only handlers, so they become the default. + xdg.dataFile."mime/packages/magica.xml".text = '' diff --git a/modules/software/gaming/minecraft.nix b/modules/software/gaming/minecraft.nix index 80c83ba..0b2c105 100644 --- a/modules/software/gaming/minecraft.nix +++ b/modules/software/gaming/minecraft.nix @@ -14,6 +14,7 @@ { pkgs, config, ... }: let home = config.home.homeDirectory; + gameDir = "${home}/media/games/minecraft"; inherit (pkgs) lib symlinkJoin makeWrapper; fetch = map (url: rec { @@ -56,7 +57,7 @@ appArgs = [ "--gameDir" - "${home}/.local/share/minecraft" + gameDir ]; }]); @@ -65,8 +66,11 @@ paths = [ base ]; nativeBuildInputs = [ makeWrapper ]; postBuild = '' + # the launch script cd's into its own --gameDir (default: $PWD), so pin it too wrapProgram $out/bin/minecraft \ - --set XDG_DATA_HOME "${home}/.local/share/minecraft" + --run 'mkdir -p "${gameDir}"' \ + --add-flags '--gameDir "${gameDir}"' \ + --set XDG_DATA_HOME "${gameDir}" ''; }; in diff --git a/modules/software/gaming/roblox.nix b/modules/software/gaming/roblox.nix new file mode 100644 index 0000000..b09e920 --- /dev/null +++ b/modules/software/gaming/roblox.nix @@ -0,0 +1,39 @@ +{ + # Roblox client manager. The package is built privately by Gitea Actions on box + # (repo /roblox) and served from the private attic cache; nothing here is + # fetchable without the tokens in ~/.config/nix/{netrc,roblox.conf}. + den.aspects.software.gaming = { + # roblox.conf holds the cache substituter, its public key and `netrc-file`. + nixos = { config, host, ... }: { + nix.extraOptions = "!include ${config.users.users.${host.owner}.home}/.config/nix/roblox.conf"; + }; + + homeManager = { pkgs, host, ... }: let + roblox = pkgs.writeShellApplication { + name = "roblox-manager"; + runtimeInputs = with pkgs; [ curl coreutils ]; + text = '' + state="''${XDG_STATE_HOME:-$HOME/.local/state}/roblox" + mkdir -p "$state" + # Follow the latest CI build; keep the last one when offline. + if path=$(curl -fsS --max-time 10 --netrc-file "$HOME/.config/nix/netrc" \ + "https://git.${host.domain}/${host.owner}/roblox/raw/branch/release/path") \ + && [[ "$(readlink "$state/current" || true)" != "$path" ]]; then + nix-store --realise "$path" --add-root "$state/current" >/dev/null + fi + [[ -e "$state/current" ]] || { echo "roblox-manager: no build available yet" >&2; exit 1; } + exec "$state/current/bin/roblox" "$@" + ''; + }; + in { + home.packages = [ roblox ]; + xdg.desktopEntries.roblox-manager = { + name = "Roblox Manager"; + comment = "Roblox client manager"; + exec = "roblox-manager"; + icon = "applications-games"; + categories = [ "Game" ]; + }; + }; + }; +} diff --git a/modules/software/music/beets.nix b/modules/software/music/beets.nix index 07210f0..de7fc2a 100644 --- a/modules/software/music/beets.nix +++ b/modules/software/music/beets.nix @@ -10,7 +10,7 @@ file.".config/beets/config.yaml".text = '' library: ~/.local/share/beets/library.db - directory: ~/Music + directory: ~/media/music import: write: true @@ -32,7 +32,7 @@ format: opus formats: opus: ffmpeg -i $source -y -vn -c:a libopus -b:a 160k $dest - dest: ${config.home.homeDirectory}/Music + dest: ${config.home.homeDirectory}/media/music fetchart: auto: yes @@ -43,7 +43,7 @@ auto: yes smartplaylist: - playlist_dir: ~/Music/playlists + playlist_dir: ~/media/music/playlists relative_to: library output: extm3u ''; diff --git a/modules/system/compat/default.nix b/modules/system/compat/default.nix index 076fcc8..1e5622d 100644 --- a/modules/system/compat/default.nix +++ b/modules/system/compat/default.nix @@ -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 = { diff --git a/modules/system/desktop/noctalia/config.toml b/modules/system/desktop/noctalia/config.toml index a50b4a3..9cd5f81 100644 --- a/modules/system/desktop/noctalia/config.toml +++ b/modules/system/desktop/noctalia/config.toml @@ -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" diff --git a/modules/system/desktop/xdg.nix b/modules/system/desktop/xdg.nix index a86b130..738bd37 100644 --- a/modules/system/desktop/xdg.nix +++ b/modules/system/desktop/xdg.nix @@ -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 = { diff --git a/modules/system/janitor/default.nix b/modules/system/janitor/default.nix index 8a3d8dc..b069ca4 100644 --- a/modules/system/janitor/default.nix +++ b/modules/system/janitor/default.nix @@ -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" ]; }; }; }; diff --git a/modules/system/monitoring.nix b/modules/system/monitoring.nix index a138017..7f0a98c 100644 --- a/modules/system/monitoring.nix +++ b/modules/system/monitoring.nix @@ -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: { diff --git a/modules/system/network/syncthing.nix b/modules/system/network/syncthing.nix index 802441e..443c564 100644 --- a/modules/system/network/syncthing.nix +++ b/modules/system/network/syncthing.nix @@ -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"; diff --git a/modules/system/tags/_tagger.py b/modules/system/tags/_tagger.py new file mode 100644 index 0000000..4fd21e3 --- /dev/null +++ b/modules/system/tags/_tagger.py @@ -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/ 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() diff --git a/modules/system/tags/backend.nix b/modules/system/tags/backend.nix new file mode 100644 index 0000000..c704b2f --- /dev/null +++ b/modules/system/tags/backend.nix @@ -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/ tag for everything in this root."; }; + kindFromSubdir = lib.mkOption { type = lib.types.bool; default = false; description = "Tag kind/."; }; + }; + }); + 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; + }; + }; + }; + }; + }; +} diff --git a/modules/system/tags/default.nix b/modules/system/tags/default.nix new file mode 100644 index 0000000..c8c1f59 --- /dev/null +++ b/modules/system/tags/default.nix @@ -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" + ]; + }; + }; + }; +}