RAPPEL : Opération de maintenance > ForgeMIA indisponible le 20 Janvier entre 7h et 12h

jvenn_server.py 4.39 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
42
43
44
45
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
#
# Copyright (C) 2015 INRA
#
# This program is free software: you can redistribute it and/or modify
# it under the terms of the GNU General Public License as published by
# the Free Software Foundation, either version 3 of the License, or
# (at your option) any later version.
#
# This program is distributed in the hope that it will be useful,
# but WITHOUT ANY WARRANTY; without even the implied warranty of
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
# GNU General Public License for more details.
#
# You should have received a copy of the GNU General Public License
# along with this program.  If not, see <http://www.gnu.org/licenses/>.
#

import cherrypy
import argparse
import textwrap
import string
import json
import os


WEB_DIR = os.path.abspath(os.path.join(__file__, "../../docs"))

class AppServer(object):
    
    OUTPUT_DIRECTORY = "/tmp"
    
    @cherrypy.expose
    def index(self):
        raise cherrypy.HTTPRedirect("/app/index.html")

    @cherrypy.expose
    def process_venn(self, **kwargs):
        file_path = self.__upload(**kwargs)
        return self.__compare_lists(file_path, True, "\t")

    def __upload(self, **kwargs):

        # the file transfer can take a long time; by default cherrypy
        # limits responses to 300s; we increase it to 1h
        cherrypy.response.timeout = 3600
        
        # upload file by chunks
        filepath = os.path.join(self.OUTPUT_DIRECTORY, kwargs["browse_upload"].filename)
        FH_sever_file = open(filepath, "w")
        while True:
            data = kwargs["browse_upload"].file.read(8192)
            if not data:
                break
            if isinstance(data, bytes):
                FH_sever_file.write(data.decode())
            else:
                FH_sever_file.write(data)
        FH_sever_file.close()
        
        return(filepath)

    def __compare_lists ( self, file , header, spliter):
        
        FH = open(file,'r')
        names = {}
        samples = {}
        for i, line in enumerate(FH.readlines()):
            if i == 0 and header:
                for j, val in enumerate(line.split(spliter)):
                    names[string.ascii_uppercase[j]] = val
            else:
                for j, val in enumerate(line.split(spliter)):
                    if j in samples:
                        samples[j].append(val)
                    else:
                        samples[j] = [val]
        
        d = {}
        j = 1
        
        for s in samples:
            for line in samples[s]:
                if line.rstrip('\n\r') in d:
                    #already view in the current file (duplicate) ?
                    if d[line.rstrip('\n\r')] - j < 0:
                        d[line.rstrip('\n\r')] += j
                else:
                    d[line.rstrip('\n\r')] = j
            j *= 10
    
        d2 = {}
        for key, val in d.items():
            if str(val).zfill(len(samples)) in d2:
                d2[str(val).zfill(len(samples))].append(key)
            else:
                d2[str(val).zfill(len(samples))] = [key]
    
        values = {}
        data = {}
        for key in sorted(d2):
            k = ""
            for i in range(len(key)):
                if key[len(key)-(i+1)] == "1":
                    k = k + string.ascii_uppercase[i]
            values[k] = len(d2[key])
            data[k] = []
            data[k].append(','.join(d2[key]))
        
        return json.dumps([{'name': names, 'values' : values, 'data':data}], indent=4, sort_keys=True)


if __name__ == '__main__':

    parser = argparse.ArgumentParser()
    parser.add_argument("--daemon", action="store_true", dest="daemon", default=False, help="Run the server as daemon")
    args = vars(parser.parse_args())

118
119
120
121
    if args["daemon"]:
        from cherrypy.process.plugins import Daemonizer
        Daemonizer(cherrypy.engine).subscribe()

122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
    app_conf = {
        '/':
            {'tools.staticdir.root': WEB_DIR},
        os.path.join('/', 'css'):
            {'tools.staticdir.on'  : True, 'tools.staticdir.dir' : './css/'},
        os.path.join('/', 'js'):
            {'tools.staticdir.on'  : True, 'tools.staticdir.dir' : './js/'},
        os.path.join('/', 'img'):
            {'tools.staticdir.on'  : True, 'tools.staticdir.dir' : './img/'},
        os.path.join('/', 'app'):
            {'tools.staticdir.on'  : True, 'tools.staticdir.dir' : './'}
    }
    
    cherrypy.quickstart(AppServer(), config=app_conf)