-
-
Notifications
You must be signed in to change notification settings - Fork 3
/
cattool.py
executable file
·2563 lines (1943 loc) · 75 KB
/
cattool.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
#! /usr/bin/env python
#
# Copyright 2022-2023 the .NET Foundation
# Licensed under the MIT License
"""
Tool for working with the WWT core dataset catalog.
"""
import argparse
from collections import OrderedDict
import csv
from io import BytesIO
import json
import math
import os.path
from pathlib import Path
import re
import shutil
import sys
import textwrap
import time
from typing import Dict, Optional, Tuple
import uuid
from xml.etree import ElementTree as etree
import yaml
from requests.exceptions import ConnectionError
from wwt_api_client import constellations as cx
from wwt_api_client.constellations.data import (
SceneAstroPix,
SceneContent,
SceneImageLayer,
ScenePlace,
)
from wwt_api_client.constellations.handles import HandleClient, AddSceneRequest
from wwt_data_formats import indent_xml
from wwt_data_formats.enums import (
Bandpass,
Classification,
Constellation,
DataSetType,
FolderType,
ProjectionType,
)
from wwt_data_formats.folder import Folder
from wwt_data_formats.imageset import ImageSet
from wwt_data_formats.place import Place
H2R = math.pi / 12
D2R = math.pi / 180
BASEDIR = Path(os.path.dirname(__file__))
def die(text, prefix="fatal error:", exitcode=1):
print(prefix, text, file=sys.stderr)
sys.exit(exitcode)
def warn(text):
print("warning:", text, file=sys.stderr)
def write_multi_yaml(path, docs):
with open(path, "wt", encoding="utf-8") as f:
yaml.dump_all(
docs,
stream=f,
allow_unicode=True,
sort_keys=True,
indent=2,
)
def write_one_yaml(path, doc):
with open(path, "wt", encoding="utf-8") as f:
yaml.dump(
doc,
stream=f,
allow_unicode=True,
sort_keys=True,
indent=2,
)
# Imageset database
class ImagesetDatabase(object):
db_dir: Path = None
by_url: Dict[str, ImageSet] = None
by_alturl: Dict[str, str] = None
def __init__(self):
self.by_url = {}
self.by_alturl = {}
self.db_dir = BASEDIR / "imagesets"
for path in self.db_dir.glob("*.xml"):
f = Folder.from_file(path)
for c in f.children:
assert isinstance(c, ImageSet)
self.add_imageset(c)
def add_imageset(
self, imgset: ImageSet, queue_constellations_handle: Optional[str] = None
):
if imgset.url in self.by_url:
warn(f"dropping duplicated imageset `{imgset.url}`")
return self.by_url[imgset.url]
main_url = self.by_alturl.get(imgset.url)
if main_url:
warn(
f"tried to add altUrl imageset `{imgset.url}`; use `{main_url}` instead"
)
return self.by_url[main_url]
if queue_constellations_handle:
if queue_constellations_handle == "skip":
imgset.xmeta.cxstatus = "skip"
else:
imgset.xmeta.cxstatus = f"queue:{queue_constellations_handle}"
if imgset.alt_url:
main_url = self.by_alturl.get(imgset.alt_url)
if main_url:
warn(
f"duplicated AltUrl: {imgset.alt_url} => {main_url} AND {imgset.url}"
)
else:
self.by_alturl[imgset.alt_url] = imgset.url
self.by_url[imgset.url] = imgset
return imgset
def get_by_url(self, url: str) -> ImageSet:
return self.by_url[url]
def rewrite(self):
by_key = {}
for imgset in self.by_url.values():
k = [str(imgset.data_set_type.value)]
if imgset.reference_frame is not None and imgset.reference_frame != "Sky":
k.append(imgset.reference_frame)
if imgset.band_pass is not None:
k.append(str(imgset.band_pass.value))
key = "_".join(k).lower()
by_key.setdefault(key, []).append(imgset)
tempdir = Path(str(self.db_dir) + ".new")
tempdir.mkdir()
for key, imgsets in by_key.items():
f = Folder(name=key)
f.children = sorted(imgsets, key=lambda s: s.url)
with (tempdir / (key + ".xml")).open("wt", encoding="utf-8") as stream:
prettify(f.to_xml(), stream)
olddir = Path(str(self.db_dir) + ".old")
self.db_dir.rename(olddir)
tempdir.rename(self.db_dir)
shutil.rmtree(olddir)
# Place database
class PlaceDatabase(object):
db_dir: Path = None
by_uuid: Dict[str, dict] = None
def __init__(self):
self.by_uuid = {}
self.db_dir = BASEDIR / "places"
for path in self.db_dir.glob("*.yml"):
with path.open("rt", encoding="utf-8") as f:
for info in yaml.load_all(f, yaml.SafeLoader):
self.by_uuid[info["_uuid"]] = info
def ingest_place(
self,
place: Place,
idb: ImagesetDatabase,
queue_constellations_handle: Optional[str] = None,
new_id: Optional[str] = None,
):
place.update_constellation()
if place.image_set is not None:
place.image_set = idb.add_imageset(
place.image_set, queue_constellations_handle=queue_constellations_handle
)
if place.foreground_image_set is not None:
place.foreground_image_set = idb.add_imageset(
place.foreground_image_set,
queue_constellations_handle=queue_constellations_handle,
)
if place.background_image_set is not None:
place.background_image_set = idb.add_imageset(
place.background_image_set,
queue_constellations_handle=queue_constellations_handle,
)
if not new_id:
new_id = str(uuid.uuid4())
info = {"_uuid": new_id}
if place.angle != 0:
info["angle"] = place.angle
if place.angular_size != 0:
info["angular_size"] = place.angular_size
if place.annotation:
info["annotation"] = place.annotation
if place.background_image_set:
info["background_image_set_url"] = place.background_image_set.url
if place.classification:
info["classification"] = place.classification.value
if place.constellation:
info["constellation"] = place.constellation.value
info["data_set_type"] = place.data_set_type.value
if info["data_set_type"] == "Sky":
info["ra_hr"] = place.ra_hr
info["dec_deg"] = place.dec_deg
else:
info["latitude"] = place.latitude
info["longitude"] = place.longitude
if place.description:
info["description"] = place.description
if place.distance != 0:
info["distance"] = place.distance
if place.dome_alt != 0:
info["dome_alt"] = place.dome_alt
if place.dome_az != 0:
info["dome_az"] = place.dome_az
if place.foreground_image_set:
info["foreground_image_set_url"] = place.foreground_image_set.url
if place.image_set:
info["image_set_url"] = place.image_set.url
if place.magnitude != 0:
info["magnitude"] = place.magnitude
if place.msr_community_id != 0:
info["msr_community_id"] = place.msr_community_id
if place.msr_component_id != 0:
info["msr_component_id"] = place.msr_component_id
info["name"] = place.name
if place.opacity != 100:
info["opacity"] = place.opacity
if place.permission != 0:
info["permission"] = place.permission
if place.rotation_deg != 0:
info["rotation_deg"] = place.rotation_deg
if place.thumbnail:
info["thumbnail"] = place.thumbnail
if place.zoom_level != 0:
info["zoom_level"] = place.zoom_level
if queue_constellations_handle == "skip":
# If we're adding to a real handle, the appropriate course of
# action will be detected from the imageset's cxstatus
info["cxstatus"] = "skip"
self.by_uuid[new_id] = info
return new_id
def reconst_by_id(self, pid: str, idb: ImagesetDatabase) -> Place:
info = self.by_uuid[pid]
place = Place()
v = info.get("angle")
if v is not None:
place.angle = v
v = info.get("angular_size")
if v is not None:
place.angular_size = v
v = info.get("annotation")
if v:
place.annotation = v
u = info.get("background_image_set_url")
if u:
place.background_image_set = idb.get_by_url(u)
v = info.get("classification")
if v:
place.classification = Classification(v)
v = info.get("constellation")
if v:
place.constellation = Constellation(v)
place.data_set_type = DataSetType(info["data_set_type"])
v = info.get("dec_deg")
if v is not None:
place.dec_deg = v
v = info.get("description")
if v:
place.description = v
v = info.get("distance")
if v is not None:
place.distance = v
v = info.get("dome_alt")
if v is not None:
place.dome_alt = v
v = info.get("dome_az")
if v is not None:
place.dome_az = v
u = info.get("foreground_image_set_url")
if u:
try:
place.foreground_image_set = idb.get_by_url(u)
except KeyError:
raise Exception(f"FG imageset URL `{u}` not found in place `{pid}`")
u = info.get("image_set_url")
if u:
place.image_set = idb.get_by_url(u)
v = info.get("latitude")
if v is not None:
place.latitude = v
v = info.get("longitude")
if v is not None:
place.longitude = v
v = info.get("magnitude")
if v is not None:
place.magnitude = v
v = info.get("msr_community_id")
if v is not None:
place.msr_community_id = v
v = info.get("msr_component_id")
if v is not None:
place.msr_component_id = v
place.name = info["name"]
v = info.get("opacity")
if v is not None:
place.opacity = v
v = info.get("permission")
if v is not None:
place.permission = v
v = info.get("ra_hr")
if v is not None:
place.ra_hr = v
v = info.get("rotation_deg")
if v is not None:
place.rotation_deg = v
v = info.get("thumbnail")
if v:
place.thumbnail = v
v = info.get("zoom_level")
if v is not None:
place.zoom_level = v
return place
def rewrite(self):
by_key = {}
const_place = Place()
for info in self.by_uuid.values():
k = [info["data_set_type"]]
ra = info.get("ra_hr")
if ra is not None:
ra = int(math.floor(ra)) % 24
k.append(f"ra{ra:02d}")
# Update constellation while we're at it
const_place.set_ra_dec(info["ra_hr"], info["dec_deg"])
info["constellation"] = const_place.constellation.value
lon = info.get("longitude")
if lon is not None:
lon = (int(math.floor(lon)) // 10) * 10
k.append(f"lon{lon:03d}")
key = "_".join(k).lower()
by_key.setdefault(key, []).append(info)
def sortkey(info):
k = []
u = info.get("foreground_image_set_url")
if u is not None:
k += u
u = info.get("image_set_url")
if u is not None:
k += u
u = info.get("background_image_set_url")
if u is not None:
k += u
dec = info.get("dec_deg")
if dec is not None:
k += [dec, info["ra_hr"]]
lat = info.get("latitude")
if lat is not None:
k.append(lat)
lon = info.get("longitude") # there is a busted dataset like this
if lon is not None:
k.append(lon)
k += [info["name"]]
return tuple(k)
tempdir = Path(str(self.db_dir) + ".new")
tempdir.mkdir()
for key, infos in by_key.items():
infos = sorted(infos, key=sortkey)
write_multi_yaml(tempdir / (key + ".yml"), infos)
olddir = Path(str(self.db_dir) + ".old")
self.db_dir.rename(olddir)
tempdir.rename(self.db_dir)
shutil.rmtree(olddir)
# Constellations prep database
def _parse_record_file(stream, path):
kind = None
fields = OrderedDict()
multiline_key = None
multiline_words = []
line_num = 0
for line in stream:
line_num += 1
line = line.strip()
if not line:
continue
if kind is None:
if line.startswith("@"):
kind = line[1:].split()[0]
else:
die(
f"expected @ indicator at line {line_num} of `{path}`; got: {line!r}"
)
elif line == "---":
if multiline_key:
fields[multiline_key] = " ".join(multiline_words)
multiline_key = None
multiline_words = []
yield kind, fields
kind = None
fields = OrderedDict()
else:
pieces = line.split()
if pieces[0].endswith(":"):
if multiline_key:
fields[multiline_key] = " ".join(multiline_words)
multiline_key = None
multiline_words = []
fields[pieces[0][:-1]] = " ".join(pieces[1:])
elif pieces[0].endswith(">"):
if multiline_key:
fields[multiline_key] = " ".join(multiline_words)
multiline_key = None
multiline_words = []
multiline_key = pieces[0][:-1]
multiline_words = pieces[1:]
elif multiline_key:
multiline_words += pieces
else:
die(
f"expected : or > indicator at line {line_num} of `{path}`; got: {line!r}"
)
if kind or fields or multiline_key:
die(f"file `{path}` must end with an end-of-record indicator (---)")
def _emit_record(kind, fields, stream):
print(f"\n@{kind}", file=stream)
prev_had_blank_line = False
for key, value in fields.items():
if key in ("text", "credits"):
if not prev_had_blank_line:
print(file=stream)
for line in textwrap.wrap(
f"{key}> {value}",
width=80,
break_long_words=False,
break_on_hyphens=False,
):
print(line, file=stream)
print(file=stream)
prev_had_blank_line = True
else:
print(f"{key}: {value}", file=stream)
prev_had_blank_line = False
print("---", file=stream)
def _retry(operation):
"""
My computer will sometimes fail during large bootstraps due to temporary,
local network errors. Here's a dumb retry system since the design of the
openidc_client library that underlies wwt_api_client doesn't allow me to
activate retries at the request/urllib3 level, as far as I can see.
"""
for _attempt in range(5):
try:
return operation()
except ConnectionError:
print("(retrying ...)")
time.sleep(0.5)
def _register_image(
client: HandleClient, fields: dict, imgset: ImageSet, dry_run: bool = False
) -> str:
"Returns the new image ID"
if imgset.band_pass != Bandpass.VISIBLE:
print(
f"warning: imageset `{imgset.name}` has non-default band_pass setting `{imgset.band_pass}`"
)
if imgset.base_tile_level != 0:
print(
f"warning: imageset `{imgset.name}` has non-default base_tile_level setting `{imgset.base_tile_level}`"
)
if imgset.data_set_type != DataSetType.SKY:
print(
f"warning: imageset `{imgset.name}` has non-default data_set_type setting `{imgset.data_set_type}`"
)
if imgset.elevation_model != False:
print(
f"warning: imageset `{imgset.name}` has non-default elevation_model setting `{imgset.elevation_model}`"
)
if imgset.generic != False:
print(
f"warning: imageset `{imgset.name}` has non-default generic setting `{imgset.generic}`"
)
if imgset.sparse != True:
print(
f"warning: imageset `{imgset.name}` has non-default sparse setting `{imgset.sparse}`"
)
if imgset.stock_set != False:
print(
f"warning: imageset `{imgset.name}` has non-default stock_set setting `{imgset.stock_set}`"
)
credits = fields["credits"]
copyright = fields["copyright"]
license_id = fields["license_id"]
alt_text = fields.get("description")
if dry_run:
print("*not* registering image:", imgset.url, "=>", end=" ")
id = "<fakeimageid>"
else:
print("registering image:", imgset.url, "=>", end=" ")
id = _retry(
lambda: client.add_image_from_set(
imgset,
copyright,
license_id,
credits=credits,
alt_text=alt_text,
)
)
print(id)
return id
def _register_scene(
client: HandleClient,
fields: dict,
place: Place,
imgid: str,
dry_run: bool = False,
apid: Optional[str] = None,
published: bool = True,
) -> str:
"Returns the new scene ID"
image_layers = [SceneImageLayer(image_id=imgid, opacity=1.0)]
api_place = ScenePlace(
ra_rad=place.ra_hr * H2R,
dec_rad=place.dec_deg * D2R,
roll_rad=place.rotation_deg * D2R,
roi_height_deg=place.zoom_level / 6,
roi_aspect_ratio=1.0,
)
content = SceneContent(image_layers=image_layers)
req = AddSceneRequest(
place=api_place,
content=content,
text=fields["text"],
outgoing_url=fields["outgoing_url"],
published=published,
)
if apid:
publisher_id, image_id = apid.split("|")
req.astropix = SceneAstroPix(
publisher_id=publisher_id,
image_id=image_id,
)
if dry_run:
print("*not* registering place/scene:", fields["place_uuid"], "=>", end=" ")
id = "<fakesceneid>"
else:
print("registering place/scene:", fields["place_uuid"], "=>", end=" ")
id = _retry(lambda: client.add_scene(req))
print(id)
return id
class ConstellationsPrepDatabase(object):
db_dir: Path = None
by_handle: Dict[str, list] = None
def __init__(self):
self.by_handle = {}
self.db_dir = BASEDIR / "cxprep"
for path in self.db_dir.glob("*.txt"):
with path.open("rt", encoding="utf-8") as f:
handle = path.name.replace(".txt", "")
items = list(_parse_record_file(f, path))
self.by_handle[handle] = items
def update(self, idb: ImagesetDatabase, pdb: PlaceDatabase):
# Figure out which imagesets are already "done": they are either
# logged as "in" in the XML, or already in one of the prep files
done_imageset_urls = set()
for url, imgset in idb.by_url.items():
cxs = getattr(imgset.xmeta, "cxstatus", "undefined")
if cxs.startswith("in:"):
done_imageset_urls.add(url)
for recs in self.by_handle.values():
for kind, fields in recs:
if kind == "image":
done_imageset_urls.add(fields["url"])
# Same idea for places/scenes
done_place_uuids = set()
for uuid, pinfo in pdb.by_uuid.items():
cxs = pinfo.get("cxstatus", "undefined")
if cxs.startswith("in:"):
done_place_uuids.add(uuid)
for recs in self.by_handle.values():
for kind, fields in recs:
if kind == "scene":
done_place_uuids.add(fields["place_uuid"])
# Build up a list of imagesets to deal with
todo_image_urls_by_handle = {}
n_images_todo = 0
for url, imgset in idb.by_url.items():
if imgset.data_set_type != DataSetType.SKY:
continue
if url in done_imageset_urls:
continue
cxs = getattr(imgset.xmeta, "cxstatus", "undefined")
if cxs.startswith("in:") or cxs == "skip":
continue
if not cxs.startswith("queue:"):
# can't handle this since we don't know what handle to
# associate it with
warn(
f"imageset {url} should have Constellations ingest status flag, but doesn't"
)
continue
handle = cxs[6:]
todo_image_urls_by_handle.setdefault(handle, set()).add(url)
n_images_todo += 1
print(f"Number of imagesets to append:", n_images_todo)
# Build up a list of places/scenes to deal with. Also associate them
# with imageset URLs so that we can emit todo places next to todo images
# -- it makes a big difference to do so in practice, because when we're
# adapting info into the Constellations schema, the relevant metadata
# gets slightly split between images and scenes.
todo_place_uuids_by_handle = {}
n_places_todo = 0
pids_by_image_url = {}
for uuid, pinfo in pdb.by_uuid.items():
cxs = pinfo.get("cxstatus", "undefined")
if cxs.startswith("in:") or cxs == "skip":
continue
handle = None
matched_url = None
for k in [
"image_set_url",
"foreground_image_set_url",
"background_image_set_url",
]:
url = pinfo.get(k)
if not url:
continue
for h, urls in todo_image_urls_by_handle.items():
if url in urls:
# Aha! This place is associated with a to-do image, under
# the specified handle
if handle is None:
handle = h
matched_url = url
elif h != handle:
warn(
f"place {uuid} matches images from multiple handles: {h}, {handle}"
)
pids_by_image_url.setdefault(url, set()).add(uuid)
if handle is None:
# This place does not refer to any images that we plan to add to
# Constellations. So we can ignore it.
continue
todo_place_uuids_by_handle.setdefault(handle, {})[uuid] = matched_url
n_places_todo += 1
print(f"Number of places/scenes to append:", n_places_todo)
# Now we can finally actually add the new items to the lists. For each
# image, we add any places associated with it right after, to achieve
# the aformentioned desired clustering. Those places are then removed
# from the todo list. Then, after doing all the imageses, we mop up any
# places that may be hanging around.
for handle, imgurls in todo_image_urls_by_handle.items():
items = self.by_handle.setdefault(handle, [])
todo_places = todo_place_uuids_by_handle.get(handle, {})
for url in sorted(imgurls):
imgset = idb.by_url[url]
fields = OrderedDict()
fields["url"] = url
fields["copyright"] = "~~COPYRIGHT~~"
fields["license_id"] = "~~LICENSE~~"
if imgset.thumbnail_url:
fields["thumbnail"] = imgset.thumbnail_url
apids = getattr(imgset.xmeta, "astropix_ids", None)
if apids:
fields["astropix_ids"] = apids
fields["credits"] = imgset.credits
fields["wip"] = "yes"
items.append(("image", fields))
for pid in pids_by_image_url.get(url, []):
if pid not in todo_places:
# Looks like this place was already emitted elsewhere.
# This won't happen in typical usage, but is OK.
continue
fields = OrderedDict()
fields["place_uuid"] = pid
fields["image_url"] = url
fields["outgoing_url"] = imgset.credits_url
pinfo = pdb.by_uuid[pid]
if pinfo.get("thumbnail"):
fields["thumbnail"] = pinfo["thumbnail"]
text = pinfo.get("description")
if not text:
text = imgset.description
if not text:
text = pinfo["name"]
fields["text"] = text
fields["wip"] = "yes"
items.append(("scene", fields))
del todo_places[pid]
for handle, pids in todo_place_uuids_by_handle.items():
items = self.by_handle.setdefault(handle, [])
for pid, matched_url in sorted(pids.items()):
imgset = idb.by_url[matched_url]
fields = OrderedDict()
fields["place_uuid"] = pid
fields["image_url"] = matched_url
fields["outgoing_url"] = imgset.credits_url
pinfo = pdb.by_uuid[pid]
text = pinfo.get("description")
if not text:
text = imgset.description
if not text:
text = pinfo["name"]
fields["text"] = text
fields["wip"] = "yes"
items.append(("scene", fields))
# All done! Call rewrite() after this if you don't want to lose all this work.
def register(
self,
client: cx.CxClient,
idb: ImagesetDatabase,
pdb: PlaceDatabase,
dry_run: bool = False,
):
# prefill the tables of image info by URL since we may need
# these to construct scene records, if we create the image in one
# session and an associated scene in another.
imgids_by_url = {}
apids_by_url = {}
for url, imgset in idb.by_url.items():
cxs = getattr(imgset.xmeta, "cxstatus", "")
if cxs.startswith("in:"):
imgids_by_url[url] = cxs[3:]
apids = getattr(imgset.xmeta, "astropix_ids", "")
if apids:
apids_by_url[url] = apids
# now we can actually register the new stuff
n = 0
done_apids = set()
for handle in list(self.by_handle.keys()):
items = self.by_handle[handle]
remove_img_urls = set()
remove_place_uuids = set()
handle_client = None
try:
for kind, fields in items:
if "wip" in fields:
# Not yet ready
continue
if "skip" in fields:
# Something to skip. We still need to do a little work here
# to log this decision in the main database files.
if kind == "image":
url = fields["url"]
idb.by_url[url].xmeta.cxstatus = f"skip"
remove_img_urls.add(url)
elif kind == "scene":
uuid = fields["place_uuid"]
pdb.by_uuid[uuid]["cxstatus"] = f"skip"
remove_place_uuids.add(uuid)
else:
warn(f"unexpected skipped prep item kind `{kind}`")
continue
# Ooh, we have something to upload!
if handle_client is None:
handle_client = client.handle_client(handle)
if kind == "image":
url = fields["url"]
imgset = idb.by_url[url]
apids = fields.get("astropix_ids")
if apids:
apids_by_url[url] = apids
id = _register_image(
handle_client, fields, imgset, dry_run=dry_run
)
imgset.xmeta.cxstatus = f"in:{id}"
imgids_by_url[url] = id
remove_img_urls.add(url)
n += 1
elif kind == "scene":
uuid = fields["place_uuid"]
img_url = fields["image_url"]
img_id = imgids_by_url.get(img_url)
if not img_id:
warn(
f"can't register place/scene {uuid} because can't determine CXID for imageset {img_url}"
)
continue
apids = apids_by_url.get(img_url)
apid = None
if apids:
apids = apids.split(",")
if len(apids) > 1:
warn(
f"place/scene {uuid} associated with multiple AstroPix IDs via imageset {img_url}; only recording the first"
)
apid = apids[0]
if apid in done_apids:
# This check only knows about what we've added
# within this one session, so it is far from
# foolproof, but hopefully it can catch the
# common case of two scenes associated with the
# same image.
warn(
f"place/scene {uuid} associated with AstroPix {apid} via imageset {img_url}, but it was already registered this session"
)
apid = None
else:
done_apids.add(apid)