Skip to content

Commit 439d558

Browse files
committed
black reformat
1 parent 32ab45b commit 439d558

8 files changed

Lines changed: 83 additions & 37 deletions

File tree

src/strings2things/app/api/endpoints.py

Lines changed: 9 additions & 4 deletions
Original file line numberDiff line numberDiff line change
@@ -4,8 +4,13 @@
44
from fastapi.responses import Response
55
from rdflib import Graph
66
from src.strings2things.app.core.rdf_transformer import RDFTransformer
7-
from src.strings2things.app.core.ontology_manager import OntologyManager # Assume this exists
8-
from src.strings2things.app.utils.rdf_utils import parse_rdf, serialize_rdf # Also assume or create
7+
from src.strings2things.app.core.ontology_manager import (
8+
OntologyManager,
9+
) # Assume this exists
10+
from src.strings2things.app.utils.rdf_utils import (
11+
parse_rdf,
12+
serialize_rdf,
13+
) # Also assume or create
914
import logging
1015

1116
router = APIRouter()
@@ -15,10 +20,10 @@
1520

1621
transformer = RDFTransformer(ontology_manager.get_label_map())
1722

23+
1824
@router.post("/transform")
1925
async def transform_rdf(
20-
file: UploadFile = File(...),
21-
serialization: str = Form("turtle")
26+
file: UploadFile = File(...), serialization: str = Form("turtle")
2227
) -> Response:
2328
"""
2429
Accepts an RDF file upload, transforms it using the label map,

src/strings2things/app/core/ontology_manager.py

Lines changed: 14 additions & 5 deletions
Original file line numberDiff line numberDiff line change
@@ -6,13 +6,16 @@
66

77
settings = Settings()
88

9+
910
class OntologyManager:
1011
def __init__(self):
1112
self.graph = Graph()
1213
self.label_map: dict[str, str] = {}
1314

1415
def load_ontologies(self):
15-
print(f"[INFO] Connecting to SPARQL endpoint: {settings.ONTOLOGY_SPARQL_ENDPOINT}")
16+
print(
17+
f"[INFO] Connecting to SPARQL endpoint: {settings.ONTOLOGY_SPARQL_ENDPOINT}"
18+
)
1619
for graph_iri in settings.get_graph_iris():
1720
print(f"[INFO] Loading named graph: {graph_iri}")
1821
g = self._load_named_graph(settings.ONTOLOGY_SPARQL_ENDPOINT, graph_iri)
@@ -23,12 +26,14 @@ def load_ontologies(self):
2326
def _load_named_graph(self, endpoint: str, graph_iri: str) -> Graph:
2427
sparql = SPARQLWrapper(endpoint)
2528
sparql.setCredentials(settings.GRAPHDB_USERNAME, settings.GRAPHDB_PASSWORD)
26-
sparql.setQuery(f"""
29+
sparql.setQuery(
30+
f"""
2731
CONSTRUCT {{ ?s ?p ?o }}
2832
WHERE {{
2933
GRAPH <{graph_iri}> {{ ?s ?p ?o }}
3034
}}
31-
""")
35+
"""
36+
)
3237
sparql.setReturnFormat(TURTLE)
3338
result = sparql.query().convert()
3439

@@ -69,7 +74,9 @@ def _build_label_map(self):
6974
print(f"[INFO] Label map built with {len(self.label_map)} unambiguous labels.")
7075

7176
def _check_ambiguities(self, seen: dict[str, str | list[str]]) -> dict[str, str]:
72-
ambiguous_labels = {label for label, iris in seen.items() if isinstance(iris, list)}
77+
ambiguous_labels = {
78+
label for label, iris in seen.items() if isinstance(iris, list)
79+
}
7380

7481
if ambiguous_labels:
7582
msg = f"Found ambiguous labels: {', '.join(sorted(ambiguous_labels))} \n Please resolve these in your ontology before proceeding."
@@ -79,7 +86,9 @@ def _check_ambiguities(self, seen: dict[str, str | list[str]]) -> dict[str, str]
7986
print(f"[WARNING] {msg}")
8087

8188
# Return only unambiguous labels (those with a single IRI string)
82-
return {label: iris for label, iris in seen.items() if not isinstance(iris, list)}
89+
return {
90+
label: iris for label, iris in seen.items() if not isinstance(iris, list)
91+
}
8392

8493
def get_label_map(self) -> dict[str, str]:
8594
return self.label_map

src/strings2things/app/core/rdf_transformer.py

Lines changed: 10 additions & 5 deletions
Original file line numberDiff line numberDiff line change
@@ -28,7 +28,9 @@ def transform(self, input_graph: Graph) -> Graph:
2828

2929
# Retain original triple (to retain backward compatibility for now)
3030
output_graph.add((s, p, o))
31-
output_graph.add((iri, URIRef("http://wwww.example.org/thingOf"), o))
31+
output_graph.add(
32+
(iri, URIRef("http://wwww.example.org/thingOf"), o)
33+
)
3234

3335
output_graph.add((s, p, iri))
3436

@@ -37,18 +39,21 @@ def transform(self, input_graph: Graph) -> Graph:
3739
predicate=str(p),
3840
original_value=str(o),
3941
replacement_iri=str(iri),
40-
reason="unambiguous match"
42+
reason="unambiguous match",
4143
)
42-
continue
44+
continue
4345

44-
4546
output_graph.add((s, p, o))
4647
self.log.add_entry(
4748
subject=str(s),
4849
predicate=str(p),
4950
original_value=str(o),
5051
replacement_iri=None,
51-
reason="not a string literal" if not isinstance(o, Literal) else "no match in label map"
52+
reason=(
53+
"not a string literal"
54+
if not isinstance(o, Literal)
55+
else "no match in label map"
56+
),
5257
)
5358

5459
return output_graph

src/strings2things/app/core/transformation_log.py

Lines changed: 13 additions & 8 deletions
Original file line numberDiff line numberDiff line change
@@ -3,21 +3,26 @@
33
Internal logger for recording transformation events.
44
"""
55

