1
1

file_tests.py 12 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414
  1. import cv2
  2. import io
  3. import numpy as np
  4. import os
  5. import uuid
  6. from PIL import Image
  7. from flask import url_for
  8. from pathlib import Path
  9. from pycs.database.File import File
  10. from pycs.util.FileOperations import BoundingBox
  11. from tests.base import pаtch_tpool_execute
  12. from tests.client.label_tests import _BaseLabelTests
  13. class _BaseFileTests(_BaseLabelTests):
  14. def setupModels(self):
  15. super().setupModels()
  16. root = Path(self.project.root_folder)
  17. data_root = Path(self.project.data_folder)
  18. for folder in [data_root, root / "temp"]:
  19. folder.mkdir(exist_ok=True, parents=True)
  20. class FileCreationTests(_BaseFileTests):
  21. @pаtch_tpool_execute
  22. def test_file_upload_project_with_external_data(self, mocked_execute=None):
  23. file_content = b"some content+1"
  24. url = url_for("upload_file", project_id=self.project.id)
  25. self.assertEqual(0, File.query.count())
  26. self.project.external_data = True
  27. self.project.commit()
  28. self.post(url,
  29. data=dict(file=(io.BytesIO(file_content), "image.jpg")),
  30. content_type="multipart/form-data",
  31. status_code=400,
  32. )
  33. self.assertEqual(0, File.query.count())
  34. @pаtch_tpool_execute
  35. def test_file_upload(self, mocked_execute=None):
  36. url = url_for("upload_file", project_id=4242)
  37. self.post(url, data=dict(), status_code=404)
  38. file_content = b"some content+1"
  39. url = url_for("upload_file", project_id=self.project.id)
  40. self.assertEqual(0, File.query.count())
  41. self.post(url, data=dict(),
  42. status_code=400)
  43. self.assertEqual(0, File.query.count())
  44. self.post(url,
  45. data=dict(file=(io.BytesIO(file_content), "image.jpg")),
  46. content_type="multipart/form-data",
  47. )
  48. self.assertEqual(1, File.query.count())
  49. # this does not work, if we do not set the CONTENT_LENGTH by ourself
  50. # file = File.query.first()
  51. # self.assertEqual(len(file_content), file.size)
  52. class FileDeletionTests(_BaseFileTests):
  53. def test_file_removal(self):
  54. file_uuid = str(uuid.uuid1())
  55. file, is_new = self.project.add_file(
  56. uuid=file_uuid,
  57. file_type="image",
  58. name=f"name",
  59. filename=f"image",
  60. extension=".jpg",
  61. size=32*1024,
  62. )
  63. self.assertTrue(is_new)
  64. self.assertEqual(1, self.project.files.count())
  65. with open(file.absolute_path, "w"):
  66. pass
  67. self.assertTrue(os.path.exists(file.absolute_path))
  68. url = url_for("remove_file", file_id=file.id)
  69. self.post(url, json=dict(), status_code=400)
  70. self.post(url, json=dict(remove=False), status_code=400)
  71. self.post(url, json=dict(remove=True))
  72. self.assertEqual(0, self.project.files.count())
  73. self.assertFalse(os.path.exists(file.absolute_path))
  74. url = url_for("remove_file", file_id=4242)
  75. self.post(url, json=dict(remove=True), status_code=404)
  76. def test_file_removal_from_project_with_external_data(self):
  77. file_uuid = str(uuid.uuid1())
  78. file, is_new = self.project.add_file(
  79. uuid=file_uuid,
  80. file_type="image",
  81. name=f"name",
  82. filename=f"image",
  83. extension=".jpg",
  84. size=32*1024,
  85. )
  86. self.assertTrue(is_new)
  87. with open(file.absolute_path, "w"):
  88. pass
  89. self.project.external_data = True
  90. self.assertTrue(os.path.exists(file.absolute_path))
  91. url = url_for("remove_file", file_id=file.id)
  92. self.assertEqual(1, self.project.files.count())
  93. self.post(url, json=dict(remove=True), status_code=400)
  94. self.assertEqual(1, self.project.files.count())
  95. class FileGettingTests(_BaseFileTests):
  96. def test_get_file_getting(self):
  97. file_uuid = str(uuid.uuid1())
  98. file, is_new = self.project.add_file(
  99. uuid=file_uuid,
  100. file_type="image",
  101. name=f"name",
  102. filename=f"image",
  103. extension=".jpg",
  104. size=32*1024,
  105. )
  106. self.assertTrue(is_new)
  107. self.assertEqual(1, self.project.files.count())
  108. url = url_for("get_file", file_id=file.id)
  109. # without an actual file, this GET request returns 404
  110. self.get(url, status_code=404)
  111. content = b"some text"
  112. with open(file.absolute_path, "wb") as f:
  113. f.write(content)
  114. response = self.get(url)
  115. self.assertFalse(response.is_json)
  116. self.assertEqual(content, response.data)
  117. def test_get_prev_next_file(self):
  118. for i in range(1, 6):
  119. file_uuid = str(uuid.uuid1())
  120. file, is_new = self.project.add_file(
  121. uuid=file_uuid,
  122. file_type="image",
  123. name=f"name_{i}",
  124. filename=f"image_{i}",
  125. extension=".jpg",
  126. size=32*1024,
  127. )
  128. self.assertTrue(is_new)
  129. with open(file.absolute_path, "wb") as f:
  130. f.write(b"some content")
  131. self.assertEqual(5, self.project.files.count())
  132. files = self.project.files.all()
  133. url = url_for("get_previous_and_next_file", file_id=4542)
  134. self.get(url, status_code=404)
  135. for i, file in enumerate(files):
  136. p_file, n_file = None, None
  137. if i != 0:
  138. p_file = files[i-1].serialize()
  139. if i < len(files)-1:
  140. n_file = files[i+1].serialize()
  141. url = url_for("get_previous_and_next_file", file_id=file.id)
  142. response = self.get(url)
  143. self.assertTrue(response.is_json)
  144. content_should = dict(
  145. next=n_file,
  146. nextInCollection=n_file,
  147. previous=p_file,
  148. previousInCollection=p_file,
  149. )
  150. self.assertDictEqual(content_should, response.json)
  151. files[1].delete()
  152. file = files[2]
  153. p_file, n_file = files[0], files[3]
  154. url = url_for("get_previous_and_next_file", file_id=file.id)
  155. response = self.get(url)
  156. self.assertTrue(response.is_json)
  157. content_should = dict(
  158. next=n_file.serialize(),
  159. nextInCollection=n_file.serialize(),
  160. previous=p_file.serialize(),
  161. previousInCollection=p_file.serialize(),
  162. )
  163. self.assertDictEqual(content_should, response.json)
  164. files[3].delete()
  165. file = files[2]
  166. p_file, n_file = files[0], files[4]
  167. url = url_for("get_previous_and_next_file", file_id=file.id)
  168. response = self.get(url)
  169. self.assertTrue(response.is_json)
  170. content_should = dict(
  171. next=n_file.serialize(),
  172. nextInCollection=n_file.serialize(),
  173. previous=p_file.serialize(),
  174. previousInCollection=p_file.serialize(),
  175. )
  176. self.assertDictEqual(content_should, response.json)
  177. class FileResizingTests(_BaseFileTests):
  178. def _add_image(self, shape, file: File):
  179. image = np.random.randint(0, 256, shape).astype(np.uint8)
  180. im = Image.fromarray(image)
  181. im.save(file.absolute_path)
  182. self.assertTrue(os.path.exists(file.absolute_path))
  183. return image
  184. def _compare_images(self, im0, im1, threshold=1e-3):
  185. im0, im1 = im0 / 255, im1 / 255
  186. mse = np.mean((im0 - im1)**2)
  187. self.assertLess(mse, threshold)
  188. @pаtch_tpool_execute
  189. def test_resize_image(self, mocked_execute):
  190. self.get(url_for("get_resized_file", file_id=4242, resolution=300), status_code=404)
  191. file_uuid = str(uuid.uuid1())
  192. file, is_new = self.project.add_file(
  193. uuid=file_uuid,
  194. file_type="image",
  195. name=f"name",
  196. filename=f"image",
  197. extension=".png",
  198. size=32*1024,
  199. )
  200. self.assertTrue(is_new)
  201. image = self._add_image((300, 300), file)
  202. for upscale in [300, 1200, 500, 320]:
  203. url = url_for("get_resized_file", file_id=file.id, resolution=upscale)
  204. response = self.get(url)
  205. self.assertFalse(response.is_json)
  206. returned_im = _im_from_bytes(response.data)
  207. self.assertEqual(image.shape, returned_im.shape)
  208. self._compare_images(image, returned_im)
  209. # repeat the last scale two times to get the cached resized image
  210. for downscale in [299, 200, 150, 32, 32]:
  211. sm_image = _resize(image, downscale)
  212. url = url_for("get_resized_file", file_id=file.id, resolution=downscale)
  213. response = self.get(url)
  214. self.assertFalse(response.is_json)
  215. returned_im = _im_from_bytes(response.data)
  216. self.assertEqual(sm_image.shape, returned_im.shape)
  217. self._compare_images(sm_image, returned_im)
  218. del sm_image
  219. @pаtch_tpool_execute
  220. def test_resize_image_not_found(self, mocked_execute):
  221. file_uuid = str(uuid.uuid1())
  222. file, is_new = self.project.add_file(
  223. uuid=file_uuid,
  224. file_type="image",
  225. name=f"name",
  226. filename=f"image",
  227. extension=".png",
  228. size=32*1024,
  229. )
  230. self.assertTrue(is_new)
  231. image = self._add_image((300, 300), file)
  232. save = file.path
  233. file.path = "/some/nonexisting/path"
  234. file.commit()
  235. url = url_for("get_resized_file", file_id=file.id, resolution=300)
  236. response = self.get(url, status_code=404)
  237. file.path = save
  238. file.commit()
  239. @pаtch_tpool_execute
  240. def test_crop_image_not_found(self, mocked_execute):
  241. file_uuid = str(uuid.uuid1())
  242. file, is_new = self.project.add_file(
  243. uuid=file_uuid,
  244. file_type="image",
  245. name=f"name",
  246. filename=f"image",
  247. extension=".png",
  248. size=32*1024,
  249. )
  250. self.assertTrue(is_new)
  251. image = self._add_image((300, 300), file)
  252. save = file.path
  253. file.path = "/some/nonexisting/path"
  254. file.commit()
  255. url = url_for("get_cropped_file", file_id=file.id,
  256. resolution=300, crop_box="0x0x1x1")
  257. response = self.get(url, status_code=404)
  258. file.path = save
  259. file.commit()
  260. @pаtch_tpool_execute
  261. def test_crop_image(self, mocked_execute):
  262. file_uuid = str(uuid.uuid1())
  263. file, is_new = self.project.add_file(
  264. uuid=file_uuid,
  265. file_type="image",
  266. name=f"name",
  267. filename=f"image",
  268. extension=".png",
  269. size=32*1024,
  270. )
  271. self.assertTrue(is_new)
  272. image = self._add_image((300, 300), file)
  273. for box in [(0,0,1,1), (0,0,1/2,1/2), (1/2,1/2, 1, 1), (1/3,1/2,3/4, 1), ]:
  274. url = url_for("get_cropped_file", file_id=file.id,
  275. resolution=300, crop_box="x".join(map(str, box)))
  276. response = self.get(url)
  277. self.assertFalse(response.is_json)
  278. returned_im = _im_from_bytes(response.data)
  279. crop = _crop(image, BoundingBox(*box))
  280. self.assertEqual(crop.shape, returned_im.shape)
  281. self._compare_images(crop, returned_im)
  282. def _im_from_bytes(data: bytes) -> np.ndarray:
  283. return np.asarray(Image.open(io.BytesIO(data)))
  284. def _resize(image: np.ndarray, size: int) -> np.ndarray:
  285. return np.asarray(Image.fromarray(image).resize((size, size)))
  286. def _crop(image: np.ndarray, box: BoundingBox) -> np.ndarray:
  287. h, w, *c = image.shape
  288. x0, y0 = int(w * box.x), int(h * box.y)
  289. crop_w, crop_h = int(w * box.w), int(h * box.h)
  290. x1, y1 = x0 + crop_w, y0 + crop_h
  291. return image[y0:y1, x0:x1]