dots-tts-runtime-cuda / runtime_bootstrap.py
stokiz's picture
Synchronize canonical AI-radio asset payload.
338daf2 verified
Raw History Blame Contribute Delete
8.79 kB
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]))