|
| 1 | +#!/usr/bin/env python3 |
| 2 | + |
| 3 | +# This software was developed at the National Institute of Standards |
| 4 | +# and Technology by employees of the Federal Government in the course |
| 5 | +# of their official duties. Pursuant to title 17 Section 105 of the |
| 6 | +# United States Code this software is not subject to copyright |
| 7 | +# protection and is in the public domain. NIST assumes no |
| 8 | +# responsibility whatsoever for its use by other parties, and makes |
| 9 | +# no guarantees, expressed or implied, about its quality, |
| 10 | +# reliability, or any other characteristic. |
| 11 | +# |
| 12 | +# We would appreciate acknowledgement if the software is used. |
| 13 | + |
| 14 | +""" |
| 15 | +This script executes a SPARQL SELECT query, returning a table representation. The design of the workflow is based on this example built on SPARQLWrapper: |
| 16 | +https://lawlesst.github.io/notebook/sparql-dataframe.html |
| 17 | +
|
| 18 | +Note that this assumes a limited syntax style in the outer SELECT clause of the query - only named variables, no aggregations, and a single space character separating all variable names. E.g.: |
| 19 | +
|
| 20 | +SELECT ?x ?y ?z |
| 21 | +WHERE |
| 22 | +{ ... } |
| 23 | +
|
| 24 | +The word "DISTINCT" will also be cut from the query, if present. |
| 25 | +
|
| 26 | +Should a more complex query be necessary, an outer, wrapping SELECT query would let this script continue to function. |
| 27 | +""" |
| 28 | + |
| 29 | +__version__ = "0.3.0" |
| 30 | + |
| 31 | +import argparse |
| 32 | +import binascii |
| 33 | +import os |
| 34 | +import logging |
| 35 | + |
| 36 | +import pandas as pd |
| 37 | +import rdflib.plugins.sparql |
| 38 | + |
| 39 | +import case_utils |
| 40 | + |
| 41 | +NS_XSD = rdflib.XSD |
| 42 | + |
| 43 | +_logger = logging.getLogger(os.path.basename(__file__)) |
| 44 | + |
| 45 | +def main(): |
| 46 | + parser = argparse.ArgumentParser() |
| 47 | + parser.add_argument("-d", "--debug", action="store_true") |
| 48 | + parser.add_argument("--disallow-empty-results", action="store_true", help="Raise error if no results are returned for query.") |
| 49 | + parser.add_argument("out_table", help="Expected extensions are .html for HTML tables or .md for Markdown tables.") |
| 50 | + parser.add_argument("in_sparql") |
| 51 | + parser.add_argument("in_graph", nargs="+") |
| 52 | + args = parser.parse_args() |
| 53 | + |
| 54 | + logging.basicConfig(level=logging.DEBUG if args.debug else logging.INFO) |
| 55 | + |
| 56 | + graph = rdflib.Graph() |
| 57 | + for in_graph_filename in args.in_graph: |
| 58 | + graph.parse(in_graph_filename, format=case_utils.guess_format(in_graph_filename)) |
| 59 | + |
| 60 | + # Inherit prefixes defined in input context dictionary. |
| 61 | + nsdict = {k:v for (k,v) in graph.namespace_manager.namespaces()} |
| 62 | + |
| 63 | + select_query_text = None |
| 64 | + with open(args.in_sparql, "r") as in_fh: |
| 65 | + select_query_text = in_fh.read().strip() |
| 66 | + _logger.debug("select_query_text = %r." % select_query_text) |
| 67 | + |
| 68 | + # Build columns list from SELECT line. |
| 69 | + select_query_text_lines = select_query_text.split("\n") |
| 70 | + select_line = [line for line in select_query_text_lines if line.startswith("SELECT ")][0] |
| 71 | + variables = select_line.replace(" DISTINCT", "").replace("SELECT ", "").split(" ") |
| 72 | + |
| 73 | + tally = 0 |
| 74 | + records = [] |
| 75 | + select_query_object = rdflib.plugins.sparql.prepareQuery(select_query_text, initNs=nsdict) |
| 76 | + for (row_no, row) in enumerate(graph.query(select_query_object)): |
| 77 | + tally = row_no + 1 |
| 78 | + record = [] |
| 79 | + for (column_no, column) in enumerate(row): |
| 80 | + if column is None: |
| 81 | + column_value = "" |
| 82 | + elif isinstance(column, rdflib.term.Literal) and column.datatype == NS_XSD.hexBinary: |
| 83 | + # Use hexlify to convert xsd:hexBinary to ASCII. |
| 84 | + # The render to ASCII is in support of this script rendering results for website viewing. |
| 85 | + # .decode() is because hexlify returns bytes. |
| 86 | + column_value = binascii.hexlify(column.toPython()).decode() |
| 87 | + else: |
| 88 | + column_value = column.toPython() |
| 89 | + if row_no == 0: |
| 90 | + _logger.debug("row[0]column[%d] = %r." % (column_no, column_value)) |
| 91 | + record.append(column_value) |
| 92 | + records.append(record) |
| 93 | + if tally == 0: |
| 94 | + if args.disallow_empty_results: |
| 95 | + raise ValueError("Failed to return any results.") |
| 96 | + |
| 97 | + df = pd.DataFrame(records, columns=variables) |
| 98 | + |
| 99 | + table_text = None |
| 100 | + if args.out_table.endswith(".html"): |
| 101 | + # https://pandas.pydata.org/pandas-docs/stable/reference/api/pandas.DataFrame.to_html.html |
| 102 | + # Add CSS classes for CASE website Bootstrap support. |
| 103 | + table_text = df.to_html(classes=("table", "table-bordered", "table-condensed")) |
| 104 | + elif args.out_table.endswith(".md"): |
| 105 | + # https://pandas.pydata.org/pandas-docs/stable/reference/api/pandas.DataFrame.to_markdown.html |
| 106 | + # https://pypi.org/project/tabulate/ |
| 107 | + # Assume Github-flavored Markdown. |
| 108 | + table_text = df.to_markdown(tablefmt="github") |
| 109 | + if table_text is None: |
| 110 | + raise NotImplementedError("Unsupported output extension for output filename %r.", args.out_table) |
| 111 | + |
| 112 | + with open(args.out_table, "w") as out_fh: |
| 113 | + out_fh.write(table_text) |
| 114 | + |
| 115 | +if __name__ == "__main__": |
| 116 | + main() |
0 commit comments