-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathapp.py
More file actions
497 lines (437 loc) · 19.9 KB
/
Copy pathapp.py
File metadata and controls
497 lines (437 loc) · 19.9 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
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
"""Streamlit Web Application - GENOTYPER"""
import json
import os
import streamlit as st
from genotyper.analyzer import load_entry_config
from genotyper.config import get_custom_css, SEQ_FOLDER
from genotyper.migration import migrate_fasta_text
from genotyper.tabs import analyze_tab, stats_tab, tree_tab, validation_tab
# Page configuration
st.set_page_config(
page_title="Soupirr's Genotyper",
page_icon="misc/icon.png",
layout="wide",
initial_sidebar_state="expanded",
)
def _read_current_theme():
cfg = os.path.join(os.path.dirname(os.path.abspath(__file__)), ".streamlit", "config.toml")
try:
with open(cfg) as f:
return "Light" if 'base = "light"' in f.read() else "Dark"
except OSError:
return "Dark"
st.markdown(get_custom_css(_read_current_theme()), unsafe_allow_html=True)
# def des onglets
tab_labels = [
"Analyze Sequences",
"Phylogenetic Trees",
"Statistics",
"Precision Validation",
]
st.html("""
<style>
/* Cache le menu kebab (trois petits points) en haut à droite */
#MainMenu, [data-testid="stMainMenu"] {
visibility: hidden;
}
/* Top bar transparente pour se fondre avec le fond de l'app */
[data-testid="stHeader"] {
position: relative;
background-color: rgba(14, 17, 23, 0.3);
backdrop-filter: blur(4px);
}
/* Réduit l'espace sous la top bar */
[data-testid="stMain"] > div,
[data-testid="block-container"],
.block-container,
.stMainBlockContainer {
padding-top: 0.5rem !important;
}
</style>
""")
def reset_app():
st.cache_resource.clear()
st.cache_data.clear()
st.session_state.pop("data_loaded", None)
st.write("Cache cleared !")
# ============================================================================
# SIDEBAR
if "form_key" not in st.session_state:
st.session_state["form_key"] = 0
if "sidebar_closed" not in st.session_state:
st.session_state["sidebar_closed"] = False
if "sidebar_opened" not in st.session_state:
st.session_state["sidebar_opened"] = True
st.components.v1.html(
"""
<script>
setTimeout(function() {
var sidebar = window.parent.document.querySelector('[data-testid="stSidebar"]');
var collapseBtn = window.parent.document.querySelector('[data-testid="stSidebarCollapseButton"] button');
if (sidebar && sidebar.getAttribute('aria-expanded') === 'false' && collapseBtn) {
collapseBtn.click();
}
}, 150);
</script>
""",
height=0,
)
with st.sidebar:
entry = sorted(os.listdir(SEQ_FOLDER))
selection = st.selectbox(
"Select an entry", entry, index=None, placeholder="Select an entry..."
)
if selection is not None and not st.session_state.get("sidebar_closed"):
st.session_state["sidebar_closed"] = True
st.components.v1.html(
"""
<script>
setTimeout(function() {
var btn = window.parent.document.querySelector('[data-testid="stSidebarCollapseButton"] button');
if (btn) btn.click();
});
</script>
""",
height=0,
)
if selection is None:
st.session_state["sidebar_closed"] = False
st.write("")
with st.expander("Add new references datasets"):
col1_side, col2_side = st.columns(2)
with col1_side:
if st.button("Single gene", use_container_width=True):
st.session_state["mode"] = "mono"
st.session_state.pop("gene_count", None)
with col2_side:
if st.button("Multi-gene", use_container_width=True):
st.session_state["mode"] = "dual"
st.session_state.pop("gene_count", None)
adding_button = False
# ====================================================================================
# =======================================MONO=========================================
# ====================================================================================
if st.session_state.get("mode") == "mono":
entry_name = st.text_input(
"Enter the name of the entry",
key=f"name_{st.session_state['form_key']}",
)
upload_file = st.file_uploader(
"Upload the reference FASTA file",
accept_multiple_files=True,
type=["fasta", "fas", "fa", "txt"],
key=f"fasta_{st.session_state['form_key']}",
)
st.divider()
st.markdown(
"**Pathogenicity configuration** *(optional - leave blank to skip)*"
)
cleavage_start = st.number_input(
"bp before the virulence motif area",
min_value=0,
step=1,
help="0-indexed nucleotide position where the cleavage/virulence site starts in the sequence.",
key=f"cleavage_start_{st.session_state['form_key']}",
)
motif_file = st.file_uploader(
"Upload virulence motif file",
type=["csv", "txt"],
help="CSV with columns: motif, label, type - where type is 'virulent' or 'avirulent'",
key=f"csv_{st.session_state['form_key']}",
)
st.caption(
"Expected format: `motif,label,type` - e.g. `RRQKRF,VFcs-1,virulent`"
)
st.divider()
mono_but_1, mono_but_2 = st.columns([2, 1])
with mono_but_1:
adding_button = st.button(
"Add to the registry", type="primary", use_container_width=True
)
with mono_but_2:
clear_input_mono = st.button("Clear", use_container_width=True)
st.write("")
if clear_input_mono:
st.session_state["form_key"] += 1
st.rerun()
# ====================================================================================
# =======================================DUAL=========================================
# ====================================================================================
if st.session_state.get("mode") == "dual":
entry_name = st.text_input(
"Enter the name of the entry",
key=f"name_{st.session_state['form_key']}",
)
if "gene_count" not in st.session_state:
st.session_state["gene_count"] = 1
for i in range(st.session_state["gene_count"]):
st.divider()
st.markdown(f"**Gene {i + 1}**")
st.text_input(
"Gene name", key=f"gene_name_{i}_{st.session_state['form_key']}"
)
st.file_uploader(
"Fasta file(s)",
accept_multiple_files=True,
type=["fasta", "fas", "fa"],
key=f"gene_fasta_{i}_{st.session_state['form_key']}",
)
st.text_input(
"Genotype pattern (ex: 'H\\d+' for H1/H2/H3/...)",
key=f"gene_patern_{i}_{st.session_state['form_key']}",
)
st.write("")
st.markdown(
"**Pathogenicity configuration** *(optional - leave blank to skip)*"
)
st.number_input(
"Cleavage start (optionnal)",
min_value=0,
step=1,
key=f"cleavage_{i}_{st.session_state['form_key']}",
)
st.file_uploader(
"Motif file (optionnal)",
type=["csv", "txt"],
key=f"motif_{i}_{st.session_state['form_key']}",
)
st.caption(
"Expected format: `motif,label,type` - e.g. `RRQKRF,VFcs-1,virulent`"
)
if st.button("+ Add gene"):
st.session_state["gene_count"] += 1
st.rerun()
st.divider()
multi_but_1, multi_but_2 = st.columns([2, 1])
with multi_but_1:
adding_button = st.button(
"Add to the registry", type="primary", use_container_width=True
)
with multi_but_2:
clear_input_multi = st.button("Clear", use_container_width=True)
st.write("")
if clear_input_multi:
st.session_state["form_key"] += 1
st.session_state["gene_count"] = 1
st.rerun()
# ====================================================================================
# =====================================VALIDATION=====================================
# ====================================================================================
if adding_button:
# =====================================================================MONO
if st.session_state.get("mode") == "mono":
if not upload_file:
st.error("Please select at least one FASTA file")
elif not entry_name.strip():
st.error("Please enter a name")
else:
entry_path = os.path.join(SEQ_FOLDER, entry_name.strip())
os.makedirs(entry_path, exist_ok=True)
mig_report = []
for uploaded_files in upload_file:
dest_path = os.path.join(entry_path, uploaded_files.name)
raw_text = (
uploaded_files.getbuffer()
.tobytes()
.decode("utf-8-sig", errors="ignore")
)
migrated_text, mig_stats = migrate_fasta_text(raw_text)
with open(dest_path, "w", encoding="utf-8") as f:
f.write(migrated_text)
mig_report.append((uploaded_files.name, mig_stats))
if cleavage_start != 0:
config_path = os.path.join(entry_path, "_config.json")
with open(config_path, "w") as f:
json.dump(
{"cleavage_start": int(cleavage_start)}, f, indent=2
)
if motif_file:
motif_path = os.path.join(
entry_path, f"{entry_name.strip()}_motifs.csv"
)
with open(motif_path, "wb") as f:
f.write(motif_file.getbuffer())
st.session_state["form_key"] += 1
st.session_state["success_msg"] = f"Entry '{entry_name}' added !"
st.session_state["mig_reports"] = mig_report
st.rerun()
# ======================================================================DUAL
elif st.session_state.get("mode") == "dual":
gene_count = st.session_state.get("gene_count", 1)
entry_name_dual = entry_name.strip()
# collecte des données de chaque gènes depuis la ss
genes = []
for i in range(gene_count):
genes.append(
{
"name": st.session_state.get(
f"gene_name_{i}_{st.session_state['form_key']}", ""
).strip(),
"files": st.session_state.get(
f"gene_fasta_{i}_{st.session_state['form_key']}", []
),
"pattern": st.session_state.get(
f"gene_patern_{i}_{st.session_state['form_key']}", ""
).strip(),
"cleavage": st.session_state.get(
f"cleavage_{i}_{st.session_state['form_key']}", 0
),
"motif": st.session_state.get(
f"motif_{i}_{st.session_state['form_key']}", None
),
}
)
# Validation des données
if not entry_name_dual:
st.error("Please enter an entry name")
elif any(not g["name"] for g in genes):
st.error("Please enter a name for each genes")
elif any(not g["files"] for g in genes):
st.error("Please upload at least one FASTA per gene")
else:
entry_path = os.path.join(SEQ_FOLDER, entry_name_dual)
os.makedirs(entry_path, exist_ok=True)
mig_report = []
for g in genes:
gene_path = os.path.join(entry_path, g["name"])
os.makedirs(gene_path, exist_ok=True)
# FASTA
for uploaded_files in g["files"]:
dest_path = os.path.join(gene_path, uploaded_files.name)
raw_text = (
uploaded_files.getbuffer()
.tobytes()
.decode("utf-8-sig", errors="ignore")
)
migrated_text, mig_stats = migrate_fasta_text(raw_text)
with open(dest_path, "w", encoding="utf-8") as f:
f.write(migrated_text)
mig_report.append(
(f"{g['name']}/{uploaded_files.name}", mig_stats)
)
# Config json
config = {}
if g["cleavage"] != 0:
config["cleavage_start"] = int(g["cleavage"])
if g["pattern"]:
config["genotype_pattern"] = g["pattern"]
if config:
with open(
os.path.join(gene_path, "_config.json"), "w"
) as f:
json.dump(config, f, indent=2)
# Fichier motif
if g["motif"]:
motif_path = os.path.join(
gene_path, f"{g['name']}_motifs.csv"
)
with open(motif_path, "wb") as f:
f.write(g["motif"].getbuffer())
st.session_state["form_key"] += 1
st.session_state["success_msg"] = (
f"Entry '{entry_name_dual}' added!"
)
st.session_state["mig_reports"] = mig_report
st.rerun()
if "success_msg" in st.session_state:
st.success(st.session_state["success_msg"])
del st.session_state["success_msg"]
if "mig_reports" in st.session_state:
for fname, mig_stats in st.session_state["mig_reports"]:
with st.expander(f"Migration report - {fname}"):
st.write(
f"**{mig_stats['converted']} / {mig_stats['input']}** sequences kept"
)
st.write(
f"- {mig_stats['duplicates']} dropped - duplicate sequence"
)
st.write(f"- {mig_stats['no_genotype']} dropped - missing genotype")
st.write(
f"- {mig_stats['malformed']} dropped - malformed header (<7 fields)"
)
del st.session_state["mig_reports"]
st.divider()
# ── Theme switcher ────────────────────────────────────────────────────────
current_theme = _read_current_theme()
theme_choice = st.segmented_control("Theme", ["Dark", "Light"], default=current_theme)
if theme_choice and theme_choice != current_theme:
import shutil
import sys
base = sys._MEIPASS if getattr(sys, "frozen", False) else os.path.dirname(os.path.abspath(__file__))
src = os.path.join(base, "misc", f"config_{'dark' if theme_choice == 'Dark' else 'light'}.toml")
dst = os.path.join(base, ".streamlit", "config.toml")
shutil.copy(src, dst)
st.info("Restart the app to apply the theme.")
st.divider()
st.markdown(
"##### **If you encounter any issues feel free to report them [here](https://github.com/Soupirr/NDV-genotyper/issues).**"
)
st.write("")
st.link_button(
"Documentation",
"https://github.com/Soupirr/soupirr-global-genotyper/wiki/Getting-Started-%E2%80%90-Adding-a-New-Entry",
)
reset_button = st.button("Reset Cache", on_click=reset_app)
# Injection du titre dans la top bar (dans la sidebar pour ne pas polluer le layout principal)
if selection:
_escaped = selection.replace("'", "\\'")
_script = f"""
(function() {{
var header = window.parent.document.querySelector('[data-testid="stHeader"]');
if (!header) return;
var el = header.querySelector('.entry-title-badge');
if (!el) {{
el = window.parent.document.createElement('span');
el.className = 'entry-title-badge';
el.style.cssText = [
'position:absolute', 'left:50%', 'top:50%',
'transform:translate(-50%,-50%)',
'font-weight:600', 'letter-spacing:3px',
'font-size:1.9rem', 'white-space:nowrap',
'pointer-events:none',
'background:linear-gradient(90deg,#00c9a7,#0099cc,#6699cc)',
'-webkit-background-clip:text',
'-webkit-text-fill-color:transparent',
].join(';');
header.appendChild(el);
}}
el.textContent = '{_escaped}';
el.style.display = 'block';
}})();
"""
else:
_script = """
(function() {
var el = window.parent.document.querySelector('.entry-title-badge');
if (el) el.style.display = 'none';
})();
"""
st.components.v1.html(f"<script>{_script}</script>", height=0)
# ============================================================================
# TITRE
if selection is None:
st.title("Soupirr's Genotyper")
st.markdown("""
Analyze Virus sequences to identify genotypes and pathogenicity.
""")
st.divider()
# ============================================================================
# TABS
if not selection:
st.info(
"There is curently no reference sequences selected, use the sidebar panel to select one or add a new entry."
)
else:
tabs = st.tabs(tab_labels)
tab_analyze, tab_tree, tab_help, tab_val = tabs[0], tabs[1], tabs[2], tabs[3]
selected_path = os.path.join(SEQ_FOLDER, selection)
entry_config = load_entry_config(selected_path)
with tab_help:
stats_tab.render(selected_path, entry_config)
with tab_analyze:
analyze_tab.render(selected_path, entry_config)
with tab_tree:
tree_tab.render(selected_path)
with tab_val:
validation_tab.render(selected_path, entry_config)
# ============================================================================