File size: 10,882 Bytes
5a8e268
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
from __future__ import annotations

import ctypes
import os
import re
import shutil
import sys
import zipfile
from pathlib import Path


def _runtime_work_root(input_root: Path) -> Path:
    explicit = os.environ.get("FISH_AUDIO_S2_RUNTIME_WORK_DIR")
    if explicit:
        return Path(explicit).expanduser().resolve()

    root_text = str(input_root)
    if root_text.startswith("/kaggle/input/"):
        return Path(os.environ.get("FISH_AUDIO_S2_SCRATCH_ROOT", "/tmp/phorcys_fish_audio_s2_work")) / "phorcys_fish_audio_s2_runtime" / input_root.name

    return input_root


def _contains_expected_payload(root: Path, target_name: str) -> bool:
    if target_name == "pyLib":
        return (root / "fish_audio_s2_runtime.py").exists() or (root / "fish_speech").exists()
    if target_name == ".venv":
        return (root / "bin" / "python").exists() or (root / "Scripts" / "python.exe").exists()
    if target_name in {"native", "native-src"}:
        return any(root.glob("**/s2")) or any(root.glob("**/*.so")) or any(root.glob("**/*.dylib")) or any(root.glob("**/*.pyd"))
    return any(root.iterdir()) if root.exists() and root.is_dir() else False


def _coerce_archive_root(target: Path, target_name: str) -> Path:
    if _contains_expected_payload(target, target_name):
        return target

    nested = target / target_name
    if nested.exists() and nested.is_dir():
        return nested

    visible_children = [child for child in target.iterdir() if child.name != ".phorcys-extracted.ok"] if target.exists() and target.is_dir() else []
    if len(visible_children) == 1 and visible_children[0].is_dir():
        nested = visible_children[0]
        if _contains_expected_payload(nested, target_name):
            return nested

    return target


def _site_packages_matches_runtime(path: Path) -> bool:
    match = re.search(r"python(\d+)\.(\d+)", str(path))
    if match is None:
        return True
    return (int(match.group(1)), int(match.group(2))) == (sys.version_info.major, sys.version_info.minor)


def _archive_fingerprint(archive: Path) -> str:
    stat = archive.stat()
    return f"{archive.name}:{stat.st_size}:{stat.st_mtime_ns}"


def _extract_archive(input_root: Path, work_root: Path, archive_names: tuple[str, ...], target_name: str, expanded_names: tuple[str, ...] = ()) -> Path:
    for expanded_name in (target_name, *expanded_names):
        mounted_target = input_root / expanded_name
        if mounted_target.exists():
            return _coerce_archive_root(mounted_target, target_name)

    target = work_root / target_name
    for archive_name in archive_names:
        archive = input_root / archive_name
        if not archive.exists():
            continue

        fingerprint = _archive_fingerprint(archive)
        marker = target / ".phorcys-extracted.ok"
        if target.exists() and marker.exists():
            try:
                if marker.read_text(encoding="utf-8") == fingerprint:
                    return _coerce_archive_root(target, target_name)
            except Exception:
                pass

        if target.exists():
            shutil.rmtree(target)
        target.mkdir(parents=True, exist_ok=True)
        with zipfile.ZipFile(archive, "r") as zip_file:
            zip_file.extractall(target)
        marker.write_text(fingerprint, encoding="utf-8")
        return _coerce_archive_root(target, target_name)

    if target.exists():
        return _coerce_archive_root(target, target_name)

    return mounted_target


def _linux_soname_alias_names(file_name: str) -> list[str]:
    match = re.match(r"^(lib.+?\.so)(?:\.(\d+)(?:\..*)?)?$", file_name)
    if match is None:
        return []
    base_name = match.group(1)
    major_version = match.group(2)
    aliases: list[str] = []
    if file_name != base_name:
        aliases.append(base_name)
    if major_version:
        major_alias = f"{base_name}.{major_version}"
        if file_name != major_alias:
            aliases.append(major_alias)
    elif file_name == base_name:
        aliases.append(f"{base_name}.0")
    return aliases


def _ensure_linux_soname_aliases(native_dir: Path) -> None:
    if not sys.platform.startswith("linux") or not native_dir.exists():
        return
    sources = [source for source in sorted(native_dir.glob("lib*.so*")) if source.is_file()]
    for source in sources:
        for alias_name in _linux_soname_alias_names(source.name):
            alias = native_dir / alias_name
            if alias.exists() or alias == source:
                continue
            try:
                try:
                    alias.symlink_to(source.name)
                except Exception:
                    shutil.copy2(source, alias)
            except Exception:
                continue


def _preload_linux_native_dependencies(native_dir: Path) -> None:
    if not sys.platform.startswith("linux") or not native_dir.exists():
        return
    _ensure_linux_soname_aliases(native_dir)
    candidate_patterns = (
        "libggml.so*",
        "libggml-base.so*",
        "libggml-cpu.so*",
        "libggml-cuda.so*",
        "libggml*.so*",
        "libllama.so*",
    )
    candidates: list[Path] = []
    for pattern in candidate_patterns:
        candidates.extend(sorted(native_dir.glob(pattern)))
    seen: set[str] = set()
    for candidate in candidates:
        if not candidate.is_file() or candidate.name in seen:
            continue
        seen.add(candidate.name)
        try:
            ctypes.CDLL(str(candidate), mode=getattr(ctypes, "RTLD_GLOBAL", 0))
        except OSError:
            continue


