-
Notifications
You must be signed in to change notification settings - Fork 0
/
main.py
executable file
·191 lines (156 loc) · 8.02 KB
/
main.py
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
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
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
#!/usr/bin/env python
"""
Handles connection with client, calls main method to build targeted vector with
arguments from the client. Websockets implementation from
https://github.com/BruceEckel/hello-flask-websockets
"""
# from __future__ import print_function
# from builtins import str
from py.genetargeter.constants import *; # main python library in py folder
from py.genetargeter.GeneTargeterMethods import *; # main python library in py folder
from py.genetargeter.inputProcessing import *; # input handling
# Imports from Websockets tutorial:
import os
import eventlet
eventlet.monkey_patch()
import time
from flask import Flask, render_template, session, request
from flask_socketio import SocketIO, emit, disconnect, join_room
import traceback # error handling
app = Flask(__name__)
app.debug = False # change in dev/prod
app.config['SECRET_KEY'] = 'secret!'
socketio = SocketIO(app, cors_allowed_origins="*")
sep = ":::"; # separates files
pk = open("pk"); # Access given file
passcode = pk.read().split(sep)[1]; # passcode
pk.close();
@app.route('/')
def index():
print('Sending index')
return render_template("index.html");
@socketio.on('join', namespace='/link')
def createChannel(msg):
print('Client joined: ' + msg['channel'])
join_room(msg['channel'])
@socketio.on('sendGeneFile', namespace='/link')
def gene_message(message):
# print(message)
# process input message into geneName, geneFileStr, HRann and other params
channel_id = message['channel'] # get this channel id
msgList = message["data"].split(sep);
queryNumber = msgList[0]; # number identifier
geneFileStr = msgList[1];
geneName = msgList[2];
HRann = (msgList[3] == "true");
lengthLHR = [int(i) for i in msgList[4].split(",")];
lengthRHR = [int(i) for i in msgList[5].split(",")];
lengthGib = [int(i) for i in msgList[6].split(",")];
optimLHR = [int(i) for i in msgList[7].split(",")];
optimRHR = [int(i) for i in msgList[8].split(",")];
endsLHR = int(msgList[9]);
endsRHR = int(msgList[10]);
endTempLHR = float(msgList[11]);
endTempRHR = float(msgList[12]);
gibTemp = float(msgList[13]);
gibTDif = float(msgList[14]);
maxDistLHR = int(msgList[15]);
maxDistRHR = int(msgList[16]);
minFragSize = int(msgList[17]);
maxFragSize = int(msgList[18]);
codonOptimize = msgList[19];
codonSampling = (msgList[20] == "Codon Sampling");
minGRNAGCContent = float(msgList[21])/100.0;
onTargetMethod = msgList[22];
minOnTargetScore = float(msgList[23]);
offTargetMethod = msgList[24];
minOffTargetScore = float(msgList[25]);
maxOffTargetHitScore = float(msgList[26]);
enzyme = msgList[27];
PAM = msgList[28];
gBlockDefault = (msgList[29] == "true");
plasmidType = msgList[30];
haTagMsg = msgList[31];
setCoding = msgList[32];
bulkFile = (msgList[33] == "true");
prefix = msgList[34];
prefixNum = int(msgList[35]) if len(msgList[35]) > 0 else '';
basePlasmid = msgList[36];
basePlasmidName = msgList[37];
locationType = msgList[38];
filterCutSites = msgList[39].split(',') if len(msgList) == 40 else cut_sites[plasmidType];
if prefix == "*None*":
prefix = "";
elif prefixNum != "" and prefixNum > -1:
prefix += str(prefixNum).zfill(3)+'_';
else:
prefix += '_';
geneGBs = preprocessInputFile(geneName, geneFileStr, useFileStrs=True, doingAltSplices=True); # obtain gb file(s) to be processed
if plasmidType == 'custom':
basePlasmidGB = preprocessPlasmidInputFile(basePlasmid, useFileStrs=True);
else:
basePlasmidGB = None;
outMsg = queryNumber; # will store output message
outMsgHA = "HA_Tag_Design-" + str(queryNumber); # will store output message for HA tag design, if any
for gbName in geneGBs: # for every gb
sigPep = chkSignalPeptide5Prime(gbName,signalPDB); # signalP info
haTag = False; # don't use HA tags by default
if (plasmidType == "pSN150" or plasmidType == "pPC101") and ( haTagMsg == "Yes" or (haTagMsg == "Auto" and not sigPep) ): # if forcing HA tags or 5' end does not contain signal peptide and auto HA-tagging
haTag = True; # use HA tags
try:
output = targetGene(gbName, geneGBs[gbName], codonOptimize=codonOptimize, useFileStrs=True, HRannotated=HRann,lengthLHR=lengthLHR, lengthRHR=lengthRHR, gibsonHomRange=lengthGib, optimRangeLHR=optimLHR, optimRangeRHR=optimRHR, endSizeLHR=endsLHR, endSizeRHR=endsRHR, endTempLHR=endTempLHR, endTempRHR=endTempRHR, gibTemp=gibTemp, gibTDif=gibTDif, maxDistLHR=maxDistLHR, maxDistRHR=maxDistRHR, minGBlockSize=minFragSize, maxGBlockSize=maxFragSize, codonSampling=codonSampling, minGRNAGCContent=minGRNAGCContent, onTargetMethod=onTargetMethod, minOnTargetScore=minOnTargetScore, offTargetMethod=offTargetMethod, minOffTargetScore=minOffTargetScore, maxOffTargetHitScore=maxOffTargetHitScore, enzyme=enzyme, PAM=PAM, gBlockDefault=gBlockDefault, plasmidType=plasmidType, haTag=haTag, sigPep=sigPep, setCoding=setCoding, bulkFile=bulkFile, prefix=prefix, basePlasmid=basePlasmidGB, basePlasmidName=basePlasmidName, locationType=locationType, filterCutSites=filterCutSites); # call result
outMsg = outMsg + sep + output["geneName"] + sep + output["geneFileStr"] + sep + output["plasmidFileStr"] + sep + output["editedLocusFileStr"] + sep + output["oligoFileStr"] + sep + output["gBlockFileStr"] + sep + output["gRNATable"] + sep + output["logFileStr"];
if haTag and (plasmidType == "pSN150" or plasmidType == "pPC101"): # if using HA tags and pSN150,
outputHA = output["outputHA"]; # save HA outputs
outMsgHA = outMsgHA + sep + outputHA["geneName"] + sep + outputHA["geneFileStr"] + sep + outputHA["plasmidFileStr"] + sep + outputHA["editedLocusFileStr"] + sep + outputHA["oligoFileStr"] + sep + outputHA["gBlockFileStr"] + sep + outputHA["gRNATable"] + sep + outputHA["logFileStr"];
sendMsg(outMsgHA, "geneOutput", channel_id);
except Exception as e:
sendMsg(traceback.format_exc(), "runError", channel_id);
raise e
sendMsg('Process complete',"misc",channel_id);
sendMsg(outMsg, "geneOutput",channel_id);
@socketio.on('misc', namespace='/link')
def misc_message(message):
print(message['data'] + " :: received")
def sendMsg(msg,pType,channel_id):
socketio.emit(pType, {'data': msg}, namespace='/link', room=channel_id);
print(pType + " :: sent")
@socketio.on('disconnect request', namespace='/link')
def disconnect_request():
emit('my response', {'data': 'Disconnected!', 'count': session['receive_count']} )
disconnect()
@socketio.on('connect', namespace='/link')
def test_connect():
emit('my response', {'data': 'Connected', 'count': 0})
@socketio.on('disconnect', namespace='/link')
def test_disconnect():
print('Client disconnected')
@socketio.on('cred', namespace='/link')
def validate_credentials(message):
print('Received credentials: ');
if message["data"] == passcode:
emit('validCred',{'data':'You know it!'});
else:
emit('invalidCred',{'data':"You either have it or you don't"});
@socketio.on('geneNames', namespace='/link')
def check_gene_files(message):
print('Received request for genes');
geneIDs = message["data"].split('\n')
genesNotFound = ''
geneFileStr = ''
for geneID in geneIDs:
geneID = geneID.strip()
if len(geneID) > 0:
if os.path.isfile("input/genomes/geneFiles/"+geneID+".gb"):
file = open("input/genomes/geneFiles/"+geneID+".gb", "r")
geneFileStr = geneFileStr + file.read() + sep
file.close()
else:
genesNotFound = genesNotFound + geneID + sep
if len(genesNotFound) > 0:
emit('genesFilesNotFound',{'data':genesNotFound[0:-len(sep)]})
elif len(geneFileStr) > 0:
emit('genesFilesFound',{'data':geneFileStr[0:-len(sep)]})
if __name__ == "__main__":
# Fetch the environment variable (so it works on Heroku):
socketio.run(app, host='0.0.0.0', port=int(os.environ.get("PORT", 5001)))