Gitlab CSE Unil

views.py 4.52 KB
Newer Older
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
# coding=utf-8
from __future__ import unicode_literals

import logging
import json

from django.http.response import Http404, HttpResponseForbidden
from django.shortcuts import render, get_object_or_404, resolve_url
from django.contrib.auth.decorators import login_required
from django.db.models import Q

from adim.models import AnObj, Annotation, AnObjMembership
from adim.permissions import SHARING_MODE_NONE
from adim_ttp.decorators import attp_login
from adim_utils.decorators import clear_function_cache

from sendfile import sendfile

logger = logging.getLogger(__name__)



def get_annot_export(anobj, user, no_header=False):
    """
    Parse annotation definition for exportation as an array of data
    """
    q = (
        Q(annotable=anobj) &
        (
            Q(owner=user) |
            (
                Q(owner__anobjmembership__publish_mode__gte=1) &
                Q(owner__anobjmembership__anobj=anobj)
            )
        )
    )

    annotations = Annotation.objects.filter(q).distinct().order_by('owner')
    for a in annotations:
        try:
            a.item = json.loads(a.item)
42
43
44
45
            item_rec = a.item[1]
            if type(item_rec) != dict:
                item_rec = a.item[1][1]
            a.item_type = item_rec.get('data').get('type')
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
        except (TypeError, ValueError):
            a.item = None

    data_export = {
        'cmsarea': [('id', 'owner', 'y_from', 'y_to', 'nbConcordances')],
        'concordantstr': [('id', 'owner', 'y', 'width', 'confidence')],
        'discordantstr': [('id', 'owner', 'y', 'width', 'confidence')],
    }
    if no_header:
        for k in data_export.keys():
            data_export[k] = []

    bad_annotations = []

    cut_pos = anobj.envparam.cimaf_cut_pos

    # ----- Area -----
    # areas = annotations.filter(type='cmsarea')
    areas = filter(lambda _a: _a.item_type == 'cmsarea', annotations)
    for area in areas:
        # -> id, owner
        area_export = [area.id, area.owner.id]

        # itm = json.loads(area.item)[1]
        itm = area.item[1]
        # -> y_from, y_to
        try:
            area_export.extend((itm['segments'][0][1], itm['segments'][3][1]))
        except KeyError:
            # Sometimes the segments are stored as dict instead of array
            # In this situation, the annotation is discarded
            bad_annotations.append(area)
            continue

        # -> nbConcordances
        area_export.append(itm['data']['prop']['nbConcordances'])

        data_export['cmsarea'].append(area_export)

    # ----- Striae -----
    # striae = annotations.filter(type__in=('concordantstr', 'discordantstr'))
    striae = filter(lambda _a: _a.item_type in ('concordantstr', 'discordantstr'), annotations)
    for stria in striae:
        # -> id, owner
        stria_export = [stria.id, stria.owner.id]

        itm = stria.item[1]
        #-> y
        try:
            y1, y2, y = float(itm['segments'][0][1]), float(itm['segments'][1][1]), None
            x1, x2 = float(itm['segments'][0][0]), float(itm['segments'][1][0])
        except KeyError:
            bad_annotations.append(stria)
            continue

        if stria.item_type == 'concordantstr':
            if y1 == y2:  # horizontal stria
                y = y1
            else:  # interpolate intersection with the cut
                y = y1 + (1.0 * (y2 - y1) / (x2 - x1)) * (cut_pos - x1)

        elif stria.item_type == 'discordantstr':
            if abs(x1 - cut_pos) < abs(x2 - cut_pos):
                y = y1
            else:
                y = y2

        stria_export.append(y)

        # -> strokeWidth
        try:
            stria_export.append(itm['strokeWidth'])
        except KeyError:
            stria_export.append(1)

        # -> confidence
        stria_export.append(itm['data']['prop']['confidence'])

        data_export[stria.item_type].append(stria_export)

    return data_export




@login_required
def analysis(request, anobj_uuid=None):

    try:
        anobj = AnObj.objects.select_related('owner', 'envparam').get(uuid__startswith=anobj_uuid, env='cimaf')
    except AnObj.DoesNotExist:
        raise Http404()
    is_owner = anobj.is_owned(request.user.id)
    if not is_owner:
        return HttpResponseForbidden()

    annotations_data = get_annot_export(anobj, request.user, no_header=True)
    context = {
        'anobj': anobj,
        'is_owner': is_owner,
        'annotations_data': json.dumps(annotations_data),
        'display_shared_annotations': anobj.sharing_mode != SHARING_MODE_NONE
    }

    return render(request, "adim/env/cimaf/analysis.html", context)