Skip to content

Commit 776315d

Browse files
authored
Shift to the new engine
2 parents 72b6eea + d8026f9 commit 776315d

File tree

6 files changed

+81
-104
lines changed

6 files changed

+81
-104
lines changed

.flake8

Lines changed: 3 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,3 @@
1+
[flake8]
2+
max-line-length = 100
3+
ignore = E203, E501, W503, E722, W605

.gitignore

Lines changed: 2 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -4,3 +4,5 @@ venv
44
secret_debug.env
55
supervisely_lib
66
src/debug
7+
__pycache__/
8+
.DS_Store

local.env

Lines changed: 5 additions & 14 deletions
Original file line numberDiff line numberDiff line change
@@ -1,20 +1,11 @@
1-
PYTHONUNBUFFERED=1
2-
3-
LOG_LEVEL="debug"
4-
5-
TASK_ID=22377
6-
7-
CONTEXT_TEAMID=8
8-
CONTEXT_WORKSPACEID=349
9-
CONTEXT_PROJECTID=14505
1+
TEAM_ID=448
2+
WORKSPACE_ID=690
3+
PROJECT_ID=37478
104

115
modal.state.Options=all # all, annotated
126
modal.state.allDatasets=true
13-
#modal.state.selectedDatasets= ["MOT15"] # ["ds1", "ds2"]
7+
modal.state.selectedDatasets= ["ds0"] # ["ds1", "ds2"]
148
modal.state.batchSize=30
159

1610
modal.state.sampleResultFrames=true
17-
modal.state.framesStep=2
18-
19-
DEBUG_APP_DIR="src/debug/app_debug_data"
20-
DEBUG_CACHE_DIR="src/debug/app_debug_cache"
11+
modal.state.framesStep=2

src/functions.py

Lines changed: 15 additions & 7 deletions
Original file line numberDiff line numberDiff line change
@@ -18,7 +18,7 @@ def upload_frames(api: sly.Api, dataset_id, names, images, anns, metas, current_
1818
)
1919
new_image_ids = [img_info.id for img_info in new_image_infos]
2020
api.annotation.upload_anns(new_image_ids, anns)
21-
g.logger.info(f"batch uploaded in {time() - local_time} seconds")
21+
sly.logger.info(f"batch uploaded in {time() - local_time} seconds")
2222

2323

2424
def convert_tags(tags, prop_container, frame_container, frame_indices=None):
@@ -49,17 +49,25 @@ def download_frames_with_retry(api: sly.Api, video_id, frames_to_convert):
4949
try:
5050
images = api.video.frame.download_nps(video_id, frames_to_convert)
5151
if len(images) != len(frames_to_convert):
52-
raise RuntimeError(f"Downloaded {len(images)} frames, but {len(frames_to_convert)} expected.")
52+
raise RuntimeError(
53+
f"Downloaded {len(images)} frames, but {len(frames_to_convert)} expected."
54+
)
5355
return images
5456
except Exception as e:
5557
curr_retry += 1
5658
if curr_retry <= retry_cnt:
57-
sleep(2 ** curr_retry)
58-
sly.logger.warn(f"Failed to download frames, retry {curr_retry} of {retry_cnt}... Error: {e}")
59-
raise RuntimeError(f"Failed to download frames with ids {frames_to_convert}. Check your data and try again later.")
59+
sleep(2**curr_retry)
60+
sly.logger.warn(
61+
f"Failed to download frames, retry {curr_retry} of {retry_cnt}... Error: {e}"
62+
)
63+
raise RuntimeError(
64+
f"Failed to download frames with ids {frames_to_convert}. Check your data and try again later."
65+
)
6066

6167

