2016-10-07 12:57:01 +02:00
import json
from SPARQLWrapper import SPARQLWrapper , JSON
misperrors = { ' error ' : ' Error ' }
2016-10-11 14:48:59 +02:00
mispattributes = { ' input ' : [ ' text ' ] , ' output ' : [ ' text ' ] }
moduleinfo = { ' version ' : ' 0.2 ' , ' author ' : ' Roman Graf ' , ' description ' : ' An expansion hover module to extract information from Wikidata to have additional information about particular term for analysis. ' , ' module-type ' : [ ' hover ' ] }
2016-10-07 12:57:01 +02:00
moduleconfig = [ ]
2016-10-11 14:48:59 +02:00
# sample query text 'Microsoft' should provide Wikidata link https://www.wikidata.org/wiki/Q2283 in response
2016-10-07 12:57:01 +02:00
wiki_api_url = ' https://query.wikidata.org/bigdata/namespace/wdq/sparql '
def handler ( q = False ) :
if q is False :
return False
request = json . loads ( q )
2016-10-11 14:48:59 +02:00
if not request . get ( ' text ' ) :
misperrors [ ' error ' ] = ' Query text missing '
2016-10-07 12:57:01 +02:00
return misperrors
2018-12-11 15:29:09 +01:00
2016-10-07 12:57:01 +02:00
sparql = SPARQLWrapper ( wiki_api_url )
query_string = \
2018-12-11 15:29:09 +01:00
" SELECT ?item \n " \
" WHERE { \n " \
" ?item rdfs:label \" " + request . get ( ' text ' ) + " \" @en \n " \
" } \n "
2016-10-07 12:57:01 +02:00
sparql . setQuery ( query_string )
sparql . setReturnFormat ( JSON )
results = sparql . query ( ) . convert ( )
2018-12-11 15:29:09 +01:00
2016-10-07 12:57:01 +02:00
summary = ' '
try :
result = results [ " results " ] [ " bindings " ] [ 0 ]
summary = result [ " item " ] [ " value " ]
except Exception as e :
misperrors [ ' error ' ] = ' wikidata API not accessible ' + e
return misperrors [ ' error ' ]
r = { ' results ' : [ { ' types ' : mispattributes [ ' output ' ] , ' values ' : summary } ] }
return r
def introspection ( ) :
return mispattributes
def version ( ) :
moduleinfo [ ' config ' ] = moduleconfig
return moduleinfo