2022-03-11 11:13:43 +00:00
|
|
|
import datetime
|
2022-07-11 21:46:10 +00:00
|
|
|
import glob
|
|
|
|
import json
|
2022-03-11 11:13:43 +00:00
|
|
|
import os
|
|
|
|
import re
|
2022-07-11 21:46:10 +00:00
|
|
|
import shutil
|
2022-09-16 18:11:00 +00:00
|
|
|
from distutils.version import LooseVersion
|
2022-07-11 21:46:10 +00:00
|
|
|
from importlib.util import module_from_spec, spec_from_file_location
|
|
|
|
from itertools import chain
|
|
|
|
from pathlib import Path
|
2022-03-11 11:13:43 +00:00
|
|
|
from pprint import pprint
|
2022-07-11 21:46:10 +00:00
|
|
|
from types import ModuleType
|
|
|
|
from typing import List, Optional, Sequence
|
|
|
|
from urllib import request
|
|
|
|
from urllib.request import Request, urlopen
|
2022-03-11 11:13:43 +00:00
|
|
|
|
2022-10-20 14:17:27 +00:00
|
|
|
import jsonargparse
|
2022-07-15 17:41:23 +00:00
|
|
|
import pkg_resources
|
2022-09-16 18:11:00 +00:00
|
|
|
from packaging.version import parse as version_parse
|
2022-03-11 11:13:43 +00:00
|
|
|
|
2022-07-11 21:46:10 +00:00
|
|
|
REQUIREMENT_FILES = {
|
|
|
|
"pytorch": (
|
|
|
|
"requirements/pytorch/base.txt",
|
|
|
|
"requirements/pytorch/extra.txt",
|
|
|
|
"requirements/pytorch/strategies.txt",
|
|
|
|
"requirements/pytorch/examples.txt",
|
2022-10-20 08:10:44 +00:00
|
|
|
),
|
|
|
|
"app": (
|
|
|
|
"requirements/app/base.txt",
|
|
|
|
"requirements/app/ui.txt",
|
|
|
|
"requirements/app/cloud.txt",
|
|
|
|
),
|
2022-10-26 18:22:46 +00:00
|
|
|
"lite": (
|
|
|
|
"requirements/lite/base.txt",
|
|
|
|
"requirements/lite/strategies.txt",
|
|
|
|
),
|
2022-07-11 21:46:10 +00:00
|
|
|
}
|
2022-10-20 14:17:27 +00:00
|
|
|
REQUIREMENT_FILES_ALL = list(chain(*REQUIREMENT_FILES.values()))
|
2022-07-11 21:46:10 +00:00
|
|
|
PACKAGE_MAPPING = {"app": "lightning-app", "pytorch": "pytorch-lightning"}
|
2022-03-11 11:13:43 +00:00
|
|
|
|
|
|
|
|
2022-09-16 18:11:00 +00:00
|
|
|
def pypi_versions(package_name: str, drop_pre: bool = True) -> List[str]:
|
|
|
|
"""Return a list of released versions of a provided pypi name.
|
|
|
|
|
|
|
|
>>> _ = pypi_versions("lightning_app", drop_pre=False)
|
|
|
|
"""
|
2022-07-11 21:46:10 +00:00
|
|
|
# https://stackoverflow.com/a/27239645/4521646
|
|
|
|
url = f"https://pypi.org/pypi/{package_name}/json"
|
|
|
|
data = json.load(urlopen(Request(url)))
|
|
|
|
versions = list(data["releases"].keys())
|
|
|
|
# todo: drop this line after cleaning Pypi history from invalid versions
|
2022-09-16 18:11:00 +00:00
|
|
|
versions = list(filter(lambda v: v.count(".") == 2, versions))
|
|
|
|
if drop_pre:
|
|
|
|
versions = list(filter(lambda v: all(c not in v for c in ["rc", "dev"]), versions))
|
|
|
|
versions.sort(key=version_parse)
|
2022-07-11 21:46:10 +00:00
|
|
|
return versions
|
|
|
|
|
|
|
|
|
|
|
|
def _load_py_module(name: str, location: str) -> ModuleType:
|
|
|
|
spec = spec_from_file_location(name, location)
|
|
|
|
py = module_from_spec(spec)
|
|
|
|
spec.loader.exec_module(py)
|
|
|
|
return py
|
2022-03-11 11:13:43 +00:00
|
|
|
|
2022-07-11 21:46:10 +00:00
|
|
|
|
2022-10-20 14:17:27 +00:00
|
|
|
def _retrieve_files(directory: str, *ext: str) -> List[str]:
|
|
|
|
all_files = []
|
|
|
|
for root, _, files in os.walk(directory):
|
|
|
|
for fname in files:
|
|
|
|
if not ext or any(os.path.split(fname)[1].lower().endswith(e) for e in ext):
|
|
|
|
all_files.append(os.path.join(root, fname))
|
|
|
|
|
|
|
|
return all_files
|
|
|
|
|
|
|
|
|
2022-07-11 21:46:10 +00:00
|
|
|
class AssistantCLI:
|
|
|
|
_PATH_ROOT = str(Path(__file__).parent.parent)
|
|
|
|
_PATH_SRC = os.path.join(_PATH_ROOT, "src")
|
2022-03-11 11:13:43 +00:00
|
|
|
|
|
|
|
@staticmethod
|
|
|
|
def prepare_nightly_version(proj_root: str = _PATH_ROOT) -> None:
|
|
|
|
"""Replace semantic version by date."""
|
|
|
|
path_info = os.path.join(proj_root, "pytorch_lightning", "__about__.py")
|
|
|
|
# get today date
|
|
|
|
now = datetime.datetime.now()
|
|
|
|
now_date = now.strftime("%Y%m%d")
|
|
|
|
|
|
|
|
print(f"prepare init '{path_info}' - replace version by {now_date}")
|
2022-10-24 13:52:04 +00:00
|
|
|
with open(path_info, encoding="utf-8") as fp:
|
2022-03-11 11:13:43 +00:00
|
|
|
init = fp.read()
|
|
|
|
init = re.sub(r'__version__ = [\d\.\w\'"]+', f'__version__ = "{now_date}"', init)
|
2022-10-24 13:52:04 +00:00
|
|
|
with open(path_info, "w", encoding="utf-8") as fp:
|
2022-03-11 11:13:43 +00:00
|
|
|
fp.write(init)
|
|
|
|
|
|
|
|
@staticmethod
|
2022-07-11 21:46:10 +00:00
|
|
|
def requirements_prune_pkgs(packages: Sequence[str], req_files: Sequence[str] = REQUIREMENT_FILES_ALL) -> None:
|
2022-03-21 12:50:50 +00:00
|
|
|
"""Remove some packages from given requirement files."""
|
|
|
|
if isinstance(req_files, str):
|
|
|
|
req_files = [req_files]
|
|
|
|
for req in req_files:
|
|
|
|
AssistantCLI._prune_packages(req, packages)
|
|
|
|
|
|
|
|
@staticmethod
|
|
|
|
def _prune_packages(req_file: str, packages: Sequence[str]) -> None:
|
2022-03-11 11:13:43 +00:00
|
|
|
"""Remove some packages from given requirement files."""
|
2022-07-15 17:41:23 +00:00
|
|
|
path = Path(req_file)
|
|
|
|
assert path.exists()
|
|
|
|
text = path.read_text()
|
2022-10-20 14:17:27 +00:00
|
|
|
lines = text.splitlines()
|
|
|
|
final = []
|
|
|
|
for line in lines:
|
|
|
|
ln_ = line.strip()
|
|
|
|
if not ln_ or ln_.startswith("#"):
|
|
|
|
final.append(line)
|
|
|
|
continue
|
|
|
|
req = list(pkg_resources.parse_requirements(ln_))[0]
|
|
|
|
if req.name not in packages:
|
|
|
|
final.append(line)
|
2022-07-15 17:41:23 +00:00
|
|
|
pprint(final)
|
|
|
|
path.write_text("\n".join(final))
|
2022-03-11 11:13:43 +00:00
|
|
|
|
|
|
|
@staticmethod
|
|
|
|
def _replace_min(fname: str) -> None:
|
2022-10-24 13:52:04 +00:00
|
|
|
req = open(fname, encoding="utf-8").read().replace(">=", "==")
|
|
|
|
open(fname, "w", encoding="utf-8").write(req)
|
2022-03-11 11:13:43 +00:00
|
|
|
|
|
|
|
@staticmethod
|
2022-07-11 21:46:10 +00:00
|
|
|
def replace_oldest_ver(requirement_fnames: Sequence[str] = REQUIREMENT_FILES_ALL) -> None:
|
2022-03-11 11:13:43 +00:00
|
|
|
"""Replace the min package version by fixed one."""
|
|
|
|
for fname in requirement_fnames:
|
|
|
|
AssistantCLI._replace_min(fname)
|
|
|
|
|
2022-07-11 21:46:10 +00:00
|
|
|
@staticmethod
|
|
|
|
def _release_pkg(pkg: str, src_folder: str = _PATH_SRC) -> bool:
|
|
|
|
pypi_ver = pypi_versions(pkg)[-1]
|
|
|
|
_version = _load_py_module("version", os.path.join(src_folder, pkg.replace("-", "_"), "__version__.py"))
|
|
|
|
local_ver = _version.version
|
|
|
|
return "dev" not in local_ver and LooseVersion(local_ver) > LooseVersion(pypi_ver)
|
|
|
|
|
|
|
|
@staticmethod
|
|
|
|
def determine_releasing_pkgs(
|
|
|
|
src_folder: str = _PATH_SRC, packages: Sequence[str] = ("pytorch", "app"), inverse: bool = False
|
|
|
|
) -> Sequence[str]:
|
|
|
|
"""Determine version of package where the name is `lightning.<name>`."""
|
|
|
|
if isinstance(packages, str):
|
|
|
|
packages = [packages]
|
|
|
|
releasing = [pkg for pkg in packages if AssistantCLI._release_pkg(PACKAGE_MAPPING[pkg], src_folder=src_folder)]
|
|
|
|
if inverse:
|
|
|
|
releasing = list(filter(lambda pkg: pkg not in releasing, packages))
|
|
|
|
return json.dumps([{"pkg": pkg for pkg in releasing}])
|
|
|
|
|
|
|
|
@staticmethod
|
|
|
|
def download_package(package: str, folder: str = ".", version: Optional[str] = None) -> None:
|
|
|
|
"""Download specific or latest package from PyPI where the name is `lightning.<name>`."""
|
|
|
|
url = f"https://pypi.org/pypi/{PACKAGE_MAPPING[package]}/json"
|
|
|
|
data = json.load(urlopen(Request(url)))
|
|
|
|
if not version:
|
2022-09-16 18:11:00 +00:00
|
|
|
pypi_vers = pypi_versions(PACKAGE_MAPPING[package], drop_pre=False)
|
2022-09-16 13:26:04 +00:00
|
|
|
version = pypi_vers[-1]
|
2022-07-11 21:46:10 +00:00
|
|
|
releases = list(filter(lambda r: r["packagetype"] == "sdist", data["releases"][version]))
|
|
|
|
assert releases, f"Missing 'sdist' for this package/version aka {package}/{version}"
|
|
|
|
release = releases[0]
|
|
|
|
pkg_url = release["url"]
|
|
|
|
pkg_file = os.path.basename(pkg_url)
|
|
|
|
pkg_path = os.path.join(folder, pkg_file)
|
|
|
|
os.makedirs(folder, exist_ok=True)
|
2022-09-09 18:38:03 +00:00
|
|
|
print(f"downloading: {pkg_url}")
|
2022-07-11 21:46:10 +00:00
|
|
|
request.urlretrieve(pkg_url, pkg_path)
|
|
|
|
|
|
|
|
@staticmethod
|
|
|
|
def _find_pkgs(folder: str, pkg_pattern: str = "lightning") -> List[str]:
|
|
|
|
"""Find all python packages with spec.
|
|
|
|
|
|
|
|
pattern in given folder, in case `src` exists dive there.
|
|
|
|
"""
|
|
|
|
pkg_dirs = [d for d in glob.glob(os.path.join(folder, "*")) if os.path.isdir(d)]
|
|
|
|
if "src" in [os.path.basename(p) for p in pkg_dirs]:
|
|
|
|
return AssistantCLI._find_pkgs(os.path.join(folder, "src"), pkg_pattern)
|
|
|
|
pkg_dirs = list(filter(lambda p: pkg_pattern in os.path.basename(p), pkg_dirs))
|
|
|
|
return pkg_dirs
|
|
|
|
|
|
|
|
@staticmethod
|
|
|
|
def mirror_pkg2source(pypi_folder: str, src_folder: str) -> None:
|
|
|
|
"""From extracted sdist packages overwrite the python package with given pkg pattern."""
|
|
|
|
pypi_dirs = [d for d in glob.glob(os.path.join(pypi_folder, "*")) if os.path.isdir(d)]
|
|
|
|
for pkg_dir in pypi_dirs:
|
|
|
|
for py_dir in AssistantCLI._find_pkgs(pkg_dir):
|
|
|
|
dir_name = os.path.basename(py_dir)
|
|
|
|
py_dir2 = os.path.join(src_folder, dir_name)
|
|
|
|
shutil.rmtree(py_dir2, ignore_errors=True)
|
|
|
|
shutil.copytree(py_dir, py_dir2)
|
|
|
|
|
2022-10-20 14:17:27 +00:00
|
|
|
@staticmethod
|
|
|
|
def copy_replace_imports(
|
|
|
|
source_dir: str, source_import: str, target_import: str, target_dir: Optional[str] = None
|
|
|
|
) -> None:
|
|
|
|
"""Recursively replace imports in given folder."""
|
|
|
|
|
|
|
|
source_imports = source_import.strip().split(",")
|
|
|
|
target_imports = target_import.strip().split(",")
|
|
|
|
assert len(source_imports) == len(target_imports), (
|
|
|
|
"source and target imports must have the same length, "
|
|
|
|
f"source: {len(source_import)}, target: {len(target_import)}"
|
|
|
|
)
|
|
|
|
|
|
|
|
if target_dir is None:
|
|
|
|
target_dir = source_dir
|
|
|
|
|
|
|
|
ls = _retrieve_files(source_dir)
|
|
|
|
|
|
|
|
for fp in ls:
|
|
|
|
if fp.endswith(".py"):
|
|
|
|
with open(fp, encoding="utf-8") as fo:
|
|
|
|
py = fo.readlines()
|
|
|
|
|
|
|
|
for source_import, target_import in zip(source_imports, target_imports):
|
|
|
|
for i, ln in enumerate(py):
|
2022-10-24 13:52:04 +00:00
|
|
|
py[i] = re.sub(rf"([^_]|^){source_import}([^_\w]|$)", rf"\1{target_import}\2", ln)
|
2022-10-20 14:17:27 +00:00
|
|
|
|
|
|
|
if target_dir:
|
|
|
|
fp_new = fp.replace(source_dir, target_dir)
|
|
|
|
os.makedirs(os.path.dirname(fp_new), exist_ok=True)
|
|
|
|
else:
|
|
|
|
fp_new = fp
|
|
|
|
|
|
|
|
with open(fp_new, "w", encoding="utf-8") as fo:
|
|
|
|
fo.writelines(py)
|
|
|
|
elif not fp.endswith(".pyc"):
|
|
|
|
fp_new = fp.replace(source_dir, target_dir)
|
|
|
|
os.makedirs(os.path.dirname(fp_new), exist_ok=True)
|
|
|
|
if os.path.abspath(fp) != os.path.abspath(fp_new):
|
|
|
|
shutil.copy2(fp, fp_new)
|
|
|
|
|
2022-03-11 11:13:43 +00:00
|
|
|
|
|
|
|
if __name__ == "__main__":
|
2022-10-20 18:23:47 +00:00
|
|
|
jsonargparse.CLI(AssistantCLI, as_positional=False)
|