okami.mom/strata
git clone https://git.nkp.pet/okami.mom/strata
cd9745050
main
1"""Where Strata's existing installs and model files are: ONE place that the launch screens, `strata models list`, the own-files import 2and `strata launch` all ask. 3 4Three kinds of place hold a model's run config (`strata-<tag>.json`), looked at in this order, the first that has any is the main one: 5 6* explicit STRATA_INSTALL_DIR or an --install-dir argument (it is the only place looked at); 7* here the Terminal's own folder, when it has run configs (a source checkout that ran setup); 8* remembered the folders earlier Strata installs wrote into the user's settings file (``installs``); 9* app the desktop app's install folder, which the Terminal shares: ``<components>/../install`` (Windows 10``%LOCALAPPDATA%\\Strata\\install``, Linux and Mac ``$XDG_DATA_HOME/strata/install``, default ``~/.local/share/strata/install``). 11The app's own settings file (``app-settings.json`` beside it) names its data folder and installs. 12 13The desktop app itself (it sets STRATA_SETTINGS_FILE) never adopts an older command-line install, so for it only the explicit place, its 14own install folder and its own settings file count. Everything here is read-only: nothing is created, copied or moved. 15 16The data folder (models, packs, mtp) is found the same way: the person's own setting first, then the app's data folder, then a 17``Documents/Strata`` folder that holds models, then the default beside the install. A model that is installed tells where it really is 18(its run config names its files), which beats all of these. 19""" 20 21from __future__import annotations 22 23import json 24import os 25from collections .abc import Iterable 26from dataclasses import dataclass ,field 27from pathlib import Path 28 29# What setup still has to fetch for an installed model whose helper files are gone (setup.py: tools/mtp_fetch.py reads the 31 MTP tensors of 30# the pinned checkpoint, 5.214 GB, and packs them into a 0.9 GB draft layer; the picture reader is one 0.9 GB file). 31MTP_FETCH_GB = 5.2 32MMPROJ_GB = 0.9 33 34 35# ----------------------------------------------------------------------------------------------- the places 36 37def _windows (windows :bool | None )-> bool : 38return os .name == "nt" if windows is None else windows 39 40 41def _home (home :Path | None )-> Path : 42return Path .home ()if home is None else Path (home ) 43 44 45def components_dir (environ = None ,* ,windows :bool | None = None ,home :Path | None = None )-> Path : 46from strata_control import engine_component 47return engine_component .components_dir (environ ,windows = windows ,home = home ) 48 49 50def app_install_dir (environ = None ,* ,windows :bool | None = None ,home :Path | None = None )-> Path : 51"""The install folder the desktop app uses and the Terminal shares (beside the components folder).""" 52return components_dir (environ ,windows = windows ,home = home ).parent / "install" 53 54 55def app_settings_file (environ = None ,* ,windows :bool | None = None ,home :Path | None = None )-> Path : 56"""The desktop app's own settings file (control-runtime.mjs: beside its components folder).""" 57return components_dir (environ ,windows = windows ,home = home ).parent / "app-settings.json" 58 59 60def in_app_mode (environ = None )-> bool : 61"""True inside the desktop app's own processes: they set STRATA_SETTINGS_FILE and never adopt an older install.""" 62return bool ((os .environ if environ is None else environ ).get ("STRATA_SETTINGS_FILE" )) 63 64 65def documents_dirs (environ = None ,* ,windows :bool | None = None ,home :Path | None = None )-> list [Path ]: 66"""The person's Documents folder(s): where the desktop app keeps ``Strata`` by default (Windows may redirect Documents to OneDrive).""" 67environ = os .environ if environ is None else environ 68home = _home (home ) 69out :list [Path ]= [] 70explicit = environ .get ("STRATA_DOCUMENTS_DIR" ) 71if explicit : 72out .append (Path (explicit )) 73if _windows (windows ): 74user = Path (environ .get ("USERPROFILE" )or str (home )) 75out += [user / "Documents" ] 76for key in ("OneDrive" ,"OneDriveConsumer" ,"OneDriveCommercial" ): 77if environ .get (key ): 78out .append (Path (environ [key ])/ "Documents" ) 79else : 80xdg = environ .get ("XDG_DOCUMENTS_DIR" ) 81if xdg : 82out .append (Path (xdg )) 83out .append (home / "Documents" ) 84found :list [Path ]= [] 85for d in out : 86if d not in found : 87found .append (d ) 88return found 89 90 91def _read_json (path :Path )-> dict : 92try : 93with path .open ("rb" )as stream : 94data = json .loads (stream .read (1024 * 1024 ).decode ("utf-8-sig" )) 95except (OSError ,UnicodeError ,ValueError ): 96return {} 97return data if isinstance (data ,dict )else {} 98 99 100def in_trash (path :str | os .PathLike )-> bool : 101"""#3410: True when ``path`` is inside a Trash / Recycle Bin folder (a Strata folder that was deleted with the file manager 102is still a folder there, and was remembered as an install): ~/.local/share/Trash/files/.., /.Trash-1000/.., ~/.Trash/.., 103$RECYCLE.BIN\\..""" 104parts = [x .lower ()for p in Path (path ).parts for x in str (p ).split ("\\" )]# a Windows-shaped path read on Linux has no separators for Path 105for i ,x in enumerate (parts ): 106if x in (".trash" ,"$recycle.bin" ,"recycler" ,"$recycle.bin.old" )or x .startswith (".trash-" ): 107return True 108if x == "trash" and i + 1 < len (parts )and parts [i + 1 ]in ("files" ,"info" ,"expunged" ): 109return True # the XDG Trash: ~/.local/share/Trash/files 110return False 111 112 113def _installs_in (settings :dict )-> list [Path ]: 114items = settings .get ("installs" ) 115found :list [Path ]= [] 116for raw in (items if isinstance (items ,list )else [])[:20 ]: 117if isinstance (raw ,str )and raw : 118p = Path (raw ).expanduser () 119if p .is_absolute ()and p not in found and not in_trash (p ): 120found .append (p ) 121return found 122 123 124def own_settings_file (environ = None ,* ,windows :bool | None = None ,home :Path | None = None )-> Path : 125"""The settings file this process uses: the app's (STRATA_SETTINGS_FILE), else the command-line Strata's (%APPDATA% / ~/.config).""" 126environ = os .environ if environ is None else environ 127if environ .get ("STRATA_SETTINGS_FILE" ): 128return Path (environ ["STRATA_SETTINGS_FILE" ]) 129home = _home (home ) 130if _windows (windows ): 131return Path (environ .get ("APPDATA" )or str (home / "AppData" / "Roaming" ))/ "Strata" / "settings.json" 132return Path (environ .get ("XDG_CONFIG_HOME" )or str (home / ".config" ))/ "strata" / "settings.json" 133 134 135def has_configs (directory :Path )-> bool : 136try : 137return directory .is_dir ()and any (_is_config (p )for p in directory .iterdir ()) 138except OSError : 139return False 140 141 142def _is_config (path :Path )-> bool : 143n = path .name 144return n .startswith ("strata-" )and n .endswith (".json" )and not n .endswith (".shared-settings.json" )and len (n )> len ("strata-.json" ) 145 146 147def config_files (directory :Path )-> list [Path ]: 148try : 149return sorted (p for p in directory .iterdir ()if _is_config (p )) 150except OSError : 151return [] 152 153 154@dataclass 155class Place : 156path :Path 157source :str # explicit | here | remembered | app 158configs :int = 0 159 160 161def places (* ,here :Path | None = None ,explicit :str | os .PathLike | None = None ,environ = None ,windows :bool | None = None , 162home :Path | None = None )-> list [Place ]: 163"""Every folder that holds run configs, in the order described above. An explicit folder is the only one.""" 164environ = os .environ if environ is None else environ 165raw = explicit if explicit is not None else environ .get ("STRATA_INSTALL_DIR" ) 166if raw is not None : 167p = Path (raw ).expanduser () 168return [Place (p ,"explicit" ,len (config_files (p )))] 169cands :list [tuple [Path ,str ]]= [] 170data_root = environ .get ("STRATA_DATA_DIR" ) 171if data_root :# the installer's own folder (install.sh / install.ps1): an install kept inside it comes first 172cands .append ((Path (data_root ).expanduser ()/ "install" ,"datadir" )) 173if here is not None : 174cands .append ((Path (here ),"here" )) 175own = own_settings_file (environ ,windows = windows ,home = home ) 176cands += [(p ,"remembered" )for p in _installs_in (_read_json (own ))] 177cands += [(app_install_dir (environ ,windows = windows ,home = home ),"app" )] 178if not in_app_mode (environ ): 179cands += [(p ,"app" )for p in _installs_in (_read_json (app_settings_file (environ ,windows = windows ,home = home )))] 180out :list [Place ]= [] 181seen :set [str ]= set () 182for path ,source in cands : 183try : 184key = os .path .normcase (str (path .resolve ())) 185except OSError : 186key = os .path .normcase (str (path )) 187if key in seen : 188continue 189seen .add (key ) 190n = len (config_files (path )) 191if n : 192out .append (Place (path if source == "here" else (path .resolve ()if path .exists ()else path ),source ,n )) 193return out 194 195 196def find_install (* ,here :Path | None = None ,explicit :str | os .PathLike | None = None ,environ = None ,windows :bool | None = None , 197home :Path | None = None )-> tuple [Path ,str ]: 198"""(the main install folder, how it was found). With no run config anywhere it is the app's folder, which is where a new model is 199installed (``default``).""" 200found = places (here = here ,explicit = explicit ,environ = environ ,windows = windows ,home = home ) 201if found : 202return found [0 ].path ,found [0 ].source 203environ = os .environ if environ is None else environ 204return app_install_dir (environ ,windows = windows ,home = home ),"default" 205 206 207# ----------------------------------------------------------------------------------------------- the data folder 208 209def _data_dir_entry (file :Path )-> tuple [str ,float ]| None : 210"""(the data folder a settings file names, when it was last changed): ``data_dir_at`` (seconds), else the file's own time.""" 211data = _read_json (file ) 212folder = data .get ("data_dir" ) 213if not isinstance (folder ,str )or not folder : 214return None 215at = data .get ("data_dir_at" ) 216if isinstance (at ,bool )or not isinstance (at , (int ,float ))or at <= 0 : 217try : 218at = file .stat ().st_mtime 219except OSError : 220at = 0.0 221return folder ,float (at ) 222 223 224def _same (a :str ,b :str )-> bool : 225return os .path .normcase (os .path .abspath (a ))== os .path .normcase (os .path .abspath (b )) 226 227 228def _write_data_dir (file :Path ,folder :str ,at :float )-> bool : 229"""Merge the data folder and its time into a settings file (atomic). False when the disk refuses; never raises.""" 230try : 231current = _read_json (file ) 232current ["data_dir" ],current ["data_dir_at" ]= folder ,at 233file .parent .mkdir (parents = True ,exist_ok = True ) 234temp = file .with_name (f" { file . name } . { os . getpid () } .tmp" ) 235temp .write_text (json .dumps (current ,indent = 1 ),encoding = "utf-8" ) 236os .replace (temp ,file ) 237return True 238except OSError : 239return False 240 241 242def sync_data_dir (* ,environ = None ,windows :bool | None = None ,home :Path | None = None )-> tuple [Path ,str ]| None : 243"""One models folder for the Terminal and the desktop app. The Terminal's settings file and the app's (``app-settings.json``) each name 244a data folder; when they disagree the one changed last wins and the other file is updated. Nothing is moved. Returns (folder, source of 245the winner) or None when neither names one. The app's own processes never call this (the app syncs from its host).""" 246environ = os .environ if environ is None else environ 247if in_app_mode (environ ): 248return None 249mine_file = own_settings_file (environ ,windows = windows ,home = home ) 250app_file = app_settings_file (environ ,windows = windows ,home = home ) 251mine ,app = _data_dir_entry (mine_file ),_data_dir_entry (app_file ) 252if mine and app and not _same (mine [0 ],app [0 ]): 253newer ,older_file ,source = (mine ,app_file ,"settings" )if mine [1 ]>= app [1 ]else (app ,mine_file ,"app" ) 254if source == "app" and not Path (app [0 ]).is_dir ():# a disk that is not connected is never adopted 255return Path (mine [0 ]),"settings" 256_write_data_dir (older_file ,newer [0 ],newer [1 ]) 257return Path (newer [0 ]),source 258if mine : 259return Path (mine [0 ]),"settings" 260return (Path (app [0 ]),"app" )if app else None 261 262 263def data_dir_choices (* ,environ = None ,windows :bool | None = None ,home :Path | None = None )-> list [tuple [Path ,str ]]: 264"""Candidate data folders with their source, best first (not checked for existence).""" 265environ = os .environ if environ is None else environ 266out :list [tuple [Path ,str ]]= [] 267own = _data_dir_entry (own_settings_file (environ ,windows = windows ,home = home )) 268app = None if in_app_mode (environ )else _data_dir_entry (app_settings_file (environ ,windows = windows ,home = home )) 269entries = [(Path (e [0 ]),src ,e [1 ])for e ,src in ((own ,"settings" ), (app ,"app" ))if e ] 270entries .sort (key = lambda x :- x [2 ])# the folder changed last first, whichever file it is in 271out .extend ((p ,src )for p ,src ,_ in entries ) 272if not in_app_mode (environ ): 273for d in documents_dirs (environ ,windows = windows ,home = home ): 274out .append ((d / "Strata" ,"documents" )) 275return out 276 277 278def data_dir (default :Path ,* ,environ = None ,windows :bool | None = None ,home :Path | None = None )-> tuple [Path ,str ]: 279"""(the data folder, source). Of the Terminal's own setting and the app's folder the one changed last wins (the other file is brought up 280to date); then a ``Documents/Strata`` that holds models; else `default`.""" 281sync_data_dir (environ = environ ,windows = windows ,home = home ) 282choices = data_dir_choices (environ = environ ,windows = windows ,home = home ) 283for path ,source in choices : 284if source == "settings" : 285return path ,source 286if source == "app" and path .is_dir (): 287return path ,source 288if source == "documents" and _holds_models (path ): 289return path ,source 290return default ,"default" 291 292 293def _holds_models (folder :Path )-> bool : 294try : 295return any ((folder / sub ).is_dir ()and any ((folder / sub ).iterdir ())for sub in ("Models" ,"models" ,"packs" )) 296except OSError : 297return False 298 299 300# ----------------------------------------------------------------------------------------------- what a model has 301 302def _flag_value (args :list [str ],flag :str )-> str | None : 303try : 304i = args .index (flag ) 305except ValueError : 306return None 307return args [i + 1 ]if i + 1 < len (args )else None 308 309 310@dataclass 311class Footprint : 312"""The files of one installed model, from its run config: what is named, where, and whether it is there.""" 313 314config :Path | None = None 315weights :list [Path ]= field (default_factory = list )# the model's GGUF file(s) 316pack :Path | None = None # the prepared expert pack (--pack) 317mtp :Path | None = None # the draft layer (--mtp) 318mmproj :Path | None = None # the picture reader's file 319pictures_wanted :bool = False 320data_dir :Path | None = None 321 322def missing (self )-> list ["Missing" ]: 323out :list [Missing ]= [] 324gone = [p for p in self .weights if not p .exists ()] 325if gone : 326out .append (Missing ("weights" ,"the model's weights" ,gone [0 ],None )) 327if self .pack is not None and not self .pack .exists (): 328out .append (Missing ("pack" ,"the prepared model data" ,self .pack ,0.0 )) 329if self .mtp is not None and not _mtp_ready (self .mtp ): 330out .append (Missing ("mtp" ,"the draft layer (makes answers faster)" ,self .mtp ,MTP_FETCH_GB )) 331if self .pictures_wanted and self .mmproj is not None and not self .mmproj .exists (): 332out .append (Missing ("mmproj" ,"the picture reader" ,self .mmproj ,MMPROJ_GB )) 333return out 334 335 336@dataclass 337class Missing : 338kind :str # weights | pack | mtp | mmproj 339label :str 340path :Path 341gb :float | None # to download; None: the whole model (the caller knows its size), 0: prepared locally, nothing to download 342 343 344def _mtp_ready (path :Path )-> bool : 345"""--mtp names the ``rt`` folder; it is usable when its experts file is there.""" 346return (path / "experts.bin" ).exists ()or (path .is_file ()and path .exists ()) 347 348 349def footprint (cfg :dict ,config :Path | None = None )-> Footprint : 350args = [str (a )for a in cfg .get ("args" )or []] 351fp = Footprint (config = config ) 352for flag in ("--native" ,"--model" ,"--gguf" ,"--ple-gguf" ): 353v = _flag_value (args ,flag ) 354if v and v .lower ().endswith (".gguf" )and Path (v )not in fp .weights and flag != "--ple-gguf" : 355fp .weights .append (Path (v )) 356if not fp .weights : 357fp .weights = [Path (a )for a in args if a .lower ().endswith (".gguf" )][:1 ] 358pack = _flag_value (args ,"--pack" ) 359fp .pack = Path (pack )if pack else None 360mtp = _flag_value (args ,"--mtp" ) 361fp .mtp = Path (mtp )if mtp and not mtp .isdigit ()else None 362vision = cfg .get ("vision" ) 363if isinstance (vision ,dict )and vision .get ("mmproj" ): 364fp .mmproj = Path (str (vision ["mmproj" ])) 365fp .pictures_wanted = True 366elif "--vision" in args : 367fp .pictures_wanted = True 368fp .data_dir = data_dir_of (fp ) 369return fp 370 371 372def data_dir_of (fp :Footprint )-> Path | None : 373"""The data folder an installed model lives in: the parent of its ``packs`` folder, else the one holding ``models``.""" 374if fp .pack is not None : 375return fp .pack .parent .parent 376if fp .mtp is not None and fp .mtp .name .lower ()== "rt" : 377return fp .mtp .parent .parent 378for w in fp .weights : 379for parent in w .parents : 380if parent .name .lower ()== "models" : 381return parent .parent 382return None 383 384 385def remembered_data_dirs (* ,environ = None ,windows :bool | None = None ,home :Path | None = None )-> list [Path ]: 386"""The data folders the Terminal's settings and the desktop app name (best first), read only: for a look at what is prepared where setup would put new files. 387Unlike ``data_dir`` this writes nothing (no settings sync).""" 388try : 389return [p for p ,source in data_dir_choices (environ = environ ,windows = windows ,home = home )if source in ("settings" ,"app" )and p .is_dir ()] 390except OSError : 391return [] 392 393 394def mtp_layer_in (* folders :"str | os.PathLike[str] | None" )-> Path | None : 395"""The ``mtp/rt`` folder of the first data folder that holds the draft layer (``<data>/mtp/rt/experts.bin``), the place setup writes it to. None when none does.""" 396for folder in folders : 397if not folder : 398continue 399try : 400rt = Path (folder )/ "mtp" / "rt" 401if (rt / "experts.bin" ).is_file (): 402return rt 403except OSError : 404continue 405return None 406 407 408def in_hf_cache (path :str | os .PathLike [str ],environ = None )-> bool : 409"""Whether `path` is inside a Hugging Face cache (a `models--<org>--<name>` folder with its snapshots/ and blobs/, or the cache folder 410itself: HF_HUB_CACHE, HF_HOME/hub, ~/.cache/huggingface). Strata never writes there: the cache is the hub library's, and a 411file added beside a snapshot's links confuses it.""" 412environ = os .environ if environ is None else environ 413p = Path (path ).expanduser () 414try : 415p = p .resolve () 416except OSError : 417pass 418if any (part .lower ().startswith ("models--" )for part in p .parts ): 419return True 420roots = [environ .get ("HF_HUB_CACHE" ),environ .get ("HUGGINGFACE_HUB_CACHE" ),environ .get ("HF_HOME" ), 421str (Path ("~/.cache/huggingface" ).expanduser ())] 422for r in roots : 423if not r : 424continue 425try : 426root = Path (r ).expanduser ().resolve () 427except OSError : 428continue 429if p == root or root in p .parents : 430return True 431try : 432return p .is_dir ()and any (c .name .lower ().startswith ("models--" )for c in p .iterdir ())# a cache folder of another name 433except OSError : 434return False 435 436 437def writable_beside (gguf :Path | None )-> Path | None : 438"""The data folder guessed from where the person's own model file sits (`prepared_beside`'s "data_dir": the folder above a `models` 439folder), only when Strata may keep its own files there: it can write to it and neither it nor its models/ is inside a Hugging Face 440cache. None: use the data folder every command agrees on instead (the model files are still used where they are).""" 441if gguf is None : 442return None 443found = prepared_beside (gguf )["data_dir" ] 444if found is None : 445return None 446found = Path (found ) 447if in_hf_cache (found )or in_hf_cache (found / "models" ): 448return None 449from strata_control import folders 450return None if folders .problem (str (found ))else found 451 452 453def prepared_beside (gguf :Path ,data_dirs :Iterable [str | os .PathLike [str ]| None ]= ())-> dict : 454"""What was already prepared for a model file that sits in ``<data>/Models/<tag>/`` (or ``<data>/models/<tag>/``): its pack, the draft 455layer and the picture reader, found by the layout setup and the desktop app both use. Reads only; absent items are None. 456 457``data_dirs`` are the data folders the launch names besides that layout (``--data-dir``, the remembered one): setup writes the draft layer to 458``<data-dir>/mtp/rt`` and the pack to ``<data-dir>/packs/<tag>``, and a model folder outside the data folder must not hide them (a second 5.2 GB fetch). 459The folder next to the model is looked at first.""" 460gguf = Path (gguf ) 461folder = gguf .parent 462out :dict = {"data_dir" :None ,"pack" :None ,"mtp" :None ,"mmproj" :None } 463for parent in folder .parents : 464if parent .name .lower ()== "models" : 465data = parent .parent 466out ["data_dir" ]= data 467tag = folder .name .lower ()if folder != parent else "" 468if tag and (data / "packs" / tag ).is_dir (): 469out ["pack" ]= data / "packs" / tag 470if (data / "mtp" / "rt" / "experts.bin" ).is_file (): 471out ["mtp" ]= data / "mtp" / "rt" 472for cand in sorted (parent .glob ("mmproj*.gguf" ))+ sorted (folder .glob ("mmproj*.gguf" )): 473out ["mmproj" ]= cand 474break 475break 476others = [Path (d )for d in data_dirs if d ] 477if out ["mtp" ]is None : 478out ["mtp" ]= mtp_layer_in (* others ) 479if out ["pack" ]is None and folder .name : 480tag = folder .name .lower () 481for d in others : 482try : 483if (d / "packs" / tag ).is_dir (): 484out ["pack" ]= d / "packs" / tag 485break 486except OSError : 487continue 488if out ["mmproj" ]is None : 489for d in others :# setup keeps the picture reader in <data>/models 490try : 491found = next (iter (sorted (p for sub in ("models" ,"Models" )for p in (d / sub ).glob ("mmproj*.gguf" ))),None ) 492except OSError : 493found = None 494if found is not None : 495out ["mmproj" ]= found 496break 497return out 498 499 500def run_config_for (gguf :Path ,install_places :list [Place ])-> Path | None : 501"""The run config in any known install folder that names this GGUF file (the model is already set up, with its own choices).""" 502want = os .path .normcase (str (Path (gguf ))) 503for place in install_places : 504for cfg_path in config_files (place .path ): 505data = _read_json (cfg_path ) 506args = [str (a )for a in data .get ("args" )or []] 507if any (os .path .normcase (a )== want for a in args if a .lower ().endswith (".gguf" )): 508return cfg_path 509return None