-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathmain.py
More file actions
220 lines (199 loc) · 8.39 KB
/
main.py
File metadata and controls
220 lines (199 loc) · 8.39 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
from fastapi import FastAPI, Query, Response
from rdflib import Graph
from rdflib.namespace import RDF, RDFS, OWL
import os
import logging
from starlette.concurrency import run_in_threadpool
import importlib.util
import time
# Configure logging
logging.basicConfig(level=logging.INFO, filename='log/api.log', filemode='a')
# Load config
spec = importlib.util.spec_from_file_location("config", os.path.join(os.path.dirname(__file__), "config.py"))
config = importlib.util.module_from_spec(spec)
spec.loader.exec_module(config)
app = FastAPI()
g = Graph()
# Load all RDF files from the data folder
data_dir = config.DATA_DIR
for filename in os.listdir(data_dir):
filepath = os.path.join(data_dir, filename)
if filename.endswith(".ttl"):
g.parse(filepath, format="turtle")
elif filename.endswith(".nt"):
g.parse(filepath, format="nt")
@app.get("/get-entity")
async def get_entities(
entity_type: str = Query(..., description="Type of entity, e.g., order, customer, product"),
entity_code: str = Query(..., description="Number or name of the entity"),
format: str = Query("text", description="Response format: 'text' or 'json'")
):
query = f'''
PREFIX : <http://www.mysparql.com/resource/northwind/>
SELECT ?s ?p ?o WHERE {{
?s ?p ?o .
FILTER(?s = :{entity_type}-{entity_code})
}}
ORDER BY ?p
'''
start_time = time.time()
try:
results = await run_in_threadpool(g.query, query)
triples = []
for row in results:
s = row['s'].n3() if hasattr(row['s'], 'n3') else str(row['s'])
p = row['p'].n3() if hasattr(row['p'], 'n3') else str(row['p'])
o = row['o'].n3() if hasattr(row['o'], 'n3') else str(row['o'])
triples.append((s, p, o))
elapsed = time.time() - start_time
logging.info(f"\nQuery: {query} \n(Number of triples: {len(triples)}, Elapsed Time: {elapsed:.3f}s)")
except Exception as e:
elapsed = time.time() - start_time
logging.error(f"Error for {entity_type}-{entity_code} after {elapsed:.3f}s: {e}")
return Response(content=f"Error: {str(e)}", media_type="text/plain", status_code=500)
if not triples:
msg = f"No results found for {entity_type} {entity_code}."
if format == "json":
return {"message": msg, "results": []}
return Response(content=msg, media_type="text/plain")
if format == "json":
return {"results": triples}
lines = [f"{s},{p},{o}" for s, p, o in triples]
return Response(content="\n".join(lines), media_type="text/plain")
@app.get("/get-schema")
async def get_schema():
classes = set()
properties = set()
# Only parse ontology file for schema info
ontology_path = os.path.join(config.DATA_DIR, "northwind-ontology.ttl")
ontology_graph = Graph()
ontology_graph.parse(ontology_path, format="turtle")
# Find classes (rdf:type owl:Class or rdfs:Class)
for s in ontology_graph.subjects(RDF.type, OWL.Class):
classes.add(s.n3())
for s in ontology_graph.subjects(RDF.type, RDFS.Class):
classes.add(s.n3())
# Find properties (rdf:type owl:ObjectProperty or owl:DatatypeProperty or rdf:Property)
for s in ontology_graph.subjects(RDF.type, OWL.ObjectProperty):
properties.add(s.n3())
for s in ontology_graph.subjects(RDF.type, OWL.DatatypeProperty):
properties.add(s.n3())
for s in ontology_graph.subjects(RDF.type, RDF.Property):
properties.add(s.n3())
return {
"classes_count": len(classes),
"classes": sorted(classes),
"properties_count": len(properties),
"properties": sorted(properties)
}
# call example: http://localhost:8000/get-class-counts
@app.get("/get-class-counts")
async def get_class_counts():
class_counts = {}
# Find all classes in ontology
ontology_path = os.path.join(config.DATA_DIR, "northwind-ontology.ttl")
ontology_graph = Graph()
ontology_graph.parse(ontology_path, format="turtle")
classes = set()
for s in ontology_graph.subjects(RDF.type, OWL.Class):
classes.add(s)
for s in ontology_graph.subjects(RDF.type, RDFS.Class):
classes.add(s)
# Count instances in data graph
for cls in classes:
count = sum(1 for _ in g.subjects(RDF.type, cls))
class_counts[cls.n3()] = count
return class_counts
from rdflib import URIRef
# call example: http://localhost:8000/get-class-properties?class_iri=http://www.mysparql.com/resource/northwind/Order
@app.get("/get-class-properties")
async def get_class_properties(class_iri: str):
ontology_path = os.path.join(config.DATA_DIR, "northwind-ontology.ttl")
ontology_graph = Graph()
ontology_graph.parse(ontology_path, format="turtle")
properties = set()
# Convert class_iri string to URIRef for comparison
class_iri_ref = URIRef(class_iri)
# Find properties with domain = class_iri for all property types
property_types = [RDF.Property, OWL.ObjectProperty, OWL.DatatypeProperty]
for prop_type in property_types:
for prop in ontology_graph.subjects(RDF.type, prop_type):
for domain in ontology_graph.objects(prop, RDFS.domain):
if domain == class_iri_ref:
logging.info(f"Found property {prop.n3()} with domain {domain.n3()}")
properties.add(prop.n3())
return {"properties": sorted(properties)}
@app.get("/facet-search")
# call example: http://localhost:8000/facet-search?class_iri=http://www.mysparql.com/resource/northwind/Product&min_unit_price=10.0&max_unit_price=11.0
async def facet_search(
class_iri: str,
min_unit_price: float = None,
max_unit_price: float = None
):
# Convert class_iri and unit_price_iri to URIRef
class_iri_ref = URIRef(class_iri)
unit_price_iri = URIRef("http://www.mysparql.com/resource/northwind/unitPrice")
# Find all instances of the class
instances = [s for s in g.subjects(RDF.type, class_iri_ref)]
results = []
for s in instances:
match = True
unit_prices = [o for o in g.objects(s, unit_price_iri)]
# If there is no unitPrice, skip filtering
if unit_prices:
for o in unit_prices:
try:
val = float(o.value if hasattr(o, 'value') else o)
if min_unit_price is not None and val < min_unit_price:
match = False
if max_unit_price is not None and val > max_unit_price:
match = False
except Exception:
match = False
if not match:
continue
# Collect all triples for this instance
for p, o in g.predicate_objects(s):
results.append((s.n3(), p.n3(), o.n3() if hasattr(o, 'n3') else str(o)))
return {"triples": results}
from rdflib import Graph
@app.get("/get-namespaces")
async def get_namespaces():
ns_path = os.path.join(config.DATA_DIR, "namespaces.ttl")
ns_graph = Graph()
ns_graph.parse(ns_path, format="turtle")
# Build a dict: {prefix: namespace}
ns_map = {prefix: str(ns) for prefix, ns in ns_graph.namespaces()}
return ns_map
@app.get("/get-products-in-unit-price-range")
async def get_products_in_unit_price_range(
class_iri: str,
min_unit_price: float = None,
max_unit_price: float = None
):
# Convert class_iri and unit_price_iri to URIRef
class_iri_ref = URIRef(class_iri)
unit_price_iri = URIRef("http://www.mysparql.com/resource/northwind/unitPrice")
# Find all instances of the class
instances = [s for s in g.subjects(RDF.type, class_iri_ref)]
results = []
for s in instances:
match = True
unit_prices = [o for o in g.objects(s, unit_price_iri)]
# If there is no unitPrice, skip filtering
if unit_prices:
for o in unit_prices:
try:
val = float(o.value if hasattr(o, 'value') else o)
if min_unit_price is not None and val < min_unit_price:
match = False
if max_unit_price is not None and val > max_unit_price:
match = False
except Exception:
match = False
if not match:
continue
# Collect all triples for this instance
for p, o in g.predicate_objects(s):
results.append((s.n3(), p.n3(), o.n3() if hasattr(o, 'n3') else str(o)))
return {"triples": results}