62-
def get_frames_from_api(api: sly.Api, video_id, video_name, frames_to_convert, dataset_name):
68+
def get_frames_from_api(
69+
api: sly.Api, video_id, video_name, frames_to_convert, dataset_name
70+
):
6371
if g.project.custom_data.get("original_images") is not None:
6472
image_names = []
6573
for frame in frames_to_convert:
@@ -79,7 +87,7 @@ def get_frames_from_api(api: sly.Api, video_id, video_name, frames_to_convert, d
7987
def get_progress_cb(message, total, is_size=False):
8088
progress = sly.Progress(message, total, is_size=is_size)
8189
progress_cb = partial(
82-
update_progress, api=g.api, task_id=g.my_app.task_id, progress=progress
90+
update_progress, api=g.api, task_id=g.task_id, progress=progress
8391
)
8492
progress_cb(0)
8593
return progress_cb

src/globals.py

Lines changed: 39 additions & 20 deletions
Original file line numberDiff line numberDiff line change
@@ -10,42 +10,60 @@
1010
load_dotenv("local.env")
1111
load_dotenv(os.path.expanduser("~/supervisely.env"))
1212

13-
logger = sly.logger
14-
15-
my_app = sly.AppService()
16-
api: sly.Api = my_app.public_api
13+
# region envvars
14+
team_id = sly.env.team_id()
15+
workspace_id = sly.env.workspace_id()
16+
project_id = sly.env.project_id()
17+
task_id = sly.env.task_id(raise_not_found=False)
18+
if sly.is_development():
19+
sly.logger.warning("Development mode, will set task_id to 0 to avoid errors")
20+
# task_id = 0
1721

18-
TEAM_ID = sly.env.team_id()
19-
WORKSPACE_ID = sly.env.workspace_id()
20-
PROJECT_ID = sly.env.project_id()
22+
# endregion
23+
sly.logger.info(
24+
f"Api initialized. Team: {team_id}. Workspace: {workspace_id}. Project: {project_id}"
25+
)
2126

22-
SAMPLE_RESULT_FRAMES = bool(strtobool(os.getenv("modal.state.sampleResultFrames")))
23-
if SAMPLE_RESULT_FRAMES:
24-
FRAMES_STEP = int(os.environ["modal.state.framesStep"])
27+
api = sly.Api.from_env()
2528

26-
LOG_LEVEL = str(os.environ["LOG_LEVEL"])
29+
# region modalvars
30+
sample_result_frames = bool(strtobool(os.getenv("modal.state.sampleResultFrames")))
31+
if sample_result_frames:
32+
frames_step = int(os.environ["modal.state.framesStep"])
33+
else:
34+
frames_step = None
2735

28-
OPTIONS = os.environ["modal.state.Options"]
29-
BATCH_SIZE = int(os.environ["modal.state.batchSize"])
36+
options = os.environ["modal.state.Options"]
37+
batch_size = int(os.environ["modal.state.batchSize"])
3038

31-
SELECTED_DATASETS = json.loads(
39+
selected_datasets = json.loads(
3240
os.environ["modal.state.selectedDatasets"].replace("'", '"')
3341
)
3442

35-
ALL_DATASETS = os.getenv("modal.state.allDatasets").lower() in ("true", "1", "t")
36-
if ALL_DATASETS or len(SELECTED_DATASETS) == 0:
37-
SELECTED_DATASETS = [dataset.name for dataset in api.dataset.get_list(PROJECT_ID)]
43+
all_datasets = os.getenv("modal.state.allDatasets").lower() in ("true", "1", "t")
44+
if all_datasets or len(selected_datasets) == 0:
45+
selected_datasets = [dataset.name for dataset in api.dataset.get_list(project_id)]
46+
# endregion
47+
sly.logger.info(
48+
f"Sample result frames: {sample_result_frames}. Frames step: {frames_step}. "
49+
f"Options: {options}. Batch size: {batch_size}. Selected datasets: {selected_datasets}. "
50+
f"All datasets: {all_datasets}"
51+
)
3852

3953
need_download_threshold = 0.15
4054

41-
storage_dir = os.path.join(my_app.data_dir, "sly_base_sir")
55+
storage_dir = os.path.join(os.getcwd(), "storage")
4256
mkdir(storage_dir, True)
4357
video_dir = os.path.join(storage_dir, "video")
4458
mkdir(video_dir)
4559
img_dir = os.path.join(storage_dir, "images")
4660
mkdir(img_dir)
61+
sly.logger.debug(
62+
f"Storage directory: {storage_dir}, video directory: {video_dir}, images directory: {img_dir}"
63+
)
4764

48-
project = api.project.get_info_by_id(PROJECT_ID)
65+
project = api.project.get_info_by_id(project_id)
66+
sly.logger.info(f"Working with project {project.name}...")
4967
if project is None:
5068
raise RuntimeError("Project {!r} not found".format(project.name))
5169
if project.type != str(sly.ProjectType.VIDEOS):
@@ -57,6 +75,7 @@
5775

5876
meta_json = api.project.get_meta(project.id)
5977
meta = sly.ProjectMeta.from_json(meta_json)
78+
sly.logger.info("Project meta received...")
6079

6180
if "object_id" not in [tag.name for tag in meta.tag_metas]:
6281
vobj_id_tag_meta = sly.TagMeta(
@@ -66,7 +85,7 @@
6685
)
6786
meta = meta.add_tag_meta(vobj_id_tag_meta)
6887

69-
if OPTIONS == "annotated" and len(meta.obj_classes) == 0 and len(meta.tag_metas) == 0:
88+
if options == "annotated" and len(meta.obj_classes) == 0 and len(meta.tag_metas) == 0:
7089
raise ValueError(
7190
"Nothing to convert, there are no tags and classes in project {!r}".format(
7291
project.name

src/main.py

Lines changed: 17 additions & 63 deletions
Original file line numberDiff line numberDiff line change
@@ -5,24 +5,23 @@
55
from supervisely.video_annotation.key_id_map import KeyIdMap
66

77
import functions as f
8+
89
import globals as g
910

1011

11-
@g.my_app.callback("turn_into_images_project")
12-
@sly.timeit
13-
def turn_into_images_project(api: sly.Api, task_id, context, state, app_logger):
12+
def turn_into_images_project(api: sly.Api):
1413
res_project_name = f"{g.project.name}(images)"
1514
dst_project = api.project.create(
16-
g.WORKSPACE_ID,
15+
g.workspace_id,
1716
res_project_name,
1817
type=sly.ProjectType.IMAGES,
1918
change_name_if_conflict=True,
2019
)
2120
api.project.update_meta(dst_project.id, g.meta.to_json())
2221

2322
key_id_map = KeyIdMap()
24-
for dataset_name in g.SELECTED_DATASETS:
25-
dataset = api.dataset.get_info_by_name(g.PROJECT_ID, dataset_name)
23+
for dataset_name in g.selected_datasets:
24+
dataset = api.dataset.get_info_by_name(g.project_id, dataset_name)
2625
dst_dataset = api.dataset.create(dst_project.id, dataset.name)
2726
videos = api.video.get_list(dataset.id)
2827
for batch in sly.batched(videos):
@@ -31,11 +30,11 @@ def turn_into_images_project(api: sly.Api, task_id, context, state, app_logger):
3130
ann_info = api.video.annotation.download(video_info.id)
3231
ann = sly.VideoAnnotation.from_json(ann_info, g.meta, key_id_map)
3332
if (
34-
g.OPTIONS == "annotated"
33+
g.options == "annotated"
3534
and len(ann.tags) == 0
3635
and len(ann.frames) == 0
3736
):
38-
g.my_app.logger.warn(
37+
sly.logger.warn(
3938
f"Video {video_info.name} annotation is empty in Dataset {dataset_name}"
4039
)
4140
continue
@@ -57,49 +56,40 @@ def turn_into_images_project(api: sly.Api, task_id, context, state, app_logger):
5756
)
5857
vobject_id = key_id_map.get_object_id(vobject.key())
5958
f.add_object_id_tag(vobject_id, object_props[vobject.key()])
60-
if g.OPTIONS == "annotated":
59+
if g.options == "annotated":
6160
frames_to_convert.extend(list(ann.frames.keys()))
6261
frames_to_convert = list(dict.fromkeys(frames_to_convert))
6362
frames_to_convert.sort()
6463
else:
6564
frames_to_convert = list(range(0, video_info.frames_count))
6665

67-
if g.SAMPLE_RESULT_FRAMES:
68-
if g.OPTIONS == "all":
69-
frames_to_convert = frames_to_convert[:: g.FRAMES_STEP]
66+
if g.sample_result_frames:
67+
if g.options == "all":
68+
frames_to_convert = frames_to_convert[:: g.frames_step]
7069
else:
7170
frames_to_convert = f.calc_frame_step(
7271
frames_to_convert=frames_to_convert,
73-
frame_step=g.FRAMES_STEP,
72+
frame_step=g.frames_step,
7473
)
7574

7675
progress = sly.Progress(
7776
"Processing video frames: {!r}".format(video_info.name),
7877
len(frames_to_convert),
7978
)
8079

81-
# total_images_size = 0
8280
for batch_index, batch_frames in enumerate(
83-
sly.batched(frames_to_convert, batch_size=g.BATCH_SIZE)
81+
sly.batched(frames_to_convert, batch_size=g.batch_size)
8482
):
8583
metas = []
8684
anns = []
8785
local_time = time()
8886
images_names, images = f.get_frames_from_api(
8987
api, video_info.id, video_info.name, batch_frames, dataset_name
9088
)
91-
g.logger.debug(
89+
sly.logger.debug(
9290
f"extracted {len(batch_frames)} by {time() - local_time} seconds"
9391
)
9492

95-
"""
96-
too slow calculations, for extreme debug
97-
images_size = f.calculate_batch_size(images) / (1024 * 1024) # in MegaBytes
98-
g.logger.debug(f'batch size: {images_size} MB')
99-
g.logger.debug(f'mean item size: {images_size / len(images)} MB')
100-
total_images_size += images_size
101-
"""
102-
10393
for idx, frame_index in enumerate(batch_frames):
10494
metas.append(
10595
{
@@ -149,57 +139,21 @@ def turn_into_images_project(api: sly.Api, task_id, context, state, app_logger):
149139
)
150140
)
151141

152-
if g.LOG_LEVEL == "debug":
153-
f.distort_frames(images)
154-
g.logger.debug(f"{len(images)} frames distorted")
155-
156142
f.upload_frames(
157143
api,
158144
dst_dataset.id,
159145
images_names,
160146
images,
161147
anns,
162148
metas,
163-
f"{batch_index}/{int(len(frames_to_convert) / g.BATCH_SIZE)}",
149+
f"{batch_index}/{int(len(frames_to_convert) / g.batch_size)}",
164150
)
165151
progress.iters_done_report(len(images_names))
166152

167-
if g.my_app.is_stopped():
168-
g.logger.debug("turn_into_images_project is finished.")
169-
return
170-
171-
# g.logger.debug(f'total images size for video: {total_images_size} MB')
172-
g.logger.info(
153+
sly.logger.info(
173154
f"video {video_info.name} converted in {time() - general_time} seconds"
174155
)
175156

176-
g.my_app.stop()
177-
178-
179-
@g.my_app.callback("stop")
180-
@sly.timeit
181-
def stop(api: sly.Api, task_id, context, state, app_logger):
182-
g.my_app.stop()
183-
184-
185-
def main():
186-
if g.LOG_LEVEL == "debug":
187-
g.logger.debug(
188-
f"DEBUG MODE ACTIVATED, we will add 50 random pixels to distort images"
189-
)
190-
191-
sly.logger.info(
192-
"Script arguments",
193-
extra={
194-
"TEAM_ID": g.TEAM_ID,
195-
"WORKSPACE_ID": g.WORKSPACE_ID,
196-
"PROJECT_ID": g.PROJECT_ID,
197-
},
198-
)
199-
200-
# Run application service
201-
g.my_app.run(initial_events=[{"command": "turn_into_images_project"}])
202-
203157

204158
if __name__ == "__main__":
205-
sly.main_wrapper("main", main)
159+
turn_into_images_project(g.api)

0 commit comments

Comments
 (0)