6+
67
class TransformationLog:
78
def __init__(self):
89
self.entries = []
910

10-
def add_entry(self, subject, predicate, original_value, replacement_iri, reason: str):
11+
def add_entry(
12+
self, subject, predicate, original_value, replacement_iri, reason: str
13+
):
1114
"""
1215
Record a transformation decision.
1316
"""
14-
self.entries.append({
15-
"subject": subject,
16-
"predicate": predicate,
17-
"original": original_value,
18-
"replacement": replacement_iri,
19-
"reason": reason
20-
})
17+
self.entries.append(
18+
{
19+
"subject": subject,
20+
"predicate": predicate,
21+
"original": original_value,
22+
"replacement": replacement_iri,
23+
"reason": reason,
24+
}
25+
)
2126

2227
def get_summary(self):
2328
"""

src/strings2things/app/utils/rdf_utils.py

Lines changed: 10 additions & 4 deletions
Original file line numberDiff line numberDiff line change
@@ -6,17 +6,18 @@
66
from rdflib import Graph
77
from rdflib.plugin import PluginException
88

9+
910
def parse_rdf(data: bytes, format: str | None = None) -> Graph:
1011
"""
1112
Parses RDF data from bytes. Tries to guess format if not provided.
12-
13+
1314
Args:
1415
data: RDF content as bytes.
1516
format: Optional RDF format (e.g., 'turtle', 'xml', 'json-ld').
1617
1718
Returns:
1819
A parsed RDFLib Graph.
19-
20+
2021
Raises:
2122
ValueError: If the data cannot be parsed.
2223
"""
@@ -36,15 +37,20 @@ def parse_rdf(data: bytes, format: str | None = None) -> Graph:
3637

3738
from rdflib import Graph
3839

40+
3941
def serialize_rdf(graph: Graph, output_format: str = "turtle") -> str:
4042
"""
4143
Serialize an RDFLib Graph to the specified RDF format.
42-
44+
4345
Args:
4446
graph (Graph): The RDFLib graph to serialize.
4547
output_format (str): The desired RDF serialization format (e.g., "turtle", "xml", "nt", "json-ld").
4648
4749
Returns:
4850
str: The serialized RDF data as a string.
4951
"""
50-
return graph.serialize(format=output_format).decode("utf-8") if isinstance(graph.serialize(format=output_format), bytes) else graph.serialize(format=output_format)
52+
return (
53+
graph.serialize(format=output_format).decode("utf-8")
54+
if isinstance(graph.serialize(format=output_format), bytes)
55+
else graph.serialize(format=output_format)
56+
)

tests/load_and_inspect.py

Lines changed: 2 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -6,6 +6,7 @@
66

77
from strings2things.app.core.ontology_manager import OntologyManager
88

9+
910
def main():
1011
manager = OntologyManager()
1112
manager.load_ontologies()
@@ -15,5 +16,6 @@ def main():
1516
for label, iri in sorted(label_map.items()):
1617
print(f"{label}{iri}")
1718

19+
1820
if __name__ == "__main__":
1921
main()

tests/test_ambigous.py

Lines changed: 21 additions & 10 deletions
Original file line numberDiff line numberDiff line change
@@ -5,20 +5,30 @@
55

66
settings = config_module.Settings() # use the global settings instance your app uses
77

8+
89
def create_ambiguous_graph():
910
g = Graph()
10-
g.add((URIRef("http://example.org/resource1"),
11-
URIRef("http://www.w3.org/2000/01/rdf-schema#label"),
12-
Literal("ambiguouslabel")))
13-
g.add((URIRef("http://example.org/resource2"),
14-
URIRef("http://www.w3.org/2000/01/rdf-schema#label"),
15-
Literal("ambiguouslabel")))
11+
g.add(
12+
(
13+
URIRef("http://example.org/resource1"),
14+
URIRef("http://www.w3.org/2000/01/rdf-schema#label"),
15+
Literal("ambiguouslabel"),
16+
)
17+
)
18+
g.add(
19+
(
20+
URIRef("http://example.org/resource2"),
21+
URIRef("http://www.w3.org/2000/01/rdf-schema#label"),
22+
Literal("ambiguouslabel"),
23+
)
24+
)
1625
return g
1726

27+
1828
def test_ambiguous_labels_detection_fail(monkeypatch):
1929
monkeypatch.setattr(
20-
"strings2things.app.core.ontology_manager.settings.FAIL_ON_AMBIGUOUS_LABELS",
21-
True
30+
"strings2things.app.core.ontology_manager.settings.FAIL_ON_AMBIGUOUS_LABELS",
31+
True,
2232
)
2333

2434
manager = OntologyManager()
@@ -28,11 +38,12 @@ def test_ambiguous_labels_detection_fail(monkeypatch):
2838
manager._build_label_map()
2939
assert "ambiguouslabel" in str(exc_info.value)
3040

41+
3142
def test_ambiguous_labels_detection_no_fail(monkeypatch):
3243
# Patch the *module-level* settings inside ontology_manager to False
3344
monkeypatch.setattr(
34-
"strings2things.app.core.ontology_manager.settings.FAIL_ON_AMBIGUOUS_LABELS",
35-
False
45+
"strings2things.app.core.ontology_manager.settings.FAIL_ON_AMBIGUOUS_LABELS",
46+
False,
3647
)
3748

3849
manager = OntologyManager()

tests/test_rdf_transformer.py

Lines changed: 4 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -5,13 +5,15 @@
55

66
EX = Namespace("http://example.org/")
77

8+
89
@pytest.fixture
910
def label_map():
1011
return {
1112
"geology": "http://example.org/ontology#Geology",
12-
"biology": "http://example.org/ontology#Biology"
13+
"biology": "http://example.org/ontology#Biology",
1314
}
1415

16+
1517
@pytest.fixture
1618
def input_graph():
1719
g = Graph()
@@ -20,6 +22,7 @@ def input_graph():
2022
g.add((EX.subj3, EX.hasValue, URIRef("http://example.org/someIRI")))
2123
return g
2224

25+
2326
def test_rdf_transformer(label_map, input_graph):
2427
transformer = RDFTransformer(label_map)
2528
output_graph = transformer.transform(input_graph)

0 commit comments

Comments
 (0)