File size: 5,934 Bytes
47746e0
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
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
import requests
from requests.auth import HTTPDigestAuth, HTTPBasicAuth
import ssl
import json






def execute_query(endpoint, query, auth):
    headers = {
        'Content-Type': 'application/x-www-form-urlencoded',
        'Accept': 'application/sparql-results+json'
    }

    params = {
        'query': query
    }

    response = requests.post(endpoint, headers=headers, params=params, auth=auth)

    if response.status_code != 200:
        raise Exception(f"Failed to execute query: {response.text}")

    return response.text


def execute_query_no_cache(endpoint, query, auth):
    headers = {
        'Content-Type': 'application/x-www-form-urlencoded',
        'Accept': 'application/sparql-results+json'
    }

    params = {
        'query': query
    }

    response = requests.post(endpoint, headers=headers, params=params, auth=auth)

    if response.status_code != 200:
        raise Exception(f"Failed to execute query: {response.text}")

    return response.text


def sparqlQuery(endpoint, query, usernameVirt, passwordVirt, USE_CACHE=True):
    """
    Make a SPARQL query to a Virtuoso SPARQL endpoint.

    Args:
    - endpoint (str): The URL of the Virtuoso SPARQL endpoint.
    - query (str): The SPARQL query to execute.
    - username (str): The username for authentication.
    - password (str): The password for authentication.

    Returns:
    - responseText (requests.Response): The responseText from the Virtuoso SPARQL endpoint.
    """

    # Use SSL context to establish a secure connection
    ssl_context = ssl.create_default_context()

    # Try HTTP Digest authentication
    try:
        auth = HTTPDigestAuth(usernameVirt, passwordVirt)
        if USE_CACHE:
            responseText = execute_query(endpoint, query, auth)
        else:
            responseText = execute_query_no_cache(endpoint, query, auth)
    except Exception as e:
        print(f"HTTP Digest authentication failed: {str(e)}")

        # Fallback to Basic Auth
        try:
            auth = HTTPBasicAuth(usernameVirt, passwordVirt)
            if USE_CACHE:
                responseText = execute_query(endpoint, query, auth)
            else:
                responseText = execute_query_no_cache(endpoint, query, auth)
        except Exception as e:
            print(f"Basic Auth failed: {str(e)}")
            return None

    return responseText


#
# def sparqlQuery(endpoint, query, usernameVirt, passwordVirt):
#     """
#     Make a SPARQL query to a Virtuoso SPARQL endpoint.
#
#     Args:
#     - endpoint (str): The URL of the Virtuoso SPARQL endpoint.
#     - query (str): The SPARQL query to execute.
#     - username (str): The username for authentication.
#     - password (str): The password for authentication.
#
#     Returns:
#     - response (requests.Response): The response from the Virtuoso SPARQL endpoint.
#     """
#     headers = {
#         'Content-Type': 'application/x-www-form-urlencoded',
#         'Accept': 'application/sparql-results+json'
#     }
#
#     params = {
#         'query': query
#     }
#
#     # Use SSL context to establish a secure connection
#     ssl_context = ssl.create_default_context()
#
#     # Try HTTP Digest authentication
#     try:
#         auth = HTTPDigestAuth(usernameVirt, passwordVirt)
#         response = requests.post(endpoint, headers=headers, params=params, auth=auth)
#     except Exception as e:
#         print(f"HTTP Digest authentication failed: {str(e)}")
#
#         # Fallback to Basic Auth
#         try:
#             auth = HTTPBasicAuth(usernameVirt, passwordVirt)
#             response = requests.post(endpoint, headers=headers, params=params, auth=auth)
#         except Exception as e:
#             print(f"Basic Auth failed: {str(e)}")
#             return None
#
#     if response.status_code != 200:
#         raise Exception(f"Failed to execute query: {response.text}")
#
#     return response


if __name__ == '__main__':
    # Example usage
    endpoint = 'https://api-vast.jrc.service.ec.europa.eu/sparql'

    VirtuosoUsername = 'dba'
    VirtuosoPassword = ''
    Virtuosokey_filename = 'VIRTUOSO-dba.key'

    USE_CACHE = False # True or False

    #############

    #query = 'SELECT * WHERE { ?s ?p ?o } LIMIT 100'

    # word ="acute sinusitis"
    # query = f"""
    #         SELECT ?concept ?label (COUNT(?edge) AS ?score)
    #         WHERE {{
    #           ?concept skos:prefLabel|rdfs:label|skos:altLabel|obo:hasRelatedSynonym ?label .
    #           FILTER (LCASE(STR(?label)) = "{word}")
    #           ?concept ?edge ?o .
    #         }}
    #         GROUP BY ?concept ?label
    #         ORDER BY DESC(?score)
    #     """

    choices = ['SNOMED', 'LOINC', 'ICD10', 'MESH', 'NCIT']  # restricts the input to these values only

    # Construct the FROM clauses
    from_clauses = ' '.join([f"FROM <{choice}>" for choice in choices])

    word = "acute sinusitis"
    # Construct the full SPARQL query
    query = f"""
            SELECT ?concept ?label (COUNT(?edge) AS ?score)
            {from_clauses}
            WHERE {{
              ?concept skos:prefLabel|rdfs:label|skos:altLabel|obo:hasRelatedSynonym ?label .
              FILTER (LCASE(STR(?label)) = "{word.lower()}")
              ?concept ?edge ?o .
            }}
            GROUP BY ?concept ?label
            ORDER BY DESC(?score)
        """

    print(query)




    ###############

    if Virtuosokey_filename:
        fkeyname = Virtuosokey_filename
        with open(fkeyname) as f:
            VirtuosoPassword = f.read()

    responseText = sparqlQuery(endpoint, query, VirtuosoUsername, VirtuosoPassword, USE_CACHE)

    # Parse the response as JSON

    results = json.loads(responseText)

    # Print the results
    if len(results) > 0 and results['results']['bindings']:
        for result in results['results']['bindings']:
            print(result)
    else:
        print("!!! VIRTUOSO NO RESULTS !!!")