File size: 8,788 Bytes
338daf2 | 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 | 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("DOTS_TTS_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("DOTS_TTS_SCRATCH_ROOT", "/tmp/phorcys_dots_work")) / "phorcys_dots_runtime" / input_root.name
return input_root
def _contains_expected_payload(root: Path, target_name: str) -> bool:
if target_name == "pyLib":
return (root / "vendor" / "dots_tts_delay").exists() or (root / "dots_tts_delay").exists()
if target_name == ".venv":
return (root / "bin" / "python").exists() or (root / "Scripts" / "python.exe").exists()
if target_name == "native-src":
return 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_python_tag(path: Path) -> tuple[int, int] | None:
match = re.search(r"python(\d+)\.(\d+)", str(path))
if match is None:
return None
return int(match.group(1)), int(match.group(2))
def _add_site_packages_path(path: Path) -> None:
if not path.exists() or not path.is_dir():
return
text = str(path)
if text in sys.path:
return
tag = _site_packages_python_tag(path)
if tag is None or tag == (sys.version_info.major, sys.version_info.minor):
sys.path.insert(0, text)
else:
# Foreign-version site-packages can still contain pure-Python dots_tts modules.
# Appending keeps Kaggle's native packages first and avoids shadowing py3.12 wheels.
sys.path.append(text)
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 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-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")
try:
site_candidates.extend(venv_root.rglob("site-packages"))
except Exception:
pass
for candidate in site_candidates:
_add_site_packages_path(candidate)
for candidate in (py_lib, vendor):
if candidate.exists():
text = str(candidate)
if text not in sys.path:
sys.path.insert(0, text)
native_dirs = [
vendor / "dots_tts_delay" / "llama_cpp",
py_lib / "vendor" / "dots_tts_delay" / "llama_cpp",
input_root / "native",
input_root / "lib",
input_root / "libs",
work_root / "native",
work_root / "lib",
work_root / "libs",
]
existing_native_dirs = [path for path in native_dirs if path.exists()]
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("DOTS_TTS_NATIVE_DLL_DIRS", "")
os.environ["DOTS_TTS_NATIVE_DLL_DIRS"] = os.pathsep.join([str(path) for path in existing_native_dirs] + ([old_windows] if old_windows else []))
for native_dir in existing_native_dirs:
_ensure_linux_soname_aliases(native_dir)
_preload_linux_native_dependencies(native_dir)
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])) |