-
Notifications
You must be signed in to change notification settings - Fork 1
Expand file tree
/
Copy pathscriptoscope.py
More file actions
8616 lines (7646 loc) · 344 KB
/
scriptoscope.py
File metadata and controls
8616 lines (7646 loc) · 344 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
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
"""
ScriptoScope — TUI Transcriptome Browser
Changelog:
0.1.0 — initial release: FASTA loading, sequence viewer, BLAST, HMMER, statistics
0.2.0 — file-browser dialog, scrollable widgets, thread-safe UI updates,
run-length encoded sequence coloring, single-pass stats
0.3.0 — consolidated into single-file script, fixed transcript selection,
moved _compute_stats off the main thread
0.4.0 — switched to method-name event handlers, fixed threaded render races,
added error surfacing + debug log at /tmp/scriptoscope.log
0.5.0 — export, filtering, sorting, bookmarks, help, ORF stats,
HMM scan performance + UI responsiveness
0.6.0 — gzip FASTA support, atomic project saves, duplicate-ID dedup,
in-dialog save feedback, project version validation,
NCBI RID cleanup on cancel, cache correctness fixes,
translate() partial-codon warnings silenced
"""
from __future__ import annotations
__version__ = "0.6.0"
# ── stdlib ────────────────────────────────────────────────────────────────────
import argparse
import asyncio
import csv
import gzip
import json
import logging
import math
import datetime
import os
import re
import signal
import shutil
import subprocess
import tempfile
import threading
import time
import urllib.request
from collections import OrderedDict
from dataclasses import dataclass, field, asdict
from functools import lru_cache
from pathlib import Path
from typing import Callable, Generator, Optional
# ── Logging ───────────────────────────────────────────────────────────────────
# Every session writes to a rotating log file. Default is /tmp/scriptoscope.log;
# override with the SCRIPTOSCOPE_LOG env var. Each session gets a unique 8-char
# session ID prefix so multi-run logs can be cleanly separated with grep.
#
# If a user reports a bug, ask them to share the last run's log lines (find the
# newest SESSION ID at the top of the file and copy from there). The startup
# banner below captures version, platform, and dependency info so reproducing
# the environment is trivial.
import uuid as _uuid
from logging.handlers import RotatingFileHandler
_LOG_PATH = os.environ.get("SCRIPTOSCOPE_LOG") or "/tmp/scriptoscope.log"
_SESSION_ID = _uuid.uuid4().hex[:8]
class _SessionFilter(logging.Filter):
"""Inject the per-session ID into every log record."""
def filter(self, record: logging.LogRecord) -> bool:
record.session = _SESSION_ID
return True
def _configure_logging() -> logging.Logger:
root = logging.getLogger("scriptoscope")
root.setLevel(logging.DEBUG)
# Idempotent: if Python re-imports the module (e.g. in tests), don't
# stack duplicate handlers on top of each other.
for h in list(root.handlers):
root.removeHandler(h)
try:
Path(_LOG_PATH).parent.mkdir(parents=True, exist_ok=True)
handler: logging.Handler = RotatingFileHandler(
_LOG_PATH,
maxBytes=5 * 1024 * 1024, # 5 MB per file
backupCount=3, # keep 3 rotated copies
encoding="utf-8",
)
except OSError:
# Fallback: if we can't open the log file, write to stderr so at
# least errors are visible somewhere.
handler = logging.StreamHandler()
handler.setFormatter(logging.Formatter(
fmt="%(asctime)s [%(session)s] %(levelname)-5s "
"%(name)s.%(funcName)s:%(lineno)d %(message)s",
datefmt="%Y-%m-%d %H:%M:%S",
))
handler.addFilter(_SessionFilter())
root.addHandler(handler)
root.propagate = False
return root
_log = _configure_logging()
def _log_startup_banner() -> None:
"""Log a clear, self-contained session header. Every bug report starts
here — tell me the session ID and I can tell you exactly what was running."""
import platform, sys as _sys
banner_lines = [
"=" * 70,
f"ScriptoScope session {_SESSION_ID} starting",
f" version : {__version__}",
f" python : {_sys.version.split()[0]} ({platform.python_implementation()})",
f" platform : {platform.platform()}",
f" cwd : {os.getcwd()}",
f" argv : {_sys.argv}",
f" log file : {_LOG_PATH}",
f" pid : {os.getpid()}",
]
# Best-effort dependency version capture. importlib.metadata works for
# any installed distribution; module.__version__ is unreliable (e.g.
# rich doesn't expose it directly).
try:
from importlib.metadata import version as _pkg_version, PackageNotFoundError
except ImportError:
_pkg_version = None # type: ignore
def _safe_version(dist_name: str, import_name: str) -> str:
if _pkg_version is not None:
try:
return _pkg_version(dist_name)
except Exception:
pass
try:
mod = __import__(import_name)
return getattr(mod, "__version__", "unknown")
except ImportError:
return "NOT INSTALLED"
for pkg_name, dist_name, import_name in [
("textual", "textual", "textual"),
("rich", "rich", "rich"),
("biopython", "biopython", "Bio"),
("pyhmmer", "pyhmmer", "pyhmmer"),
]:
banner_lines.append(f" {pkg_name:<15} : {_safe_version(dist_name, import_name)}")
banner_lines.append("=" * 70)
for line in banner_lines:
_log.info(line)
def _install_exception_hooks() -> None:
"""Capture unhandled exceptions from the main thread AND worker threads.
Without this, a crash in a background worker is silently lost to the TUI."""
import sys as _sys
prev_excepthook = _sys.excepthook
def _hook(exc_type, exc_value, exc_tb):
_log.critical(
"UNCAUGHT EXCEPTION (main thread)",
exc_info=(exc_type, exc_value, exc_tb),
)
prev_excepthook(exc_type, exc_value, exc_tb)
_sys.excepthook = _hook
# threading.excepthook exists in Python 3.8+
prev_thread_hook = getattr(threading, "excepthook", None)
def _thread_hook(args):
_log.critical(
"UNCAUGHT EXCEPTION in thread %s",
args.thread.name if args.thread else "<unknown>",
exc_info=(args.exc_type, args.exc_value, args.exc_traceback),
)
if prev_thread_hook is not None:
prev_thread_hook(args)
if hasattr(threading, "excepthook"):
threading.excepthook = _thread_hook
_install_exception_hooks()
# ── third-party ───────────────────────────────────────────────────────────────
from rich.console import Group
from rich.table import Table
from rich.text import Text
from textual import events, on, work
from textual.app import App, ComposeResult
from textual.binding import Binding
from textual.containers import Horizontal, ScrollableContainer, Vertical, VerticalScroll
from textual.reactive import reactive
from textual.screen import ModalScreen
from textual.timer import Timer
from textual.widgets import (
Button,
DataTable,
Footer,
Header,
Input,
Label,
LoadingIndicator,
ProgressBar,
RadioButton,
RadioSet,
Select,
Static,
Switch,
TabbedContent,
TabPane,
TextArea,
)
# ══════════════════════════════════════════════════════════════════════════════
# Data model
# ══════════════════════════════════════════════════════════════════════════════
@dataclass
class Transcript:
id: str
description: str
sequence: str
length: int = field(init=False, repr=False)
_counts: dict[str, int] | None = field(init=False, repr=False, compare=False, default=None)
_gc: float | None = field(init=False, repr=False, compare=False, default=None)
def __post_init__(self) -> None:
self.length = len(self.sequence)
def _ensure_gc(self) -> None:
"""Compute GC% only — 4 C-level str.count() calls, no Counter."""
if self._gc is None:
if self.length == 0:
self._gc = 0.0
else:
s = self.sequence
gc = s.count("G") + s.count("g") + s.count("C") + s.count("c")
self._gc = gc / self.length * 100
def _ensure_counts(self) -> None:
"""Full ACGTN counts — 10 C-level str.count() calls.
Only called when the user clicks a transcript (composition legend
in the Sequence tab header). NOT called during bulk table load,
which only needs gc_content.
"""
if self._counts is None:
s = self.sequence
c_count = s.count("C") + s.count("c")
g_count = s.count("G") + s.count("g")
self._counts = {
"A": s.count("A") + s.count("a"),
"C": c_count,
"G": g_count,
"T": s.count("T") + s.count("t"),
"N": s.count("N") + s.count("n"),
}
self._gc = (g_count + c_count) / self.length * 100 if self.length > 0 else 0.0
@property
def gc_content(self) -> float:
self._ensure_gc()
return self._gc # type: ignore[return-value]
@property
def short_id(self) -> str:
return self.id[:40] + ("…" if len(self.id) > 40 else "")
def nucleotide_counts(self) -> dict[str, int]:
self._ensure_counts()
return dict(self._counts) # type: ignore[arg-type]
# ══════════════════════════════════════════════════════════════════════════════
# FASTA loader
# ══════════════════════════════════════════════════════════════════════════════
class FastaFormatError(ValueError):
"""Raised when a file does not look like a FASTA."""
def _open_fasta(path: Path):
"""Open a FASTA file, transparently handling gzip-compressed files.
Detects gzip by magic bytes rather than extension so mislabeled files
still work.
"""
with open(path, "rb") as probe:
magic = probe.read(2)
if magic == b"\x1f\x8b":
return gzip.open(path, "rt", encoding="utf-8", errors="replace")
return open(path, "rt", encoding="utf-8", errors="replace")
def _parse_fasta(path: str | Path) -> Generator[Transcript, None, None]:
path = Path(path)
seq_id = None
description = ""
seq_parts: list[str] = []
saw_header = False
saw_content = False
with _open_fasta(path) as fh:
for line in fh:
line = line.rstrip("\n")
if line.strip():
saw_content = True
if line.startswith(">"):
saw_header = True
if seq_id is not None:
yield Transcript(id=seq_id, description=description,
sequence="".join(seq_parts))
header = line[1:]
parts = header.split(None, 1)
seq_id = parts[0]
description = parts[1] if len(parts) > 1 else ""
seq_parts = []
elif seq_id is not None:
seq_parts.append(line.rstrip())
if saw_content and not saw_header:
raise FastaFormatError(
f"{path.name} does not look like a FASTA file (no '>' header found)"
)
if seq_id is not None:
yield Transcript(id=seq_id, description=description,
sequence="".join(seq_parts))
def load_all(path: str | Path) -> list[Transcript]:
"""Load all transcripts from a FASTA file, deduplicating IDs.
Duplicate IDs are renamed with a numeric suffix (e.g. "foo", "foo__2",
"foo__3") and the total number of duplicates is logged.
"""
transcripts: list[Transcript] = []
seen_ids: dict[str, int] = {}
duplicate_count = 0
for t in _parse_fasta(path):
prev = seen_ids.get(t.id)
if prev is None:
seen_ids[t.id] = 1
else:
duplicate_count += 1
prev += 1
seen_ids[t.id] = prev
new_id = f"{t.id}__{prev}"
# Rebuild Transcript with a unique ID so _by_id is lossless
t = Transcript(id=new_id, description=t.description, sequence=t.sequence)
transcripts.append(t)
if duplicate_count:
_log.warning(
"Loaded %s: %d duplicate transcript ID(s) renamed with __N suffix",
path, duplicate_count,
)
return transcripts
# ══════════════════════════════════════════════════════════════════════════════
# Project save / load (JSON)
# ══════════════════════════════════════════════════════════════════════════════
_PROJECT_VERSION = 1
def save_project(
path: str | Path,
transcripts: list[Transcript],
fasta_path: str | None,
scan_cache: dict[str, list] | None = None,
confirm_cache: dict | None = None,
pfam_hits: dict[str, set[str]] | None = None,
) -> None:
"""Save transcriptome + analysis results to a JSON project file."""
data: dict = {
"version": _PROJECT_VERSION,
"fasta_path": fasta_path or "",
"transcripts": [
{"id": t.id, "description": t.description, "sequence": t.sequence}
for t in transcripts
],
}
if scan_cache:
data["scan_cache"] = {
tid: [asdict(h) for h in hits]
for tid, hits in scan_cache.items()
}
if confirm_cache:
data["confirm_cache"] = {
tid: asdict(conf)
for tid, conf in confirm_cache.items()
}
if pfam_hits:
data["pfam_hits"] = {
tid: sorted(families)
for tid, families in pfam_hits.items()
}
# Atomic write: serialize to a sibling temp file, then rename.
# Avoids leaving a half-written project file if the process dies mid-write.
dest = Path(path)
dest.parent.mkdir(parents=True, exist_ok=True)
tmp_fd, tmp_name = tempfile.mkstemp(
prefix=f".{dest.name}.", suffix=".tmp", dir=str(dest.parent),
)
try:
with os.fdopen(tmp_fd, "w", encoding="utf-8") as fh:
json.dump(data, fh, separators=(",", ":"))
fh.flush()
try:
os.fsync(fh.fileno())
except OSError:
pass
os.replace(tmp_name, dest)
except Exception:
try:
os.unlink(tmp_name)
except OSError:
pass
raise
class ProjectFormatError(ValueError):
"""Raised when a project file is malformed or from an unsupported version."""
def _coerce_dataclass(cls, raw: dict):
"""Build a dataclass from a dict, ignoring unknown keys and filling
defaults for missing ones. Tolerates forward/backward-compat drift."""
import dataclasses
fields = {f.name for f in dataclasses.fields(cls)}
kwargs = {k: v for k, v in raw.items() if k in fields}
return cls(**kwargs)
def load_project(path: str | Path) -> dict:
"""Load a JSON project file and return the raw dict.
Returns dict with keys: transcripts, fasta_path, scan_cache,
confirm_cache, pfam_hits.
"""
try:
with open(path, "r", encoding="utf-8") as fh:
raw = json.load(fh)
except json.JSONDecodeError as exc:
raise ProjectFormatError(f"Invalid JSON in {Path(path).name}: {exc}") from exc
if not isinstance(raw, dict):
raise ProjectFormatError(
f"{Path(path).name} is not a ScriptoScope project (expected JSON object)"
)
version = raw.get("version")
if version is None:
raise ProjectFormatError(
f"{Path(path).name} is missing a 'version' field — not a project file?"
)
if not isinstance(version, int) or version > _PROJECT_VERSION:
raise ProjectFormatError(
f"{Path(path).name} uses project version {version}; "
f"this build understands up to version {_PROJECT_VERSION}"
)
raw_transcripts = raw.get("transcripts", [])
if not isinstance(raw_transcripts, list):
raise ProjectFormatError("'transcripts' must be a list")
result: dict = {"fasta_path": raw.get("fasta_path", "") or ""}
transcripts: list[Transcript] = []
for i, t in enumerate(raw_transcripts):
if not isinstance(t, dict) or "id" not in t or "sequence" not in t:
raise ProjectFormatError(f"Transcript #{i} is missing id or sequence")
transcripts.append(Transcript(
id=str(t["id"]),
description=str(t.get("description", "")),
sequence=str(t["sequence"]),
))
result["transcripts"] = transcripts
scan_cache: dict[str, list] = {}
for tid, hit_list in (raw.get("scan_cache") or {}).items():
if not isinstance(hit_list, list):
continue
parsed: list[HmmerHit] = []
for h in hit_list:
if isinstance(h, dict):
try:
parsed.append(_coerce_dataclass(HmmerHit, h))
except (TypeError, ValueError) as exc:
_log.warning("Skipping malformed HmmerHit for %s: %s", tid, exc)
scan_cache[str(tid)] = parsed
result["scan_cache"] = scan_cache
confirm_cache: dict = {}
for tid, conf in (raw.get("confirm_cache") or {}).items():
if isinstance(conf, dict):
try:
confirm_cache[str(tid)] = _coerce_dataclass(BlastConfirmation, conf)
except (TypeError, ValueError) as exc:
_log.warning("Skipping malformed BlastConfirmation for %s: %s", tid, exc)
result["confirm_cache"] = confirm_cache
pfam_hits: dict[str, set[str]] = {}
for tid, families in (raw.get("pfam_hits") or {}).items():
if isinstance(families, (list, tuple, set)):
pfam_hits[str(tid)] = {str(f) for f in families}
result["pfam_hits"] = pfam_hits
return result
# ══════════════════════════════════════════════════════════════════════════════
# Annotation sidecar files
# ══════════════════════════════════════════════════════════════════════════════
_ANNOTATION_VERSION = 4
def _annotation_path(fasta_path: str) -> Path:
"""Return the sidecar annotation path for a given FASTA file."""
return Path(fasta_path).with_suffix(Path(fasta_path).suffix + ".annotations.json")
def save_annotations(
fasta_path: str,
scan_cache: dict,
confirm_cache: dict,
pfam_hits: dict,
bookmarks: set,
orf_cache: dict,
predictions: dict | None = None,
prodigal_cache: dict | None = None,
) -> None:
"""Save annotation sidecar file next to the FASTA. Atomic write."""
data: dict = {"version": _ANNOTATION_VERSION}
if scan_cache:
data["scan_cache"] = {
tid: [asdict(h) if hasattr(h, "__dataclass_fields__") else h for h in hits]
for tid, hits in scan_cache.items()
}
else:
data["scan_cache"] = {}
if confirm_cache:
data["confirm_cache"] = {
tid: asdict(conf) if hasattr(conf, "__dataclass_fields__") else conf
for tid, conf in confirm_cache.items()
}
else:
data["confirm_cache"] = {}
if pfam_hits:
data["pfam_hits"] = {
tid: sorted(families) for tid, families in pfam_hits.items()
}
else:
data["pfam_hits"] = {}
data["bookmarks"] = sorted(bookmarks) if bookmarks else []
if orf_cache:
data["orf_cache"] = {
tid: {
"nt_start": orf.nt_start,
"nt_end": orf.nt_end,
"aa_length": orf.aa_length,
"strand": orf.strand,
"frame": orf.frame,
}
for tid, orf in orf_cache.items()
if orf is not None
}
else:
data["orf_cache"] = {}
if predictions:
data["predictions"] = {
tid: {
"hexamer_score": pred.hexamer_score,
"kozak_score": pred.kozak_score,
"cai_score": pred.cai_score,
"completeness": pred.completeness,
"confidence": pred.confidence,
"combined_score": pred.combined_score,
}
for tid, pred in predictions.items()
}
else:
data["predictions"] = {}
if prodigal_cache:
data["prodigal_cache"] = {
tid: [
{
"gene_id": g.gene_id,
"start": g.start,
"end": g.end,
"strand": g.strand,
"partial": g.partial,
"score": g.score,
"aa_sequence": g.aa_sequence,
}
for g in genes
]
for tid, genes in prodigal_cache.items()
}
else:
data["prodigal_cache"] = {}
dest = _annotation_path(fasta_path)
dest.parent.mkdir(parents=True, exist_ok=True)
tmp_fd, tmp_name = tempfile.mkstemp(
prefix=f".{dest.name}.", suffix=".tmp", dir=str(dest.parent),
)
try:
with os.fdopen(tmp_fd, "w", encoding="utf-8") as fh:
json.dump(data, fh, separators=(",", ":"))
fh.flush()
try:
os.fsync(fh.fileno())
except OSError:
pass
os.replace(tmp_name, dest)
_log.info("Saved annotations sidecar: %s", dest)
except Exception:
try:
os.unlink(tmp_name)
except OSError:
pass
raise
def load_annotations(fasta_path: str) -> dict | None:
"""Load annotation sidecar if it exists. Returns None if no sidecar."""
dest = _annotation_path(fasta_path)
if not dest.is_file():
return None
try:
with open(dest, "r", encoding="utf-8") as fh:
raw = json.load(fh)
except (json.JSONDecodeError, OSError) as exc:
_log.warning("Failed to load annotations sidecar %s: %s", dest, exc)
return None
if not isinstance(raw, dict):
_log.warning("Annotation sidecar %s is not a JSON object", dest)
return None
version = raw.get("version", 0)
if not isinstance(version, int) or version > _ANNOTATION_VERSION:
_log.warning(
"Annotation sidecar %s has version %s (max supported: %d)",
dest, version, _ANNOTATION_VERSION,
)
return None
result: dict = {}
# scan_cache
scan_cache: dict[str, list] = {}
for tid, hit_list in (raw.get("scan_cache") or {}).items():
if not isinstance(hit_list, list):
continue
parsed: list = []
for h in hit_list:
if isinstance(h, dict):
try:
parsed.append(_coerce_dataclass(HmmerHit, h))
except (TypeError, ValueError) as exc:
_log.warning("Skipping malformed HmmerHit for %s: %s", tid, exc)
scan_cache[str(tid)] = parsed
result["scan_cache"] = scan_cache
# confirm_cache
confirm_cache: dict = {}
for tid, conf in (raw.get("confirm_cache") or {}).items():
if isinstance(conf, dict):
try:
confirm_cache[str(tid)] = _coerce_dataclass(BlastConfirmation, conf)
except (TypeError, ValueError) as exc:
_log.warning("Skipping malformed BlastConfirmation for %s: %s", tid, exc)
result["confirm_cache"] = confirm_cache
# pfam_hits
pfam_hits: dict[str, set[str]] = {}
for tid, families in (raw.get("pfam_hits") or {}).items():
if isinstance(families, (list, tuple, set)):
pfam_hits[str(tid)] = {str(f) for f in families}
result["pfam_hits"] = pfam_hits
# bookmarks
bm = raw.get("bookmarks") or []
result["bookmarks"] = set(str(b) for b in bm) if isinstance(bm, list) else set()
# orf_cache — stored as plain dicts, not ORFCoord (no sequence stored)
result["orf_cache"] = raw.get("orf_cache") or {}
# predictions — CDSPrediction stored as plain dicts (no ORFCoord inside)
predictions: dict[str, CDSPrediction] = {}
for tid, pred in (raw.get("predictions") or {}).items():
if isinstance(pred, dict):
try:
predictions[str(tid)] = CDSPrediction(
transcript_id=str(tid),
orf=None, # ORF is reconstructed lazily, not stored
hexamer_score=float(pred.get("hexamer_score", 0.0)),
kozak_score=float(pred.get("kozak_score", 0.0)),
cai_score=float(pred.get("cai_score", 0.0)),
completeness=str(pred.get("completeness", "no_orf")),
confidence=str(pred.get("confidence", "NONE")),
combined_score=float(pred.get("combined_score", 0.0)),
)
except (TypeError, ValueError) as exc:
_log.warning("Skipping malformed CDSPrediction for %s: %s", tid, exc)
result["predictions"] = predictions
# prodigal_cache — reconstruct ProdigalGene objects
prodigal_cache: dict[str, list[ProdigalGene]] = {}
for tid, gene_list in (raw.get("prodigal_cache") or {}).items():
if not isinstance(gene_list, list):
continue
genes: list[ProdigalGene] = []
for g in gene_list:
if isinstance(g, dict):
try:
genes.append(ProdigalGene(
gene_id=str(g.get("gene_id", "")),
start=int(g.get("start", 0)),
end=int(g.get("end", 0)),
strand=str(g.get("strand", "+")),
partial=str(g.get("partial", "00")),
score=float(g.get("score", 0.0)),
aa_sequence=str(g.get("aa_sequence", "")),
))
except (TypeError, ValueError) as exc:
_log.warning("Skipping malformed ProdigalGene for %s: %s", tid, exc)
if genes:
prodigal_cache[str(tid)] = genes
result["prodigal_cache"] = prodigal_cache
_log.info(
"Loaded annotations sidecar: %s (scan=%d, confirm=%d, pfam=%d, bookmarks=%d, predictions=%d, prodigal=%d)",
dest, len(scan_cache), len(confirm_cache), len(pfam_hits),
len(result["bookmarks"]), len(predictions), len(prodigal_cache),
)
return result
# ══════════════════════════════════════════════════════════════════════════════
# Library registry (~/.scriptoscope/library.json)
# ══════════════════════════════════════════════════════════════════════════════
_LIBRARY_PATH = Path.home() / ".scriptoscope" / "library.json"
def load_library() -> list[dict]:
"""Load the library registry. Returns empty list on any error.
Automatically prunes entries whose FASTA files no longer exist
(temp files from test runs, deleted downloads, moved files).
"""
if not _LIBRARY_PATH.is_file():
return []
try:
with open(_LIBRARY_PATH, "r", encoding="utf-8") as fh:
raw = json.load(fh)
entries = raw.get("transcriptomes", [])
if not isinstance(entries, list):
return []
except (json.JSONDecodeError, OSError) as exc:
_log.warning("Failed to load library: %s", exc)
return []
# Prune stale entries (missing FASTA files, temp paths)
valid = []
pruned = 0
for entry in entries:
p = entry.get("fasta_path", "")
if not p or p.startswith("/tmp/") or not Path(p).is_file():
pruned += 1
continue
valid.append(entry)
if pruned:
_log.info("Pruned %d stale library entries", pruned)
save_library(valid)
return valid
def save_library(entries: list[dict]) -> None:
"""Save the library registry. Atomic write."""
_LIBRARY_PATH.parent.mkdir(parents=True, exist_ok=True)
data = {"transcriptomes": entries}
tmp_fd, tmp_name = tempfile.mkstemp(
prefix=".library.", suffix=".tmp", dir=str(_LIBRARY_PATH.parent),
)
try:
with os.fdopen(tmp_fd, "w", encoding="utf-8") as fh:
json.dump(data, fh, indent=2)
fh.flush()
try:
os.fsync(fh.fileno())
except OSError:
pass
os.replace(tmp_name, _LIBRARY_PATH)
except Exception:
try:
os.unlink(tmp_name)
except OSError:
pass
raise
def register_transcriptome(
fasta_path: str, name: str, organism: str, transcript_count: int,
) -> None:
"""Register or update a transcriptome in the library.
Files in /tmp/ are silently skipped — they are test artifacts that
get cleaned up and would leave stale library entries.
"""
if fasta_path.startswith("/tmp/"):
return
entries = load_library()
resolved = str(Path(fasta_path).resolve())
has_ann = _annotation_path(fasta_path).is_file()
# Find existing entry by resolved path
for entry in entries:
if str(Path(entry.get("fasta_path", "")).resolve()) == resolved:
entry["name"] = name
entry["organism"] = organism
entry["transcript_count"] = transcript_count
entry["last_opened"] = datetime.datetime.now().isoformat(timespec="seconds")
entry["has_annotations"] = has_ann
save_library(entries)
_log.info("Updated library entry: %s", name)
return
# New entry
entries.append({
"fasta_path": fasta_path,
"name": name,
"organism": organism,
"transcript_count": transcript_count,
"scanned_count": 0,
"last_opened": datetime.datetime.now().isoformat(timespec="seconds"),
"has_annotations": has_ann,
})
save_library(entries)
_log.info("Registered new library entry: %s", name)
def update_library_entry(fasta_path: str, **updates) -> None:
"""Update fields on an existing library entry by FASTA path."""
entries = load_library()
resolved = str(Path(fasta_path).resolve())
for entry in entries:
if str(Path(entry.get("fasta_path", "")).resolve()) == resolved:
entry.update(updates)
save_library(entries)
_log.info("Updated library entry %s: %s", fasta_path, list(updates.keys()))
return
_log.debug("update_library_entry: no entry found for %s", fasta_path)
def remove_library_entry(fasta_path: str) -> bool:
"""Remove a transcriptome from the library registry. Returns True if removed."""
entries = load_library()
resolved = str(Path(fasta_path).resolve())
before = len(entries)
entries = [
e for e in entries
if str(Path(e.get("fasta_path", "")).resolve()) != resolved
]
if len(entries) < before:
save_library(entries)
_log.info("Removed library entry: %s", fasta_path)
return True
return False
# ══════════════════════════════════════════════════════════════════════════════
# GenBank transcriptome search
# ══════════════════════════════════════════════════════════════════════════════
@dataclass
class GenBankResult:
"""A single GenBank search result."""
accession: str
title: str
organism: str
seq_count: int = 0
update_date: str = ""
def _entrez_available() -> bool:
try:
from Bio import Entrez # noqa: F401
return True
except ImportError:
return False
def genbank_search_transcriptomes(query: str, max_results: int = 10) -> list[GenBankResult]:
"""Search NCBI Nucleotide for TSA transcriptome assemblies by organism name.
Uses a cascading search strategy: TSA master records first, then TSA keyword,
then transcriptome in title, then free text. Returns up to max_results entries.
"""
from Bio import Entrez
Entrez.email = "scriptoscope@example.com"
# Cascading search strategies — from most specific to broadest.
# Quoted query prevents false matches (e.g. "coli" matching random
# records). Strategies progress: TSA master → TSA keyword → RefSeq
# mRNA → broader fallbacks for model organisms that lack TSA entries.
q = query.strip()
# All strategies use [Organism] to avoid false positives from free-text
# matching (e.g. "coli" appearing in unrelated locust records).
# The cascade goes: TSA master → TSA keyword → RefSeq mRNA → mRNA.
strategies = [
f'"{q}"[Organism] AND tsa-master[prop]',
f'"{q}"[Organism] AND TSA[Keyword]',
# For model organisms (E. coli, yeast, etc.) that don't have TSA
# entries — search mRNA sequences in nuccore instead.
f'"{q}"[Organism] AND biomol_mrna[prop] AND refseq[filter]',
f'"{q}"[Organism] AND biomol_mrna[prop]',
]
id_list: list[str] = []
for search_term in strategies:
handle = Entrez.esearch(db="nuccore", term=search_term, retmax=max_results,
sort="relevance", usehistory="n")
search_results = Entrez.read(handle)
handle.close()
if "ErrorList" in search_results:
_log.warning("NCBI search error: %s", search_results["ErrorList"])
id_list = search_results.get("IdList", [])
if id_list:
break
if not id_list:
# Fallback: try RefSeq assemblies (for bacteria/model organisms)
_log.info("No TSA/mRNA results for '%s', trying RefSeq assemblies", q)
return refseq_search_genomes(q, max_results=max_results)
# Also check RefSeq assemblies and merge — even if we found some mRNA
# results, they may be individual clones (not a full transcriptome).
# RefSeq CDS from a reference genome is often more useful for microbes.
try:
refseq_results = refseq_search_genomes(q, max_results=3)
except Exception:
refseq_results = []
# Fetch summaries
handle = Entrez.esummary(db="nuccore", id=",".join(id_list), retmax=max_results)
summaries = Entrez.read(handle)
handle.close()
if isinstance(summaries, dict) and "ERROR" in summaries:
raise RuntimeError(f"NCBI summary fetch failed: {summaries['ERROR']}")
results: list[GenBankResult] = []
for doc in summaries:
acc = doc.get("AccessionVersion", doc.get("Caption", ""))
title = doc.get("Title", "")
organism = doc.get("Organism", "")
length = int(doc.get("Length", 0))
update = doc.get("UpdateDate", "")
results.append(GenBankResult(
accession=acc, title=title, organism=organism,
seq_count=length, update_date=update,
))
# Prepend RefSeq genome results (more useful for microbes than
# individual mRNA clones). They appear first in the search results
# so the user sees "RefSeq CDS" as the top option.
if refseq_results:
return refseq_results + results
return results
def refseq_search_genomes(query: str, max_results: int = 10) -> list[GenBankResult]:
"""Search NCBI Assembly database for RefSeq bacterial/archaeal genomes.
Returns GenBankResult entries where:
- accession = RefSeq assembly accession (GCF_...)
- title = organism name + assembly info
- organism = species name
- seq_count = number of scaffolds (from assembly stats)
"""
from Bio import Entrez
Entrez.email = "scriptoscope@example.com"
q = query.strip()
handle = Entrez.esearch(
db="assembly",
term=f'"{q}"[Organism] AND "latest refseq"[filter]',
retmax=max_results,
sort="relevance",