File size: 38,137 Bytes
d086025 | 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 276 277 278 279 280 281 282 283 284 285 286 287 288 289 290 291 292 293 294 295 296 297 298 299 300 301 302 303 304 305 306 307 308 309 310 311 312 313 314 315 316 317 318 319 320 321 322 323 324 325 326 327 328 329 330 331 332 333 334 335 336 337 338 339 340 341 342 343 344 345 346 347 348 349 350 351 352 353 354 355 356 357 358 359 360 361 362 363 364 365 366 367 368 369 370 371 372 373 374 375 376 377 378 379 380 381 382 383 384 385 386 387 388 389 390 391 392 393 394 395 396 397 398 399 400 401 402 403 404 405 406 407 408 409 410 411 412 413 414 415 416 417 418 419 420 421 422 423 424 425 426 427 428 429 430 431 432 433 434 435 436 437 438 439 440 441 442 443 444 445 446 447 448 449 450 451 452 453 454 455 456 457 458 459 460 461 462 463 464 465 466 467 468 469 470 471 472 473 474 475 476 477 478 479 480 481 482 483 484 485 486 487 488 489 490 491 492 493 494 495 496 497 498 499 500 501 502 503 504 505 506 507 508 509 510 511 512 513 514 515 516 517 518 519 520 521 522 523 524 525 526 527 528 529 530 531 532 533 534 535 536 537 538 539 540 541 542 543 544 545 546 547 548 549 550 551 552 553 554 555 556 557 558 559 560 561 562 563 564 565 566 567 568 569 570 571 572 573 574 575 576 577 578 579 580 581 582 583 584 585 586 587 588 589 590 591 592 593 594 595 596 597 598 599 600 601 602 603 604 605 606 607 608 609 610 611 612 613 614 615 616 617 618 619 620 621 622 623 624 625 626 627 628 629 630 631 632 633 634 635 636 637 638 639 640 641 642 643 644 645 646 647 648 649 650 651 652 653 654 655 656 657 658 659 660 661 662 663 664 665 666 667 668 669 670 671 672 673 674 675 676 677 678 679 680 681 682 683 684 685 686 687 688 689 690 691 692 693 694 695 696 697 698 699 700 701 702 703 704 705 706 707 708 709 710 711 712 713 714 715 716 717 718 719 720 721 722 723 724 725 726 727 728 729 730 731 732 733 734 735 736 737 738 739 740 741 742 743 744 745 746 747 748 749 750 751 752 753 754 755 756 757 758 759 760 761 762 763 764 765 766 767 768 769 770 771 772 773 774 775 776 777 778 779 780 781 782 783 784 785 786 787 788 789 790 791 792 793 794 795 796 797 798 799 800 801 802 803 804 805 806 807 808 809 810 811 812 813 814 815 816 817 818 819 820 821 822 823 824 825 826 827 828 829 830 831 832 833 834 835 836 837 838 839 840 841 842 843 844 845 846 847 848 849 850 851 852 853 854 855 856 857 858 859 860 861 862 863 864 865 866 867 868 869 870 871 872 873 874 875 876 877 878 879 880 881 882 883 884 885 886 887 888 889 890 891 892 893 894 895 896 897 898 899 900 901 902 903 904 905 906 907 908 909 910 911 912 913 914 915 916 917 918 919 920 921 922 923 924 925 926 927 928 929 930 931 932 933 934 935 936 937 938 939 940 941 942 943 944 945 946 947 948 949 950 951 952 953 954 955 956 957 958 959 960 961 962 963 964 965 966 967 968 969 970 971 972 973 974 975 976 977 978 979 980 981 982 983 984 985 986 987 988 989 990 991 992 993 994 995 996 997 998 999 1000 1001 1002 1003 1004 1005 1006 1007 1008 1009 1010 1011 1012 1013 1014 1015 1016 1017 1018 1019 1020 1021 1022 1023 1024 1025 1026 1027 1028 1029 1030 1031 1032 1033 1034 1035 1036 1037 1038 1039 1040 1041 1042 1043 1044 1045 1046 1047 1048 1049 1050 1051 1052 1053 1054 1055 1056 1057 1058 1059 1060 1061 1062 1063 1064 1065 1066 1067 1068 1069 1070 1071 1072 1073 1074 1075 1076 1077 1078 1079 1080 1081 1082 1083 1084 1085 1086 1087 1088 1089 1090 1091 1092 1093 1094 1095 1096 1097 1098 1099 1100 1101 1102 1103 1104 1105 1106 1107 1108 1109 1110 1111 1112 1113 1114 1115 1116 1117 1118 1119 1120 1121 1122 1123 1124 1125 1126 1127 1128 1129 1130 1131 1132 1133 1134 1135 1136 1137 1138 1139 1140 1141 1142 1143 1144 1145 1146 1147 1148 1149 1150 1151 1152 1153 1154 1155 1156 1157 1158 1159 1160 1161 1162 1163 1164 1165 1166 1167 1168 1169 1170 1171 1172 1173 1174 1175 1176 1177 1178 1179 1180 1181 1182 1183 1184 1185 1186 1187 1188 1189 1190 1191 1192 1193 1194 1195 1196 1197 1198 1199 1200 1201 1202 1203 1204 1205 1206 1207 1208 1209 1210 1211 1212 1213 1214 1215 1216 1217 1218 1219 1220 1221 1222 1223 1224 1225 1226 1227 1228 1229 1230 1231 1232 1233 1234 1235 1236 1237 1238 | 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
|