Просмотр исходного кода

Create query option returning full cell data

Arkadiusz Ryś 2 лет назад
Родитель
Сommit
84354b7db3
1 измененных файлов с 44 добавлено и 0 удалено
  1. 44 0
      spendpoint/router.py

+ 44 - 0
spendpoint/router.py

@@ -135,6 +135,50 @@ class SparqlRouter(APIRouter):
                         query = parse.unquote(params[1])
             return await sparql_endpoint_get(request, query)
 
+        @self.get("/cell/")
+        async def sparql_cell_endpoint_get(request: Request, iri, file_name, row, column, verbose: bool = True, query: Optional[str] = Query(None)) -> Response:
+            """
+            SELECT ?s ?p ?o WHERE {
+              BIND(ENCODE_FOR_URI("http://ua.be/sdo2l/description/artifacts/artifacts#random-artefact") as ?e)
+              BIND(uri(concat("http://localhost:8000/cell/?iri=", ?e ,"&row=2&column=2&file_name=example.csv")) as ?c)
+              SERVICE ?c {?s ?p ?o}
+            }
+            """
+            logging.debug(f"Received cell GET request [{iri}:{file_name}->{row}:{column}].")
+            graph = ConjunctiveGraph()
+            graph_ns = dict(graph.namespaces())
+            # graph_ns["tabular"] = "http://ua.be/sdo2l/vocabulary/formalisms/tabular#"
+            df = pd.read_csv(f"data/{file_name}", index_col=None, header=None)
+            cell_value = df.iat[int(row), int(column)]
+
+            tabular_prefix = "http://ua.be/sdo2l/vocabulary/formalism/tabular"
+
+            # instance_prefix, instance_designator = iri.split("#")
+            cell = URIRef(f"{iri}-cell-{row}-{column}")
+            # Store the triples in a temporary graph. This allows us to use the rdflib query engine for the sub-query instead of finding the matching pairs manually.
+            graph.add((cell, URIRef(f"{tabular_prefix}#holdsContent"), Literal(cell_value)))
+            graph.add((cell, URIRef(f"{tabular_prefix}#hasRowPosition"), Literal(int(row))))
+            graph.add((cell, URIRef(f"{tabular_prefix}#hasColumnPosition"), Literal(int(column))))
+
+            if verbose:
+                graph.add((cell, URIRef(f"{tabular_prefix}#isCellOfTabularData"), URIRef(f"{iri}")))
+                graph.add((cell, URIRef(f"{tabular_prefix}#isInCollection"), URIRef(f"{iri}-column-{int(column)}")))
+                graph.add((cell, URIRef(f"{tabular_prefix}#isInCollection"), URIRef(f"{iri}-row-{int(row)}")))
+
+                graph.add((cell, RDF.type, OWL.Thing))
+                graph.add((cell, RDF.type, URIRef("http://ua.be/sdo2l/vocabulary/formalism/tabular#Cell")))
+                graph.add((cell, RDF.type, URIRef("http://ua.be/sdo2l/vocabulary/formalism/file#Data")))
+                graph.add((cell, OWL.sameAs, URIRef(f"{iri}-cell-{int(row)}-{int(column)}")))
+
+            logging.debug(f"{cell_value=}")
+
+            try:
+                query_results = graph.query(query, initNs=graph_ns)
+            except Exception as e:
+                logging.error("Error executing the SPARQL query on the RDFLib Graph: " + str(e))
+                return JSONResponse(status_code=400, content={"message": "Error executing the SPARQL query on the RDFLib Graph."})
+            return await encode_graph_query_results(request, query_results)
+
 
         @self.get("/cell/{file_name}/")
         async def sparql_sheet_endpoint_get(request: Request, file_name, query: Optional[str] = Query(None)) -> Response: