forked from allenai/ai2thor
-
Notifications
You must be signed in to change notification settings - Fork 0
/
tasks.py
3393 lines (2845 loc) · 106 KB
/
tasks.py
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
import os
import sys
import datetime
import json
import re
import time
import zipfile
import threading
import hashlib
import shutil
import subprocess
import pprint
from invoke import task
import boto3
import botocore.exceptions
import multiprocessing
import io
import platform
import ai2thor.build
from ai2thor.build import PUBLIC_S3_BUCKET, PRIVATE_S3_BUCKET, PUBLIC_WEBGL_S3_BUCKET, PYPI_S3_BUCKET
import logging
logger = logging.getLogger()
logger.setLevel(logging.INFO)
handler = logging.StreamHandler(sys.stdout)
handler.setLevel(logging.INFO)
formatter = logging.Formatter(
"%(asctime)s [%(process)d] %(funcName)s - %(levelname)s - %(message)s"
)
handler.setFormatter(formatter)
logger.addHandler(handler)
def add_files(zipf, start_dir):
for root, dirs, files in os.walk(start_dir):
for f in files:
fn = os.path.join(root, f)
arcname = os.path.relpath(fn, start_dir)
# print("adding %s" % arcname)
zipf.write(fn, arcname)
def push_build(build_archive_name, zip_data, include_private_scenes):
import boto3
# subprocess.run("ls %s" % build_archive_name, shell=True)
# subprocess.run("gsha256sum %s" % build_archive_name)
s3 = boto3.resource("s3")
acl = "public-read"
bucket = PUBLIC_S3_BUCKET
if include_private_scenes:
bucket = PRIVATE_S3_BUCKET
acl = "private"
archive_base = os.path.basename(build_archive_name)
key = "builds/%s" % (archive_base,)
sha256_key = "builds/%s.sha256" % (os.path.splitext(archive_base)[0],)
s3.Object(bucket, key).put(Body=zip_data, ACL=acl)
s3.Object(bucket, sha256_key).put(
Body=hashlib.sha256(zip_data).hexdigest(), ACL=acl, ContentType="text/plain"
)
logger.info("pushed build %s to %s" % (bucket, build_archive_name))
def _webgl_local_build_path(prefix, source_dir="builds"):
return os.path.join(
os.getcwd(), "unity/{}/thor-{}-WebGL/".format(source_dir, prefix)
)
def _unity_version():
import yaml
with open("unity/ProjectSettings/ProjectVersion.txt") as pf:
project_version = yaml.load(pf.read(), Loader=yaml.FullLoader)
return project_version["m_EditorVersion"]
def _unity_path():
unity_version = _unity_version()
standalone_path = None
if sys.platform.startswith("darwin"):
unity_hub_path = (
"/Applications/Unity/Hub/Editor/{}/Unity.app/Contents/MacOS/Unity".format(
unity_version
)
)
standalone_path = (
"/Applications/Unity-{}/Unity.app/Contents/MacOS/Unity".format(
unity_version
)
)
elif "win" in sys.platform:
unity_hub_path = "C:/PROGRA~1/Unity/Hub/Editor/{}/Editor/Unity.exe".format(
unity_version
)
# TODO: Verify windows unity standalone path
standalone_path = "C:/PROGRA~1/{}/Editor/Unity.exe".format(unity_version)
elif sys.platform.startswith("linux"):
unity_hub_path = "{}/Unity/{}/Editor/Unity".format(
os.environ["HOME"], unity_version
)
if standalone_path and os.path.exists(standalone_path):
unity_path = standalone_path
else:
unity_path = unity_hub_path
return unity_path
def _build(unity_path, arch, build_dir, build_name, env={}):
import yaml
project_path = os.path.join(os.getcwd(), unity_path)
command = (
"%s -quit -batchmode -logFile %s.log -projectpath %s -executeMethod Build.%s"
% (_unity_path(), build_name, project_path, arch)
)
target_path = os.path.join(build_dir, build_name)
full_env = os.environ.copy()
full_env.update(env)
full_env["UNITY_BUILD_NAME"] = target_path
result_code = subprocess.check_call(command, shell=True, env=full_env)
print("Exited with code {}".format(result_code))
success = result_code == 0
if success:
generate_build_metadata(os.path.join(project_path, build_dir, "metadata.json"))
return success
def generate_build_metadata(metadata_path):
# this server_types metadata is maintained
# to allow future versions of the Python API
# to launch older versions of the Unity build
# and know whether the Fifo server is available
server_types = ["WSGI"]
try:
import ai2thor.fifo_server
server_types.append("FIFO")
except Exception as e:
pass
with open(os.path.join(metadata_path), "w") as f:
f.write(json.dumps(dict(server_types=server_types)))
def class_dataset_images_for_scene(scene_name):
import ai2thor.controller
from itertools import product
from collections import defaultdict
import numpy as np
import cv2
import hashlib
env = ai2thor.controller.Controller(quality="Low")
player_size = 300
zoom_size = 1000
target_size = 256
rotations = [0, 90, 180, 270]
horizons = [330, 0, 30]
buffer = 15
# object must be at least 40% in view
min_size = ((target_size * 0.4) / zoom_size) * player_size
env.start(width=player_size, height=player_size)
env.reset(scene_name)
event = env.step(
dict(
action="Initialize",
gridSize=0.25,
renderInstanceSegmentation=True,
renderSemanticSegmentation=False,
renderImage=False,
)
)
for o in event.metadata["objects"]:
if o["receptacle"] and o["receptacleObjectIds"] and o["openable"]:
print("opening %s" % o["objectId"])
env.step(
dict(action="OpenObject", objectId=o["objectId"], forceAction=True)
)
event = env.step(dict(action="GetReachablePositions", gridSize=0.25))
visible_object_locations = []
for point in event.metadata["actionReturn"]:
for rot, hor in product(rotations, horizons):
exclude_colors = set(
map(tuple, np.unique(event.instance_segmentation_frame[0], axis=0))
)
exclude_colors.update(
set(
map(
tuple,
np.unique(event.instance_segmentation_frame[:, -1, :], axis=0),
)
)
)
exclude_colors.update(
set(
map(tuple, np.unique(event.instance_segmentation_frame[-1], axis=0))
)
)
exclude_colors.update(
set(
map(
tuple,
np.unique(event.instance_segmentation_frame[:, 0, :], axis=0),
)
)
)
event = env.step(
dict(
action="TeleportFull",
x=point["x"],
y=point["y"],
z=point["z"],
rotation=rot,
horizon=hor,
forceAction=True,
),
raise_for_failure=True,
)
visible_objects = []
for o in event.metadata["objects"]:
if o["visible"] and o["objectId"] and o["pickupable"]:
color = event.object_id_to_color[o["objectId"]]
mask = (
(event.instance_segmentation_frame[:, :, 0] == color[0])
& (event.instance_segmentation_frame[:, :, 1] == color[1])
& (event.instance_segmentation_frame[:, :, 2] == color[2])
)
points = np.argwhere(mask)
if len(points) > 0:
min_y = int(np.min(points[:, 0]))
max_y = int(np.max(points[:, 0]))
min_x = int(np.min(points[:, 1]))
max_x = int(np.max(points[:, 1]))
max_dim = max((max_y - min_y), (max_x - min_x))
if (
max_dim > min_size
and min_y > buffer
and min_x > buffer
and max_x < (player_size - buffer)
and max_y < (player_size - buffer)
):
visible_objects.append(
dict(
objectId=o["objectId"],
min_x=min_x,
min_y=min_y,
max_x=max_x,
max_y=max_y,
)
)
print(
"[%s] including object id %s %s"
% (scene_name, o["objectId"], max_dim)
)
if visible_objects:
visible_object_locations.append(
dict(point=point, rot=rot, hor=hor, visible_objects=visible_objects)
)
env.stop()
env = ai2thor.controller.Controller()
env.start(width=zoom_size, height=zoom_size)
env.reset(scene_name)
event = env.step(dict(action="Initialize", gridSize=0.25))
for o in event.metadata["objects"]:
if o["receptacle"] and o["receptacleObjectIds"] and o["openable"]:
print("opening %s" % o["objectId"])
env.step(
dict(action="OpenObject", objectId=o["objectId"], forceAction=True)
)
for vol in visible_object_locations:
point = vol["point"]
event = env.step(
dict(
action="TeleportFull",
x=point["x"],
y=point["y"],
z=point["z"],
rotation=vol["rot"],
horizon=vol["hor"],
forceAction=True,
),
raise_for_failure=True,
)
for v in vol["visible_objects"]:
object_id = v["objectId"]
min_y = int(round(v["min_y"] * (zoom_size / player_size)))
max_y = int(round(v["max_y"] * (zoom_size / player_size)))
max_x = int(round(v["max_x"] * (zoom_size / player_size)))
min_x = int(round(v["min_x"] * (zoom_size / player_size)))
delta_y = max_y - min_y
delta_x = max_x - min_x
scaled_target_size = max(delta_x, delta_y, target_size) + buffer * 2
if min_x > (zoom_size - max_x):
start_x = min_x - (scaled_target_size - delta_x)
end_x = max_x + buffer
else:
end_x = max_x + (scaled_target_size - delta_x)
start_x = min_x - buffer
if min_y > (zoom_size - max_y):
start_y = min_y - (scaled_target_size - delta_y)
end_y = max_y + buffer
else:
end_y = max_y + (scaled_target_size - delta_y)
start_y = min_y - buffer
# print("max x %s max y %s min x %s min y %s" % (max_x, max_y, min_x, min_y))
# print("start x %s start_y %s end_x %s end y %s" % (start_x, start_y, end_x, end_y))
print("storing %s " % object_id)
img = event.cv2img[start_y:end_y, start_x:end_x, :]
seg_img = event.cv2img[min_y:max_y, min_x:max_x, :]
dst = cv2.resize(
img, (target_size, target_size), interpolation=cv2.INTER_LANCZOS4
)
object_type = object_id.split("|")[0].lower()
target_dir = os.path.join("images", scene_name, object_type)
h = hashlib.md5()
h.update(json.dumps(point, sort_keys=True).encode("utf8"))
h.update(json.dumps(v, sort_keys=True).encode("utf8"))
os.makedirs(target_dir, exist_ok=True)
cv2.imwrite(os.path.join(target_dir, h.hexdigest() + ".png"), dst)
env.stop()
return scene_name
@task
def build_class_dataset(context):
import concurrent.futures
import ai2thor.controller
multiprocessing.set_start_method("spawn")
controller = ai2thor.controller.Controller()
executor = concurrent.futures.ProcessPoolExecutor(max_workers=4)
futures = []
for scene in controller.scene_names():
print("processing scene %s" % scene)
futures.append(executor.submit(class_dataset_images_for_scene, scene))
for f in concurrent.futures.as_completed(futures):
scene = f.result()
print("scene name complete: %s" % scene)
def local_build_name(prefix, arch):
return "thor-%s-%s" % (prefix, arch)
@task
def local_build(context, prefix="local", arch="OSXIntel64"):
build = ai2thor.build.Build(arch, prefix, False)
env = dict()
if os.path.isdir("unity/Assets/Private/Scenes"):
env["INCLUDE_PRIVATE_SCENES"] = "true"
build_dir = os.path.join("builds", build.name)
if _build("unity", arch, build_dir, build.name, env=env):
print("Build Successful")
else:
print("Build Failure")
generate_quality_settings(context)
def fix_webgl_unity_loader_regex(unity_loader_path):
# Bug in the UnityLoader.js causes Chrome on Big Sur to fail to load
# https://issuetracker.unity3d.com/issues/unity-webgl-builds-do-not-run-on-macos-big-sur
with open(unity_loader_path) as f:
loader = f.read()
loader = loader.replace("Mac OS X (10[\.\_\d]+)", "Mac OS X (1[\.\_\d][\.\_\d]+)")
with open(unity_loader_path, "w") as f:
f.write(loader)
@task
def webgl_build(
context,
scenes="",
room_ranges=None,
directory="builds",
prefix="local",
verbose=False,
content_addressable=False,
crowdsource_build=False,
):
"""
Creates a WebGL build
:param context:
:param scenes: String of scenes to include in the build as a comma separated list
:param prefix: Prefix name for the build
:param content_addressable: Whether to change the unityweb build files to be content-addressable
have their content hashes as part of their names.
:return:
"""
from functools import reduce
def file_to_content_addressable(file_path, json_metadata_file_path, json_key):
# name_split = os.path.splitext(file_path)
path_split = os.path.split(file_path)
directory = path_split[0]
file_name = path_split[1]
print("File name {} ".format(file_name))
with open(file_path, "rb") as f:
h = hashlib.md5()
h.update(f.read())
md5_id = h.hexdigest()
new_file_name = "{}_{}".format(md5_id, file_name)
os.rename(file_path, os.path.join(directory, new_file_name))
with open(json_metadata_file_path, "r+") as f:
unity_json = json.load(f)
print("UNITY json {}".format(unity_json))
unity_json[json_key] = new_file_name
print("UNITY L {}".format(unity_json))
f.seek(0)
json.dump(unity_json, f, indent=4)
arch = "WebGL"
build_name = local_build_name(prefix, arch)
if room_ranges is not None:
floor_plans = [
"FloorPlan{}_physics".format(i)
for i in reduce(
lambda x, y: x + y,
map(
lambda x: x + [x[-1] + 1],
[
list(range(*tuple(int(y) for y in x.split("-"))))
for x in room_ranges.split(",")
],
),
)
]
scenes = ",".join(floor_plans)
if verbose:
print(scenes)
env = dict(SCENE=scenes)
if crowdsource_build:
env["DEFINES"] = "CROWDSOURCE_TASK"
if _build("unity", arch, directory, build_name, env=env):
print("Build Successful")
else:
print("Build Failure")
build_path = _webgl_local_build_path(prefix, directory)
fix_webgl_unity_loader_regex(os.path.join(build_path, "Build/UnityLoader.js"))
generate_quality_settings(context)
# the remainder of this is only used to generate scene metadata, but it
# is not part of building webgl player
rooms = {
"kitchens": {"name": "Kitchens", "roomRanges": range(1, 31)},
"livingRooms": {"name": "Living Rooms", "roomRanges": range(201, 231)},
"bedrooms": {"name": "Bedrooms", "roomRanges": range(301, 331)},
"bathrooms": {"name": "Bathrooms", "roomRanges": range(401, 431)},
"foyers": {"name": "Foyers", "roomRanges": range(501, 531)},
}
room_type_by_id = {}
for room_type, room_data in rooms.items():
for room_num in room_data["roomRanges"]:
room_id = "FloorPlan{}_physics".format(room_num)
room_type_by_id[room_id] = {"type": room_type, "name": room_data["name"]}
scene_metadata = {}
for scene_name in scenes.split(","):
if scene_name not in room_type_by_id:
# allows for arbitrary scenes to be included dynamically
room_type = {
"type": "Other", "name": None
}
else:
room_type = room_type_by_id[scene_name]
if room_type["type"] not in scene_metadata:
scene_metadata[room_type["type"]] = {
"scenes": [],
"name": room_type["name"],
}
scene_metadata[room_type["type"]]["scenes"].append(scene_name)
if verbose:
print(scene_metadata)
to_content_addressable = [
("{}.data.unityweb".format(build_name), "dataUrl"),
("{}.wasm.code.unityweb".format(build_name), "wasmCodeUrl"),
("{}.wasm.framework.unityweb".format(build_name), "wasmFrameworkUrl"),
]
for file_name, key in to_content_addressable:
file_to_content_addressable(
os.path.join(build_path, "Build/{}".format(file_name)),
os.path.join(build_path, "Build/{}.json".format(build_name)),
key,
)
with open(os.path.join(build_path, "scenes.json"), "w") as f:
f.write(json.dumps(scene_metadata, sort_keys=False, indent=4))
@task
def generate_quality_settings(ctx):
import yaml
class YamlUnity3dTag(yaml.SafeLoader):
def let_through(self, node):
return self.construct_mapping(node)
YamlUnity3dTag.add_constructor(
u"tag:unity3d.com,2011:47", YamlUnity3dTag.let_through
)
qs = yaml.load(
open("unity/ProjectSettings/QualitySettings.asset").read(),
Loader=YamlUnity3dTag,
)
quality_settings = {}
default = "Ultra"
for i, q in enumerate(qs["QualitySettings"]["m_QualitySettings"]):
quality_settings[q["name"]] = i
assert default in quality_settings
with open("ai2thor/_quality_settings.py", "w") as f:
f.write("# GENERATED FILE - DO NOT EDIT\n")
f.write("DEFAULT_QUALITY = '%s'\n" % default)
f.write("QUALITY_SETTINGS = " + pprint.pformat(quality_settings))
def git_commit_comment():
comment = (
subprocess.check_output("git log -n 1 --format=%B", shell=True)
.decode("utf8")
.strip()
)
return comment
def git_commit_id():
commit_id = (
subprocess.check_output("git log -n 1 --format=%H", shell=True)
.decode("ascii")
.strip()
)
return commit_id
@task
def deploy_pip(context):
if "TWINE_PASSWORD" not in os.environ:
raise Exception("Twine token not specified in environment")
subprocess.check_call("twine upload -u __token__ dist/*", shell=True)
@task
def push_pip_commit(context):
import glob
commit_id = git_commit_id()
s3 = boto3.resource("s3")
for g in glob.glob('dist/ai2thor-0+%s*' % commit_id):
acl = "public-read"
pip_name = os.path.basename(g)
logger.info("pushing pip file %s" % g)
with open(g, "rb") as f:
s3.Object(PYPI_S3_BUCKET, os.path.join('ai2thor', pip_name)).put(Body=f, ACL=acl)
@task
def build_pip_commit(context):
commit_id = git_commit_id()
if os.path.isdir("dist"):
shutil.rmtree("dist")
generate_quality_settings(context)
# must use this form to create valid PEP440 version specifier
version = "0+" + commit_id
with open("ai2thor/_builds.py", "w") as fi:
fi.write("# GENERATED FILE - DO NOT EDIT\n")
fi.write("COMMIT_ID = '%s'\n" % commit_id)
with open("ai2thor/_version.py", "w") as fi:
fi.write("# Copyright Allen Institute for Artificial Intelligence 2021\n")
fi.write("# GENERATED FILE - DO NOT EDIT\n")
fi.write("__version__ = '%s'\n" % (version))
subprocess.check_call("python setup.py clean --all", shell=True)
subprocess.check_call(
"python setup.py sdist bdist_wheel --universal", shell=True
)
@task
def build_pip(context, version):
from ai2thor.build import platform_map
import re
import xml.etree.ElementTree as ET
import requests
res = requests.get("https://pypi.org/rss/project/ai2thor/releases.xml")
res.raise_for_status()
root = ET.fromstring(res.content)
latest_version = None
for title in root.findall("./channel/item/title"):
latest_version = title.text
break
# make sure that the tag is on this commit
commit_tags = (
subprocess.check_output("git tag --points-at", shell=True)
.decode("ascii")
.strip()
.split("\n")
)
if version not in commit_tags:
raise Exception("tag %s is not on current commit" % version)
commit_id = git_commit_id()
res = requests.get(
"https://api.github.com/repos/allenai/ai2thor/commits?sha=main"
)
res.raise_for_status()
if commit_id not in map(lambda c: c["sha"], res.json()):
raise Exception("tag %s is not off the main branch" % version)
if not re.match(r"^[0-9]{1,3}\.+[0-9]{1,3}\.[0-9]{1,3}$", version):
raise Exception("invalid version: %s" % version)
for arch in platform_map.keys():
commit_build = ai2thor.build.Build(arch, commit_id, False)
if not commit_build.exists():
raise Exception("Build does not exist for %s/%s" % (commit_id, arch))
current_maj, current_min, current_sub = list(map(int, latest_version.split(".")))
next_maj, next_min, next_sub = list(map(int, version.split(".")))
if (
(next_maj == current_maj + 1)
or (next_maj == current_maj and next_min == current_min + 1)
or (
next_maj == current_maj
and next_min == current_min
and next_sub >= current_sub + 1
)
):
if os.path.isdir("dist"):
shutil.rmtree("dist")
generate_quality_settings(context)
with open("ai2thor/_builds.py", "w") as fi:
fi.write("# GENERATED FILE - DO NOT EDIT\n")
fi.write("COMMIT_ID = '%s'\n" % commit_id)
with open("ai2thor/_version.py", "w") as fi:
fi.write("# Copyright Allen Institute for Artificial Intelligence 2021\n")
fi.write("# GENERATED FILE - DO NOT EDIT\n")
fi.write("__version__ = '%s'\n" % (version))
subprocess.check_call("python setup.py clean --all", shell=True)
subprocess.check_call(
"python setup.py sdist bdist_wheel --universal", shell=True
)
else:
raise Exception(
"Invalid version increment: new version=%s,current version=%s; must increment the major, minor or patch by only 1"
% (version, latest_version)
)
@task
def fetch_source_textures(context):
import ai2thor.downloader
import io
zip_data = ai2thor.downloader.download(
"http://s3-us-west-2.amazonaws.com/ai2-thor/assets/source-textures.zip",
"source-textures",
"75476d60a05747873f1173ba2e1dbe3686500f63bcde3fc3b010eea45fa58de7",
)
z = zipfile.ZipFile(io.BytesIO(zip_data))
z.extractall(os.getcwd())
def build_log_push(build_info, include_private_scenes):
with open(build_info["log"]) as f:
build_log = f.read() + "\n" + build_info.get("build_exception", "")
build_log_key = "builds/" + build_info["log"]
s3 = boto3.resource("s3")
bucket = PUBLIC_S3_BUCKET
acl = "public-read"
if include_private_scenes:
bucket = PRIVATE_S3_BUCKET
acl = "private"
s3.Object(bucket, build_log_key).put(
Body=build_log, ACL=acl, ContentType="text/plain"
)
def archive_push(unity_path, build_path, build_dir, build_info, include_private_scenes):
threading.current_thread().success = False
archive_name = os.path.join(unity_path, build_path)
zip_buf = io.BytesIO()
zipf = zipfile.ZipFile(zip_buf, "w", zipfile.ZIP_DEFLATED)
add_files(zipf, os.path.join(unity_path, build_dir))
zipf.close()
zip_buf.seek(0)
zip_data = zip_buf.read()
push_build(archive_name, zip_data, include_private_scenes)
build_log_push(build_info, include_private_scenes)
print("Build successful")
threading.current_thread().success = True
@task
def pre_test(context):
import ai2thor.controller
import shutil
c = ai2thor.controller.Controller()
os.makedirs("unity/builds/%s" % c.build_name())
shutil.move(
os.path.join("unity", "builds", c.build_name() + ".app"),
"unity/builds/%s" % c.build_name(),
)
def clean():
import scripts.update_private
# a deploy key is used on the build server and an .ssh/config entry has been added
# to point to the deploy key caclled ai2thor-private-github
scripts.update_private.private_repo_url = (
"git@ai2thor-private-github:allenai/ai2thor-private.git"
)
subprocess.check_call("git reset --hard", shell=True)
subprocess.check_call("git clean -f -d -x", shell=True)
shutil.rmtree("unity/builds", ignore_errors=True)
shutil.rmtree(scripts.update_private.private_dir, ignore_errors=True)
scripts.update_private.checkout_branch()
def link_build_cache(branch):
library_path = os.path.join("unity", "Library")
logger.info("linking build cache for %s" % branch)
if os.path.lexists(library_path):
os.unlink(library_path)
# this takes takes care of branches with '/' in it
# to avoid implicitly creating directories under the cache dir
encoded_branch = re.sub(r"[^a-zA-Z0-9_\-.]", "_", re.sub("_", "__", branch))
cache_base_dir = os.path.join(os.environ["HOME"], "cache")
main_cache_dir = os.path.join(cache_base_dir, "main")
branch_cache_dir = os.path.join(cache_base_dir, encoded_branch)
# use the main cache as a starting point to avoid
# having to re-import all assets, which can take up to 1 hour
if not os.path.exists(branch_cache_dir) and os.path.exists(main_cache_dir):
logger.info("copying main cache for %s" % encoded_branch)
subprocess.check_call(
"cp -a %s %s" % (main_cache_dir, branch_cache_dir), shell=True
)
logger.info("copying main cache complete for %s" % encoded_branch)
branch_library_cache_dir = os.path.join(branch_cache_dir, "Library")
os.makedirs(branch_library_cache_dir, exist_ok=True)
os.symlink(branch_library_cache_dir, library_path)
def travis_build(build_id):
import requests
res = requests.get(
"https://api.travis-ci.com/build/%s" % build_id,
headers={
"Accept": "application/json",
"Content-Type": "application/json",
"Travis-API-Version": "3",
},
)
res.raise_for_status()
return res.json()
def pending_travis_build():
import requests
res = requests.get(
"https://api.travis-ci.com/repo/3459357/builds?include=build.id%2Cbuild.commit%2Cbuild.branch%2Cbuild.request%2Cbuild.created_by%2Cbuild.repository&build.state=started&sort_by=started_at:desc",
headers={
"Accept": "application/json",
"Content-Type": "application/json",
"Travis-API-Version": "3",
},
)
for b in res.json()["builds"]:
tag = None
if b["tag"]:
tag = b["tag"]["name"]
return {
"branch": b["branch"]["name"],
"commit_id": b["commit"]["sha"],
"tag": tag,
"id": b["id"],
}
def pytest_s3_object(commit_id):
s3 = boto3.resource("s3")
pytest_key = "builds/pytest-%s.json" % commit_id
return s3.Object(PUBLIC_S3_BUCKET, pytest_key)
def ci_pytest(build):
import requests
logger.info(
"running pytest for %s %s" % (build["branch"], build["commit_id"])
)
commit_id = git_commit_id()
s3_obj = pytest_s3_object(commit_id)
s3_pytest_url = "http://s3-us-west-2.amazonaws.com/%s/%s" % (
s3_obj.bucket_name,
s3_obj.key,
)
logger.info("pytest url %s" % s3_pytest_url)
res = requests.get(s3_pytest_url)
if res.status_code == 200 and res.json()["success"]:
# if we already have a successful pytest, skip running
logger.info("pytest results already exist for %s %s" % (build['branch'], build['commit_id']))
return
proc = subprocess.run(
"pytest", shell=True, stdout=subprocess.PIPE, stderr=subprocess.PIPE
)
result = dict(
success=proc.returncode == 0,
stdout=proc.stdout.decode("ascii"),
stderr=proc.stderr.decode("ascii"),
)
s3_obj.put(
Body=json.dumps(result), ACL="public-read", ContentType="application/json"
)
logger.info(
"finished pytest for %s %s" % (build["branch"], build["commit_id"])
)
@task
def ci_build(context):
import fcntl
import io
lock_f = open(os.path.join(os.environ["HOME"], ".ci-build.lock"), "w")
try:
fcntl.flock(lock_f, fcntl.LOCK_EX | fcntl.LOCK_NB)
build = pending_travis_build()
blacklist_branches = ["vids", "video"]
if build and build["branch"] not in blacklist_branches:
logger.info(
"pending build for %s %s" % (build["branch"], build["commit_id"])
)
clean()
subprocess.check_call("git fetch", shell=True)
subprocess.check_call("git checkout %s" % build["branch"], shell=True)
subprocess.check_call(
"git checkout -qf %s" % build["commit_id"], shell=True
)
private_scene_options = [False]
if build["branch"] == "erick/challenge2021":
os.environ["INCLUDE_PRIVATE_SCENES"] = "true"
elif build["branch"] == "erick/challenge2021-eval":
private_scene_options = [False, True]
procs = []
for include_private_scenes in private_scene_options:
for arch in ["OSXIntel64", "Linux64"]:
logger.info(
"starting build for %s %s %s"
% (arch, build["branch"], build["commit_id"])
)
rdir = os.path.normpath(
os.path.dirname(os.path.realpath(__file__)) + "/unity/builds"
)
commit_build = ai2thor.build.Build(
arch,
build["commit_id"],
include_private_scenes=include_private_scenes,
releases_dir=rdir)
if commit_build.exists():
logger.info(
"found build for commit %s %s" % (build["commit_id"], arch)
)
# download the build so that we can run the tests
if arch == 'OSXIntel64':
commit_build.download()
else:
# this is done here so that when a tag build request arrives and the commit_id has already
# been built, we avoid bootstrapping the cache since we short circuited on the line above
link_build_cache(build["branch"])
p = ci_build_arch(arch, include_private_scenes)
logger.info(
"finished build for %s %s %s"
% (arch, build["branch"], build["commit_id"])
)
procs.append(p)
# don't run tests for a tag since results should exist
# for the branch commit
if build["tag"] is None:
# its possible that the cache doesn't get linked if the builds
# succeeded during an earlier runh
link_build_cache(build["branch"])
ci_test_utf(context, build)
pytest_proc = multiprocessing.Process(
target=ci_pytest,
args=(build,)
)
pytest_proc.start()
procs.append(pytest_proc)
# give the travis poller time to see the result
for i in range(6):
b = travis_build(build["id"])
logger.info("build state for %s: %s" % (build["id"], b["state"]))
if b["state"] != "started":
break
time.sleep(10)