Conghao97's picture tcftrees's picture
ProgramGen release
d086025
Raw History Blame Contribute Delete
38.1 kB
diff --git a/examples/starpack_basic_example/gradio_example.py b/examples/starpack_basic_example/gradio_example.py new file mode 100644 index 0000000000000000000000000000000000000000..19931dda03413bdf3b0d804c28f6f868b14fe1f8 --- /dev/null +++ b/examples/starpack_basic_example/gradio_example.py @@ -0,0 +1,56 @@ +import gradio as gr +import pandas as pd +import requests +import io + + +def predict(age, sex, chest_pain, resting_blood_pressure, cholesterol, fbs, restecg, thalach, exang, oldpeak, slope, ca, + thal): + df = pd.DataFrame([{"age": age, + "sex": int(sex[0]), + "cp": int(chest_pain[0]), + "trestbps": resting_blood_pressure, + "chol": cholesterol, + "fbs": int(fbs), + "restecg": int(restecg[0]), + "thalach": thalach, + "exang": int(exang), + "oldpeak": oldpeak, + "slope": int(slope[0]), + "ca": ca, + "thal": int(thal[0]), + }]) + + bytes_input = df.to_csv(index=False).encode() + request_file = {"file": (f"test.csv", bytes_input, "application/vnd.ms-excel")} + + output_response = requests.post("http://localhost/models/predict/starpack_deployment", files=request_file) + print(output_response.text) + + prediction = bool(pd.read_csv(io.StringIO(output_response.text))["tgt_heart_disease"][0]) + + return str(prediction) + + +gradio_app = gr.Interface(fn=predict, + inputs=[ + "number", + gr.Radio(["0: Male", "1: Female"]), + gr.Radio(["0: Typical Angina", "1: Atypical Angina", "2: Non-anginal Pain", + "3: Asymptomatic"]), + "number", + "number", + gr.Checkbox(), + gr.Radio(["0: Normal", "1: ST-T wave abnormality", "2: Left ventricular hypertrophy"]), + "number", + gr.Checkbox(), + "number", + gr.Radio(["0: Positive", "1: Flat", "2: Negative"]), + gr.Slider(minimum=0, maximum=4), + gr.Radio(["1: Normal", "2: Fixed Defect", "3: Reversable Defect"]) + ], + outputs=["text"], + ) + +if __name__ == "__main__": + gradio_app.launch() diff --git a/examples/starpack_basic_example/predict.py b/examples/starpack_basic_example/predict.py new file mode 100644 index 0000000000000000000000000000000000000000..7f5e7bdcf82c19ecc2707d0f4328b20bd323c07f --- /dev/null +++ b/examples/starpack_basic_example/predict.py @@ -0,0 +1,33 @@ +import pandas as pd +import pickle +import os +from typing import Any +from pathlib import Path + + +def predict(model: Any, patient_metrics: pd.DataFrame) -> pd.DataFrame: + + # Apply predictions to scoring file + # Optional, but we will give back the input, with the predictions appended to the 'tgt_heart_disease' column. + dfOut = patient_metrics + dfOut["tgt_heart_disease"] = model.predict(patient_metrics) + + # Read out the prediction + return dfOut + + +# For testing, you can make sure this function properly runs +if __name__ == "__main__": + input_path = Path(input("Please give the path to the input file: ")) + model_paths = [Path(input("Please give the path to your model file: "))] + + input_type = input_path.suffix + + if input_type == "json": + input = pd.read_json(input_path) + elif input_type == ".csv": + input = pd.read_csv(input_path) + + output = predict(model_paths, input) + + print(output) diff --git a/examples/starpack_basic_example/streamlit_example.py b/examples/starpack_basic_example/streamlit_example.py new file mode 100644 index 0000000000000000000000000000000000000000..4b74b74f44e3398c9b451991e71b9c3e64c00cd3 --- /dev/null +++ b/examples/starpack_basic_example/streamlit_example.py @@ -0,0 +1,20 @@ +import streamlit as st +import pandas as pd +import numpy as np +from pathlib import Path + + +st.text("test_file") + + +@st.cache +def load_data(): + working_dir = Path(__file__).parent.resolve() + df = pd.read_csv(working_dir / "heart_disease_score.csv") + + return df + + +heart_disease_df = load_data() + +st.table(heart_disease_df) diff --git a/src/starpack/__init__.py b/src/starpack/__init__.py new file mode 100644 index 0000000000000000000000000000000000000000..3fdf784a790e70109347f9ce184e91e6ba735f85 --- /dev/null +++ b/src/starpack/__init__.py @@ -0,0 +1,10 @@ +__version__ = "0.2.1" + +from starpack.core import ( + upload, + initialize_directory, + terminate, + package_directory, + deploy_directory, + initialize_engine, +) diff --git a/src/starpack/__main__.py b/src/starpack/__main__.py new file mode 100644 index 0000000000000000000000000000000000000000..9e88e953e935213b9a61bec950aa5f88e626a7e3 --- /dev/null +++ b/src/starpack/__main__.py @@ -0,0 +1,147 @@ +from pathlib import Path +from rich import print +from rich.pretty import pprint + +import typer + +from starpack import ( + __version__, + upload, + initialize_directory, + initialize_engine, + terminate, + package_directory, + deploy_directory, +) +from starpack._config import settings + +app = typer.Typer(pretty_exceptions_show_locals=False) + +engine_app = typer.Typer(pretty_exceptions_show_locals=False) + +app.add_typer( + engine_app, + name="engine", + help="Commands to control and manipulate the Starpack Engine itself.", +) + +# Config app for changing config + +config_app = typer.Typer(pretty_exceptions_show_locals=False) + +app.add_typer( + config_app, + name="config", + help="View the current Starpack Configuration. You can edit this configuration manually at ~/.starpack/", + hidden=True, +) + + +@config_app.command(name="view") +def cmd_view_config(): + """ + View a pretty-printed version of the config, found + """ + pprint(settings, expand_all=True) + + +@engine_app.command(name="start") +def cmd_start_engine( + force: bool = typer.Option( + False, + "--force", + "-F", + help="Force a removal of all older starpack-engine containers", + ) +): + """ + Starts the Starpack Engine. If given a custom Docker image name, will attempt to run it instead. + If `force` is passed, will remove any existing containers and ensure that the latest version is pulled. + """ + + initialize_engine(force=force) + + +@engine_app.command(name="terminate") +def cmd_engine_terminate( + all_resources: bool = typer.Option( + False, "--all", "-A", help="Remove associated volumes and saved data as well." + ) +) -> None: + """ + Terminates and removes the Starpack Engine container and optionally removes all associated data. + """ + + terminate(all_resources=all_resources) + + +def version_callback(give_version: bool) -> None: + """ + Returns the current version of Starpack + """ + if give_version: + print(f"Starpack CLI version: {__version__}") + raise typer.Exit() + + +@app.callback() +def main( + version: bool = typer.Option( + None, + "--version", + "-v", + callback=version_callback, + is_eager=True, + help="Returns current version of Starpack CLI", + ) +) -> None: + return + + +@app.command(name="upload") +def cmd_upload(directory: Path = typer.Argument(Path("."))) -> None: + """ + Command to upload the contents of a local directory to the Starpack Engine + + `directory` should be a path that exists on your local host machine. + """ + upload(directory=directory) + + +@app.command(name="init") +def cmd_init( + directory: Path = typer.Argument(Path(".")), + overwrite: bool = typer.Option( + False, "--overwrite", "-o", help="Overwrite files without further user input" + ), +) -> None: + """ + Initializes the given directory with starter code, an example + requirements.txt, and an example starpack.yaml + """ + + initialize_directory( + directory=directory, + overwrite=overwrite, + ) + + +@app.command(name="package") +def cmd_package(package_path: Path = typer.Argument(Path("."))) -> None: + """ + Given a directory, uploads the contents and passes through the contained `starpack.yaml`; given a file, passes as a + payload as the `yaml` file. + """ + package_directory(package_path) + + +@app.command(name="deploy") +def cmd_deploy(deploy_path: Path = typer.Argument(Path("."))) -> None: + """ + Given a starpack.yaml, deploys a Starpack Package into the environment designated within. + """ + deploy_directory(deploy_path) + + +if __name__ == "__main__": + app() diff --git a/src/starpack/_config.py b/src/starpack/_config.py new file mode 100644 index 0000000000000000000000000000000000000000..746ccdc2f88c620f6c61d0331a976e2e6233d5a2 --- /dev/null +++ b/src/starpack/_config.py @@ -0,0 +1,38 @@ +from pathlib import Path +import typer +from pydantic import BaseSettings, root_validator +from typing import Optional + +# Configuration for the app name +APP_NAME = "starpack" +APP_DIR = Path(typer.get_app_dir(APP_NAME)) +ENV_FILE = APP_DIR / "starpack.config" +BASE_DIR = Path(__file__).resolve().parent + +# Generate the configuration folder and file if it doesn't exist +APP_DIR.mkdir(exist_ok=True, parents=True) +ENV_FILE.touch() + + +class Settings(BaseSettings): + engine_port: int = 1976 + engine_image: str = "starpack/starpack-engine:latest" + pull_image: bool = True + app_name: str = APP_NAME + app_dir: Path = APP_DIR + plugins_dir: Optional[Path] = None + + @root_validator + def ensure_plugins_dir(cls, values): + if not values["plugins_dir"]: + values["plugins_dir"] = values["app_dir"] / "plugins" + values["plugins_dir"].mkdir(exist_ok=True, parents=True) + + return values + + class Config: + env_file = str(ENV_FILE) + env_file_encoding = "utf-8" + + +settings = Settings() diff --git a/src/starpack/client.py b/src/starpack/client.py new file mode 100644 index 0000000000000000000000000000000000000000..547648df119975d4b236f8a7f7fc5f2e87ea6dfe --- /dev/null +++ b/src/starpack/client.py @@ -0,0 +1,252 @@ +from pathlib import Path +from tempfile import TemporaryDirectory +from time import sleep, time +from typing import Any, Dict, List, Optional +import requests +import docker +from docker.models.containers import Container +import shutil + +from rich import print +from rich.progress import track + +from starpack._config import settings, APP_DIR +from starpack.errors import * + + +class StarpackClient: + volumes: Dict[str, Dict[str, str]] = { + "artifacts": { + "host": "starpack-model-artifacts", + "container": "/app/engine/external/artifacts", + }, + "plugins": { + "host": f"{APP_DIR}/plugins", + "container": "/app/engine/external/plugins", + }, + } + app_label: str = "starpack-engine" + + def __init__( + self, + host: str = "http://localhost", + port: Optional[int] = 1976, + start: bool = False, + docker: bool = False, + force: bool = False, + ) -> None: + + # Generate the URL based on the provided host and port + self.host = host + self.port = port + + if docker: + self._init_docker_client() + + if start: + self.start_server(force=force) + + def check_health(self) -> bool: + """ + Tries to run a healthcheck to see if a server is up. + """ + + try: + health_response = requests.get(f"{self.url}/healthcheck") + except requests.ConnectionError: + return False + + if health_response.status_code != 200: + return False + + print(f"Successfully connected to server at {self.url}") + return True + + def deploy(self, payload: Dict[str, Any]) -> None: + """ + Deploys a packaged model image or if the image does not exist, attempts to run the packaging in the YAML file + """ + deploy_url = f"{self.url}/deploy" + + output = requests.post(deploy_url, json=payload) + + if output.status_code / 100 == 2: + endpoints = output.json().get("endpoints") + deployment_name = payload["deployment"]["metadata"]["name"] + if not endpoints: + print( + f"Deployed {deployment_name} at an unknown location. " + f"Please check Docker to find your running container." + ) + else: + for wrapper, url in endpoints.items(): + print( + f"Deployed {deployment_name} using wrapper {wrapper} at {url}." + ) + + else: + print(output.status_code) + print(output.text) + + def package(self, payload: Dict[str, Any]) -> None: + """ + Packages model artifacts, given a starpack YAML/JSON payload + """ + package_url = f"{self.url}/package" + + output = requests.post(package_url, json=payload) + + if output.status_code / 100 == 2: + print(f"Successfully packaged {payload['package']['metadata']['name']}") + else: + print(output.status_code) + print(output.text) + + def remove_engines(self) -> None: + """ + Finds all instances of starpack engine applications and removes them. + """ + engines = self._find_engines() + if engines: + for engine in engines: + engine.remove(force=True) + + def start_server(self, force: bool = False): + """ + Starts the Starpack Engine locally after removing all other instances. + """ + if force: + self.remove_engines() + else: + engines = self._find_engines() + if len(engines) == 1: + # Grab the singular engine if we're not forcing a new start + self.engine = engines[0] + if self.engine.status != "running": + self.engine.start() + self.port = self.engine.attrs["HostConfig"]["PortBindings"]["1976/tcp"][ + 0 + ]["HostPort"] + self._engine_startup_check() + print(f"Connected to existing engine running at {self.url}") + return + elif engines: + # Case with many engines: Just clean it all out and start again + self.remove_engines() + + # Ensure that we have the Docker Volume to hold saved artifacts and + # the latest version of our Starpack Engine image from Docker Hub + self.docker_client.volumes.create( + name=self.volumes["artifacts"]["host"], labels={"app": self.app_label} + ) + if settings.pull_image: + self.docker_client.images.pull(settings.engine_image) + + print(f"Starting Starpack Engine at {self.url}") + self.engine = self.docker_client.containers.run( + image=settings.engine_image, + name=f"starpack-engine-{round(time())}", + tty=True, + ports={1976: self.port}, + volumes={ + # Docker-in-Docker mounting + "/var/run/docker.sock": { + "bind": "/var/run/docker.sock", + "mode": "rw", + }, + self.volumes["artifacts"]["host"]: { + "bind": self.volumes["artifacts"]["container"], + "mode": "rw", + }, + self.volumes["plugins"]["host"]: { + "bind": self.volumes["plugins"]["container"], + "mode": "rw", + }, + }, + stdin_open=True, + detach=True, + labels={"app": self.app_label}, + ) + + self._engine_startup_check() + + def terminate(self, all: bool = False) -> None: + """ + Terminates a local Docker instance of Starpack Engine and optionally deletes the associated volumes. + """ + self._init_docker_client() + self.remove_engines() + print("Removed all instances of the Starpack Engine") + + if all: + volume = self.docker_client.volumes.get(self.volume_name) + + volume.remove(force=True) + + print("Removed associated Starpack Engine data") + + def upload_artifacts(self, directory: Path) -> None: + """ + Given a directory, uploads the contents to our artifacts docker volume. + """ + + directory = directory.resolve() + + # Create a temporary directory to hold our packed up files and create a tarball + with TemporaryDirectory() as temp_dir: + dir_archive = shutil.make_archive( + f"../{directory.name}", + "tar", + str(directory.parent), + str(directory.name), + ) + + with open(dir_archive, "rb") as tar_data: + self.engine.put_archive( + self.volumes["artifacts"]["container"], tar_data + ) + + print( + f"Successfully saved {directory} to {directory.name} on the Docker Volume {self.volumes['artifacts']['host']}" + ) + + def _find_engines(self) -> List[Container]: + engines = [ + container + for container in self.docker_client.containers.list(all=True) + if ("app", self.app_label) in container.labels.items() + ] + return engines + + def _init_docker_client(self) -> None: + """ + Initializes a Docker Client + """ + try: + self.docker_client = docker.from_env() + except docker.errors.DockerException: + raise DockerNotFoundError() + + def _engine_startup_check(self) -> None: + # Check the engine status a few times + max_attempts = 5 + success = False + for _ in track( + range(max_attempts), description="Waiting for the engine to come up..." + ): + if not success: + success = self.check_health() + sleep(1) + + if not success: + raise EngineInitializationError() + + @property + def url(self): + """ + Allows for edge cases if we just have the engine registered with a FQDN + """ + if self.port is not None: + return f"{self.host}:{self.port}" + else: + return self.host diff --git a/src/starpack/core.py b/src/starpack/core.py new file mode 100644 index 0000000000000000000000000000000000000000..58eac32f9279964cb353dfb9ffa7faf704e0a45c --- /dev/null +++ b/src/starpack/core.py @@ -0,0 +1,117 @@ +from pathlib import Path +from typing import Optional + +from starpack import initialize, __version__, utils +from starpack.client import StarpackClient +from starpack.errors import * + + +def upload(directory: Path, client: Optional[StarpackClient] = None) -> None: + """ + Uploads the contents of a local directory to the Starpack Engine + """ + + if not client: + client = StarpackClient(start=True, docker=True) + + client.upload_artifacts(directory=directory) + + +def initialize_directory(directory: Path, overwrite: bool = False) -> None: + """ + Starts the starpack-engine container locally and furthermore initializes + the given directory if given with starter code, an example + requirements.txt, and an example starpack.yaml + """ + if directory: + directory = directory.resolve() + directory.mkdir(parents=True, exist_ok=True) + initialize.initialize_project_files(directory, overwrite=overwrite) + + +def initialize_engine(force: bool = True) -> StarpackClient: + """ + Starts the Starpack Engine. If given an image name, will initialize that image. If given + """ + client = StarpackClient(start=True, docker=True, force=force) + + return client + + +def terminate( + all_resources: bool = False, client: Optional[StarpackClient] = None +) -> None: + """ + Terminates and removes the Starpack Engine container and optionally removes all associated data + """ + + if not client: + client = StarpackClient() + + client.terminate(all_resources) + + +def package(yaml_path: Path, client: Optional[StarpackClient] = None) -> None: + """ + Takes a YAML file or directory to start the packaging process into a Docker image + """ + if not yaml_path.exists(): + raise PathExistsError(yaml_path) + + if not client: + client = StarpackClient(start=True, docker=True) + + input_dict = utils.load_yaml(yaml_path) + + client.package(input_dict) + + +def package_directory(directory: Path, client: Optional[StarpackClient] = None) -> None: + """ + Given a directory, uploads the contents, finds the "starpack.yaml", and converts into into a JSON payload for the Starpack Engine to run packaging + """ + if not directory.is_dir(): + return package(directory) + + yaml_file = directory / "starpack.yaml" + + if not yaml_file.exists(): + raise PathExistsError(yaml_file) + + if not client: + client = StarpackClient(start=True, docker=True) + + upload(directory, client=client) + package(yaml_file, client=client) + + +def deploy(yaml_path: Path, client: Optional[StarpackClient] = None) -> None: + """ + Takes a YAML file or directory to start the deployment process. If no package exists, also packages the given Starpack artifacts if present in the YAML file. + """ + + if not client: + client = StarpackClient(start=True, docker=True) + + input_dict = utils.load_yaml(yaml_path) + + client.deploy(input_dict) + + +def deploy_directory(directory: Path, client: Optional[StarpackClient] = None) -> None: + """ + Given a directory, uploads the contents, packages, and runs deployment. + """ + if not directory.is_dir(): + return deploy(directory) + + yaml_file = directory / "starpack.yaml" + + if not yaml_file.exists(): + raise PathExistsError(yaml_file) + + if not client: + client = StarpackClient(start=True, docker=True) + + package_directory(directory, client=client) + deploy(yaml_file, client=client) diff --git a/src/starpack/errors.py b/src/starpack/errors.py new file mode 100644 index 0000000000000000000000000000000000000000..033a2d9549e8954c95adeb5c6a3d8de73d3d69c8 --- /dev/null +++ b/src/starpack/errors.py @@ -0,0 +1,32 @@ +from pathlib import Path +from typer import Exit + +from rich import print + + +class DockerNotFoundError(Exit): + def __init__(self) -> None: + print("Unable to find Docker running on your system.") + super().__init__(1) + + +class LocalOnlyError(Exit): + def __init__(self) -> None: + print("Currently Unable to tear down non-local Engines.") + super().__init__(1) + + +class EngineInitializationError(Exit): + def __init__(self) -> None: + print("The Starpack Engine was unable to start up. Please try again.") + super().__init__(1) + + +class PathExistsError(Exit): + def __init__(self, path: Path) -> None: + print(f"The path given ({path}) does not exist. Please check and try again.") + super().__init__(1) + + +class UserDeclined(Exception): + ... diff --git a/src/starpack/initialize.py b/src/starpack/initialize.py new file mode 100644 index 0000000000000000000000000000000000000000..cbbfcd71a85915fa411f50958abcece1f859eeef --- /dev/null +++ b/src/starpack/initialize.py @@ -0,0 +1,80 @@ +from pathlib import Path +from string import Template +import shutil +from typing import Dict +from rich import print +from starpack._config import BASE_DIR +from starpack.errors import UserDeclined +import typer + + +def initialize_project_files(directory: Path, overwrite: bool = False): + """ + Given a directory to initialize, copies over some starter files. + """ + template_dir = BASE_DIR / "templates" + + # Copy the simple files + copy_file(template_dir / "requirements.txt", directory, overwrite=overwrite) + copy_file(template_dir / "predict.py", directory, overwrite=overwrite) + + # Add the full directory path as a parameter for ease of use + starpack_yaml_mapping = {"directory": directory.name} + render_file( + template_dir / "starpack.yaml", + directory, + starpack_yaml_mapping, + overwrite=overwrite, + ) + + print(f"Completed initializing project directory: {directory}") + + +def setup_file_output( + template_file: Path, output_dir: Path, overwrite: bool = False +) -> Path: + """ + Checks for the existence of the output file and either returns the path or raises an error + """ + filename = template_file.name + output_path = output_dir / filename + + if output_path.exists() and not overwrite: + confirmation = typer.confirm( + f"{filename} already exists in {output_dir}. Would you like to overwrite it?" + ) + if not confirmation: + raise UserDeclined() + + print(f"Creating {output_path}") + return output_path + + +def render_file( + template_file: Path, + output_dir: Path, + render_mapping: Dict[str, str], + overwrite: bool = False, +) -> None: + """ + Given an input template file and where to render it to, renders according to a render mapping. + """ + try: + output_path = setup_file_output(template_file, output_dir, overwrite) + except UserDeclined: + return + + output = Template(template_file.read_text()).substitute(render_mapping) + output_path.write_text(output) + + +def copy_file(template_file: Path, output_dir: Path, overwrite: bool = False) -> None: + """ + Copies a template file to a target directory. + """ + try: + output_path = setup_file_output(template_file, output_dir, overwrite) + except UserDeclined: + return + + shutil.copy(template_file, output_path) diff --git a/src/starpack/templates/predict.py b/src/starpack/templates/predict.py new file mode 100644 index 0000000000000000000000000000000000000000..db8fe93ff2a84ede8bb39699145838f241cec8c0 --- /dev/null +++ b/src/starpack/templates/predict.py @@ -0,0 +1,37 @@ +import pandas as pd +import pickle +import os +from typing import List +from pathlib import Path + + +def predict(model, patient_metrics: pd.DataFrame) -> pd.DataFrame: + + # Apply predictions to scoring file + # Optional, but we will give back the input, with the predictions appended to the 'tgt_heart_disease' column. + dfOut = patient_metrics + dfOut["tgt_heart_disease"] = model.predict(patient_metrics) + + # Read out the prediction + return dfOut + + +# For testing, you can make sure this script properly runs (`python predict.py`) +if __name__ == "__main__": + input_path = Path(input("Please give the path to the input file: ")) + model_path = Path(input("Please give the path to your model file: ")) + + input_type = input_path.suffix + + if input_type == "json": + input = pd.read_json(input_path) + elif input_type == ".csv": + input = pd.read_csv(input_path) + + # Load Pretrained Model + with open(model_path, "rb") as pretrained_model_file: + pretrained_model = pickle.load(pretrained_model_file) + + output = predict(pretrained_model, input) + + print(output) diff --git a/src/starpack/testing/__init__.py b/src/starpack/testing/__init__.py new file mode 100644 index 0000000000000000000000000000000000000000..e69de29bb2d1d6434b8b29ae775ad8c2e48c5391 diff --git a/src/starpack/utils.py b/src/starpack/utils.py new file mode 100644 index 0000000000000000000000000000000000000000..120fe159b72910bca3f9269a002a720e4062e75d --- /dev/null +++ b/src/starpack/utils.py @@ -0,0 +1,13 @@ +from typing import Any, Dict +from yaml import load, Loader +from pathlib import Path + + +def load_yaml(yaml_path: Path) -> Dict[str, Any]: + """ + Given a path, load in the YAML as a Python dict + """ + with open(yaml_path) as yaml_file: + output_dict = load(yaml_file, Loader) + + return output_dict diff --git a/src/tests/README.md b/src/tests/README.md new file mode 100644 index 0000000000000000000000000000000000000000..b6489a2cd1429aa164d8f28eb4e53482306172f0 --- /dev/null +++ b/src/tests/README.md @@ -0,0 +1,3 @@ +# Testing and Notes for Developers + +TBD diff --git a/src/tests/__init__.py b/src/tests/__init__.py new file mode 100644 index 0000000000000000000000000000000000000000..e69de29bb2d1d6434b8b29ae775ad8c2e48c5391 diff --git a/src/tests/test_commands.py b/src/tests/test_commands.py new file mode 100644 index 0000000000000000000000000000000000000000..4a57b13ae98bf3cb9eb66aa3efcdd218108a174b --- /dev/null +++ b/src/tests/test_commands.py @@ -0,0 +1,182 @@ +from pathlib import Path +import pytest +from typer.testing import CliRunner +import docker + +from starpack.__main__ import app +from starpack.client import StarpackClient + + +class FakeContainer: + labels = { + "desktop.docker.io/wsl-distro": "Ubuntu-20.04", + "app": "starpack-engine", + } + attrs = { + "HostConfig": { + "PortBindings": {"1976/tcp": [{"HostIp": "", "HostPort": "1976"}]}, + } + } + + status = "running" + + def remove(*args, **kwargs): + ... + + def put_archive(*args, **kwargs): + ... + + +class FakeContainerModule: + def list(*args, **kwargs): + return [FakeContainer] + + def run(*args, **kwargs): + pass + + +class FakeImageModule: + def pull(*args): + pass + + +class FakeVolume: + def remove(*args, **kwargs): + ... + + +class FakeVolumesModule: + def get(*args, **kwargs): + return FakeVolume() + + def create(*args, **kwargs): + ... + + +class FakeDockerClient: + def __init__(self, *args, **kwargs) -> None: + self.containers = FakeContainerModule + self.images = FakeImageModule + self.volumes = FakeVolumesModule + + +@pytest.fixture(autouse=True) +def mock_docker(monkeypatch, requests_mock): + monkeypatch.setattr(docker, "from_env", FakeDockerClient) + requests_mock.get( + "http://localhost:1976/healthcheck", text='{"healthy": "true"}', status_code=200 + ) + + +@pytest.fixture +def test_runner(monkeypatch): + return CliRunner() + + +def test_command_init(tmp_path: Path, test_runner: CliRunner): + """Tests `starpack init $PATH`""" + result = test_runner.invoke(app, ["init", str(tmp_path)]) + assert result.exit_code == 0 + assert "Completed initializing project directory:" in result.stdout + + +def test_command_init_overwrite(tmp_path: Path, test_runner: CliRunner): + """Tests `starpack init $PATH` with duplicate files""" + _ = test_runner.invoke(app, ["init", str(tmp_path)]) + result = test_runner.invoke(app, ["init", str(tmp_path)], "y\nn\ny\n") + assert result.exit_code == 0 + assert "Completed initializing project directory:" in result.stdout + assert "predict.py already exists" in result.stdout + + +def test_command_version(test_runner: CliRunner): + result = test_runner.invoke(app, ["--version"]) + assert result.exit_code == 0 + assert "Starpack CLI version" in result.stdout + + +def test_command_engine_start(test_runner: CliRunner): + result = test_runner.invoke(app, ["engine", "start"]) + assert result.exit_code == 0 + + +def test_command_upload(tmp_path: Path, test_runner: CliRunner): + result = test_runner.invoke(app, ["upload", str(tmp_path)]) + assert result.exit_code == 0 + + +def test_command_terminate(test_runner: CliRunner): + + result = test_runner.invoke(app, ["engine", "terminate"]) + + assert result.exit_code == 0 + + +fake_payload = """ +package: + metadata: + # Set the package name to use later for the deployment + name: &package_name starpack_test + description: "Testing package" + version: 0.0.1 + author: Andromeda 360, Inc. + author_email: irvin.shen@andromeda360.com + artifacts: + root_location: starpack_test + validation_data: + training_data: + inference: + function_name: predict + script_name: predict.py + model_data: pred_heart_disease.pkl + dependencies: requirements.txt + steps: + - name: fastapi + version: 1.0.0 + - name: docker_desktop_push + labels: + image_name: "irvin-killed-it" # optional, defaults to metadata name + image_tags: # optional + - latest + +deployment: + metadata: + name: final_test + version: 1.0.0 + steps: + - name: local_docker_find + version: 1.0.0 + image: + name: *package_name + tag: latest + - name: local_docker_deploy + version: 1.0.0 + port: # optional +""" + + +# @pytest.mark.parametrize() +def test_command_package(test_runner: CliRunner, tmp_path, monkeypatch, requests_mock): + url = "http://localhost:1976/package" + requests_mock.post(url, status_code=200, text="") + + yaml_path = tmp_path / "starpack.yaml" + yaml_path.write_text(fake_payload) + + monkeypatch.setattr(StarpackClient, "package", lambda x, y: ...) + result = test_runner.invoke(app, ["package", str(tmp_path)]) + + assert result.exit_code == 0 + + +def test_command_deploy(test_runner: CliRunner, tmp_path, monkeypatch, requests_mock): + requests_mock.post("http://localhost:1976/deploy", status_code=200, text="") + requests_mock.post("http://localhost:1976/package", status_code=200, text="") + + yaml_path = tmp_path / "starpack.yaml" + yaml_path.write_text(fake_payload) + + monkeypatch.setattr(StarpackClient, "deploy", lambda x, y: ...) + result = test_runner.invoke(app, ["deploy", str(tmp_path)]) + + assert result.exit_code == 0 diff --git a/src/tests/test_core.py b/src/tests/test_core.py new file mode 100644 index 0000000000000000000000000000000000000000..5677146ae6431c2c0d416300131985ff1215815d --- /dev/null +++ b/src/tests/test_core.py @@ -0,0 +1,2 @@ +from starpack import core +import pytest diff --git a/src/tests/test_engine_client.py b/src/tests/test_engine_client.py new file mode 100644 index 0000000000000000000000000000000000000000..d3edc0dc9f5b2c831a664f61983b010f95ae97cb --- /dev/null +++ b/src/tests/test_engine_client.py @@ -0,0 +1,72 @@ +from starpack.client import StarpackClient +import requests +import pytest +from typing import Optional + + +@pytest.fixture +def starpack_client(): + client = StarpackClient() + + return client + + +def test_client_initialization(): + client = StarpackClient(host="http://google.com", port=80) + + assert client.url == "http://google.com:80" + + +@pytest.mark.parametrize( + ("status_code", "output", "exception"), + [(200, True, None), (404, False, None), (200, False, requests.ConnectionError)], +) +def test_client_healthcheck( + starpack_client, + requests_mock, + status_code: int, + output: bool, + exception: Optional[Exception], +): + url = "http://localhost:1976/healthcheck" + if exception: + requests_mock.get(url, exc=exception) + else: + requests_mock.get(url, text="nice", status_code=status_code) + assert starpack_client.check_health() == output + + +@pytest.mark.parametrize( + ("status_code", "output"), + [(200, "http://localhost:2000"), (500, "500"), (300, "300")], +) +def test_client_deploy( + starpack_client, requests_mock, capsys, status_code: int, output: str +): + url = "http://localhost:1976/deploy" + payload = {"deployment": {"metadata": {"name": "test"}}} + requests_mock.post( + url, + status_code=status_code, + json={"endpoints": {"fastapi": "http://localhost:2000"}}, + ) + starpack_client.deploy(payload) + print_out = capsys.readouterr().out + + assert output in print_out + + +@pytest.mark.parametrize( + ("status_code", "output"), + [(200, "Successfully packaged"), (500, "500"), (300, "300")], +) +def test_client_package( + starpack_client, requests_mock, capsys, status_code: int, output: str +): + url = "http://localhost:1976/package" + payload = {"package": {"metadata": {"name": "test"}}} + requests_mock.post(url, status_code=status_code, text="") + starpack_client.package(payload) + print_out = capsys.readouterr().out + + assert output in print_out diff --git a/src/tests/test_errors.py b/src/tests/test_errors.py new file mode 100644 index 0000000000000000000000000000000000000000..4bb7ecd71e353b29a91a4b14fcab6fc49c0c516e --- /dev/null +++ b/src/tests/test_errors.py @@ -0,0 +1,35 @@ +import pytest +from pathlib import Path +from starpack import errors + + +def test_docker_not_found_error() -> None: + with pytest.raises(errors.DockerNotFoundError) as e: + raise errors.DockerNotFoundError() + + assert e.value.exit_code == 1 + + +def test_local_only_error() -> None: + with pytest.raises(errors.LocalOnlyError) as e: + raise errors.LocalOnlyError() + + assert e.value.exit_code == 1 + + +def test_path_exists_error(capsys) -> None: + with pytest.raises(errors.PathExistsError) as e: + path = Path() + raise errors.PathExistsError(path) + + output = capsys.readouterr() + + assert str(path) in output.out + assert e.value.exit_code == 1 + + +def test_engine_initialization_error() -> None: + with pytest.raises(errors.EngineInitializationError) as e: + raise errors.EngineInitializationError() + + assert e.value.exit_code == 1
diff --git a/examples/starpack_basic_example/gradio_example.py b/examples/starpack_basic_example/gradio_example.py
new file mode 100644
index 0000000000000000000000000000000000000000..19931dda03413bdf3b0d804c28f6f868b14fe1f8
--- /dev/null
+++ b/examples/starpack_basic_example/gradio_example.py
@@ -0,0 +1,56 @@
+import gradio as gr
+import pandas as pd
+import requests
+import io
+
+
+def predict(age, sex, chest_pain, resting_blood_pressure, cholesterol, fbs, restecg, thalach, exang, oldpeak, slope, ca,
+ thal):
+ df = pd.DataFrame([{"age": age,
+ "sex": int(sex[0]),
+ "cp": int(chest_pain[0]),
+ "trestbps": resting_blood_pressure,
+ "chol": cholesterol,
+ "fbs": int(fbs),
+ "restecg": int(restecg[0]),
+ "thalach": thalach,
+ "exang": int(exang),
+ "oldpeak": oldpeak,
+ "slope": int(slope[0]),
+ "ca": ca,
+ "thal": int(thal[0]),
+ }])
+
+ bytes_input = df.to_csv(index=False).encode()
+ request_file = {"file": (f"test.csv", bytes_input, "application/vnd.ms-excel")}
+
+ output_response = requests.post("http://localhost/models/predict/starpack_deployment", files=request_file)
+ print(output_response.text)
+
+ prediction = bool(pd.read_csv(io.StringIO(output_response.text))["tgt_heart_disease"][0])
+
+ return str(prediction)
+
+
+gradio_app = gr.Interface(fn=predict,
+ inputs=[
+ "number",
+ gr.Radio(["0: Male", "1: Female"]),
+ gr.Radio(["0: Typical Angina", "1: Atypical Angina", "2: Non-anginal Pain",
+ "3: Asymptomatic"]),
+ "number",
+ "number",
+ gr.Checkbox(),
+ gr.Radio(["0: Normal", "1: ST-T wave abnormality", "2: Left ventricular hypertrophy"]),
+ "number",
+ gr.Checkbox(),
+ "number",
+ gr.Radio(["0: Positive", "1: Flat", "2: Negative"]),
+ gr.Slider(minimum=0, maximum=4),
+ gr.Radio(["1: Normal", "2: Fixed Defect", "3: Reversable Defect"])
+ ],
+ outputs=["text"],
+ )
+
+if __name__ == "__main__":
+ gradio_app.launch()
diff --git a/examples/starpack_basic_example/predict.py b/examples/starpack_basic_example/predict.py
new file mode 100644
index 0000000000000000000000000000000000000000..7f5e7bdcf82c19ecc2707d0f4328b20bd323c07f
--- /dev/null
+++ b/examples/starpack_basic_example/predict.py
@@ -0,0 +1,33 @@
+import pandas as pd
+import pickle
+import os
+from typing import Any
+from pathlib import Path
+
+
+def predict(model: Any, patient_metrics: pd.DataFrame) -> pd.DataFrame:
+
+ # Apply predictions to scoring file
+ # Optional, but we will give back the input, with the predictions appended to the 'tgt_heart_disease' column.
+ dfOut = patient_metrics
+ dfOut["tgt_heart_disease"] = model.predict(patient_metrics)
+
+ # Read out the prediction
+ return dfOut
+
+
+# For testing, you can make sure this function properly runs
+if __name__ == "__main__":
+ input_path = Path(input("Please give the path to the input file: "))
+ model_paths = [Path(input("Please give the path to your model file: "))]
+
+ input_type = input_path.suffix
+
+ if input_type == "json":
+ input = pd.read_json(input_path)
+ elif input_type == ".csv":
+ input = pd.read_csv(input_path)
+
+ output = predict(model_paths, input)
+