Overview
Overview
import os
import supervisely as sly
from dotenv import load_dotenv
from supervisely.app import widgets
# PART 1: BASE UI
models = widgets.RadioTable(columns=["Name"], rows=[["Model_1", "Model_2"]])
start_btn = widgets.Button(text="Start app")
layout = widgets.Container(
widgets=[
models,
start_btn
]
)
# PART 2: SETUP
app = sly.Application(layout=layout)
api = sly.Api.from_env()
if not sly.is_production():
# set more appropriate checkpoints_dir for local debug
os.environ["SLY_APP_DATA_DIR"] = "./artifacts"
load_dotenv("debug.env")
TEAM_ID = sly.env.team_id()
TASK_ID = sly.env.task_id()
# Using this checkpoints_dir is important in order to avoid data loss
checkpoints_dir = sly.app.get_synced_data_dir()
my_train_app_name = "MyTrainApp"
# PART 3: TRAIN FUNCTIONS
def get_model_instance_by_name():
name = models.get_selected_row()
# Initialize model with default params by name
...
return model
def train_process(model, data, app: sly.Application):
# pre-train preparing
...
# start train cycle
for epoch in epochs:
for batch in data:
# train on batch
...
# check if app receive stop signal
if app.is_stopped():
raise app.StopException
# Save checkpoint
model_path = os.path.join(checkpoints_dir, f"checkpoint_{epoch}.pth")
model.save(model.state_dict(), model_path)
last_checkpoint = os.path.join(checkpoints_dir, f"checkpoint_last.pth")
model.save(model.state_dict(), last_checkpoint)
def upload_artifacts():
out_path = api.file.upload_directory(
team_id=TEAM_ID,
local_dir=checkpoint_dir,
remote_dir=f"/my_train_app_name/{TASK_ID}"
)
return out_path
# PART 4: APP LOGIC
# start train on button click
@start_btn.click
def start_train():
model = get_model_instance_by_name()
with app.handle_stop(graceful=True):
train_process(model, data, app)
# The following code will only be executed if:
# 1. training loop successfuly finished (like normal python code - execution line by line)
# 2. if STOP event recieved during training and `graceful=True`
if sly.is_production():
out_path = upload_artifacts()
# allows you to display the path in the output
last_checkpoint = os.path.join(checkpoints_dir, f"checkpoint_last.pth")
file_info = g.api.file.get_info_by_path(TEAM_ID, last_checkpoint)
api.task.set_output_directory(g.api.task_id, file_info.id, out_path)
# clean agent memory
sly.fs.remove_dir(checkpoints_dir)
# stop application
app.stop()Use cases and best practice
Base UI
Checkpoints
Description
Tools
Example
Application stop
Description
Tools
Example
Last updated