generators.py 2.6 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104
  1. import io
  2. import random
  3. from hashlib import sha1
  4. from math import floor
  5. import requests
  6. import numpy
  7. from PIL import Image
  8. from rdflib import Graph, URIRef, Literal
  9. from rdflib.namespace import Namespace, NamespaceManager
  10. # @TODO Update this to include code point ranges to be sampled
  11. include_ranges = [
  12. ( 0x0021, 0x0021 ),
  13. ( 0x0023, 0x0026 ),
  14. ( 0x0028, 0x007E ),
  15. ( 0x00A1, 0x00AC ),
  16. ( 0x00AE, 0x00FF ),
  17. ( 0x0100, 0x017F ),
  18. ( 0x0180, 0x024F ),
  19. ( 0x2C60, 0x2C7F ),
  20. ( 0x16A0, 0x16F0 ),
  21. ( 0x0370, 0x0377 ),
  22. ( 0x037A, 0x037E ),
  23. ( 0x0384, 0x038A ),
  24. ( 0x038C, 0x038C ),
  25. ]
  26. def random_utf8_string(length):
  27. alphabet = [
  28. chr(code_point) for current_range in include_ranges
  29. for code_point in range(current_range[0], current_range[1] + 1)
  30. ]
  31. return ''.join(random.choice(alphabet) for i in range(length))
  32. def random_image(tn=8, ims=256):
  33. """
  34. Generate a random square image with pretty color tiles.
  35. :param int tn: Number of tiles in each dimension of the image.
  36. :param int ims: Size in pixel of each dimension of the image.
  37. """
  38. imarray = numpy.random.rand(tn, tn, 3) * 255
  39. im = Image.fromarray(imarray.astype('uint8')).convert('RGBA')
  40. im = im.resize((ims, ims), Image.NEAREST)
  41. imf = io.BytesIO()
  42. im.save(imf, format='png')
  43. imf.seek(0)
  44. hash = sha1(imf.read()).hexdigest()
  45. return {
  46. 'content' : imf,
  47. 'hash' : hash,
  48. 'filename' : random_utf8_string(32) + '.png'
  49. }
  50. nsm = NamespaceManager(Graph())
  51. nsc = {
  52. 'extp': Namespace('http://ex.org/exturi_p#'),
  53. 'intp': Namespace('http://ex.org/inturi_p#'),
  54. 'litp': Namespace('http://ex.org/lit_p#'),
  55. }
  56. for pfx, ns in nsc.items():
  57. nsm.bind(pfx, ns)
  58. def random_graph(size, ref, subj=''):
  59. '''
  60. Generate a synthetic graph.
  61. @param size (int) size Size of the graph. It will be rounded by a
  62. multiplier of 4.
  63. '''
  64. gr = Graph()
  65. gr.namespace_manager = nsm
  66. for ii in range(floor(size / 4)):
  67. gr.add((
  68. URIRef(subj),
  69. nsc['intp'][f'u{ii % size}'],
  70. URIRef(ref)
  71. ))
  72. gr.add((
  73. URIRef(subj),
  74. nsc['extp'][f'u{ii % size}'],
  75. URIRef('http://example.edu/res/{}'.format(ii // 10))
  76. ))
  77. gr.add((
  78. URIRef(subj),
  79. nsc['litp'][f'l{ii % size}'],
  80. Literal(random_utf8_string(64))
  81. ))
  82. gr.add((
  83. URIRef(subj),
  84. nsc['litp'][f'l{ii % size + size}'],
  85. Literal(random_utf8_string(64))
  86. ))
  87. #print('Graph: {}'.format(gr.serialize(format='turtle').decode('utf-8')))
  88. return gr