okami.mom/strata

git clone https://git.nkp.pet/okami.mom/strata

Niko1221Merge main 6c642df75 into f-own-int (round 16: network waits, robustness, Windows kill-on-close job start, GitHub and transfer fixes)cd9745050

main
23.3 KiB509 linesraw
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``).
11             The 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:
38    return os.name == "nt" if windows is None else windows
39
40
41def _home(home: Path | None) -> Path:
42    return 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:
46    from strata_control import engine_component
47    return 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)."""
52    return 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)."""
57    return 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."""
62    return 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)."""
67    environ = os.environ if environ is None else environ
68    home = _home(home)
69    out: list[Path] = []
70    explicit = environ.get("STRATA_DOCUMENTS_DIR")
71    if explicit:
72        out.append(Path(explicit))
73    if _windows(windows):
74        user = Path(environ.get("USERPROFILE") or str(home))
75        out += [user / "Documents"]
76        for key in ("OneDrive", "OneDriveConsumer", "OneDriveCommercial"):
77            if environ.get(key):
78                out.append(Path(environ[key]) / "Documents")
79    else:
80        xdg = environ.get("XDG_DOCUMENTS_DIR")
81        if xdg:
82            out.append(Path(xdg))
83        out.append(home / "Documents")
84    found: list[Path] = []
85    for d in out:
86        if d not in found:
87            found.append(d)
88    return found
89
90
91def _read_json(path: Path) -> dict:
92    try:
93        with path.open("rb") as stream:
94            data = json.loads(stream.read(1024 * 1024).decode("utf-8-sig"))
95    except (OSError, UnicodeError, ValueError):
96        return {}
97    return 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
102    is still a folder there, and was remembered as an install): ~/.local/share/Trash/files/.., /.Trash-1000/.., ~/.Trash/..,
103    $RECYCLE.BIN\\.."""
104    parts = [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
105    for i, x in enumerate(parts):
106        if x in (".trash", "$recycle.bin", "recycler", "$recycle.bin.old") or x.startswith(".trash-"):
107            return True
108        if x == "trash" and i + 1 < len(parts) and parts[i + 1] in ("files", "info", "expunged"):
109            return True                                  # the XDG Trash: ~/.local/share/Trash/files
110    return False
111
112
113def _installs_in(settings: dict) -> list[Path]:
114    items = settings.get("installs")
115    found: list[Path] = []
116    for raw in (items if isinstance(items, list) else [])[:20]:
117        if isinstance(raw, str) and raw:
118            p = Path(raw).expanduser()
119            if p.is_absolute() and p not in found and not in_trash(p):
120                found.append(p)
121    return 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)."""
126    environ = os.environ if environ is None else environ
127    if environ.get("STRATA_SETTINGS_FILE"):
128        return Path(environ["STRATA_SETTINGS_FILE"])
129    home = _home(home)
130    if _windows(windows):
131        return Path(environ.get("APPDATA") or str(home / "AppData" / "Roaming")) / "Strata" / "settings.json"
132    return Path(environ.get("XDG_CONFIG_HOME") or str(home / ".config")) / "strata" / "settings.json"
133
134
135def has_configs(directory: Path) -> bool:
136    try:
137        return directory.is_dir() and any(_is_config(p) for p in directory.iterdir())
138    except OSError:
139        return False
140
141
142def _is_config(path: Path) -> bool:
143    n = path.name
144    return 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]:
148    try:
149        return sorted(p for p in directory.iterdir() if _is_config(p))
150    except OSError:
151        return []
152
153
154@dataclass
155class Place:
156    path: Path
157    source: str                     # explicit | here | remembered | app
158    configs: int = 0
159
160
161def places(*, here: Path | None = None, explicit: str | os.PathLike | None = None, environ=None, windows: bool | None = None,
162           home: Path | None = None) -> list[Place]:
163    """Every folder that holds run configs, in the order described above. An explicit folder is the only one."""
164    environ = os.environ if environ is None else environ
165    raw = explicit if explicit is not None else environ.get("STRATA_INSTALL_DIR")
166    if raw is not None:
167        p = Path(raw).expanduser()
168        return [Place(p, "explicit", len(config_files(p)))]
169    cands: list[tuple[Path, str]] = []
170    data_root = environ.get("STRATA_DATA_DIR")
171    if data_root:                                    # the installer's own folder (install.sh / install.ps1): an install kept inside it comes first
172        cands.append((Path(data_root).expanduser() / "install", "datadir"))
173    if here is not None:
174        cands.append((Path(here), "here"))
175    own = own_settings_file(environ, windows=windows, home=home)
176    cands += [(p, "remembered") for p in _installs_in(_read_json(own))]
177    cands += [(app_install_dir(environ, windows=windows, home=home), "app")]
178    if not in_app_mode(environ):
179        cands += [(p, "app") for p in _installs_in(_read_json(app_settings_file(environ, windows=windows, home=home)))]
180    out: list[Place] = []
181    seen: set[str] = set()
182    for path, source in cands:
183        try:
184            key = os.path.normcase(str(path.resolve()))
185        except OSError:
186            key = os.path.normcase(str(path))
187        if key in seen:
188            continue
189        seen.add(key)
190        n = len(config_files(path))
191        if n:
192            out.append(Place(path if source == "here" else (path.resolve() if path.exists() else path), source, n))
193    return out
194
195
196def find_install(*, here: Path | None = None, explicit: str | os.PathLike | None = None, environ=None, windows: bool | None = None,
197                 home: 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
199    installed (``default``)."""
200    found = places(here=here, explicit=explicit, environ=environ, windows=windows, home=home)
201    if found:
202        return found[0].path, found[0].source
203    environ = os.environ if environ is None else environ
204    return 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."""
211    data = _read_json(file)
212    folder = data.get("data_dir")
213    if not isinstance(folder, str) or not folder:
214        return None
215    at = data.get("data_dir_at")
216    if isinstance(at, bool) or not isinstance(at, (int, float)) or at <= 0:
217        try:
218            at = file.stat().st_mtime
219        except OSError:
220            at = 0.0
221    return folder, float(at)
222
223
224def _same(a: str, b: str) -> bool:
225    return 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."""
230    try:
231        current = _read_json(file)
232        current["data_dir"], current["data_dir_at"] = folder, at
233        file.parent.mkdir(parents=True, exist_ok=True)
234        temp = file.with_name(f"{file.name}.{os.getpid()}.tmp")
235        temp.write_text(json.dumps(current, indent=1), encoding="utf-8")
236        os.replace(temp, file)
237        return True
238    except OSError:
239        return 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
244    a data folder; when they disagree the one changed last wins and the other file is updated. Nothing is moved. Returns (folder, source of
245    the winner) or None when neither names one. The app's own processes never call this (the app syncs from its host)."""
246    environ = os.environ if environ is None else environ
247    if in_app_mode(environ):
248        return None
249    mine_file = own_settings_file(environ, windows=windows, home=home)
250    app_file = app_settings_file(environ, windows=windows, home=home)
251    mine, app = _data_dir_entry(mine_file), _data_dir_entry(app_file)
252    if mine and app and not _same(mine[0], app[0]):
253        newer, older_file, source = (mine, app_file, "settings") if mine[1] >= app[1] else (app, mine_file, "app")
254        if source == "app" and not Path(app[0]).is_dir():          # a disk that is not connected is never adopted
255            return Path(mine[0]), "settings"
256        _write_data_dir(older_file, newer[0], newer[1])
257        return Path(newer[0]), source
258    if mine:
259        return Path(mine[0]), "settings"
260    return (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)."""
265    environ = os.environ if environ is None else environ
266    out: list[tuple[Path, str]] = []
267    own = _data_dir_entry(own_settings_file(environ, windows=windows, home=home))
268    app = None if in_app_mode(environ) else _data_dir_entry(app_settings_file(environ, windows=windows, home=home))
269    entries = [(Path(e[0]), src, e[1]) for e, src in ((own, "settings"), (app, "app")) if e]
270    entries.sort(key=lambda x: -x[2])                              # the folder changed last first, whichever file it is in
271    out.extend((p, src) for p, src, _ in entries)
272    if not in_app_mode(environ):
273        for d in documents_dirs(environ, windows=windows, home=home):
274            out.append((d / "Strata", "documents"))
275    return 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
280    to date); then a ``Documents/Strata`` that holds models; else `default`."""
281    sync_data_dir(environ=environ, windows=windows, home=home)
282    choices = data_dir_choices(environ=environ, windows=windows, home=home)
283    for path, source in choices:
284        if source == "settings":
285            return path, source
286        if source == "app" and path.is_dir():
287            return path, source
288        if source == "documents" and _holds_models(path):
289            return path, source
290    return default, "default"
291
292
293def _holds_models(folder: Path) -> bool:
294    try:
295        return any((folder / sub).is_dir() and any((folder / sub).iterdir()) for sub in ("Models", "models", "packs"))
296    except OSError:
297        return False
298
299
300# ----------------------------------------------------------------------------------------------- what a model has
301
302def _flag_value(args: list[str], flag: str) -> str | None:
303    try:
304        i = args.index(flag)
305    except ValueError:
306        return None
307    return 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
314    config: Path | None = None
315    weights: list[Path] = field(default_factory=list)       # the model's GGUF file(s)
316    pack: Path | None = None                               # the prepared expert pack (--pack)
317    mtp: Path | None = None                                # the draft layer (--mtp)
318    mmproj: Path | None = None                             # the picture reader's file
319    pictures_wanted: bool = False
320    data_dir: Path | None = None
321
322    def missing(self) -> list["Missing"]:
323        out: list[Missing] = []
324        gone = [p for p in self.weights if not p.exists()]
325        if gone:
326            out.append(Missing("weights", "the model's weights", gone[0], None))
327        if self.pack is not None and not self.pack.exists():
328            out.append(Missing("pack", "the prepared model data", self.pack, 0.0))
329        if self.mtp is not None and not _mtp_ready(self.mtp):
330            out.append(Missing("mtp", "the draft layer (makes answers faster)", self.mtp, MTP_FETCH_GB))
331        if self.pictures_wanted and self.mmproj is not None and not self.mmproj.exists():
332            out.append(Missing("mmproj", "the picture reader", self.mmproj, MMPROJ_GB))
333        return out
334
335
336@dataclass
337class Missing:
338    kind: str                    # weights | pack | mtp | mmproj
339    label: str
340    path: Path
341    gb: 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."""
346    return (path / "experts.bin").exists() or (path.is_file() and path.exists())
347
348
349def footprint(cfg: dict, config: Path | None = None) -> Footprint:
350    args = [str(a) for a in cfg.get("args") or []]
351    fp = Footprint(config=config)
352    for flag in ("--native", "--model", "--gguf", "--ple-gguf"):
353        v = _flag_value(args, flag)
354        if v and v.lower().endswith(".gguf") and Path(v) not in fp.weights and flag != "--ple-gguf":
355            fp.weights.append(Path(v))
356    if not fp.weights:
357        fp.weights = [Path(a) for a in args if a.lower().endswith(".gguf")][:1]
358    pack = _flag_value(args, "--pack")
359    fp.pack = Path(pack) if pack else None
360    mtp = _flag_value(args, "--mtp")
361    fp.mtp = Path(mtp) if mtp and not mtp.isdigit() else None
362    vision = cfg.get("vision")
363    if isinstance(vision, dict) and vision.get("mmproj"):
364        fp.mmproj = Path(str(vision["mmproj"]))
365        fp.pictures_wanted = True
366    elif "--vision" in args:
367        fp.pictures_wanted = True
368    fp.data_dir = data_dir_of(fp)
369    return 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``."""
374    if fp.pack is not None:
375        return fp.pack.parent.parent
376    if fp.mtp is not None and fp.mtp.name.lower() == "rt":
377        return fp.mtp.parent.parent
378    for w in fp.weights:
379        for parent in w.parents:
380            if parent.name.lower() == "models":
381                return parent.parent
382    return 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.
387    Unlike ``data_dir`` this writes nothing (no settings sync)."""
388    try:
389        return [p for p, source in data_dir_choices(environ=environ, windows=windows, home=home) if source in ("settings", "app") and p.is_dir()]
390    except OSError:
391        return []
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."""
396    for folder in folders:
397        if not folder:
398            continue
399        try:
400            rt = Path(folder) / "mtp" / "rt"
401            if (rt / "experts.bin").is_file():
402                return rt
403        except OSError:
404            continue
405    return 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
410    itself: HF_HUB_CACHE, HF_HOME/hub, ~/.cache/huggingface). Strata never writes there: the cache is the hub library's, and a
411    file added beside a snapshot's links confuses it."""
412    environ = os.environ if environ is None else environ
413    p = Path(path).expanduser()
414    try:
415        p = p.resolve()
416    except OSError:
417        pass
418    if any(part.lower().startswith("models--") for part in p.parts):
419        return True
420    roots = [environ.get("HF_HUB_CACHE"), environ.get("HUGGINGFACE_HUB_CACHE"), environ.get("HF_HOME"),
421             str(Path("~/.cache/huggingface").expanduser())]
422    for r in roots:
423        if not r:
424            continue
425        try:
426            root = Path(r).expanduser().resolve()
427        except OSError:
428            continue
429        if p == root or root in p.parents:
430            return True
431    try:
432        return p.is_dir() and any(c.name.lower().startswith("models--") for c in p.iterdir())     # a cache folder of another name
433    except OSError:
434        return 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`
439    folder), 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
440    cache. None: use the data folder every command agrees on instead (the model files are still used where they are)."""
441    if gguf is None:
442        return None
443    found = prepared_beside(gguf)["data_dir"]
444    if found is None:
445        return None
446    found = Path(found)
447    if in_hf_cache(found) or in_hf_cache(found / "models"):
448        return None
449    from strata_control import folders
450    return 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
455    layer 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).
459    The folder next to the model is looked at first."""
460    gguf = Path(gguf)
461    folder = gguf.parent
462    out: dict = {"data_dir": None, "pack": None, "mtp": None, "mmproj": None}
463    for parent in folder.parents:
464        if parent.name.lower() == "models":
465            data = parent.parent
466            out["data_dir"] = data
467            tag = folder.name.lower() if folder != parent else ""
468            if tag and (data / "packs" / tag).is_dir():
469                out["pack"] = data / "packs" / tag
470            if (data / "mtp" / "rt" / "experts.bin").is_file():
471                out["mtp"] = data / "mtp" / "rt"
472            for cand in sorted(parent.glob("mmproj*.gguf")) + sorted(folder.glob("mmproj*.gguf")):
473                out["mmproj"] = cand
474                break
475            break
476    others = [Path(d) for d in data_dirs if d]
477    if out["mtp"] is None:
478        out["mtp"] = mtp_layer_in(*others)
479    if out["pack"] is None and folder.name:
480        tag = folder.name.lower()
481        for d in others:
482            try:
483                if (d / "packs" / tag).is_dir():
484                    out["pack"] = d / "packs" / tag
485                    break
486            except OSError:
487                continue
488    if out["mmproj"] is None:
489        for d in others:                                         # setup keeps the picture reader in <data>/models
490            try:
491                found = next(iter(sorted(p for sub in ("models", "Models") for p in (d / sub).glob("mmproj*.gguf"))), None)
492            except OSError:
493                found = None
494            if found is not None:
495                out["mmproj"] = found
496                break
497    return 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)."""
502    want = os.path.normcase(str(Path(gguf)))
503    for place in install_places:
504        for cfg_path in config_files(place.path):
505            data = _read_json(cfg_path)
506            args = [str(a) for a in data.get("args") or []]
507            if any(os.path.normcase(a) == want for a in args if a.lower().endswith(".gguf")):
508                return cfg_path
509    return None