forked from libis/rdm-integration
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathcdi_generator_jsonld.py
More file actions
1808 lines (1536 loc) · 64.5 KB
/
cdi_generator_jsonld.py
File metadata and controls
1808 lines (1536 loc) · 64.5 KB
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 python3
# ----------------------------- requirements.txt -----------------------------
# rdflib==7.0.0
# chardet==5.2.0
# datasketch==1.5.9
# python-dateutil==2.9.0.post0
# ---------------------------------------------------------------------------
"""
CSV/TSV -> DDI-CDI JSON-LD generation utilities.
- Streams large tabular files row-by-row; never loads the whole file.
- Infers per-column XSD datatype and a role (identifier/dimension/measure/attribute).
- Uses HyperLogLog (datasketch) to approximate distinct counts with tiny memory.
- Emits DDI-CDI 1.0 compliant JSON-LD with official context.
- Processes dataset manifests that describe multiple files at once.
USAGE
------
python cdi_generator_jsonld.py \\
--manifest /tmp/manifest.json \\
--output /tmp/dataset.cdi.jsonld \\
--quiet
Manifest JSON format:
{
"dataset_pid": "doi:10.70122/FK2/EXAMPLE",
"dataset_uri_base": "https://rdr.kuleuven.be/dataset",
"dataset_title": "Example dataset",
"dataset_metadata_path": "/path/to/metadata.json", // optional
"files": [
{
"csv_path": "/data/file1.csv",
"file_name": "file1.csv",
"file_uri": "https://example.org/api/access/datafile/123",
"ddi_path": "/path/to/file1_ddi.xml", // optional
"header": "auto", // "auto", "present", or "absent"
"delimiter": ",", // optional, sniffed if not provided
"encoding": "utf-8", // optional, detected if not provided
"skip_md5": false,
"allow_xconvert": true
}
]
}
Notes
-----
- Header auto-detects by default.
- Encoding is detected on a sample via chardet; override in manifest if needed.
- Delimiter is sniffed unless provided in manifest.
- Output is JSON-LD with official DDI-CDI 1.0 context.
"""
from __future__ import annotations
import argparse
import csv
import hashlib
import json
import logging
import re
import sys
from pathlib import Path
from typing import Any, List, Optional, Dict, Tuple, Union
import xml.etree.ElementTree as ET
import chardet
from datasketch import HyperLogLog
from dateutil import parser as dateparser
# ---- Official DDI-CDI 1.0 JSON-LD Context URL ----
DDI_CDI_CONTEXT = "https://ddi-cdi.github.io/m2t-ng/DDI-CDI_1-0/encoding/json-ld/ddi-cdi.jsonld"
# ---- Generator Version (increment when making changes to track generated files) ----
GENERATOR_VERSION = "0.8"
# ---- DDI Controlled Vocabulary Data Types ----
DDI_DATATYPE_CV = "http://rdf-vocabulary.ddialliance.org/cv/DataType/1.1.2/#"
# Mapping from XSD types to DDI CV data types
XSD_TO_DDI_DATATYPE = {
"integer": f"{DDI_DATATYPE_CV}Integer",
"decimal": f"{DDI_DATATYPE_CV}Double",
"double": f"{DDI_DATATYPE_CV}Double",
"boolean": f"{DDI_DATATYPE_CV}Boolean",
"date": f"{DDI_DATATYPE_CV}Date",
"dateTime": f"{DDI_DATATYPE_CV}DateTime",
"string": f"{DDI_DATATYPE_CV}String",
}
# Mapping from inferred roles to DDI-CDI component types
ROLE_TO_COMPONENT_TYPE = {
"identifier": "IdentifierComponent",
"measure": "MeasureComponent",
"dimension": "DimensionComponent",
"attribute": "AttributeComponent",
}
# -------------------------- Streaming type inference --------------------------
MISSING = {"", "na", "n/a", "null", "none", "nan", "NA", "N/A", "NULL", "None", "NaN"}
def is_int(s: str) -> bool:
"""Check if string represents an integer."""
try:
int(s)
return True
except (ValueError, TypeError):
return False
def is_float(s: str) -> bool:
"""Check if string represents a float (but not an integer)."""
try:
float(s)
return not is_int(s)
except (ValueError, TypeError):
return False
def is_bool(s: str) -> bool:
"""Check if string represents a boolean value."""
return s.lower() in {"true", "false", "t", "f", "0", "1", "yes", "no", "y", "n"}
def is_datetime(s: str) -> bool:
"""Check if string represents a datetime value."""
try:
dateparser.parse(s, fuzzy=False)
return True
except (ValueError, TypeError, OverflowError):
return False
class ColumnStats:
"""
Holds streaming stats for a single column to infer:
- xsd datatype (integer/decimal/boolean/dateTime/string)
- distinct count (approx via HLL)
- role (identifier/dimension/measure/attribute)
"""
__slots__ = (
"name",
"n_non_missing",
"n_rows",
"hll",
"could_be_int",
"could_be_float",
"could_be_bool",
"could_be_datetime",
)
def __init__(self, name: str):
self.name = name
self.n_non_missing = 0
self.n_rows = 0
self.hll = HyperLogLog(p=12)
self.could_be_int = True
self.could_be_float = True
self.could_be_bool = True
self.could_be_datetime = True
def update(self, raw: Optional[str]):
self.n_rows += 1
if raw is None:
return
s = raw.strip()
if s in MISSING:
return
self.n_non_missing += 1
self.hll.update(s.encode("utf-8", "ignore"))
if self.could_be_int and not is_int(s):
self.could_be_int = False
if self.could_be_float and not (is_float(s) or is_int(s)):
self.could_be_float = False
if self.could_be_bool and not is_bool(s):
self.could_be_bool = False
if self.could_be_datetime and not is_datetime(s):
self.could_be_datetime = False
def xsd_datatype_name(self) -> str:
"""Return XSD datatype name (without namespace)."""
if self.could_be_int and self.n_non_missing > 0:
return "integer"
if self.could_be_float and self.n_non_missing > 0:
return "decimal"
if self.could_be_bool and self.n_non_missing > 0:
return "boolean"
if self.could_be_datetime and self.n_non_missing > 0:
return "dateTime"
return "string"
def ddi_datatype_uri(self) -> str:
"""Return DDI CV datatype URI."""
return XSD_TO_DDI_DATATYPE.get(self.xsd_datatype_name(), f"{DDI_DATATYPE_CV}String")
def approx_distinct(self) -> int:
return int(self.hll.count())
def role(self) -> str:
"""
Heuristic role inference:
- identifier: ~unique column (>= 95% distinct among non-missing)
- measure: numeric (int/decimal) non-unique
- dimension: low cardinality text or boolean
- attribute: everything else
"""
if self.n_non_missing == 0:
return "attribute"
distinct = self.approx_distinct()
uniq_ratio = distinct / max(1, self.n_non_missing)
if uniq_ratio >= 0.95 and self.n_non_missing >= 50:
return "identifier"
dt = self.xsd_datatype_name()
if dt in ("integer", "decimal") and uniq_ratio < 0.95:
return "measure"
if dt == "boolean" or distinct <= min(50, int(0.1 * self.n_non_missing)):
return "dimension"
return "attribute"
# ------------------------------ CSV streaming core ------------------------------
def setup_logging(verbose: bool = False, quiet: bool = False) -> None:
"""Set up logging configuration."""
if quiet:
level = logging.WARNING
else:
level = logging.DEBUG if verbose else logging.INFO
logging.basicConfig(
level=level,
format='%(asctime)s - %(levelname)s - %(message)s',
datefmt='%Y-%m-%d %H:%M:%S'
)
def detect_encoding(path: Path, sample_bytes: int = 1024 * 1024) -> str:
"""Detect file encoding using chardet."""
logging.info(f"Detecting encoding for {path}")
try:
with path.open("rb") as f:
raw = f.read(sample_bytes)
res = chardet.detect(raw)
encoding = (res.get("encoding") or "utf-8").lower()
confidence = res.get("confidence", 0)
logging.info(f"Detected encoding: {encoding} (confidence: {confidence:.2f})")
return encoding
except Exception as e:
logging.warning(f"Error detecting encoding: {e}. Using UTF-8 as fallback.")
return "utf-8"
def detect_dialect(path: Path, encoding: str, sample_bytes: int = 256 * 1024) -> csv.Dialect:
"""Detect CSV dialect (delimiter, quoting, etc.)."""
logging.info("Detecting CSV dialect")
try:
with path.open("rb") as fb:
raw = fb.read(sample_bytes)
text = raw.decode(encoding, errors="replace")
sniffer = csv.Sniffer()
dialect = sniffer.sniff(text)
logging.info(f"Detected delimiter: '{dialect.delimiter}', quotechar: '{dialect.quotechar}'")
return dialect
except Exception as e:
logging.warning(f"Error detecting CSV dialect: {e}. Using defaults.")
class _D(csv.Dialect):
delimiter = ","
quotechar = '"'
doublequote = True
skipinitialspace = False
lineterminator = "\n"
quoting = csv.QUOTE_MINIMAL
return _D()
def detect_header_mode(
path: Path,
encoding: str,
dialect: csv.Dialect,
sample_bytes: int = 256 * 1024,
typed_threshold: float = 0.75,
) -> bool:
"""Heuristically determine whether the file has a header row."""
sample_text = ""
try:
with path.open("r", encoding=encoding, errors="replace", newline="") as f:
sample_text = f.read(sample_bytes)
except Exception as exc:
logging.debug("Failed to read sample for header detection: %s", exc)
sniffed_header = True
if sample_text.strip():
try:
sniffer = csv.Sniffer()
sniffed_header = sniffer.has_header(sample_text)
except Exception as exc:
logging.debug("csv.Sniffer header detection failed: %s", exc)
first_row: List[str] = []
try:
with path.open("r", encoding=encoding, errors="replace", newline="") as f:
reader = csv.reader(f, dialect)
first_row = next(reader)
except StopIteration:
logging.debug("File %s appears to be empty during header detection", path)
return False
except Exception as exc:
logging.debug("Failed to analyse first rows for header detection: %s", exc)
return sniffed_header
typed_cells = 0
total_cells = 0
for cell in first_row:
value = cell.strip()
if not value:
continue
total_cells += 1
if is_int(value) or is_float(value) or is_bool(value) or is_datetime(value):
typed_cells += 1
if total_cells:
ratio = typed_cells / total_cells
else:
ratio = 0.0
looks_like_data_row = ratio >= typed_threshold
if looks_like_data_row:
logging.info(
"Header auto-detect: first row of %s resembles data (typed_ratio=%.2f); treating as no header",
path,
ratio,
)
return False
return sniffed_header
def md5sum(path: Path, chunk: int = 1024 * 1024) -> str:
"""Calculate MD5 hash of file."""
logging.info(f"Calculating MD5 hash for {path}")
h = hashlib.md5()
try:
with path.open("rb") as f:
for b in iter(lambda: f.read(chunk), b""):
h.update(b)
return h.hexdigest()
except Exception as e:
logging.error(f"Error calculating MD5 hash: {e}")
return ""
def safe_fragment(s: str) -> str:
"""Convert string to safe URI fragment identifier."""
frag = re.sub(r"[^A-Za-z0-9_\-]", "_", s.strip())
if not frag:
frag = "unnamed"
return frag
def stream_profile_csv(
path: Path,
encoding: Optional[str] = None,
delimiter: Optional[str] = None,
header: Union[bool, str] = "auto",
limit_rows: Optional[int] = None,
compute_md5: bool = True,
) -> Tuple[List[str], List[ColumnStats], Dict[str, int], Optional[str], csv.Dialect]:
"""
Stream the CSV once and build column stats.
Returns: (column_names, stats[], row_count_info, file_md5, dialect)
"""
logging.info(f"Starting to profile CSV: {path}")
if not path.exists():
raise FileNotFoundError(f"CSV file not found: {path}")
if path.stat().st_size == 0:
raise ValueError(f"CSV file is empty: {path}")
enc = encoding or detect_encoding(path)
dialect = detect_dialect(path, enc)
if delimiter:
dialect.delimiter = delimiter
logging.info(f"Using forced delimiter: '{delimiter}'")
if compute_md5:
file_md5 = md5sum(path)
else:
logging.info("Skipping MD5 hash calculation as requested")
file_md5 = None
try:
with path.open("r", encoding=enc, errors="replace", newline="") as f:
reader = csv.reader(f, dialect)
header_decision: bool
auto_detect = False
if isinstance(header, str):
header_key = header.lower()
if header_key == "auto":
auto_detect = True
elif header_key in {"present", "true", "yes"}:
header_decision = True
elif header_key in {"absent", "false", "no"}:
header_decision = False
else:
raise ValueError(f"Invalid header mode: {header}")
else:
header_decision = bool(header)
if auto_detect:
header_decision = detect_header_mode(path, enc, dialect)
logging.info("Header auto-detection result for %s: %s", path, header_decision)
if header_decision:
try:
columns = next(reader)
logging.info(f"Found {len(columns)} columns in header")
except StopIteration:
raise RuntimeError("Empty CSV; no header row found.")
else:
try:
first_row = next(reader)
columns = [f"col_{i+1}" for i in range(len(first_row))]
logging.info(f"No header specified, auto-generated {len(columns)} column names")
f.seek(0)
reader = csv.reader(f, dialect)
except StopIteration:
raise RuntimeError("Empty CSV; no data rows found.")
stats = [ColumnStats(name.strip() or f"col_{i+1}") for i, name in enumerate(columns)]
data_rows_processed = 0
for row in reader:
if len(row) < len(columns):
row += [""] * (len(columns) - len(row))
elif len(row) > len(columns):
row = row[: len(columns)]
for i, val in enumerate(row):
stats[i].update(val)
data_rows_processed += 1
if data_rows_processed % 10000 == 0:
logging.info(f"Processed {data_rows_processed} rows...")
if limit_rows and data_rows_processed >= limit_rows:
logging.info(f"Reached row limit of {limit_rows}")
break
logging.info(f"Finished profiling. Processed {data_rows_processed} data rows.")
return columns, stats, {"rows_read": data_rows_processed}, file_md5, dialect
except UnicodeDecodeError as e:
raise ValueError(f"Error decoding file with encoding '{enc}': {e}")
except Exception as e:
raise RuntimeError(f"Error processing CSV file: {e}")
# ------------------------------ DDI Metadata Loading ------------------------------
def _strip_ddi_tag(tag: str) -> str:
return tag.split('}', 1)[1] if '}' in tag else tag
def load_ddi_metadata(ddi_path: Path) -> Tuple[Optional[str], Dict[str, Dict[str, Any]], bool]:
"""Read and parse a DDI fragment, returning sanitized XML and per-variable metadata."""
try:
raw_bytes = ddi_path.read_bytes()
except OSError as exc:
logging.warning("Failed to read DDI file %s: %s", ddi_path, exc)
return None, {}, False
raw_text = raw_bytes.decode("utf-8", errors="replace")
try:
root = ET.fromstring(raw_text)
except ET.ParseError as exc:
logging.warning("Failed to parse DDI XML from %s: %s", ddi_path, exc)
return raw_text.strip(), {}, False
sanitized_xml = ET.tostring(root, encoding="unicode").strip()
variables: Dict[str, Dict[str, Any]] = {}
for var_elem in root.iter():
if _strip_ddi_tag(var_elem.tag) != "var":
continue
name = var_elem.attrib.get("name")
if not name:
continue
info: Dict[str, Any] = {
"label": None,
"categories": [],
"statistics": {},
}
for child in list(var_elem):
tag = _strip_ddi_tag(child.tag)
if tag == "labl" and child.text:
info["label"] = child.text.strip()
elif tag == "sumStat":
stat_type = child.attrib.get("type")
if stat_type and child.text:
info["statistics"][stat_type] = child.text.strip()
elif tag == "catgry":
cat_value: Optional[str] = None
cat_label: Optional[str] = None
for cat_child in list(child):
cat_tag = _strip_ddi_tag(cat_child.tag)
if cat_tag == "catValu" and cat_child.text:
cat_value = cat_child.text.strip()
elif cat_tag == "labl" and cat_child.text:
cat_label = cat_child.text.strip()
if cat_value:
info["categories"].append((cat_value, cat_label))
variables[name] = info
return sanitized_xml, variables, True
# ------------------------------ Dataverse Metadata Extraction ------------------------------
def load_metadata_from_file(path: Path) -> Optional[Dict[str, Any]]:
"""Load dataset metadata from a JSON file."""
if not path.exists():
return None
try:
return json.loads(path.read_text(encoding="utf-8"))
except Exception as exc:
logging.warning("Failed to parse metadata from %s: %s", path, exc)
return None
def extract_dataset_title(metadata: Dict[str, Any]) -> Optional[str]:
"""Pull dataset title from Dataverse-style metadata."""
dataset_version = metadata.get("datasetVersion") or metadata.get("latestVersion")
if not isinstance(dataset_version, dict):
return None
metadata_blocks = dataset_version.get("metadataBlocks")
if not isinstance(metadata_blocks, dict):
return None
citation_block = metadata_blocks.get("citation")
if not isinstance(citation_block, dict):
return None
fields = citation_block.get("fields")
if not isinstance(fields, list):
return None
for field in fields:
if not isinstance(field, dict):
continue
if field.get("typeName") != "title":
continue
value = field.get("value")
if isinstance(value, str):
return value
if isinstance(value, list) and value:
first = value[0]
if isinstance(first, str):
return first
return None
def extract_dataset_description(metadata: Dict[str, Any]) -> Optional[str]:
"""Extract dataset description from Dataverse-style metadata."""
dataset_version = metadata.get("datasetVersion") or metadata.get("latestVersion")
if not isinstance(dataset_version, dict):
return None
metadata_blocks = dataset_version.get("metadataBlocks")
if not isinstance(metadata_blocks, dict):
return None
citation_block = metadata_blocks.get("citation")
if not isinstance(citation_block, dict):
return None
fields = citation_block.get("fields")
if not isinstance(fields, list):
return None
for field in fields:
if not isinstance(field, dict):
continue
type_name = field.get("typeName")
if type_name not in ("dsDescription", "description"):
continue
value = field.get("value")
if isinstance(value, str):
return value
if isinstance(value, list) and value:
first = value[0]
if isinstance(first, str):
return first
if isinstance(first, dict):
desc_value = first.get("dsDescriptionValue") or first.get("value")
if isinstance(desc_value, dict):
return desc_value.get("value")
if isinstance(desc_value, str):
return desc_value
return None
def _get_citation_fields(metadata: Dict[str, Any]) -> Optional[List[Dict[str, Any]]]:
"""Get citation fields list from Dataverse metadata structure."""
dataset_version = metadata.get("datasetVersion") or metadata.get("latestVersion")
if not isinstance(dataset_version, dict):
return None
metadata_blocks = dataset_version.get("metadataBlocks")
if not isinstance(metadata_blocks, dict):
return None
citation_block = metadata_blocks.get("citation")
if not isinstance(citation_block, dict):
return None
fields = citation_block.get("fields")
return fields if isinstance(fields, list) else None
def _extract_field_value(fields: List[Dict[str, Any]], type_name: str) -> Optional[str]:
"""Extract a simple string value from Dataverse citation fields."""
for field in fields:
if not isinstance(field, dict):
continue
if field.get("typeName") != type_name:
continue
value = field.get("value")
if isinstance(value, str):
return value
if isinstance(value, list) and value:
first = value[0]
if isinstance(first, str):
return first
return None
def _extract_compound_list(
fields: List[Dict[str, Any]], type_name: str, sub_field: str
) -> List[str]:
"""Extract list of sub-field values from a compound Dataverse field."""
results: List[str] = []
for field in fields:
if not isinstance(field, dict):
continue
if field.get("typeName") != type_name:
continue
value = field.get("value")
if not isinstance(value, list):
continue
for item in value:
if not isinstance(item, dict):
continue
sub_val = item.get(sub_field)
if isinstance(sub_val, dict):
sub_val = sub_val.get("value")
if isinstance(sub_val, str) and sub_val.strip():
results.append(sub_val.strip())
return results
def extract_rich_metadata(metadata: Dict[str, Any]) -> Dict[str, Any]:
"""Extract comprehensive dataset metadata from Dataverse JSON.
Returns a dict with keys:
- title: str
- subtitle: str (alternative title)
- description: str (abstract/summary)
- authors: List[Dict] (name, affiliation, identifier)
- contributors: List[Dict]
- publisher: str
- publication_date: str (ISO format)
- keywords: List[str]
- subjects: List[str]
- language: str
- license_name: str
- license_uri: str
- related_publications: List[str]
- grant_numbers: List[str]
- depositor: str
- date_of_deposit: str
- production_date: str
- distribution_date: str
"""
result: Dict[str, Any] = {}
fields = _get_citation_fields(metadata)
if not fields:
return result
# Title
result["title"] = _extract_field_value(fields, "title")
# Subtitle (alternative title)
result["subtitle"] = _extract_field_value(fields, "subtitle")
# Alternative title
alt_titles = _extract_compound_list(fields, "alternativeTitle", "alternativeTitleValue")
if alt_titles:
result["alternative_title"] = alt_titles[0]
# Authors with affiliation and identifier
authors: List[Dict[str, Any]] = []
for field in fields:
if not isinstance(field, dict):
continue
if field.get("typeName") != "author":
continue
value = field.get("value")
if not isinstance(value, list):
continue
for item in value:
if not isinstance(item, dict):
continue
author: Dict[str, Any] = {}
name_val = item.get("authorName")
if isinstance(name_val, dict):
name_val = name_val.get("value")
if name_val:
author["name"] = name_val
affil_val = item.get("authorAffiliation")
if isinstance(affil_val, dict):
affil_val = affil_val.get("value")
if affil_val:
author["affiliation"] = affil_val
ident_scheme = item.get("authorIdentifierScheme")
if isinstance(ident_scheme, dict):
ident_scheme = ident_scheme.get("value")
ident_val = item.get("authorIdentifier")
if isinstance(ident_val, dict):
ident_val = ident_val.get("value")
if ident_val:
author["identifier"] = ident_val
if ident_scheme:
author["identifier_scheme"] = ident_scheme
if author:
authors.append(author)
if authors:
result["authors"] = authors
# Contributors (similar structure)
contributors: List[Dict[str, Any]] = []
for field in fields:
if not isinstance(field, dict):
continue
if field.get("typeName") != "contributor":
continue
value = field.get("value")
if not isinstance(value, list):
continue
for item in value:
if not isinstance(item, dict):
continue
contrib: Dict[str, Any] = {}
name_val = item.get("contributorName")
if isinstance(name_val, dict):
name_val = name_val.get("value")
if name_val:
contrib["name"] = name_val
type_val = item.get("contributorType")
if isinstance(type_val, dict):
type_val = type_val.get("value")
if type_val:
contrib["type"] = type_val
if contrib:
contributors.append(contrib)
if contributors:
result["contributors"] = contributors
# Publisher
result["publisher"] = _extract_field_value(fields, "distributorName")
if not result.get("publisher"):
result["publisher"] = _extract_field_value(fields, "publisher")
# Contact (as backup publisher info)
contacts = _extract_compound_list(fields, "datasetContact", "datasetContactName")
if contacts and not result.get("publisher"):
result["publisher"] = contacts[0]
# Publication/Distribution date
result["publication_date"] = _extract_field_value(fields, "distributionDate")
if not result.get("publication_date"):
result["publication_date"] = _extract_field_value(fields, "dateOfDeposit")
# Production date
result["production_date"] = _extract_field_value(fields, "productionDate")
# Keywords
keywords = _extract_compound_list(fields, "keyword", "keywordValue")
if keywords:
result["keywords"] = keywords
# Subjects
subjects: List[str] = []
for field in fields:
if not isinstance(field, dict):
continue
if field.get("typeName") != "subject":
continue
value = field.get("value")
if isinstance(value, str):
subjects.append(value)
elif isinstance(value, list):
for v in value:
if isinstance(v, str):
subjects.append(v)
if subjects:
result["subjects"] = subjects
# Language
for field in fields:
if not isinstance(field, dict):
continue
if field.get("typeName") != "language":
continue
value = field.get("value")
if isinstance(value, str):
result["language"] = value
elif isinstance(value, list) and value:
result["language"] = value[0] if isinstance(value[0], str) else None
# License
dataset_version = metadata.get("datasetVersion") or metadata.get("latestVersion")
if isinstance(dataset_version, dict):
license_info = dataset_version.get("license")
if isinstance(license_info, dict):
result["license_name"] = license_info.get("name")
result["license_uri"] = license_info.get("uri")
terms = dataset_version.get("termsOfUse")
if isinstance(terms, str):
result["terms_of_use"] = terms
# Related publications
related_pubs = _extract_compound_list(fields, "publication", "publicationCitation")
if related_pubs:
result["related_publications"] = related_pubs
# Related materials (URLs)
related_urls = _extract_compound_list(fields, "publication", "publicationURL")
if related_urls:
result["related_urls"] = related_urls
# Grant/Funding numbers
grants = _extract_compound_list(fields, "grantNumber", "grantNumberValue")
if grants:
result["grant_numbers"] = grants
# Funding agencies
funders = _extract_compound_list(fields, "grantNumber", "grantNumberAgency")
if funders:
result["funding_agencies"] = funders
# Depositor
result["depositor"] = _extract_field_value(fields, "depositor")
# Date of deposit
result["date_of_deposit"] = _extract_field_value(fields, "dateOfDeposit")
# Time period covered
time_period_start = _extract_compound_list(fields, "timePeriodCovered", "timePeriodCoveredStart")
time_period_end = _extract_compound_list(fields, "timePeriodCovered", "timePeriodCoveredEnd")
if time_period_start:
result["time_period_start"] = time_period_start[0]
if time_period_end:
result["time_period_end"] = time_period_end[0]
# Geographic coverage
geo_coverage = _extract_compound_list(fields, "geographicCoverage", "country")
if geo_coverage:
result["geographic_coverage"] = geo_coverage
return {k: v for k, v in result.items() if v} # Remove empty values
# ------------------------------ JSON-LD Graph Building ------------------------------
def _build_catalog_details(
rich_metadata: Dict[str, Any],
dataset_pid: Optional[str] = None,
) -> Dict[str, Any]:
"""Build a DDI-CDI CatalogDetails node from rich metadata.
This follows the SHACL shape for CatalogDetails which supports:
- title, subTitle, alternativeTitle
- summary (abstract)
- creator, contributor, publisher (as AgentInRole)
- date (CombinedDate)
- access (AccessInformation with license)
- languageOfObject
- provenance (with funding info)
- relatedResource
- identifier (InternationalIdentifier)
"""
catalog: Dict[str, Any] = {
"@id": "#catalogDetails",
"@type": "CatalogDetails",
}
# Title (InternationalString)
if rich_metadata.get("title"):
catalog["title"] = {
"@type": "InternationalString",
"languageSpecificString": {
"@type": "LanguageString",
"content": rich_metadata["title"],
}
}
# Subtitle
if rich_metadata.get("subtitle"):
catalog["subTitle"] = {
"@type": "InternationalString",
"languageSpecificString": {
"@type": "LanguageString",
"content": rich_metadata["subtitle"],
}
}
# Alternative title
if rich_metadata.get("alternative_title"):
catalog["alternativeTitle"] = {
"@type": "InternationalString",
"languageSpecificString": {
"@type": "LanguageString",
"content": rich_metadata["alternative_title"],
}
}
# Summary (description/abstract)
if rich_metadata.get("description"):
catalog["summary"] = {
"@type": "InternationalString",
"languageSpecificString": {
"@type": "LanguageString",
"content": rich_metadata["description"],
}
}
# Creators (authors as AgentInRole)
if rich_metadata.get("authors"):
creators: List[Dict[str, Any]] = []
for i, author in enumerate(rich_metadata["authors"]):
agent_id = f"#author_{i}"
agent_in_role: Dict[str, Any] = {
"@type": "AgentInRole",
"agent": {
"@id": agent_id,
"@type": "Individual",
}
}
# Build individual name (BibliographicName with affiliation)
if author.get("name"):
name_node: Dict[str, Any] = {
"@type": "BibliographicName",
"languageSpecificString": {
"@type": "LanguageString",
"content": author["name"],
}
}
if author.get("affiliation"):
name_node["affiliation"] = author["affiliation"]
agent_in_role["agent"]["individualName"] = name_node
# Add identifier (e.g., ORCID)
if author.get("identifier"):
ident_node: Dict[str, Any] = {
"@type": "Identifier",
}
ident_value = author["identifier"]
scheme = author.get("identifier_scheme", "")
if scheme.upper() == "ORCID" and not ident_value.startswith("http"):
ident_node["uri"] = f"https://orcid.org/{ident_value}"
else:
ident_node["uri"] = ident_value
agent_in_role["agent"]["identifier"] = ident_node
creators.append(agent_in_role)
if creators:
catalog["creator"] = creators
# Contributors
if rich_metadata.get("contributors"):
contributors: List[Dict[str, Any]] = []
for i, contrib in enumerate(rich_metadata["contributors"]):
agent_id = f"#contributor_{i}"
agent_in_role: Dict[str, Any] = {
"@type": "AgentInRole",
"agent": {