def _ensure_linux_executable_bits(native_dir: Path) -> None:
    if not sys.platform.startswith("linux") or not native_dir.exists():
        return
    for executable in native_dir.glob("**/s2"):
        if not executable.is_file():
            continue
        try:
            executable.chmod(executable.stat().st_mode | 0o755)
        except Exception:
            continue


def _ensure_fish_speech_project_root_markers(paths: list[Path]) -> list[str]:
    markers: list[str] = []
    candidates: list[Path] = []
    for root in paths:
        if not root.exists():
            continue
        package_dir = root / "fish_speech"
        if package_dir.exists() and package_dir.is_dir():
            candidates.append(package_dir)
        if root.name == "fish_speech" and root.is_dir():
            candidates.append(root)

    seen: set[str] = set()
    for package_dir in candidates:
        for marker_root in (package_dir.parent, package_dir):
            marker = marker_root / ".project-root"
            key = str(marker)
            if key in seen:
                continue
            seen.add(key)
            try:
                if not marker.exists():
                    marker.write_text("phorcys generated marker for pip-installed fish-speech runtime\n", encoding="utf-8")
                markers.append(key)
            except Exception:
                continue
    return markers


def activate(runtime_root: str | os.PathLike[str] | None = None) -> Path:
    input_root = Path(runtime_root).resolve() if runtime_root else Path(__file__).resolve().parent
    work_root = _runtime_work_root(input_root)
    work_root.mkdir(parents=True, exist_ok=True)

    py_lib = _extract_archive(input_root, work_root, ("pyLib.phzip", "pyLib.zip"), "pyLib")
    _extract_archive(input_root, work_root, ("requirements.phzip", "requirements.zip"), "requirements")
    _extract_archive(input_root, work_root, ("native.phzip", "native.zip"), "native")
    _extract_archive(input_root, work_root, ("native-src.phzip", "native-src.zip"), "native-src")
    _extract_archive(input_root, work_root, ("stressLexicons.phzip", "stressLexicons.zip"), "stressLexicons")
    _extract_archive(input_root, work_root, ("wheelhouse.phzip", "wheelhouse.zip"), "wheelhouse")
    _extract_archive(input_root, work_root, ("models.phzip", "models.zip"), "models")
    venv_root = _extract_archive(input_root, work_root, ("dot-venv.phzip", "dot-venv.zip", ".venv.zip", "venv.zip"), ".venv", ("dot-venv", "venv"))

    vendor = py_lib / "vendor"
    site_candidates = []
    site_candidates.extend((venv_root / "lib").glob("python*/site-packages"))
    site_candidates.append(venv_root / "Lib" / "site-packages")
    for candidate in site_candidates:
        if candidate.exists() and _site_packages_matches_runtime(candidate):
            text = str(candidate)
            if text not in sys.path:
                sys.path.insert(0, text)
    source_roots = [vendor / "sglang-omni", vendor / "sglang_omni"]
    for candidate in (py_lib, vendor, *source_roots):
        if candidate.exists():
            text = str(candidate)
            if text not in sys.path:
                sys.path.insert(0, text)

    native_dirs = [
        vendor / "fish_speech",
        py_lib / "vendor" / "fish_speech",
        input_root / "native",
        input_root / "lib",
        input_root / "libs",
        work_root / "native",
        work_root / "lib",
        work_root / "libs",
    ]
    expanded_native_dirs: list[Path] = []
    for native_root in (input_root / "native", work_root / "native"):
        if native_root.exists():
            expanded_native_dirs.append(native_root)
            expanded_native_dirs.extend([child for child in native_root.glob("**") if child.is_dir() and (any(child.glob("s2")) or any(child.glob("*.so*")))])
    existing_native_dirs = []
    seen_native_dirs: set[str] = set()
    for path in [*native_dirs, *expanded_native_dirs]:
        if not path.exists():
            continue
        key = str(path.resolve())
        if key in seen_native_dirs:
            continue
        seen_native_dirs.add(key)
        existing_native_dirs.append(path)
    if existing_native_dirs:
        old = os.environ.get("LD_LIBRARY_PATH", "")
        os.environ["LD_LIBRARY_PATH"] = os.pathsep.join([str(path) for path in existing_native_dirs] + ([old] if old else []))
        old_windows = os.environ.get("FISH_AUDIO_S2_NATIVE_DLL_DIRS", "")
        os.environ["FISH_AUDIO_S2_NATIVE_DLL_DIRS"] = os.pathsep.join([str(path) for path in existing_native_dirs] + ([old_windows] if old_windows else []))
        os.environ["FISH_AUDIO_S2_RUNTIME_NATIVE_DIRS"] = os.pathsep.join(str(path) for path in existing_native_dirs)
        for native_dir in existing_native_dirs:
            _ensure_linux_executable_bits(native_dir)
            _ensure_linux_soname_aliases(native_dir)
            _preload_linux_native_dependencies(native_dir)

    os.environ["FISH_AUDIO_S2_RUNTIME_ACTIVATED_ROOT"] = str(work_root)
    _ensure_fish_speech_project_root_markers([py_lib, vendor, *site_candidates])
    return work_root


if __name__ == "__main__":
    activated = activate(sys.argv[1] if len(sys.argv) > 1 else None)
    print(f"activated={activated}")
    print("sys.path[0:8]=" + repr(sys.path[:8]))