views.py 8.7 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295
  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. # by default user restart expe
  46. request.session['expe_started'] = False
  47. # get base data
  48. data = get_base_data()
  49. # expe data
  50. data['scenes'] = scenes
  51. data['expes'] = expes
  52. return render(request, 'expe/expe_list.html', data)
  53. def indications(request):
  54. # get param
  55. expe_name = request.GET.get('expe')
  56. # get base data
  57. data = get_base_data()
  58. # expe parameters
  59. data['expe_name'] = expe_name
  60. data['question'] = cfg.expes_configuration[expe_name]['text']['question']
  61. data['indication'] = cfg.expes_configuration[expe_name]['text']['indication']
  62. return render(request, 'expe/expe_indications.html', data)
  63. # Create your views here.
  64. def expe(request):
  65. # get param
  66. expe_name = request.GET.get('expe')
  67. scene_name = request.GET.get('scene')
  68. # unique user ID during session (user can launch multiple exeperiences)
  69. if 'id' not in request.session:
  70. request.session['id'] = functions.uniqueID()
  71. # first time expe is launched add expe information
  72. if 'expe' not in request.session or expe_name != request.session.get('expe'):
  73. refresh_data(request, expe_name, scene_name)
  74. # refresh if scene_name changed
  75. if 'scene' not in request.session or scene_name != request.session.get('scene'):
  76. refresh_data(request, expe_name, scene_name)
  77. # create output folder for expe_result
  78. current_day = datetime.strftime(datetime.utcnow(), "%Y-%m-%d")
  79. results_folder = os.path.join(settings.MEDIA_ROOT, cfg.output_expe_folder_name_day.format(expe_name, current_day))
  80. if not os.path.exists(results_folder):
  81. os.makedirs(results_folder)
  82. result_filename = scene_name + '_' + request.session.get('id') + '_' + request.session.get('timestamp') +".csv"
  83. results_filepath = os.path.join(results_folder, result_filename)
  84. if not os.path.exists(results_filepath):
  85. output_file = open(results_filepath, 'w')
  86. functions.write_header_expe(output_file, expe_name)
  87. else:
  88. output_file = open(results_filepath, 'a')
  89. # TODO : add crontab task to erase generated img and model data
  90. # create `quest` object if not exists
  91. models_folder = os.path.join(settings.MEDIA_ROOT, cfg.model_expe_folder.format(expe_name, current_day))
  92. if not os.path.exists(models_folder):
  93. os.makedirs(models_folder)
  94. model_filename = result_filename.replace('.csv', '.obj')
  95. model_filepath = os.path.join(models_folder, model_filename)
  96. # run expe method using `expe_name`
  97. function_name = 'run_' + expe_name
  98. try:
  99. run_expe_method = getattr(run_expe, function_name)
  100. except AttributeError:
  101. raise NotImplementedError("Run expe method `{}` not implement `{}`".format(run_expe.__name__, function_name))
  102. expe_data = run_expe_method(request, model_filepath, output_file)
  103. if request.session.get('expe_finished'):
  104. # reinit session as default value
  105. # here generic expe params
  106. del request.session['expe']
  107. del request.session['scene']
  108. del request.session['qualities']
  109. del request.session['timestamp']
  110. # specific current expe session params (see `config.py`)
  111. for key in cfg.expes_configuration[expe_name]['session_params']:
  112. del request.session[key]
  113. # set expe current data into session (replace only if experiments data changed)
  114. if expe_data is not None:
  115. request.session['expe_data'] = expe_data
  116. # get base data
  117. data = get_base_data(expe_name)
  118. # other experimentss information
  119. data['expe_name'] = expe_name
  120. data['end_text'] = cfg.expes_configuration[expe_name]['text']['end_text']
  121. return render(request, cfg.expes_configuration[expe_name]['template'], data)
  122. @login_required(login_url="login/")
  123. def list_results(request, expe=None):
  124. """
  125. Return all results obtained from experimentss
  126. """
  127. if expe is None:
  128. folders = cfg.expe_name_list
  129. return render(request, 'expe/expe_results.html', {'expe': expe, 'folders': folders})
  130. else:
  131. if expe in cfg.expe_name_list:
  132. folder_path = os.path.join(settings.MEDIA_ROOT, cfg.output_expe_folder, expe)
  133. # init folder dictionnary
  134. folders = {}
  135. if os.path.exists(folder_path):
  136. days = sorted(os.listdir(folder_path), reverse=True)
  137. for day in days:
  138. day_path = os.path.join(folder_path, day)
  139. filenames = os.listdir(day_path)
  140. folders[day] = filenames
  141. else:
  142. raise Http404("Expe does not exists")
  143. # get base data
  144. data = get_base_data()
  145. # expe parameters
  146. data['expe'] = expe
  147. data['folders'] = folders
  148. data['infos'] = cfg.expes_configuration[expe]['text']
  149. return render(request, 'expe/expe_results.html', data)
  150. @login_required(login_url="login/")
  151. def download_result(request):
  152. path = request.POST.get('path')
  153. folder_path = os.path.join(settings.MEDIA_ROOT, cfg.output_expe_folder, path)
  154. # Folder is required
  155. if os.path.exists(folder_path):
  156. # Open BytesIO to grab in-memory ZIP contents
  157. s = BytesIO()
  158. # check if file or folder
  159. if os.path.isdir(folder_path):
  160. # get files from a specific day
  161. filenames = os.listdir(folder_path)
  162. # Folder name in ZIP archive which contains the above files
  163. # E.g [thearchive.zip]/somefiles/file2.txt
  164. # FIXME: Set this to something better
  165. zip_subdir = folder_path.split('/')[-1]
  166. zip_filename = "%s.zip" % zip_subdir
  167. # The zip compressor
  168. zf = zipfile.ZipFile(s, "w")
  169. for fpath in filenames:
  170. fpath = os.path.join(folder_path, fpath)
  171. # Calculate path for file in zip
  172. fdir, fname = os.path.split(fpath)
  173. zip_path = os.path.join(zip_subdir, fname)
  174. # Add file, at correct path
  175. zf.write(fpath, zip_path)
  176. # Must close zip for all contents to be written
  177. zf.close()
  178. output_filename = zip_filename
  179. content = s.getvalue()
  180. else:
  181. with open(folder_path, 'rb') as f:
  182. content = f.readlines()
  183. # filename only
  184. fdir, fname = os.path.split(path)
  185. output_filename = fname
  186. # Grab ZIP file from in-memory, make response with correct MIME-type
  187. resp = HttpResponse(content, content_type="application/gzip")
  188. # ..and correct content-disposition
  189. resp['Content-Disposition'] = 'attachment; filename=%s' % output_filename
  190. return resp
  191. else:
  192. return Http404("Path does not exist")
  193. def refresh_data(request, expe_name, scene_name):
  194. '''
  195. Utils method to refresh data from session
  196. '''
  197. request.session['expe'] = expe_name
  198. request.session['scene'] = scene_name
  199. request.session['expe_started'] = False
  200. request.session['expe_finished'] = False
  201. request.session['qualities'] = api.get_scene_qualities(scene_name)
  202. # update unique timestamp each time new experiments is launched
  203. request.session['timestamp'] = datetime.strftime(datetime.utcnow(), "%Y-%m-%d_%Hh%Mm%Ss")
  204. # TODO : add in cache ref_image
  205. # get reference image
  206. #ref_image = api.get_image(scene_name, 'max')
  207. # save ref image as list (can't save python object)
  208. #request.session['ref_img'] = np.array(ref_image).tolist()