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
2022-03-04 10:07:53 +01:00
sparql = SPARQLWrapper ( wiki_api_url , agent = ' Mozilla/5.0 (Macintosh; Intel Mac OS X 10_11_5) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/50.0.2661.102 Safari/537.36 ' )
2016-10-07 12:57:01 +02:00
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 ( )
try :
2019-10-08 13:28:23 +02:00
result = results [ " results " ] [ " bindings " ]
summary = result [ 0 ] [ " item " ] [ " value " ] if result else ' No additional data found on Wikidata '
2016-10-07 12:57:01 +02:00
except Exception as e :
2019-10-08 13:28:23 +02:00
misperrors [ ' error ' ] = ' wikidata API not accessible {} ' . format ( e )
2016-10-07 12:57:01 +02:00
return misperrors [ ' error ' ]
r = { ' results ' : [ { ' types ' : mispattributes [ ' output ' ] , ' values ' : summary } ] }
return r
def introspection ( ) :
return mispattributes
def version ( ) :
moduleinfo [ ' config ' ] = moduleconfig
return moduleinfo