-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathapp.py
More file actions
2549 lines (2109 loc) · 94.6 KB
/
app.py
File metadata and controls
2549 lines (2109 loc) · 94.6 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
import base64
import logging
import os
import re
from io import BytesIO
from typing import Any, List, Optional, Tuple, Annotated
from urllib.parse import unquote, urlparse
from xmlrpc.client import Boolean
import requests
import uvicorn
import yaml
from fastapi import Body, FastAPI, HTTPException, Request, Query
from fastapi.middleware.cors import CORSMiddleware
from fastapi.responses import HTMLResponse, StreamingResponse, JSONResponse
from fastapi.encoders import jsonable_encoder
from fastapi.staticfiles import StaticFiles
from fastapi.templating import Jinja2Templates
from pydantic import AnyUrl, BaseModel, Field
from pyshacl import validate
from rdflib import Graph, Namespace, URIRef, BNode, Literal
from rdflib.namespace import CSVW, RDF, RDFS, PROV, XSD
from rdflib.util import guess_format
from starlette.middleware import Middleware
from starlette.middleware.sessions import SessionMiddleware
from starlette_wtf import StarletteForm
from starlette.background import BackgroundTask
from wtforms import BooleanField, URLField
from wtforms.validators import Optional as WTFOptional
from rmlmapper import count_rules_str, replace_data_source, replace_all_data_sources, strip_namespace
from enum import Enum
YARRRML_URL = os.environ.get("YARRRML_URL")
MAPPER_URL = os.environ.get("MAPPER_URL")
SSL_VERIFY = os.getenv("SSL_VERIFY", "True").lower() in ("true", "1", "t")
if not SSL_VERIFY:
requests.packages.urllib3.disable_warnings()
TEMPLATE_NAMESPACE = "http://template_base/"
import settings
setting = settings.Setting()
config_name = os.environ.get("APP_MODE", "production")
middleware = [
Middleware(
SessionMiddleware, secret_key=os.environ.get("APP_SECRET", "changemeNOW")
),
# Middleware(CSRFProtectMiddleware, csrf_secret=os.environ.get('APP_SECRET','changemeNOW')),
Middleware(
CORSMiddleware,
allow_origins=["*"], # Allows all origins
allow_methods=["*"], # Allows all methods
allow_headers=["*"], # Allows all headers
),
Middleware(
uvicorn.middleware.proxy_headers.ProxyHeadersMiddleware, trusted_hosts="*"
),
]
tags_metadata = [
{
"name": "convert",
"description": "Convert data to RDF or between mapping formats.",
},
{
"name": "validate",
"description": "Validate mappings or RDF graphs.",
},
{
"name": "debug",
"description": "Test and inspect mappings with detailed output.",
},
{
"name": "info",
"description": "Application configuration and status.",
},
]
app = FastAPI(
title=setting.name,
description=setting.desc,
version=setting.version,
contact={
"name": "Thomas Hanke, Mat-O-Lab",
"url": "https://github.com/Mat-O-Lab",
"email": setting.admin_email,
},
# contact={"name": setting.contact_name, "url": setting.org_site, "email": setting.admin_email},
license_info={
"name": "Apache 2.0",
"url": "https://www.apache.org/licenses/LICENSE-2.0.html",
},
openapi_url=setting.openapi_url,
openapi_tags=tags_metadata,
docs_url=setting.docs_url,
redoc_url=None,
swagger_ui_parameters={"syntaxHighlight": False},
# swagger_favicon_url="/static/resources/favicon.svg",
middleware=middleware,
root_path=setting.root_path or "",
servers=[
{"url": setting.server, "description": "Production environment"},
],
)
# Override OpenAPI schema generation to always use configured SERVER_URL
# This ensures Swagger UI generates correct URLs regardless of reverse proxy headers
def custom_openapi():
"""Override OpenAPI schema to force configured SERVER_URL.
This makes the app robust against reverse proxy configurations by
always using the explicitly configured SERVER_URL instead of trying
to detect it from X-Forwarded-* headers.
"""
if app.openapi_schema:
return app.openapi_schema
# Generate the default OpenAPI schema
from fastapi.openapi.utils import get_openapi
openapi_schema = get_openapi(
title=app.title,
version=app.version,
description=app.description,
routes=app.routes,
tags=app.openapi_tags,
servers=app.servers,
)
# Force the servers to always use configured SERVER_URL
# This overrides any automatic detection from request headers
openapi_schema["servers"] = [
{"url": setting.server, "description": "Production environment"}
]
app.openapi_schema = openapi_schema
return app.openapi_schema
app.openapi = custom_openapi
# Startup validation to ensure configuration is correct
@app.on_event("startup")
async def startup_validation():
"""Validate configuration on startup and log important settings."""
logging.info("=" * 80)
logging.info("RDFConverter Startup Configuration")
logging.info("=" * 80)
logging.info(f"App Name: {setting.name}")
logging.info(f"App Version: {setting.version}")
logging.info(f"App Mode: {setting.config_name}")
logging.info(f"SERVER_URL: {setting.server}")
logging.info(f"ROOT_PATH: {setting.root_path or '(empty)'}")
logging.info(f"OpenAPI docs: {setting.server}{setting.docs_url}")
# Warn about potential security issues
if setting.server.startswith("http://") and "localhost" not in setting.server and "127.0.0.1" not in setting.server:
logging.warning("⚠️ SERVER_URL uses HTTP for non-localhost - consider using HTTPS for production")
# Validate internal services
try:
logging.info(f"YARRRML Parser URL: {YARRRML_URL}")
logging.info(f"RML Mapper URL: {MAPPER_URL}")
except Exception as e:
logging.error(f"Error checking internal services: {e}")
logging.info("=" * 80)
app.mount("/static/", StaticFiles(directory="static", html=True), name="static")
templates = Jinja2Templates(directory="templates")
# flash integration flike flask flash
def flash(request: Request, message: Any, category: str = "info") -> None:
if "_messages" not in request.session:
request.session["_messages"] = []
request.session["_messages"].append({"message": message, "category": category})
def get_flashed_messages(request: Request):
return request.session.pop("_messages") if "_messages" in request.session else []
templates.env.globals["get_flashed_messages"] = get_flashed_messages
OBO = Namespace("http://purl.obolibrary.org/obo/")
MSEO_URL = "http://purl.matolab.org/mseo/mid/"
CCO_URL = "https://github.com/CommonCoreOntology/CommonCoreOntologies/raw/master/cco-merged/MergedAllCoreOntology-v1.3-2021-03-01.ttl"
MSEO = Namespace(MSEO_URL)
CCO = Namespace("http://www.ontologyrepository.com/CommonCoreOntologies/")
CSVW = Namespace("http://www.w3.org/ns/csvw#")
OA = Namespace("http://www.w3.org/ns/oa#")
QUDT = Namespace("http://qudt.org/schema/qudt/")
QUNIT = Namespace("http://qudt.org/vocab/unit/")
IOF = Namespace("https://spec.industrialontologies.org/ontology/core/Core/")
# RDF = Namespace('http://www.w3.org/2000/01/rdf-schema#')
class ReturnType(str, Enum):
jsonld = "json-ld"
n3 = "n3"
# nquads="nquads" #only makes sense for context-aware stores
nt = "nt"
hext = "hext"
# prettyxml="pretty-xml" #only makes sense for context-aware stores
trig = "trig"
# trix="trix" #only makes sense for context-aware stores
turtle = "turtle"
longturtle = "longturtle"
xml = "xml"
@classmethod
def get(cls, format):
for member in cls:
if format.lower() == member.value.lower():
return member
raise ValueError(f"Invalid Return type: {format}")
RETURN_TYPE_EXT = {
"turtle": ".ttl",
"longturtle": ".ttl",
"json-ld": ".jsonld",
"xml": ".rdf",
"n3": ".n3",
"nt": ".nt",
"trig": ".trig",
"hext": ".hext",
}
class RDFMimeType(str, Enum):
xml = "application/rdf+xml"
turtle = "text/turtle"
n3 = "application/n-triples"
nquads = "application/n-quads"
jsonld = "application/ld+json"
@classmethod
def get(cls, format):
for member in cls:
if format.lower() == member.value.lower():
return member
raise ValueError(f"Invalid Return type: {format}")
class RDFStreamingResponse(StreamingResponse):
def __init__(
self,
content,
filename: str,
status_code: int = 200,
background: Optional[BackgroundTask] = None,
):
headers = {
"Content-Disposition": "attachment; filename={}".format(filename),
"Access-Control-Expose-Headers": "Content-Disposition",
}
media_type = RDFMimeType[ReturnType.get(guess_format(filename)).name].value
super(RDFStreamingResponse, self).__init__(
content, status_code, headers, media_type
)
def replace_between(
text: str, begin: str = "", end: str = "", alternative: str = ""
) -> str:
if not (begin and end):
raise ValueError
return re.sub(
r"{}.*?{}".format(re.escape(begin), re.escape(end)), alternative, text
)
def open_file(uri: AnyUrl, authorization=None) -> Tuple["filedata":str, "filename":str]:
try:
uri_parsed = urlparse(uri)
# print(uri_parsed)
except Exception as e:
raise HTTPException(
status_code=400,
detail=f"{uri} is not a valid URI - if local file add file:// as prefix. Error: {str(e)}",
) from e
else:
if uri_parsed.scheme in ["https", "http"]:
# r = urlopen(uri)
s = requests.Session()
s.verify = SSL_VERIFY
s.headers.update({"Authorization": authorization})
r = s.get(uri, allow_redirects=True, stream=True)
# r.raise_for_status()
if r.status_code != 200:
# logging.debug(r.content)
raise HTTPException(
status_code=r.status_code, detail="cant get file at {}".format(uri)
)
filedata = r.content
# Extract filename from the FINAL URL after redirects, not the original URL
final_url = r.url
final_url_parsed = urlparse(final_url)
filename = unquote(final_url_parsed.path).rsplit("/download/upload")[0].split("/")[-1]
logging.debug(f"Original URL: {uri}")
logging.debug(f"Final URL after redirects: {final_url}")
logging.debug(f"Extracted filename: {filename}")
# charset=r.info().get_content_charset()
# if not charset:
# charset='utf-8'
# filedata = r.read().decode(charset)
elif uri_parsed.scheme == "file":
filedata = open(unquote(uri_parsed.path), "rb").read()
else:
raise HTTPException(
status_code=400, detail="unknown scheme {}".format(uri_parsed.scheme)
)
return filedata, filename
from datetime import datetime
from jsonpath_ng import parse as jsonpath_parse
from jsonpath_ng.exceptions import JsonPathParserError
# ============================================================================
# CONDITION EVALUATION FOR YARRRML MAPPINGS
# ============================================================================
def normalize_function_name(function_ref: str, prefixes: dict) -> str:
"""
Normalize function reference to standard name.
Handles three formats:
- Short name: "equal"
- Prefixed: "idlab-fn:equal"
- Full IRI: "https://w3id.org/imec/idlab/function#equal"
Args:
function_ref: Function reference from YARRRML condition
prefixes: Dict of prefix -> namespace mappings
Returns:
Normalized function name (e.g., "equal", "notEqual", etc.)
"""
# If it's already a short name, return it
if ":" not in function_ref and "/" not in function_ref:
return function_ref
# Handle prefixed format (e.g., "idlab-fn:equal")
if ":" in function_ref and "/" not in function_ref:
prefix, local_name = function_ref.split(":", 1)
return local_name
# Handle full IRI - extract last part after # or /
if "#" in function_ref:
return function_ref.split("#")[-1]
elif "/" in function_ref:
return function_ref.split("/")[-1]
return function_ref
def extract_jsonpath_value(jsonpath_expr: str, data_item: dict) -> any:
"""
Extract value from data item using JSONPath expression.
Args:
jsonpath_expr: JSONPath expression like "$(label)" or "$.id"
data_item: Dictionary to extract value from
Returns:
Extracted value or None if not found
"""
# Remove $() wrapper if present - convert $(label) to $.label
if jsonpath_expr.startswith("$(") and jsonpath_expr.endswith(")"):
field_name = jsonpath_expr[2:-1]
jsonpath_expr = f"$.{field_name}"
# If it's just a literal value (not starting with $), return as-is
if not jsonpath_expr.startswith("$"):
return jsonpath_expr
try:
jsonpath_expression = jsonpath_parse(jsonpath_expr)
matches = jsonpath_expression.find(data_item)
if matches:
# Return first match value
return matches[0].value
return None
except JsonPathParserError as e:
logging.warning(f"JSONPath parse error for '{jsonpath_expr}': {e}")
return None
except Exception as e:
logging.warning(f"Error extracting JSONPath value for '{jsonpath_expr}': {e}")
return None
def evaluate_fno_function(function_name: str, parameters: dict) -> bool:
"""
Evaluate an FnO function with given parameters.
Args:
function_name: Normalized function name (e.g., "equal", "notEqual")
parameters: Dict of parameter name -> value
Returns:
Boolean result of function evaluation
"""
# Get common parameter names
str1 = parameters.get("str1") or parameters.get("grel:valueParam") or parameters.get("valueParam")
str2 = parameters.get("str2") or parameters.get("grel:valueParam2") or parameters.get("valueParam2")
# Convert to strings for comparison (handle None)
str1 = str(str1) if str1 is not None else ""
str2 = str(str2) if str2 is not None else ""
if function_name == "equal":
result = str1 == str2
logging.debug(f" equal('{str1}', '{str2}') = {result}")
return result
elif function_name == "notEqual":
result = str1 != str2
logging.debug(f" notEqual('{str1}', '{str2}') = {result}")
return result
elif function_name == "stringContainsOtherString":
other_str = parameters.get("otherStr") or parameters.get("idlab-fn:_otherStr")
delimiter = parameters.get("delimiter") or parameters.get("idlab-fn:_delimiter", ",")
if not other_str:
return False
# Split str1 by delimiter and check if other_str is in the list
parts = str1.split(delimiter)
result = other_str in parts
logging.debug(f" stringContainsOtherString('{str1}', '{other_str}', delimiter='{delimiter}') = {result}")
return result
elif function_name == "listContainsElement":
list_param = parameters.get("list") or parameters.get("idlab-fn:_list")
str_param = parameters.get("str") or parameters.get("idlab-fn:_str")
if not list_param or not str_param:
return False
# list_param might be a string representation or actual list
if isinstance(list_param, str):
# Try to split by common delimiters
list_items = list_param.split(",")
elif isinstance(list_param, list):
list_items = list_param
else:
return False
result = str_param in list_items
logging.debug(f" listContainsElement({list_items}, '{str_param}') = {result}")
return result
elif function_name == "isNull":
str_param = parameters.get("str") or parameters.get("idlab-fn:_str") or str1
result = str_param is None or str_param == "" or str_param == "null"
logging.debug(f" isNull('{str_param}') = {result}")
return result
elif function_name == "inRange":
test_val = parameters.get("test") or parameters.get("idlab-fn:_test")
from_val = parameters.get("from") or parameters.get("idlab-fn:_from")
to_val = parameters.get("to") or parameters.get("idlab-fn:_to")
try:
test_num = float(test_val) if test_val is not None else None
from_num = float(from_val) if from_val is not None else None
to_num = float(to_val) if to_val is not None else None
if test_num is None or from_num is None or to_num is None:
return False
result = from_num <= test_num <= to_num
logging.debug(f" inRange({test_num}, {from_num}, {to_num}) = {result}")
return result
except (ValueError, TypeError):
return False
else:
# Unknown function - log warning and return True (permissive)
logging.warning(f"Unknown FnO function '{function_name}' - assuming true")
return True
def evaluate_condition(condition_dict: dict, data_item: dict, prefixes: dict) -> bool:
"""
Evaluate a YARRRML condition against a data item.
Args:
condition_dict: Condition from YARRRML mapping
Example: {
"function": "equal",
"parameters": [
["str1", "$(label)"],
["str2", "aktuelle Probe"]
]
}
data_item: Single JSON object from iterator
prefixes: Dict of prefix -> namespace URL mappings
Returns:
True if condition evaluates to true, False otherwise
"""
if not condition_dict:
# No condition means always applicable
return True
function_ref = condition_dict.get("function")
if not function_ref:
logging.warning("Condition missing 'function' field - assuming true")
return True
# Normalize function name
function_name = normalize_function_name(function_ref, prefixes)
# Extract parameters
param_list = condition_dict.get("parameters", [])
parameters = {}
for param in param_list:
if isinstance(param, list) and len(param) == 2:
param_name = param[0]
param_value = param[1]
# Extract actual value if it's a JSONPath expression
actual_value = extract_jsonpath_value(param_value, data_item)
parameters[param_name] = actual_value
# Evaluate the function
return evaluate_fno_function(function_name, parameters)
# ============================================================================
# HELPER FUNCTIONS - Parameter Resolution
# ============================================================================
def validate_iterator(iterator: str, source_name: str = "") -> tuple[bool, str]:
"""
Validate if an iterator pattern is supported.
Args:
iterator: JSONPath iterator string from YARRRML source
source_name: Name of the source (for better error messages)
Returns:
Tuple of (is_valid, error_message)
- is_valid: True if supported, False if unsupported
- error_message: Empty string if valid, descriptive error if invalid
"""
# Check for unsupported pattern: $..[*]
if iterator == "$..[*]":
source_info = f" in source '{source_name}'" if source_name else ""
return False, (
f"Unsupported iterator '$..[*]'{source_info}. "
f"This iterator pattern (recursive descent with wildcard array) is too ambiguous. "
f"Please use a specific path like '$.notes[*]', '$.columns[*]', or '$.items[*]' instead."
)
# Check for other potentially problematic patterns
# Add more validations here as needed
return True, ""
def validate_mapping_sources(mapping_dict: dict) -> tuple[bool, str, int]:
"""
Validate all source iterators in a YARRRML mapping.
Args:
mapping_dict: Parsed YARRRML mapping dictionary
Returns:
Tuple of (is_valid, error_message, num_rules)
- is_valid: True if all iterators are valid
- error_message: Empty if valid, descriptive error if invalid
- num_rules: Total number of mapping rules defined
"""
sources = mapping_dict.get("sources", {})
num_rules = len(mapping_dict.get("mappings", {}))
for source_name, source_def in sources.items():
if isinstance(source_def, dict):
iterator = source_def.get("iterator", "")
if iterator:
is_valid, error_msg = validate_iterator(iterator, source_name)
if not is_valid:
return False, error_msg, num_rules
return True, "", num_rules
def resolve_parameters(body, query_params: dict) -> dict:
"""
Resolve parameters using all-or-nothing strategy.
Rules:
1. If ANY query parameter is provided (non-empty), use ONLY query parameters
2. If NO query parameters are provided, use JSON body
3. Never mix - it's either query OR body, not both
Args:
body: Optional Pydantic model (RDFRequest/RMLRequest)
query_params: Dict of query parameter names to values (can be None)
Returns:
Dict with resolved parameter values (keys match query_params keys)
Example:
params = resolve_parameters(
body,
{"mapping_url": mapping_url, "data_url": data_url}
)
final_mapping_url = params["mapping_url"]
final_data_url = params["data_url"]
"""
# Check if ANY query parameter is provided and non-empty
has_any_query_param = any(value for value in query_params.values())
if has_any_query_param:
# Use ONLY query parameters - ignore body completely
logging.debug("Using query parameters (at least one provided)")
return {key: value for key, value in query_params.items()}
else:
# Use JSON body - all query params were None/empty
logging.debug("Using JSON body (no query parameters provided)")
if body:
result = {}
for key in query_params.keys():
attr_value = getattr(body, key, None)
result[key] = str(attr_value) if attr_value else None
return result
else:
return {key: None for key in query_params.keys()}
# ============================================================================
# HELPER FUNCTIONS - Data Processing & RML Execution
# ============================================================================
def get_standard_jsonld_context() -> dict:
"""Return standard JSON-LD context for CSVW normalization.
Returns:
Dict containing standard namespace mappings for JSON-LD serialization
"""
return {
"@vocab": str(CSVW),
"rdf": str(RDF),
"qudt": str(QUDT),
"qunit": str(QUNIT),
"label": "http://www.w3.org/2000/01/rdf-schema#label",
}
def extract_jsonld_namespaces(content: bytes) -> tuple[dict, str | None]:
"""Extract namespace bindings from JSON-LD @context.
Args:
content: JSON-LD content as bytes
Returns:
Tuple of (namespace_dict, csv_namespace)
- namespace_dict: Dict mapping prefix -> namespace URL
- csv_namespace: The 'csv' namespace URL if found, else None
"""
import json
namespace_dict = {}
csv_namespace = None
try:
json_data = json.loads(content)
ctx = json_data.get("@context", [])
# Context can be a list or dict
contexts_to_process = []
if isinstance(ctx, list):
contexts_to_process = [item for item in ctx if isinstance(item, dict)]
elif isinstance(ctx, dict):
contexts_to_process = [ctx]
for context in contexts_to_process:
for prefix, ns in context.items():
if isinstance(ns, str) and prefix not in ["@vocab"]:
namespace_dict[prefix] = ns
logging.debug(f"Extracted namespace from JSON-LD context: {prefix} -> {ns}")
if prefix == "csv":
csv_namespace = ns
logging.info(f"Stored CSV namespace from JSON-LD: {csv_namespace}")
except Exception as e:
logging.warning(f"Could not extract context from JSON-LD: {e}")
return namespace_dict
def detect_data_format(content: bytes, url: str) -> tuple[str | None, bool]:
"""Detect if content is JSON, RDF, or unknown.
Args:
content: Data content as bytes
url: Source URL (used for format guessing)
Returns:
Tuple of (format_string, is_rdf)
- format_string: 'json' for plain JSON, or RDF format like 'turtle', 'json-ld', etc.
- is_rdf: True if RDF format detected, False for plain JSON
Raises:
HTTPException: If format cannot be determined
"""
import json
# Try plain JSON first
try:
json.loads(content)
logging.info("Content detected as plain JSON")
return "json", False
except (json.JSONDecodeError, ValueError):
pass
# Try RDF format
data_format = guess_format(url)
if data_format:
logging.info(f"Content detected as RDF format: {data_format}")
return data_format, True
raise HTTPException(
status_code=422,
detail=f"Could not determine data format from URL: {url}",
)
def process_data_to_jsonld(
content: bytes,
url: str,
preserve_namespaces: bool = True
) -> tuple[str, bool, str | None]:
"""Process data content to JSON-LD format for RML mapper.
PRESERVES ORIGINAL STRUCTURE - no normalization/transformation!
Args:
content: Data content as bytes
url: Source URL
preserve_namespaces: Whether to preserve original namespaces from JSON-LD
Returns:
Tuple of (processed_content, is_rdf_data, csv_namespace)
- processed_content: Data in JSON-LD format as string (structure preserved!)
- is_rdf_data: True if source was non-JSON-LD RDF, False if JSON/JSON-LD
- csv_namespace: CSV namespace if found in original data, else None
Raises:
HTTPException: If data processing fails
"""
import json
# ALWAYS try to extract @context from JSON FIRST, before any RDF parsing
namespace_dict = None
csv_namespace = None
if preserve_namespaces:
try:
namespace_dict = extract_jsonld_namespaces(content)
logging.debug(f"Extracted {len(namespace_dict)} namespaces from JSON-LD @context")
except Exception as e:
logging.debug(f"No JSON @context found (file may not be JSON or JSON-LD): {e}")
# Try to parse as JSON/JSON-LD first (most common case)
try:
json_data = json.loads(content)
logging.info("Content detected as JSON/JSON-LD - preserving original structure")
# Check if it's JSON-LD (has @context)
has_context = "@context" in json_data if isinstance(json_data, dict) else False
# Return as-is - NO TRANSFORMATION!
processed_content = content.decode() if isinstance(content, bytes) else content
# is_rdf_data = False means "don't add data_graph to final output"
# For JSON-LD, RML mapper will handle everything
return processed_content, False, namespace_dict
except (json.JSONDecodeError, ValueError):
# Not JSON - must be other RDF format (Turtle, RDF/XML, etc.)
logging.info("Content is not JSON - checking for other RDF formats")
# Try as non-JSON RDF format (Turtle, RDF/XML, N-Triples, etc.)
data_format = guess_format(url)
if not data_format:
raise HTTPException(
status_code=422,
detail=f"Could not determine data format from URL: {url}",
)
try:
logging.info(f"Loading {url} as RDF in {data_format} format")
# Parse as RDF
temp_graph = Graph()
temp_graph.parse(data=content, format=data_format)
# Convert to JSON-LD with minimal context
# We must do this for non-JSON formats, but keep it minimal
context = get_standard_jsonld_context()
if namespace_dict:
context.update(namespace_dict)
processed_content = temp_graph.serialize(format="json-ld", context=context)
logging.info(f"Converted {data_format} to JSON-LD (minimal transformation)")
# is_rdf_data = True means "this was originally RDF, may need data_graph"
return processed_content, True, namespace_dict
except Exception as e:
raise HTTPException(
status_code=422,
detail=f"Could not read source {url} - not valid RDF or JSON format: {str(e)}",
) from e
def convert_yarrrml_to_rml(mapping_data: bytes | str) -> str:
"""Convert YARRRML to RML format via web API.
Args:
mapping_data: YARRRML content as bytes or string
Returns:
RML rules as string in Turtle format
Raises:
requests.RequestException: If conversion fails
"""
response = requests.post(YARRRML_URL, data={"yarrrml": mapping_data})
response.raise_for_status()
return response.text
def parse_and_replace_rml_source(rml_rules: str, source_placeholder: str) -> str:
"""Parse RML rules and replace data source with placeholder.
Args:
rml_rules: RML rules in Turtle format
source_placeholder: Placeholder filename (e.g., 'source.json')
Returns:
Modified RML rules as string
Raises:
Exception: If parsing fails
"""
rml_graph = Graph()
rml_graph.parse(data=rml_rules, format="ttl")
replace_data_source(rml_graph, source_placeholder)
return rml_graph.serialize(format="ttl")
def execute_rml_mapper(
rml_rules: str,
sources: dict[str, str],
serialization: str = "turtle"
) -> str:
"""Execute RML mapper web API and return output.
Args:
rml_rules: RML rules in Turtle format
sources: Dict of {placeholder_filename: content_string}
serialization: Output format (default: 'turtle')
Returns:
Mapping output as string
Raises:
HTTPException: If mapper fails
"""
payload = {
"rml": rml_rules,
"sources": sources,
"serialization": serialization,
}
logging.debug(f"Calling RML mapper at: {MAPPER_URL}/execute")
logging.debug(f"Number of sources: {len(sources)}")
try:
response = requests.post(MAPPER_URL + "/execute", json=payload)
logging.debug(f"RML Mapper response status: {response.status_code}")
if response.status_code != 200:
logging.error(f"RML Mapper error response: {response.text}")
raise HTTPException(
status_code=response.status_code,
detail=f"RML mapper failed: {response.text}"
)
result = response.json()["output"]
logging.debug(f"RML Mapper output length: {len(result)} chars")
return result
except requests.RequestException as e:
logging.error(f"Exception calling RML mapper: {str(e)}", exc_info=True)
raise HTTPException(
status_code=500,
detail=f"Could not generate mapping results with rmlmapper: {str(e)}",
) from e
def download_sources(
sources: dict,
opt_data_url: str | None = None,
authorization: str | None = None,
injected_content: Optional[bytes] = None,
) -> tuple[dict, str, str]:
"""Download all sources from mapping and build URL mapping.
Args:
sources: Sources dict from YARRRML mapping
opt_data_url: Optional override URL for first source
authorization: Authorization header value
Returns:
Tuple of (url_mapping, primary_data_url, filename)
- url_mapping: Dict mapping original_url -> {placeholder, content, actual_url, original_url}
- primary_data_url: The primary data URL (first source)
- filename: Suggested output filename
Raises:
HTTPException: If download fails
"""
if not sources:
raise HTTPException(
status_code=422, detail="No sources found in mapping file"
)
url_mapping = {}
counter = 1
primary_data_url = None
filename = "data-joined.ttl"
for source_name, source_def in sources.items():
# Strip trailing slash only for downloading - preserve for namespace matching later
original_url_for_download = source_def["access"].strip("/")
original_url = source_def["access"] # Keep as-is for namespace matching
# Handle optional data_url override for the first source
if counter == 1:
if opt_data_url:
actual_url = opt_data_url.strip("/") # Strip for download
primary_data_url = opt_data_url # Keep as-is for namespace
else:
actual_url = original_url_for_download
primary_data_url = original_url
else:
actual_url = original_url_for_download
placeholder = f"source_{counter}.json"
# Use injected content for any source whose URL resolves to opt_data_url.
# This covers mappings where multiple sources reference the same file
# (all replaced by Phase 0) so none of them need to be fetched.
use_injected = (
injected_content is not None
and opt_data_url is not None
and actual_url == opt_data_url.strip("/")
)
if use_injected:
logging.debug(f"Using injected content for source {source_name} (url: {actual_url})")
data_content = injected_content
data_filename = actual_url.rstrip("/").split("/")[-1]
else:
logging.debug(f"Downloading source {source_name} from {actual_url}")
data_content, data_filename = open_file(actual_url, authorization)
url_mapping[original_url] = {
"placeholder": placeholder,
"content": data_content,
"original_url": original_url,
"actual_url": actual_url
}
# Store filename from first source
if counter == 1:
filename = data_filename.rsplit(".", 1)[0].rsplit("-", 1)[0] + "-joined.ttl"