-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathapp.py
More file actions
204 lines (172 loc) · 6.63 KB
/
app.py
File metadata and controls
204 lines (172 loc) · 6.63 KB
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
192
193
194
195
196
197
198
199
200
201
202
203
204
import os
import subprocess
import shutil
import uuid
import csv
import threading
import sys
from Bio import SeqIO
from flask import Flask, request, jsonify, render_template
app = Flask(__name__)
# Ensure temp and output directories exist
TEMP_DIR = os.path.join(os.path.dirname(__file__), "webapp_temp")
OUTPUT_DIR = os.path.join(os.path.dirname(__file__), "output")
os.makedirs(TEMP_DIR, exist_ok=True)
# Global dictionary to track async tasks
TASKS = {}
def run_analysis_task(task_id, command, env, file_path, project_name, seq_lengths):
process = subprocess.Popen(
command,
env=env,
stdout=subprocess.PIPE,
stderr=subprocess.STDOUT,
text=True,
bufsize=1
)
# Read output line by line
for line in iter(process.stdout.readline, ''):
TASKS[task_id]['logs'].append(line)
process.stdout.close()
returncode = process.wait()
if returncode != 0:
TASKS[task_id]['status'] = 'failed'
TASKS[task_id]['error'] = "Analysis failed. Check logs for details."
return
# Extract protein sequences
seq_data = {}
fasta_path = os.path.join(OUTPUT_DIR, project_name, "fastas", "fasta_all.fasta")
if os.path.exists(fasta_path):
try:
for record in SeqIO.parse(fasta_path, "fasta"):
seq_data[record.id] = str(record.seq)
except Exception as e:
print("Failed to parse protein sequences:", e)
# Parse ALL domain hits for domain architecture diagrams
all_domains = {}
results_dir = os.path.join(OUTPUT_DIR, project_name, "results")
for tbl_file in ["RREfam_hmm_results.tbl", "RREfinder_hmm_results.tbl"]:
tbl_path = os.path.join(results_dir, tbl_file)
if os.path.exists(tbl_path):
try:
with open(tbl_path) as f:
for line in f:
if line.startswith('#'):
continue
tabs = [t for t in line.strip().split(' ') if t != '']
if len(tabs) < 19:
continue
protein_name = tabs[0]
domain_name = tabs[3]
if '.' in domain_name:
domain_name = domain_name.rpartition('.')[0]
try:
evalue = float(tabs[12])
bitscore = float(tabs[13])
seq_start = int(tabs[17])
seq_end = int(tabs[18])
except (ValueError, IndexError):
continue
if protein_name not in all_domains:
all_domains[protein_name] = []
all_domains[protein_name].append({
"name": domain_name,
"start": seq_start,
"end": seq_end,
"evalue": evalue,
"bitscore": bitscore,
"source": "RREfam" if "RREfam" in tbl_file else "RREfinder"
})
except Exception as e:
print(f"Failed to parse domain table {tbl_file}:", e)
# Parse the output
result_file_path = os.path.join(OUTPUT_DIR, project_name, f"{project_name}_rrefinder_results.txt")
rrefam_path = os.path.join(OUTPUT_DIR, project_name, f"{project_name}_rrefam_results.txt")
results = []
if os.path.exists(result_file_path):
with open(result_file_path, "r", encoding="utf-8") as f:
reader = csv.DictReader(f, delimiter="\t")
for row in reader:
results.append(row)
rrefam_results = []
if os.path.exists(rrefam_path):
with open(rrefam_path, "r", encoding="utf-8") as f:
reader = csv.DictReader(f, delimiter="\t")
for row in reader:
rrefam_results.append(row)
if not os.path.exists(result_file_path) and not os.path.exists(rrefam_path):
TASKS[task_id]['status'] = 'failed'
TASKS[task_id]['error'] = "No output files found. The analysis might not have found any RREs."
return
# Cleanup
try:
os.remove(file_path)
except:
pass
TASKS[task_id]['status'] = 'completed'
TASKS[task_id]['results'] = {
"project_name": project_name,
"rrefinder": results,
"rrefam": rrefam_results,
"seq_data": seq_data,
"all_domains": all_domains
}
@app.route("/")
def index():
return render_template("index.html")
@app.route("/api/analyze", methods=["POST"])
def analyze():
if "file" not in request.files:
return jsonify({"error": "No file uploaded"}), 400
file = request.files["file"]
if file.filename == "":
return jsonify({"error": "No file selected"}), 400
mode = request.form.get("mode", "precision")
# Save the file securely
unique_id = str(uuid.uuid4())[:8]
project_name = f"web_{unique_id}"
safe_filename = f"{unique_id}_{file.filename.replace(' ', '_')}"
file_path = os.path.join(TEMP_DIR, safe_filename)
try:
file.save(file_path)
command = [
sys.executable, "RRE.py",
"-i", file_path,
"-m", mode,
project_name
]
env = os.environ.copy()
if "HHLIB" not in env:
env["HHLIB"] = "/opt/miniconda3/envs/RREFinder_mac"
if "PATH" in env:
env["PATH"] = f"{env['HHLIB']}/scripts:{env['PATH']}"
else:
env["PATH"] = f"{env['HHLIB']}/scripts"
task_id = str(uuid.uuid4())
TASKS[task_id] = {
'status': 'running',
'logs': [],
'results': None,
'error': None
}
thread = threading.Thread(
target=run_analysis_task,
args=(task_id, command, env, file_path, project_name, {})
)
thread.daemon = True
thread.start()
return jsonify({"success": True, "task_id": task_id})
except Exception as e:
return jsonify({"error": str(e)}), 500
@app.route("/api/status/<task_id>", methods=["GET"])
def get_status(task_id):
if task_id not in TASKS:
return jsonify({"error": "Task not found"}), 404
task = TASKS[task_id]
return jsonify({
"status": task["status"],
"logs": "".join(task["logs"]),
"results": task["results"],
"error": task["error"]
})
if __name__ == "__main__":
app.run(debug=True, port=5000)