def view_consent(request): ec = get_experiment_context(request) uname = ec["username"] condition = ec["condition"] errors = "" uname = request.user.username u = User.objects.get(username=uname) # handle post within this element. save data to survey table, if request.method == "POST": form = AnitaConsentForm(request.POST) if form.is_valid(): obj = form.save(commit=False) obj.user = u obj.save() log_event("CONSENT_COMPLETED", request=request) return redirect("next") else: print form.errors errors = form.errors survey = AnitaConsentForm(request.POST) else: log_event("CONSENT_STARTED", request=request) survey = AnitaConsentForm() # provide link to search interface / next system context_dict = { "participant": uname, "condition": condition, "formset": survey, "action": "/treconomics/consent/", "errors": errors, } return render(request, "survey/anita_consent_form.html", context_dict)
def handle_task_and_questions_survey(request, taskid, SurveyForm, survey_name, action, template, show_topic=True): request.session["taskid"] = taskid ec = get_experiment_context(request) condition = ec["condition"] topicnum = ec["topicnum"] interface = ec["interface"] t = TaskDescription.objects.get(topic_num=topicnum) errors = "" uname = request.user.username u = User.objects.get(username=uname) # handle post within this element. save data to survey table, if request.method == "POST": form = SurveyForm(request.POST) if form.is_valid(): obj = form.save(commit=False) obj.user = u obj.task_id = taskid obj.topic_num = topicnum obj.condition = condition obj.interface = interface obj.save() log_event(event=survey_name.upper() + "_SURVEY_COMPLETED", request=request) return redirect("next") else: print form.errors errors = form.errors survey = SurveyForm(request.POST) else: log_event(event=survey_name.upper() + "_SURVEY_STARTED", request=request) survey = SurveyForm() # if we had a survey questions we could ask them here # else we can provide a link to a hosted questionnaire action_url = action + taskid + "/" # provide link to search interface / next system context_dict = { "participant": uname, "condition": condition, "interface": interface, "task": taskid, "topic": t.topic_num, "tasktitle": t.title, "taskdescription": t.description, "formset": survey, "action": action_url, "errors": errors, "show_topic": show_topic, } return render(request, template, context_dict)
def show_saved_documents(request): """ Displays a list of all the documents that were marked as relevant by the user. """ # Timed out? if time_search_experiment_out(request): return redirect('timeout') ec = get_experiment_context(request) taskid = ec['taskid'] condition = ec['condition'] uname = ec['username'] current_search = request.session['queryurl'] user_judgement = -2 if request.method == 'GET': getdict = request.GET if 'judge' not in getdict and 'docid' not in getdict: # Log only if user is entering the page, not after clicking a relevant button logging.debug('LOG_VIEW_SAVED_DOCS') log_event(event="VIEW_SAVED_DOCS", request=request) if 'judge' in getdict: user_judgement = int(getdict['judge']) if 'docid' in getdict: docid = int(getdict['docid']) if (user_judgement > -2) and (docid > -1): # updates the judgement for this document doc_length = ixr.doc_field_length(docid, 'content') trecid = ixr.stored_fields(docid)['docid'] user_judgement = mark_document(request=request, whooshid=docid, trecid=trecid, judgement=user_judgement, doc_length=doc_length) # Get documents that are for this task, and for this user u = User.objects.get(username=uname) docs = DocumentsExamined.objects.filter(user=u).filter(task=taskid) context_dict = {'participant': uname, 'task': taskid, 'condition': condition, 'current_search': current_search, 'docs': docs} return render(request, 'trecdo/saved_documents.html', context_dict)
def view_concept_listing_survey(request, taskid, when): context = RequestContext(request) # Set the tasks id manually from request request.session['taskid'] = taskid ec = get_experiment_context(request) uname = ec["username"] condition = ec["condition"] topicnum = ec["topicnum"] t = TaskDescription.objects.get(topic_num=topicnum) errors = "" uname = request.user.username u = User.objects.get(username=uname) # handle post within this element. save data to survey table, if request.method == 'POST': form = ConceptListingSurveyForm(request.POST) if form.is_valid(): obj = form.save(commit=False) obj.user = u obj.task_id = ec["taskid"] obj.topic_num = ec["topicnum"] obj.when = when obj.save() log_event(event="CONCEPT_LISTING_COMPLETED", request=request) return HttpResponseRedirect('/treconomics/next/') else: print form.errors errors = form.errors survey = ConceptListingSurveyForm(request.POST) else: survey = ConceptListingSurveyForm() action = '/treconomics/conceptlistingsurvey/' + taskid + '/' + when + '/' # provide link to search interface / next system context_dict = {'participant': uname, 'condition': condition, 'task': taskid, 'topic': t.topic_num, 'tasktitle': t.title, 'taskdescription': t.description, 'formset': survey, 'action': action, 'errors': errors} return render(request, 'survey/concept_listing_survey.html', context_dict)
def autocomplete_suggestion(request): """ Handles the autocomplete suggestion service. """ # Get the condition from the user's experiment context. # This will yield us access to the autocomplete trie! ec = get_experiment_context(request) condition = ec['condition'] rotation = ec['rotation'] taskid = ec['taskid'] es = experiment_setups[condition] exp = es.get_exp_dict(taskid, rotation) if time_search_experiment_out(request): log_event(event="EXPERIMENT_TIMEOUT", request=request) return HttpResponseBadRequest(json.dumps({'timeout': True}), content_type='application/json') if request.GET.get('suggest'): results = [] if exp['autocomplete']: chars = unicode(request.GET.get('suggest')) # See if the cache has what we are looking for. # If it does, pull it out and use that. # If it doesn't, query the trie and store the results in the cache before returning. autocomplete_cache = cache.get_cache('autocomplete') results = autocomplete_cache.get(chars) if not results: suggestion_trie = exp['trie'] results = suggestion_trie.suggest(chars) cache_time = 300 autocomplete_cache.set(chars, results, cache_time) response_data = { 'count': len(results), 'results': results, } return JsonResponse(response_data) return JsonResponse({'error': True})
def view_log_hover(request): """ View which logs a user hovering over a search result. """ if time_search_experiment_out(request): log_event(event="EXPERIMENT_TIMEOUT", request=request) return HttpResponseBadRequest(json.dumps({'timeout': True}), content_type='application/json') ec = get_experiment_context(request) uname = ec['username'] taskid = ec['taskid'] u = User.objects.get(username=uname) status = request.GET.get('status') rank = request.GET.get('rank') page = request.GET.get('page') trec_id = request.GET.get('trecID') whoosh_id = request.GET.get('whooshID') doc_length = ixr.doc_field_length(long(whoosh_id), 'content') try: examined = DocumentsExamined.objects.get(user=u, task=taskid, doc_num=trec_id) judgement = examined.judgement except ObjectDoesNotExist: judgement = -2 msg = '' if status == 'in': msg = "DOCUMENT_HOVER_IN" elif status == 'out': msg = "DOCUMENT_HOVER_OUT" log_event(event=msg, request=request, whooshid=whoosh_id, trecid=trec_id, rank=rank, page=page, judgement=judgement, doc_length=doc_length) return JsonResponse({'logged': True})
def view_performance(request): ec = get_experiment_context(request) uname = ec["username"] condition = ec["condition"] #TODO rotation = ec["rotation"] def ratio(rels, nonrels): """ expect two floats """ dem = rels + nonrels if dem > 0.0: return round((rels * rels) / dem, 2) else: return 0.0 topics = experiment_setups[condition].topics avg_wellness = 0.0 performances = [] for t in topics: perf = get_performance(uname, t) topic_desc = TaskDescription.objects.get(topic_num=t).title perf["num"] = t perf["title"] = topic_desc perf["score"] = ratio(float(perf["rels"]), float(perf["nons"])) perf["total"] = get_topic_relevant_count(t) # Should log the performance of each topic here. log_performance(request, perf) performances.append(perf) avg_wellness += perf["score"] avg_wellness = avg_wellness / float(len(topics)) for p in performances: logging.debug(p) context_dict = {'participant': uname, 'condition': condition, 'performances': performances, 'avg_wellness': avg_wellness} return render(request, 'base/performance_experiment.html', context_dict)
def handle_survey(request, SurveyForm, survey_name, action, template): context = RequestContext(request) ec = get_experiment_context(request) uname = ec["username"] condition = ec["condition"] u = User.objects.get(username=uname) # handle post within this element. save data to survey table, if request.method == 'POST': form = SurveyForm(request.POST) if form.is_valid(): obj = form.save(commit=False) obj.user = u obj.save() log_event(event=survey_name.upper() + "_SURVEY_COMPLETED", request=request) return HttpResponseRedirect('/treconomics/next/') else: print form.errors survey = SurveyForm(request.POST) else: log_event(event=survey_name.upper() + "_SURVEY_STARTED", request=request) survey = SurveyForm() context_dict = {'participant': uname, 'condition': condition, 'formset': survey, 'action': action} return render(request, template, context_dict)
def show_document(request, whoosh_docid): # check for timeout """ Displays the document selected by the user :param request: :param whoosh_docid: the way of identifying the selected document :return: """ if time_search_experiment_out(request): return redirect('timeout') ec = get_experiment_context(request) uname = ec["username"] taskid = ec["taskid"] condition = ec["condition"] current_search = request.session['queryurl'] # get document from index fields = ixr.stored_fields(int(whoosh_docid)) title = fields["title"] content = fields["content"] doc_num = fields["docid"] doc_date = fields["timedate"] doc_source = fields["source"] doc_id = whoosh_docid # topic_num = ec["topicnum"] def get_document_rank(): """ Returns the rank (integer) for the given document ID. -1 is returned if the document is not found in the session ranked list. """ the_docid = int(whoosh_docid) ranked_results = request.session.get('results_ranked', []) # Some list comprehension - returns a list of one integer with the rank of a given document # if it exists in ranked_results; returns a blank list if the document is not present. at_rank = [item[1] for item in ranked_results if item[0] == the_docid] if len(at_rank) > 0: return at_rank[0] else: return -1 # check if there are any get parameters. user_judgement = -2 # rank = 0 if request.is_ajax(): getdict = request.GET if 'judge' in getdict: user_judgement = int(getdict['judge']) rank = get_document_rank() # marks that the document has been marked rel or nonrel doc_length = ixr.doc_field_length(long(request.GET.get('docid', 0)), 'content') user_judgement = mark_document(request, doc_id, user_judgement, title, doc_num, rank, doc_length) # mark_document handles logging of this event return JsonResponse(user_judgement, safe=False) else: log_event(event="DOC_CLICKED", request=request, whooshid=whoosh_docid) # marks that the document has been viewed rank = get_document_rank() doc_length = ixr.doc_field_length(long(doc_id), 'content') user_judgement = mark_document(request, doc_id, user_judgement, title, doc_num, rank, doc_length) context_dict = {'participant': uname, 'task': taskid, 'condition': condition, 'current_search': current_search, 'docid': doc_id, 'docnum': doc_num, 'title': title, 'doc_date': doc_date, 'doc_source': doc_source, 'content': content, 'user_judgement': user_judgement, 'rank': rank} if request.GET.get('backtoassessment', False): context_dict['backtoassessment'] = True return render(request, 'trecdo/document.html', context_dict)
def search(request, taskid=-1): sys.stdout.flush() if isinstance(taskid, unicode): taskid = int(taskid) # If taskid is set, then it marks the start of a new search task # Update the session variable to reflect this if taskid >= 0: request.session['start_time'] = datetime.datetime.now().strftime("%Y-%m-%d %H:%M:%S") request.session['taskid'] = taskid if taskid == 0: log_event(event="PRACTICE_SEARCH_TASK_COMMENCED", request=request) else: log_event(event="SEARCH_TASK_COMMENCED", request=request) #FIXME this might cause issues check for timeout if time_search_experiment_out(request): return redirect('timeout') else: """show base index view""" ec = get_experiment_context(request) condition = ec["condition"] rotation = ec["rotation"] interface = ec["interface"] print taskid, rotation, interface print '--------' page_len = ec["rpp"] page = 1 result_dict = {'participant': ec["username"], 'task': ec["taskid"], 'topicno': ec["topicnum"], 'condition': condition, 'interface': interface, 'application_root': '/treconomics/', 'ajax_search_url': 'searcha/', 'autocomplete': ec['autocomplete'], 'is_fast': 'true' } # Ensure that we set a queryurl. # This means that if a user clicks "View Saved" before posing a query, there will be something # to go back to! if not request.session.get('queryurl'): query_url = result_dict['application_root'] + 'search/' # TODO revise logging.debug('Set queryurl to : %s', query_url) request.session['queryurl'] = query_url suggestions = False query_flag = False if request.method == 'POST': # handle the searches from the different interfaces user_query = request.POST['query'].strip() log_event(event="QUERY_ISSUED", request=request, query=user_query) query_flag = True result_dict['page'] = page elif request.method == 'GET': getdict = request.GET if 'query' in getdict: user_query = getdict['query'] query_flag = True if 'suggestion' in getdict: suggestions = True if suggestions: log_event(event="QUERY_SUGGESTION_ISSUED", request=request, query=user_query) if 'page' in getdict: page = int(getdict['page']) else: page = 1 if query_flag: # If the user poses a blank query, we just send back a results page saying so. if user_query == '': result_dict['blank_query'] = True return render(request, 'trecdo/results.html', result_dict) else: # Get some results! Call this wrapper function which uses the Django cache backend. print "INTERFACE IS {0}".format(interface) print "page: {0} pagelen: {1}".format(page,page_len) get_results(request, result_dict, page, page_len, condition, user_query, interface) log_event(event="QUERY_COMPLETE", request=request, query=user_query) result_dict['page'] = page result_dict['focus_querybox'] = 'false' if result_dict['trec_results'] is None: result_dict['focus_querybox'] = 'true' if result_dict['trec_results']: qrp = query_result_performance(result_dict['trec_results'], ec["topicnum"]) log_event(event='SEARCH_RESULTS_PAGE_QUALITY', request=request, whooshid=page, rank=qrp[0], judgement=qrp[1]) #TODO fix this using url-resolvers (reverse()) query_params = urlencode({'query': user_query, 'page': page, 'noperf': 'true'}) query_url = '/treconomics/search/?' + query_params logging.debug('Set queryurl to : %s', query_url) request.session['queryurl'] = query_url result_dict['display_query'] = result_dict['query'] if len(result_dict['query']) > 50: result_dict['display_query'] = result_dict['query'][0:50] + '...' set_results_session_var(request, result_dict) log_event(event='VIEW_SEARCH_RESULTS_PAGE', request=request, page=page) request.session['last_request_time'] = datetime.datetime.utcnow().strftime('%Y-%m-%d %H:%M:%S.%f') return render(request, 'trecdo/results.html', result_dict) else: log_event(event='VIEW_SEARCH_BOX', request=request, page=page) return render(request, 'trecdo/search.html', result_dict)