1313from aperturedb .CommonLibrary import create_connector , execute_query
1414from aperturedb .Utils import Utils
1515
16+ SAFE_PREFIX = "adb_"
17+
1618
1719class SPARQL :
1820 def __init__ (self , client = None , debug = False , log_level = None ):
@@ -93,6 +95,12 @@ def _format_triple(self, triple):
9395 def _format_triples (self , triples ):
9496 return " .\n " .join ([self ._format_triple (triple ) for triple in triples ])
9597
98+ def _make_safe_prefix (self , suffix ):
99+ return f"{ SAFE_PREFIX } { suffix [1 :]} " if suffix .startswith ("_" ) else suffix
100+
101+ def _make_command_name (self , t ):
102+ return "Find" + t [len (SAFE_PREFIX ):] if t .startswith (f"{ SAFE_PREFIX } " ) else "FindEntity"
103+
96104 def _load_schema (self ):
97105 self .schema = self ._utils .get_schema ()
98106 self .connections = {}
@@ -109,14 +117,17 @@ def _load_schema(self):
109117 d_list = [d ] if isinstance (d , dict ) else d
110118
111119 for d in d_list :
112- self .connections [uri ][0 ].add (d ["src" ])
113- self .connections [uri ][1 ].add (d ["dst" ])
120+ self .connections [uri ][0 ].add (
121+ self ._make_safe_prefix (d ["src" ]))
122+ self .connections [uri ][1 ].add (
123+ self ._make_safe_prefix (d ["dst" ]))
114124 if not self .connections :
115125 self .logger .warning ("No connections found in schema" )
116126
117127 self .properties = {}
118128 if "entities" in self .schema and self .schema ["entities" ] is not None and "classes" in self .schema ["entities" ]:
119129 for e , d in self .schema ["entities" ]["classes" ].items ():
130+ e = self ._make_safe_prefix (e )
120131 for p in d ["properties" ]:
121132 uri = self ._make_uri ("p" , p )
122133 if uri not in self .properties :
@@ -166,9 +177,9 @@ def evalBGP(self, ctx: "QueryContext",
166177 def add_find (v , t ):
167178 """Create new Find* command for variable v with type t"""
168179 from rdflib .term import Variable
169- command_name = "FindEntity" if t [0 ] != "_" else "Find" + t [1 :]
170180 body = {}
171- if t [0 ] != "_" :
181+ command_name = self ._make_command_name (t )
182+ if command_name == "FindEntity" :
172183 body ["with_class" ] = t
173184 body ["_ref" ] = len (query ) + 1
174185 body ["uniqueids" ] = True
@@ -445,7 +456,7 @@ def add_types(k, tt):
445456 add_types (s , [self ._parse_uri_with_ns ('t' , o )])
446457 elif p in self .knn_properties :
447458 if p == self .namespaces ["knn" ] + "similarTo" :
448- add_types (s , {"_Descriptor" })
459+ add_types (s , {self . _make_safe_prefix ( "_Descriptor" ) })
449460 elif p == self .namespaces ["c" ] + "ANY" :
450461 pass
451462 else :
@@ -509,9 +520,10 @@ def get_blob(self, uri: Union[str, "URIRef"], type: Optional[str] = None) -> byt
509520 assert type == self ._deduce_type (
510521 uri ), f"Type { type } does not match deduced type { self ._deduce_type (uri )} "
511522 assert type is not None , f"Cannot get blob for entity URI: { uri } "
512- assert type [0 ] == "_" , f"Cannot get blob for entity URI: { uri } with type { type } "
523+ assert type .startswith (
524+ f"{ SAFE_PREFIX } " ), f"Cannot get blob for entity URI: { uri } with type { type } "
513525 uniqueid = self ._deduce_uniqueid (uri )
514- command_name = "Find" + type [ 1 :]
526+ command_name = self . _make_command_name ( type )
515527 query = [
516528 {command_name : {
517529 "constraints" : {
@@ -539,9 +551,10 @@ def get_blobs(self, uris: List[Union[str, "URIRef"]], type: Optional[str] = None
539551 t == type for t in types ), f"Types do not match: { types } "
540552
541553 assert type is not None , f"Cannot get blob for entity URI: { uri } "
542- assert type [0 ] == "_" , f"Cannot get blob for entity URI: { uri } with type { type } "
554+ assert type .startswith (
555+ f"{ SAFE_PREFIX } " ), f"Cannot get blob for entity URI: { uri } with type { type } "
543556 uniqueids = [self ._deduce_uniqueid (uri ) for uri in uris ]
544- command_name = "Find" + type [ 1 :]
557+ command_name = self . _make_command_name ( type )
545558 query = [
546559 {command_name : {
547560 "results" : {"list" : ["_uniqueid" ]},
@@ -568,7 +581,7 @@ def get_image(self, uri: Union[str, "URIRef"]) -> "np.ndarray":
568581 import numpy as np
569582 import cv2
570583
571- blob = self .get_blob (uri , type = "_Image" )
584+ blob = self .get_blob (uri , type = self . _make_safe_prefix ( "_Image" ) )
572585 nparr = np .fromstring (blob , np .uint8 )
573586 image = cv2 .imdecode (nparr , cv2 .IMREAD_COLOR )
574587 image = cv2 .cvtColor (image , cv2 .COLOR_BGR2RGB )
@@ -581,7 +594,7 @@ def get_images(self, uris: List[Union[str, "URIRef"]]) -> List["np.ndarray"]:
581594 import numpy as np
582595 import cv2
583596
584- blobs = self .get_blobs (uris , type = "_Image" )
597+ blobs = self .get_blobs (uris , type = self . _make_safe_prefix ( "_Image" ) )
585598 images = []
586599 for blob in blobs :
587600 if blob is not None :
@@ -616,13 +629,14 @@ def get_descriptor(self, uri: Union[str, "URIRef"]) -> "np.ndarray":
616629 Get the descriptor associated with a URI or QName
617630 """
618631 import numpy as np
619- blob = self .get_blob (uri , type = "_Descriptor" )
632+ blob = self .get_blob (uri , type = self . _make_safe_prefix ( "_Descriptor" ) )
620633 return np .frombuffer (blob , dtype = np .float32 )
621634
622635 def get_descriptors (self , uris : List [Union [str , "URIRef" ]]) -> List ["np.ndarray" ]:
623636 """
624637 Get the descriptors associated with a list of URI or QName
625638 """
626639 import numpy as np
627- blobs = self .get_blobs (uris , type = "_Descriptor" )
640+ blobs = self .get_blobs (
641+ uris , type = self ._make_safe_prefix ("_Descriptor" ))
628642 return [np .frombuffer (blob , dtype = np .float32 ) for blob in blobs ]
0 commit comments