mustrd 0.2.6.2__py3-none-any.whl → 0.2.7a0__py3-none-any.whl

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
mustrd/anzo_utils.py ADDED
@@ -0,0 +1,121 @@
1
+ """
2
+ MIT License
3
+
4
+ Copyright (c) 2023 Semantic Partners Ltd
5
+
6
+ Permission is hereby granted, free of charge, to any person obtaining a copy
7
+ of this software and associated documentation files (the "Software"), to deal
8
+ in the Software without restriction, including without limitation the rights
9
+ to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
10
+ copies of the Software, and to permit persons to whom the Software is
11
+ furnished to do so, subject to the following conditions:
12
+
13
+ The above copyright notice and this permission notice shall be included in all
14
+ copies or substantial portions of the Software.
15
+
16
+ THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
17
+ IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
18
+ FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
19
+ AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
20
+ LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
21
+ OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
22
+ SOFTWARE.
23
+ """
24
+
25
+ import json
26
+ from typing import List
27
+ from urllib.parse import quote
28
+ from rdflib import Graph
29
+ import requests
30
+ from requests import Response, HTTPError, RequestException
31
+ from bs4 import BeautifulSoup
32
+ import logging
33
+
34
+
35
+ def query_azg(anzo_config: dict, query: str,
36
+ format: str = "json", is_update: bool = False,
37
+ data_layers: List[str] = None):
38
+ params = {
39
+ 'skipCache': True,
40
+ 'format': format,
41
+ 'datasourceURI': anzo_config['gqe_uri'],
42
+ 'default-graph-uri': data_layers,
43
+ 'named-graph-uri': data_layers
44
+ }
45
+ url = f"{anzo_config['url']}/sparql"
46
+ return send_anzo_query(anzo_config, url=url, params=params, query=query, is_update=is_update)
47
+
48
+
49
+ def query_graphmart(anzo_config: dict,
50
+ graphmart: str,
51
+ query: str,
52
+ format: str = "json",
53
+ data_layers: List[str] = None):
54
+ params = {
55
+ 'skipCache': True,
56
+ 'format': format,
57
+ 'default-graph-uri': data_layers,
58
+ 'named-graph-uri': data_layers
59
+ }
60
+
61
+ url = f"{anzo_config['url']}/sparql/graphmart/{quote(graphmart, safe='')}"
62
+ return send_anzo_query(anzo_config, url=url, params=params, query=query)
63
+
64
+
65
+ def query_configuration(anzo_config: dict, query: str, format: str = "json"):
66
+ params = {
67
+ 'format': format,
68
+ 'includeMetadataGraphs': True
69
+ }
70
+ url = f"{anzo_config['url']}/sparql"
71
+ return send_anzo_query(anzo_config, url=url, params=params, query=query)
72
+
73
+
74
+ # https://github.com/Semantic-partners/mustrd/issues/73
75
+ def manage_anzo_response(response: Response) -> str:
76
+ content_string = response.content.decode("utf-8")
77
+ if response.status_code == 200:
78
+ logging.debug(f"Response content: {content_string}")
79
+ return content_string
80
+ elif response.status_code == 403:
81
+ html = BeautifulSoup(content_string, 'html.parser')
82
+ title_tag = html.title.string
83
+ raise HTTPError(f"Anzo authentication error, status code: {response.status_code}, content: {title_tag}")
84
+ else:
85
+ raise RequestException(f"Anzo error, status code: {response.status_code}, content: {content_string}")
86
+
87
+
88
+ def send_anzo_query(anzo_config, url, params, query, is_update=False):
89
+ headers = {"Content-Type": f"application/sparql-{'update' if is_update else 'query' }"}
90
+ return manage_anzo_response(requests.post(url=url, params=params, data=query,
91
+ auth=(anzo_config['username'], anzo_config['password']),
92
+ headers=headers, verify=False))
93
+
94
+
95
+ def json_to_dictlist(json_string: str):
96
+ return list(map(lambda result: process_result(result), json.loads(json_string)['results']['bindings']))
97
+
98
+
99
+ def ttl_to_graph(ttl_string: str):
100
+ return Graph().parse(data=ttl_string)
101
+
102
+
103
+ # Convert result to the right type
104
+ def process_result(result):
105
+ xsd = "http://www.w3.org/2001/XMLSchema#"
106
+ types = {
107
+ f"{xsd}int": int,
108
+ f"{xsd}integer": int,
109
+ f"{xsd}decimal": float,
110
+ f"{xsd}float": float,
111
+ f"{xsd}double": float,
112
+ f"{xsd}long": int
113
+ }
114
+ res = {}
115
+ for key, type_value in result.items():
116
+ if type_value['type'] in types:
117
+ value = types[type_value['type']](type_value['value'])
118
+ else:
119
+ value = type_value['value']
120
+ res.update({key: value})
121
+ return res
mustrd/logger_setup.py CHANGED
@@ -34,6 +34,10 @@ LOG_FORMAT = '%(log_color)s%(levelname)s:%(name)s:%(white)s%(message)s'
34
34
  def setup_logger(name: str) -> logging.Logger:
35
35
  log = logging.getLogger(name)
36
36
  log.setLevel(LOG_LEVEL)
37
+
38
+ stderr_handler = logging.StreamHandler(sys.stderr)
39
+ stderr_handler.setLevel(logging.ERROR)
40
+ log.addHandler(stderr_handler)
37
41
 
38
42
  ch = logging.StreamHandler(sys.stdout)
39
43
  ch.setLevel(LOG_LEVEL)
@@ -26,8 +26,6 @@
26
26
  #
27
27
  # https://mustrd.com/triplestore/password
28
28
  #
29
- # https://mustrd.com/triplestore/port
30
- #
31
29
  # https://mustrd.com/triplestore/repository
32
30
  #
33
31
  # https://mustrd.com/triplestore/url
@@ -89,12 +87,6 @@ For those triple stores, this property must be mandatory""";
89
87
  rdfs:range xsd:string;
90
88
  rdfs:label "password" .
91
89
 
92
- :port a owl:DatatypeProperty;
93
- rdfs:domain :ExternalTripleStore;
94
- rdfs:range xsd:string;
95
- rdfs:comment "Triple store port";
96
- rdfs:label "port" .
97
-
98
90
  :repository a owl:DatatypeProperty;
99
91
  rdfs:domain :GraphDb;
100
92
  rdfs:range xsd:string;
@@ -12,9 +12,6 @@ triplestore:ExternalTripleStoreShape
12
12
  sh:property [ sh:path triplestore:url ;
13
13
  sh:minCount 1 ;
14
14
  sh:maxCount 1 ],
15
- [ sh:path triplestore:port ;
16
- sh:minCount 1 ;
17
- sh:maxCount 1 ],
18
15
  [ sh:path triplestore:username ;
19
16
  sh:maxCount 1 ],
20
17
  [ sh:path triplestore:password ;