views.py 13 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415
  1. # django imports
  2. from django.shortcuts import render
  3. from django.http import HttpResponse
  4. from django.conf import settings
  5. from django.contrib.auth.decorators import login_required
  6. from django.http import Http404
  7. # main imports
  8. import os
  9. import json
  10. import base64
  11. import random
  12. import numpy as np
  13. from datetime import datetime
  14. import pickle
  15. import time
  16. import zipfile
  17. from io import BytesIO
  18. # expe imports
  19. from .expes.classes.quest_plus import QuestPlus
  20. from .expes.classes.quest_plus import psychometric_fun
  21. from .expes import run as run_expe
  22. # image processing imports
  23. import io
  24. from PIL import Image
  25. # module imports
  26. from .utils import api
  27. from .utils import functions
  28. from .utils.processing import crop_images
  29. from . import config as cfg
  30. def get_base_data(expe_name=None):
  31. '''
  32. Used to store default data to send for each view
  33. '''
  34. data = {}
  35. data['BASE'] = settings.WEBEXPE_PREFIX_URL
  36. # if expe name is used
  37. if expe_name is not None:
  38. data['javascript'] = cfg.expes_configuration[expe_name]['javascript']
  39. return data
  40. def expe_list(request):
  41. # get all scenes from dataset
  42. scenes = api.get_scenes()
  43. # get list of experimentss
  44. expes = cfg.expe_name_list
  45. data = get_base_data()
  46. # by default user restart expe
  47. request.session['expe_started'] = False
  48. # get base data
  49. data = get_base_data()
  50. # expe data
  51. data['scenes'] = scenes
  52. data['expes'] = expes
  53. return render(request, 'expe/expe_list.html', data)
  54. def indications(request):
  55. random.seed(10)
  56. # get param
  57. expe_name = request.GET.get('expe')
  58. scene_name = request.GET.get('scene')
  59. example_number = request.GET.get('example')
  60. print(example_number)
  61. # get base data
  62. data = get_base_data()
  63. # expe parameters
  64. data['expe_name'] = expe_name
  65. data['scene_name'] = scene_name
  66. data['question'] = cfg.expes_configuration[expe_name]['text']['question']
  67. data['indication'] = cfg.expes_configuration[expe_name]['text']['indication']
  68. number_of_examples = len(cfg.expes_configuration[expe_name]['text']['examples']['images'])
  69. start_experiment = False
  70. if (int(example_number) >= number_of_examples):
  71. start_experiment = True
  72. else:
  73. # get expected image qualities indices (load noisy and ref image)
  74. params_image = cfg.expes_configuration[expe_name]['text']['examples']['images'][int(example_number)]
  75. qualities = api.get_scene_qualities(scene_name)
  76. noisy_quality = qualities[params_image[0]]
  77. ref_quality = qualities[params_image[1]]
  78. noisy_image = api.get_image(scene_name, noisy_quality)
  79. ref_image = api.get_image(scene_name, ref_quality)
  80. # get crop params from configuration
  81. crop_params = cfg.expes_configuration[expe_name]['text']['examples']['crop_params'][int(example_number)]
  82. img_merge, percentage, orientation, position = crop_images(noisy_image,
  83. ref_image,
  84. per=crop_params[0],
  85. orien=crop_params[1],
  86. swap_img=crop_params[2])
  87. example_sentence = cfg.expes_configuration[expe_name]['text']['examples']['sentence']
  88. if orientation == 0:
  89. example_sentence = example_sentence.format('vertically', str(percentage*100))
  90. else:
  91. example_sentence = example_sentence.format('horizontally', str(percentage*100))
  92. data['example_sentence'] = example_sentence
  93. # Temporary save of image
  94. tmp_folder = os.path.join(settings.MEDIA_ROOT, cfg.output_tmp_folder)
  95. if not os.path.exists(tmp_folder):
  96. os.makedirs(tmp_folder)
  97. # generate tmp merged image (pass as BytesIO was complicated..)
  98. filepath_img = os.path.join(tmp_folder, 'example_' + scene_name + '' + expe_name + '.png')
  99. # replace img_merge if necessary (new iteration of expe)
  100. if img_merge is not None:
  101. img_merge.save(filepath_img)
  102. print(filepath_img)
  103. data['example'] = filepath_img
  104. data['start'] = start_experiment
  105. return render(request, 'expe/expe_indications.html', data)
  106. # Create your views here.
  107. def expe(request):
  108. # get param
  109. expe_name = request.GET.get('expe')
  110. scene_name = request.GET.get('scene')
  111. # unique user ID during session (user can launch multiple exeperiences)
  112. if 'id' not in request.session:
  113. request.session['id'] = functions.uniqueID()
  114. # first time expe is launched add expe information
  115. if 'expe' not in request.session or expe_name != request.session.get('expe'):
  116. refresh_data(request, expe_name, scene_name)
  117. # refresh if scene_name changed
  118. if 'scene' not in request.session or scene_name != request.session.get('scene'):
  119. refresh_data(request, expe_name, scene_name)
  120. # create output folder for expe_result
  121. current_day = datetime.strftime(datetime.utcnow(), "%Y-%m-%d")
  122. user_identifier = request.session.get('id')
  123. experiment_id = request.session.get('experimentId')
  124. print("ExperimentId is : " + experiment_id)
  125. # check if experimentId is used or not
  126. if len(experiment_id) == 0:
  127. output_expe_folder = cfg.output_expe_folder_name_day.format(expe_name, current_day, user_identifier)
  128. else:
  129. output_expe_folder = cfg.output_expe_folder_name_id_day.format(expe_name, experiment_id, current_day, user_identifier)
  130. results_folder = os.path.join(settings.MEDIA_ROOT, output_expe_folder)
  131. if not os.path.exists(results_folder):
  132. os.makedirs(results_folder)
  133. result_filename = scene_name + '_' + request.session.get('timestamp') +".csv"
  134. results_filepath = os.path.join(results_folder, result_filename)
  135. if not os.path.exists(results_filepath):
  136. output_file = open(results_filepath, 'w')
  137. functions.write_header_expe(output_file, expe_name)
  138. else:
  139. output_file = open(results_filepath, 'a')
  140. # TODO : add crontab task to erase generated img and model data
  141. # create `quest` object if not exists
  142. models_folder = os.path.join(settings.MEDIA_ROOT, cfg.model_expe_folder.format(expe_name, current_day))
  143. if not os.path.exists(models_folder):
  144. os.makedirs(models_folder)
  145. model_filename = result_filename.replace('.csv', '.obj')
  146. model_filepath = os.path.join(models_folder, model_filename)
  147. # run expe method using `expe_name`
  148. function_name = 'run_' + expe_name
  149. try:
  150. run_expe_method = getattr(run_expe, function_name)
  151. except AttributeError:
  152. raise NotImplementedError("Run expe method `{}` not implement `{}`".format(run_expe.__name__, function_name))
  153. expe_data = run_expe_method(request, model_filepath, output_file)
  154. if request.session.get('expe_finished'):
  155. # reinit session as default value
  156. # here generic expe params
  157. del request.session['expe']
  158. del request.session['scene']
  159. del request.session['experimentId']
  160. del request.session['qualities']
  161. del request.session['timestamp']
  162. # specific current expe session params (see `config.py`)
  163. for key in cfg.expes_configuration[expe_name]['session_params']:
  164. del request.session[key]
  165. # set expe current data into session (replace only if experiments data changed)
  166. if expe_data is not None:
  167. request.session['expe_data'] = expe_data
  168. # get base data
  169. data = get_base_data(expe_name)
  170. # other experimentss information
  171. data['expe_name'] = expe_name
  172. data['end_text'] = cfg.expes_configuration[expe_name]['text']['end_text']
  173. return render(request, cfg.expes_configuration[expe_name]['template'], data)
  174. @login_required(login_url="login/")
  175. def list_results(request, expe=None):
  176. """
  177. Return all results obtained from experimentss
  178. """
  179. if expe is None:
  180. folders = cfg.expe_name_list
  181. return render(request, 'expe/expe_results.html', {'expe': expe, 'folders': folders})
  182. else:
  183. if expe in cfg.expe_name_list:
  184. folder_date_path = os.path.join(settings.MEDIA_ROOT, cfg.output_expe_folder_date, expe)
  185. folder_id_path = os.path.join(settings.MEDIA_ROOT, cfg.output_expe_folder_id, expe)
  186. # extract date files
  187. folders_date = {}
  188. if os.path.exists(folder_date_path):
  189. days = sorted(os.listdir(folder_date_path), reverse=True)
  190. # get all days
  191. for day in days:
  192. day_path = os.path.join(folder_date_path, day)
  193. users = os.listdir(day_path)
  194. folders_user = {}
  195. # get all users files
  196. for user in users:
  197. user_path = os.path.join(day_path, user)
  198. filenames = os.listdir(user_path)
  199. folders_user[user] = filenames
  200. # attach users to this day
  201. folders_date[day] = folders_user
  202. # extract expe id files
  203. folders_id = {}
  204. if os.path.exists(folder_id_path):
  205. ids = sorted(os.listdir(folder_id_path), reverse=True)
  206. # get all days
  207. for identifier in ids:
  208. id_path = os.path.join(folder_id_path, identifier)
  209. days = sorted(os.listdir(id_path), reverse=True)
  210. folder_days = {}
  211. # get all days
  212. for day in days:
  213. day_path = os.path.join(id_path, day)
  214. users = os.listdir(day_path)
  215. folders_user = {}
  216. # get all users files
  217. for user in users:
  218. user_path = os.path.join(day_path, user)
  219. filenames = os.listdir(user_path)
  220. folders_user[user] = filenames
  221. # attach users to this day
  222. folder_days[day] = folders_user
  223. folders_id[identifier] = folder_days
  224. folders = { 'date': folders_date, 'expeId': folders_id}
  225. else:
  226. raise Http404("Expe does not exists")
  227. # get base data
  228. data = get_base_data()
  229. # expe parameters
  230. data['expe'] = expe
  231. data['folders'] = folders
  232. data['infos'] = cfg.expes_configuration[expe]['text']
  233. return render(request, 'expe/expe_results.html', data)
  234. @login_required(login_url="login/")
  235. def download_result(request):
  236. path = request.POST.get('path')
  237. folder_path = os.path.join(settings.MEDIA_ROOT, cfg.output_expe_folder, path)
  238. # Folder is required
  239. if os.path.exists(folder_path):
  240. # Open BytesIO to grab in-memory ZIP contents
  241. s = BytesIO()
  242. # check if file or folder
  243. if os.path.isdir(folder_path):
  244. # get files from a specific day
  245. filenames = os.listdir(folder_path)
  246. # Folder name in ZIP archive which contains the above files
  247. # E.g [thearchive.zip]/somefiles/file2.txt
  248. # FIXME: Set this to something better
  249. zip_subdir = folder_path.split('/')[-1]
  250. zip_filename = "%s.zip" % zip_subdir
  251. # The zip compressor
  252. zf = zipfile.ZipFile(s, "w")
  253. for fpath in filenames:
  254. fpath = os.path.join(folder_path, fpath)
  255. # Calculate path for file in zip
  256. fdir, fname = os.path.split(fpath)
  257. zip_path = os.path.join(zip_subdir, fname)
  258. # Add file, at correct path
  259. zf.write(fpath, zip_path)
  260. # Must close zip for all contents to be written
  261. zf.close()
  262. output_filename = zip_filename
  263. content = s.getvalue()
  264. else:
  265. with open(folder_path, 'rb') as f:
  266. content = f.readlines()
  267. # filename only
  268. fdir, fname = os.path.split(path)
  269. output_filename = fname
  270. # Grab ZIP file from in-memory, make response with correct MIME-type
  271. resp = HttpResponse(content, content_type="application/gzip")
  272. # ..and correct content-disposition
  273. resp['Content-Disposition'] = 'attachment; filename=%s' % output_filename
  274. return resp
  275. else:
  276. return Http404("Path does not exist")
  277. def refresh_data(request, expe_name, scene_name):
  278. '''
  279. Utils method to refresh data from session
  280. '''
  281. request.session['expe'] = expe_name
  282. request.session['scene'] = scene_name
  283. request.session['expe_started'] = False
  284. request.session['expe_finished'] = False
  285. request.session['qualities'] = api.get_scene_qualities(scene_name)
  286. # update unique timestamp each time new experiments is launched
  287. request.session['timestamp'] = datetime.strftime(datetime.utcnow(), "%Y-%m-%d_%Hh%Mm%Ss")
  288. # retrieve and store experimentId
  289. expe_id = request.GET.get('experimentId')
  290. request.session['experimentId'] = expe_id
  291. # TODO : add in cache ref_image
  292. # get reference image
  293. #ref_image = api.get_image(scene_name, 'max')
  294. # save ref image as list (can't save python object)
  295. #request.session['ref_img'] = np.array(ref_image).tolist()