-
Notifications
You must be signed in to change notification settings - Fork 2
/
Copy pathmain.py
executable file
·748 lines (589 loc) · 20.8 KB
/
main.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
#!/usr/bin/env python3
# SPDX-FileCopyrightText: 2022 Helmholtz Centre Potsdam - GFZ German Research Centre for Geosciences
# SPDX-FileCopyrightText: 2023 Helmholtz Centre for Environmental Research (UFZ)
#
# SPDX-License-Identifier: EUPL-1.2
"""
Migration script for the spotlights from the hifis.net website.
"""
import argparse
import asyncio
import base64
import glob
import logging
import os
import re
import jwt
import magic
import yaml
from postgrest import APIError, AsyncPostgrestClient
from mdparser.mdparser import SvHtmlParser
VERBOSE = False
DELETE_SPOTLIGHTS = False
UPDATE_IMPRINT = False
POSTGREST_URL = os.environ.get("POSTGREST_URL")
PGRST_JWT_SECRET = os.environ.get("PGRST_JWT_SECRET")
JWT_PAYLOAD = {"role": "rsd_admin"}
JWT_ALGORITHM = "HS256"
ORGANISATIONS = {
"Helmholtz Centre for Environmental Research (UFZ)": {
"logo": "UFZ.svg",
"ror": "000h6jb29",
},
"Helmholtz Centre Potsdam GFZ German Research Centre for Geosciences": {
"logo": "GFZ.svg",
"ror": "04z8jg394",
},
"German Aerospace Center (DLR)": {
"logo": "DLR.svg",
"ror": "04bwf3e34",
},
"Alfred Wegener Institute for Polar and Marine Research (AWI)": {
"logo": "AWI.svg",
"ror": "032e6b942",
},
"Karlsruhe Institute of Technology (KIT)": {
"logo": "KIT.svg",
"ror": "04t3en479",
},
"CISPA Helmholtz Center for Information Security": {
"logo": "CISPA.png",
"ror": "02njgxr09",
},
"Helmholtz Centre for Heavy Ion Research (GSI)": {
"logo": "GSI.svg",
"ror": "02k8cbn47",
},
"Helmholtz Centre For Ocean Research Kiel (GEOMAR)": {
"logo": "GEOMAR.jpg",
"ror": "02h2x0161",
},
"Helmholtz-Zentrum Dresden-Rossendorf": {
"logo": "HZDR.png",
"ror": "01zy2cs03",
},
"Forschungszentrum Jülich": {
"logo": "FZJ.svg",
"ror": "02nv7yv05",
},
"Deutsches Elektronen-Synchrotron DESY": {
"logo": "DESY.svg",
"ror": "01js2sh04",
},
"German Cancer Research Center (DKFZ)": {
"logo": "dkfz.svg",
"ror": "04cdgtt98",
},
}
MISSING_LOGOS = []
mime = magic.Magic(mime=True)
def get_md_without_front_matter(file):
found = 0
retlines = []
with open(file, "r") as opened_file:
alllines = opened_file.readlines()
for line in alllines:
if line.startswith("---"):
found += 1
elif found >= 2:
retlines.append(line)
raw_markdown = "".join(retlines)
# Parse to remove html tags
md_parser = SvHtmlParser()
md_parser.feed(raw_markdown)
md_parsed = md_parser.close().to_markdown()
# Now split by code blocks
md_split = md_parsed.split(r"```")
if len(md_split) % 2 == 0:
raise Exception("There was an error parsing markdown code blocks in %s" % file)
# Remove line breaks inside paragraphs, because they would be rendered as <br>
# Only every scond block, because we do not want to replace newlines in code blocks
for i in range(0, len(md_split), 2):
md_split[i] = re.sub(
r"(?<=[\w., \(\)\[\]])(\n)(?=[\w.,\(\)\[\]])", " ", md_split[i]
)
return "```".join(md_split)
def get_spotlights():
if not os.path.exists(SPOTLIGHTS_DIR):
logging.error("Spotlights directory %s does not exist.", SPOTLIGHTS_DIR)
raise SystemExit("Can't find Spotlights.")
files = glob.glob(SPOTLIGHTS_DIR + os.sep + "*.md")
filtered = list(filter(lambda x: "_template.md" not in x, files))
spotlights = []
for file in filtered:
with open(file, "r") as opened_file:
try:
logging.info("Preparing %s", file)
# https://stackoverflow.com/a/34727830
load_all = yaml.load_all(opened_file, Loader=yaml.FullLoader)
metadata = next(load_all)
metadata["description"] = get_md_without_front_matter(file)
if metadata.get("name") is None:
raise Exception("Spotlight %s has no name" % file)
spotlights.append(metadata)
except yaml.YAMLError as exc:
print(exc)
return spotlights
def name_to_slug(name):
remove_chars = name.lower()
replacements = [
(r"\s+", "-"), # replace whitespaces
(r"[^A-Za-z0-9_ ]+", ""), # remove non-alphanumeric chars
(r"\-+", "-"), # remove multiple '-'
]
for pattern, replace in replacements:
remove_chars = re.sub(pattern, replace, remove_chars)
return remove_chars
def org_name_to_slug(name):
name = (
name.replace(" ", "-")
.replace("ä", "a")
.replace("ö", "o")
.replace("ü", "u")
.replace("ß", "ss")
.lower()
)
name = "".join(char for char in name if (char.isalnum() or char == "-"))
return name
async def slug_to_id(client, slug):
res = await client.from_("software").select("id", "slug").eq("slug", slug).execute()
if len(res.data) > 0:
return res.data[0].get("id")
return None
def convert_spotlight_to_software(spotlight):
name = spotlight.get("name")
doi = spotlight.get("doi")
description = spotlight.get("description", "")
assert len(description) <= 10000
software = {
"slug": name_to_slug(name),
"brand_name": name,
"is_published": True,
"short_statement": spotlight.get("excerpt", "")[:300],
"description": description,
}
if doi is None:
# nothing more to do
return software
if type(doi) == list:
logging.warning(
"Multiple DOIs are not supported. " "Consider adding %s as a project.",
name,
)
elif not doi.startswith("10."):
logging.warning("Spotlight %s: %s is not a valid DOI.", name, doi)
else:
software["concept_doi"] = doi
return software
async def spotlight_exists(client, spotlight) -> bool:
name = spotlight.get("name")
slug = name_to_slug(name)
software_id = await slug_to_id(client, slug)
if software_id is not None:
return True
else:
return False
async def remove_spotlight(client, spotlight):
name = spotlight.get("name")
slug = name_to_slug(name)
software_id = await slug_to_id(client, slug)
logging.info("Removing %s", name)
if software_id is not None:
# remove related entries
res = (
await client.from_("maintainer_for_software")
.delete()
.eq("software", software_id)
.execute()
)
res = (
await client.from_("release")
.select("software")
.eq("software", software_id)
.execute()
)
for rel in res.data:
res = (
await client.from_("release_version")
.delete()
.eq("release_id", rel.get("software"))
.execute()
)
res = (
await client.from_("release").delete().eq("software", software_id).execute()
)
res = (
await client.from_("repository_url")
.delete()
.eq("software", software_id)
.execute()
)
res = (
await client.from_("license_for_software")
.delete()
.eq("software", software_id)
.execute()
)
res = (
await client.from_("contributor")
.delete()
.eq("software", software_id)
.execute()
)
res = (
await client.from_("keyword_for_software")
.delete()
.eq("software", software_id)
.execute()
)
res = (
await client.from_("software_for_organisation")
.delete()
.eq("software", software_id)
.execute()
)
res = (
await client.from_("software_highlight")
.delete()
.eq("software", software_id)
.execute()
)
logging.info("Remove %s", name)
res = await client.from_("software").delete().eq("slug", slug).execute()
logging.info(res.data)
async def add_spotlight(client, spotlight):
name = spotlight.get("name")
logging.info("Add %s", name)
sw_data = convert_spotlight_to_software(spotlight)
logging.info(sw_data)
res = await client.from_("software").insert(sw_data).execute()
logging.info(res.data)
async def add_spotlight_urls(client, spotlight):
name = spotlight.get("name")
slug = name_to_slug(name)
platforms = spotlight.get("platforms", [])
if len(platforms) == 0:
logging.info("Spotlight %s has no platforms", name)
return
found_github = None
found_gitlab = None
found_webpage = None
to_add = None
to_update = None
for plat in platforms:
ptype = plat.get("type")
if ptype == "gitlab":
found_gitlab = plat.get("link_as")
if ptype == "github":
found_github = plat.get("link_as")
if ptype == "webpage":
found_webpage = plat.get("link_as")
software_id = await slug_to_id(client, slug)
# first check for GitLab as we prefer it over GitHub and only one entry
# can be made in the RSD
if found_gitlab is not None:
to_add = {
"software": software_id,
"code_platform": "gitlab",
"url": found_gitlab,
}
elif found_github is not None:
to_add = {
"software": software_id,
"code_platform": "github",
"url": found_github,
}
if to_add is not None:
logging.info("Add repository URL for %s", name)
res = await client.from_("repository_url").insert(to_add).execute()
logging.info(res.data)
if found_webpage is not None:
to_update = {
"get_started_url": found_webpage,
}
logging.info("Add get started URL for %s", name)
res = (
await client.from_("software")
.update(to_update)
.eq("id", software_id)
.execute()
)
logging.info(res.data)
async def add_license(client, spotlight):
slicense = spotlight.get("license")
if slicense is None or len(slicense) == 0:
# no license specified
return
name = spotlight.get("name")
slug = name_to_slug(name)
software_id = await slug_to_id(client, slug)
logging.info("Add license for %s", name)
res = (
await client.from_("license_for_software")
.insert({"software": software_id, "license": slicense})
.execute()
)
logging.info(res.data)
async def get_id_for_keyword(client, keyword):
res = (
await client.from_("keyword")
.select("id", "value")
.eq("value", keyword)
.execute()
)
if len(res.data) > 0:
return res.data[0].get("id")
return None
async def add_keywords(client, spotlight):
keywords = spotlight.get("keywords")
if keywords is None or len(keywords) == 0:
# no keyword specified
return
name = spotlight.get("name")
slug = name_to_slug(name)
software_id = await slug_to_id(client, slug)
logging.info("Add keywords for %s", name)
for keyword in keywords:
kw_id = await get_id_for_keyword(client, keyword)
if kw_id is None:
logging.info("Adding keyword %s" % keyword)
res = await client.from_("keyword").insert({"value": keyword}).execute()
logging.info(res.data)
kw_id = await get_id_for_keyword(client, keyword)
res = (
await client.from_("keyword_for_software")
.insert({"software": software_id, "keyword": kw_id})
.execute()
)
logging.info(res.data)
async def get_id_for_organisation(client, org):
res = (
await client.from_("organisation")
.select("id", "name")
.eq("name", org)
.execute()
)
if len(res.data) > 0:
return res.data[0].get("id")
return None
async def get_organisation_id_by_ror(client, ror):
res = (
await client.from_("organisation")
.select("id", "ror_id")
.eq("ror_id", f"https://ror.org/{ror}")
.execute()
)
if len(res.data) > 0:
return res.data[0].get("id")
return None
async def organisation_has_logo(client, org_id) -> bool:
res = (
await client.from_("organisation")
.select("id", "logo_id")
.eq("id", org_id)
.execute()
)
if len(res.data) == 1 and res.data[0]["logo_id"] is not None:
return True
else:
return False
async def add_organisations(client, spotlight):
orgs = spotlight.get("hgf_centers")
if isinstance(orgs, str):
orgs = [orgs]
if orgs is None or len(orgs) == 0:
# no organisation specified
return
name = spotlight.get("name")
slug = name_to_slug(name)
software_id = await slug_to_id(client, slug)
logging.info("Add organisations for %s", name)
for org in orgs:
org_id = await get_organisation_id_by_ror(
client, ORGANISATIONS.get(org).get("ror")
)
if org_id is None:
logging.info("Adding organisation %s" % org)
org_slug = org_name_to_slug(org)
ror_id = "https://ror.org/%s" % ORGANISATIONS.get(org).get("ror") or None
if ror_id is None or ror_id == "https://ror.org/":
logging.warn("Could not find ROR Id for: %s" % org)
res_img = (
await client.from_("organisation")
.insert({"name": org, "slug": org_slug, "ror_id": ror_id})
.execute()
)
logging.info(res_img.data)
org_id = await get_id_for_organisation(client, org)
logo_exists = await organisation_has_logo(client, org_id)
logo_available = (
org in ORGANISATIONS.keys() and "logo" in ORGANISATIONS.get(org).keys()
)
if not logo_exists and not logo_available:
logging.warn("No logo found for %s" % org)
MISSING_LOGOS.append(org)
elif not logo_exists:
logo_filename = f"./resources/logos/{ORGANISATIONS[org]['logo']}"
logging.info("Adding logo %s" % logo_filename)
with open(logo_filename, "rb") as logo:
logo_base64 = base64.b64encode(logo.read()).decode("utf-8")
mime_type = mime.from_file(logo_filename)
logo_data = {
"data": logo_base64,
"mime_type": mime_type,
}
res_img = await client.from_("image").insert(logo_data).execute()
logging.info(res_img.data)
logo_id = res_img.data[0]["id"]
logging.info("Uploaded logo %s" % logo_filename)
res_org = (
await client.from_("organisation")
.update({"logo_id": logo_id})
.eq("id", org_id)
.execute()
)
logging.info("Added logo %s to organisation %s" % (logo_id, org_id))
logging.info(res_org.data)
logging.info("Adding organisation %s to software %s" % (org, name))
res_img = (
await client.from_("software_for_organisation")
.insert({"software": software_id, "organisation": org_id})
.execute()
)
logging.info(res_img.data)
async def add_research_field(client, spotlight):
research_field = spotlight.get("hgf_research_field")
if research_field is None or len(research_field) == 0:
# no research field specified
return
name = spotlight.get("name")
slug = name_to_slug(name)
software_id = await slug_to_id(client, slug)
logging.info("Add research field for %s", name)
kw_id = await get_id_for_keyword(client, research_field)
if kw_id is None:
logging.info("Adding research field %s" % research_field)
res = await client.from_("keyword").insert({"value": research_field}).execute()
logging.info(res.data)
kw_id = await get_id_for_keyword(client, research_field)
res = (
await client.from_("keyword_for_software")
.insert({"software": software_id, "keyword": kw_id})
.execute()
)
logging.info(res.data)
async def process_imprint(client):
filename = "./resources/Imprint.md"
with open(filename, "r") as imprint:
logging.info("Processing imprint from %s", filename)
data = {
"slug": "imprint",
"title": "Imprint",
"description": imprint.read(),
"is_published": True,
"position": 1,
}
db_imprint = (
await client.from_("meta_pages").select("*").eq("slug", "imprint").execute()
)
if len(db_imprint.data) > 0 and not UPDATE_IMPRINT:
logging.info("Imprint already exists, but will not be updated.")
return
elif len(db_imprint.data) > 0 and UPDATE_IMPRINT:
logging.info("Imprint already exsits. Updating.")
res = await client.from_("meta_pages").update(data).execute()
else:
logging.info("Imprint not found. Creating.")
res = await client.from_("meta_pages").insert(data).execute()
logging.info(res.data)
def check_env():
errors = 0
if not POSTGREST_URL:
errors += 1
logging.error("POSTGREST_URL undefined.")
if not PGRST_JWT_SECRET:
errors += 1
logging.error("PGRST_JWT_SECRET undefined.")
if errors > 0:
raise RuntimeError("Environment variables are missing.")
logging.info("Runtime variables checked.")
async def main():
check_env()
token = jwt.encode(JWT_PAYLOAD, PGRST_JWT_SECRET, algorithm=JWT_ALGORITHM)
spotlights = get_spotlights()
created_spotlights = []
skipped_errors = []
skipped_no_update = []
async with AsyncPostgrestClient(POSTGREST_URL) as client:
client.auth(token=token)
# await process_imprint(client)
for spot in spotlights:
# check if spotlight matches our criteria
if len(spot.get("description", "")) > 10000:
skipped_errors.append([spot.get("name"), "Description too long."])
continue
already_exists = await spotlight_exists(client, spot)
if already_exists and DELETE_SPOTLIGHTS:
# update existing -> remove first
await remove_spotlight(client, spot)
elif already_exists and not DELETE_SPOTLIGHTS:
skipped_no_update.append(spot.get("name"))
continue
await add_spotlight(client, spot)
await add_spotlight_urls(client, spot)
await add_license(client, spot)
await add_keywords(client, spot)
await add_research_field(client, spot)
await add_organisations(client, spot)
created_spotlights.append(spot.get("name"))
if len(created_spotlights) == 0:
print("No new spotlights created.")
else:
print("The following spotlights were created:")
for name in created_spotlights:
print(" %s" % name)
if len(skipped_no_update) > 0:
print("The following spoltights already existed and were not updated:")
for name in skipped_no_update:
print(" %s" % name)
if len(skipped_errors) > 0:
print("The following spotlights were skipped because there were errors:")
for name, reason in skipped_errors:
print(" %s: %s" % (name, reason))
if len(MISSING_LOGOS) > 0:
print("There were logos missing of the following organisations:")
for org in MISSING_LOGOS:
print(" %s" % org)
def init_parser() -> argparse.ArgumentParser:
parser = argparse.ArgumentParser(
description="Migrate Software spotlights from a local file path to the RSD.",
usage="%(prog)s [OPTION] PATH",
)
parser.add_argument(
"-d",
"--delete_all",
action="store_true",
help="Delete all spotlights and overwrite with current versions.",
)
parser.add_argument(
"-i",
"--update_imprint",
action="store_true",
help="Update imprint if it already exists.",
)
parser.add_argument(
"-v", "--verbose", action="store_true", help="Increase verbosity."
)
parser.add_argument("PATH", help="The file path where to find the spotlights.")
return parser
if __name__ == "__main__":
mdparser = init_parser()
args = mdparser.parse_args()
DELETE_SPOTLIGHTS = args.delete_all
UPDATE_IMPRINT = args.update_imprint
SPOTLIGHTS_DIR = args.PATH
if args.verbose:
logging.basicConfig(level=logging.INFO)
else:
logging.basicConfig(level=logging.WARN)
asyncio.run(main())