translator.py 2.6 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114
  1. from flask import request
  2. from rdflib.term import URIRef
  3. from lakesuperior.core.namespaces import ns_collection as nsc
  4. class Translator:
  5. '''
  6. Utility class to perform translations of strings and their wrappers.
  7. All static methods.
  8. '''
  9. @staticmethod
  10. def camelcase(word):
  11. '''
  12. Convert a string with underscores with a camel-cased one.
  13. Ripped from https://stackoverflow.com/a/6425628
  14. '''
  15. return ''.join(x.capitalize() or '_' for x in word.split('_'))
  16. @staticmethod
  17. def uuid_to_uri(uuid):
  18. '''Convert a UUID to a URI.
  19. @return URIRef
  20. '''
  21. return URIRef('{}rest/{}'.format(request.host_url, uuid))
  22. @staticmethod
  23. def localize_string(s):
  24. '''Convert URIs into URNs in a string using the application base URI.
  25. @param string s Input string.
  26. @return string
  27. '''
  28. return s.replace(
  29. request.host_url + 'rest/',
  30. str(nsc['fcres'])
  31. )
  32. @staticmethod
  33. def globalize_string(s):
  34. '''Convert URNs into URIs in a string using the application base URI.
  35. @param string s Input string.
  36. @return string
  37. '''
  38. return s.replace(
  39. str(nsc['fcres']),
  40. request.host_url + 'rest/'
  41. )
  42. @staticmethod
  43. def globalize_term(urn):
  44. '''
  45. Convert an URN into an URI using the application base URI.
  46. @param rdflib.term.URIRef urn Input URN.
  47. @return rdflib.term.URIRef
  48. '''
  49. return URIRef(Translator.globalize_string(str(urn)))
  50. @staticmethod
  51. def globalize_graph(g):
  52. '''
  53. Globalize a graph.
  54. '''
  55. q = '''
  56. CONSTRUCT {{ ?s ?p ?o . }} WHERE {{
  57. {{
  58. ?s ?p ?o .
  59. FILTER STRSTARTS(str(?s), "{0}") .
  60. }}
  61. UNION
  62. {{
  63. ?s ?p ?o .
  64. FILTER STRSTARTS(str(?o), "{0}") .
  65. }}
  66. }}'''.format(nsc['fcres'])
  67. flt_g = g.query(q)
  68. for t in flt_g:
  69. print('Triple: {}'.format(t))
  70. global_s = Translator.globalize_term(t[0])
  71. global_o = Translator.globalize_term(t[2]) \
  72. if isinstance(t[2], URIRef) \
  73. else t[2]
  74. g.remove(t)
  75. g.add((global_s, t[1], global_o))
  76. return g
  77. @staticmethod
  78. def globalize_rsrc(rsrc):
  79. '''
  80. Globalize a resource.
  81. '''
  82. g = rsrc.graph
  83. urn = rsrc.identifier
  84. global_g = Translator.globalize_graph(g)
  85. global_uri = Translator.globalize_term(urn)
  86. return global_g.resource(global_uri)