okami.mom/strata

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

Niko1221Merge f-0213-fixux (82d3a0345): user screenshots - a data folder on an external drive under /run/media is no longer refused as a system folder (real system folders still are; the doubled sentence is gone); one fit label everywhere (owner 11-08): 'fits' when the model files without the n-gram/PLE/Engram table fit graphics memory plus RAM, else 'may run slower' (the Unsloth sets were measured against RAM only; DeepSeek Needs shows the whole size; no-card PCs and small Macs say 'may run slower'; NVFP4-QAD sized by its 76.8 GB pack)b7bcbcde9

main
5.7 KiB125 linesraw
1"""Is this a folder Strata can keep model files in? Said in plain words before anything is downloaded (the Folder step, --data-dir, setup).
2
3`problem(path)` returns (what is wrong, what to do) or None. Nothing is created and nothing is left behind: a missing folder is judged by the
4nearest folder above it that exists (can a file be made there, so the folder could be created), and "can be written" is tried by creating and
5deleting a small file, never read from the permission bits.
6"""
7
8from __future__ import annotations
9
10import os
11import re
12import uuid
13from pathlib import Path
14
15NEXT = "Pick another folder, for example one on a drive you own, like D:\\Strata-models. Nothing was downloaded or changed."
16NEXT_POSIX = "Pick another folder you own, for example ~/strata-models. Nothing was downloaded or changed."
17
18_WIN_BAD = re.compile(r'[<>"|?*\x00-\x1f]')
19_POSIX_SYSTEM = ("/bin", "/boot", "/dev", "/etc", "/lib", "/lib32", "/lib64", "/proc", "/root", "/run", "/sbin", "/sys", "/usr", "/var/lib", "/System",
20                 "/Library", "/private/etc")
21# Where a desktop (udisks, GNOME, KDE) mounts the drives a person plugs in. It sits inside /run, a system folder, but it is not system
22# state: a model drive there is normal. Whether it is the person's to write to is the write test below, not the name.
23_POSIX_MOUNTS = ("/run/media",)
24SAID_NOTHING_CHANGED = "Nothing was downloaded or changed."
25
26
27def _next() -> str:
28    return NEXT if os.name == "nt" else NEXT_POSIX
29
30
31def _system_roots() -> list[str]:
32    if os.name != "nt":
33        return list(_POSIX_SYSTEM)
34    roots = []
35    for var in ("SystemRoot", "windir", "ProgramFiles", "ProgramFiles(x86)", "ProgramW6432"):
36        value = os.environ.get(var)
37        if value:
38            roots.append(value)
39    drive = os.environ.get("SystemDrive", "C:")
40    roots += [drive + "\\Windows", drive + "\\Program Files", drive + "\\Program Files (x86)"]
41    return roots
42
43
44def _norm(path: str) -> str:
45    return os.path.normcase(os.path.normpath(path)).rstrip("\\/")
46
47
48def _inside(path: str, root: str) -> bool:
49    p, r = _norm(path), _norm(root)
50    return p == r or p.startswith(r + os.sep)
51
52
53def _is_system(full: str) -> bool:
54    for root in _system_roots():
55        if not _inside(full, root) or _inside(full, os.path.expanduser("~")):     # the running user's own home is theirs (root's /root included)
56            continue
57        if any(_inside(full, mount) and _norm(full) != _norm(mount) for mount in _POSIX_MOUNTS):
58            continue                                                               # /run/media/<user>/<drive>/...: a mounted drive
59        return True
60    return False
61
62
63def _can_write(folder: Path) -> bool:
64    probe = folder / f".strata-write-test-{uuid.uuid4().hex[:8]}"
65    try:
66        with open(probe, "wb") as fh:
67            fh.write(b"x")
68    except OSError:
69        return False
70    try:
71        probe.unlink()
72    except OSError:
73        pass
74    return True
75
76
77def problem(raw: str | os.PathLike | None) -> tuple[str, str] | None:
78    """(what is wrong, what to do) for a folder meant for model files, None when it is usable (or empty: the default folder is used)."""
79    text = os.fspath(raw).strip().strip('"') if raw else ""
80    if not text:
81        return None
82    if _WIN_BAD.search(text.replace("\\\\?\\", "", 1)) or (os.name == "nt" and ":" in text[2:] and not text.startswith("\\\\?\\")):
83        return (f"This does not look like one folder path: {text}.",
84                "Type one full path, like D:\\Strata-models, with nothing else in front of or behind it. Nothing was downloaded or changed."
85                if os.name == "nt" else "Type one full path, like ~/strata-models. Nothing was downloaded or changed.")
86    path = Path(text).expanduser()
87    if not path.is_absolute():
88        return (f"This is not a full path: {text}.",
89                "Type the whole path, starting with the drive, like D:\\Strata-models. Nothing was downloaded or changed."
90                if os.name == "nt" else "Type the whole path, starting with /, like /data/strata-models. Nothing was downloaded or changed.")
91    full = os.path.abspath(path)
92    if _is_system(full):
93        return (f"{full} is a system folder, and Strata should not keep model files there.", _next())
94    try:
95        if path.exists():
96            if not path.is_dir():
97                return (f"{full} is a file, not a folder.", _next())
98            if not _can_write(path):
99                return (f"Strata cannot write to {full}: Windows or the folder's owner does not allow it." if os.name == "nt"
100                        else f"Strata cannot write to {full}: you do not have permission.", _next())
101            return None
102        above = path
103        while not above.exists():
104            if above.parent == above:
105                return (f"The drive or folder for {full} is not there. Check the spelling, and that the drive is connected.", _next())
106            above = above.parent
107        if not above.is_dir():
108            return (f"{above} is a file, so {full} cannot be created inside it.", _next())
109        if not _can_write(above):
110            return (f"{full} does not exist yet and cannot be created: Strata cannot write to {above}.", _next())
111    except OSError as e:
112        return (f"Strata cannot look at {full} ({type(e).__name__}).", _next())
113    return None
114
115
116def words(problem_: tuple[str, str]) -> str:
117    return f"{problem_[0]} {problem_[1]}".strip()
118
119
120def without_nothing_changed(problem_: tuple[str, str]) -> str:
121    """The same words with the closing "Nothing was downloaded or changed." left off, for a caller that says it again in its own sentence."""
122    what, nxt = problem_
123    if nxt.endswith(SAID_NOTHING_CHANGED):
124        nxt = nxt[: -len(SAID_NOTHING_CHANGED)]
125    return f"{what} {nxt}".strip()