cgeorgiaw HF Staff commited on
Commit
d0d6e7b
·
verified ·
1 Parent(s): 7c1aeef

Lead with an interactive eukaryotic coverage tree

Browse files
Files changed (6) hide show
  1. FEATURE_BACKLOG.md +3 -3
  2. README.md +7 -3
  3. app.py +39 -42
  4. atlas.css +59 -0
  5. atlas.js +28 -0
  6. taxonomy.py +222 -114
FEATURE_BACKLOG.md CHANGED
@@ -17,7 +17,7 @@ Last updated: 2026-09-30.
17
 
18
  ## F001 — GenBank inference coverage map
19
 
20
- Current implementation: the taxonomy sunburst colors each group by the fraction of current GenBank assembly versions with published annotations. Hover shows counts and percentages; partial assemblies count as present, and this is explicitly distinguished from base coverage. The inventory includes completed published shards plus metadata from unmarked/legacy outputs, deduplicates assembly versions, and reports versions outside the current NCBI snapshot. `refresh_coverage.py` caches metadata by content fingerprints; `refresh_taxonomy.py` rolls coverage into SQLite. Refreshes are manual. See [coverage refresh and evidence limitations](README.md#refresh-annotation-coverage).
21
 
22
  Remaining: partial versus complete assembly/base coverage, automatic updates and history, and navigation to available annotations. The existing completion markers do not bind input content hashes; stronger publication manifests would make the inventory independently auditable.
23
 
@@ -40,7 +40,7 @@ Decisions and dependencies for implementation:
40
 
41
  ## F002 — Taxonomy map and navigation
42
 
43
- Current implementation: the first tab shows an NCBI taxonomy sunburst sized by current GenBank assembly counts and colored by published annotation presence. It supports branch expansion, child/parent navigation, and scientific-name/taxon-ID search. A separate SQLite snapshot stores aggregated counts and provenance; see [refresh instructions](README.md#refresh-annotation-coverage). The chart includes all assembly groups. Linking taxa to annotation accessions remains future work.
44
 
45
  **Goal:** Provide a taxonomy-based view of the available genomes and annotations.
46
 
@@ -53,7 +53,7 @@ Desired behavior:
53
 
54
  Decisions and dependencies for implementation:
55
 
56
- - Implemented: sunburst with bounded subtrees and exact “Other taxa” counts; NCBI taxonomy with source checksums and dates; merged IDs resolved and unresolved IDs explicitly counted.
57
  - Remaining: connect the taxonomy inventory to accession-level annotation results and distinguish partial/complete base coverage.
58
 
59
  ## F003 — Comparison with RefSeq annotations
 
17
 
18
  ## F001 — GenBank inference coverage map
19
 
20
+ Current implementation: the landing-page eukaryotic tree colors each group by the fraction of current GenBank assembly versions with published annotations. Visible labels and hover show counts and percentages; partial assemblies count as present, and this is explicitly distinguished from base coverage. The display and its denominator are restricted to Eukaryota, matching the model's scope. The inventory includes completed published shards plus metadata from unmarked/legacy outputs and deduplicates assembly versions. `refresh_coverage.py` caches metadata by content fingerprints; `refresh_taxonomy.py` rolls coverage into SQLite. Refreshes are manual. See [coverage refresh and evidence limitations](README.md#refresh-annotation-coverage).
21
 
22
  Remaining: partial versus complete assembly/base coverage, automatic updates and history, and navigation to available annotations. The existing completion markers do not bind input content hashes; stronger publication manifests would make the inventory independently auditable.
23
 
 
40
 
41
  ## F002 — Taxonomy map and navigation
42
 
43
+ Current implementation: an illustrated SVG taxonomy tree leads the page, above annotation lookup. It supports click/keyboard branch expansion, breadcrumbs, parent navigation, shortcuts, and scientific-name/taxon-ID search. Every route is restricted to Eukaryota. Coverage colors, counts, and percentages use a separate SQLite snapshot; see [refresh instructions](README.md#refresh-annotation-coverage). Linking taxa to annotation accessions remains future work.
44
 
45
  **Goal:** Provide a taxonomy-based view of the available genomes and annotations.
46
 
 
53
 
54
  Decisions and dependencies for implementation:
55
 
56
+ - Implemented: eukaryotic tree with bounded subtrees and exact, expandable “Other lineages” aggregates; NCBI taxonomy with source checksums and dates; merged IDs resolved. Unresolved taxonomy is excluded from the eukaryotic view.
57
  - Remaining: connect the taxonomy inventory to accession-level annotation results and distinguish partial/complete base coverage.
58
 
59
  ## F003 — Comparison with RefSeq annotations
README.md CHANGED
@@ -17,11 +17,15 @@ Future features and open design decisions are tracked in the [feature backlog](F
17
 
18
  ## GenBank taxonomy
19
 
20
- The first tab shows an interactive sunburst of **GenBank genome assemblies**, using NCBI's current GenBank assembly summary and taxonomy. Sector area represents assembly count. Color represents the fraction of assemblies with published annotations: gray for none found in the inventory, increasingly dark teal for higher percentages. Hover shows the numerator, denominator, and percentage. The second tab provides annotation lookup over the existing small index, which is independent of the broader coverage inventory.
21
 
22
- The taxonomy includes all taxonomic groups and assembly levels in the current summary, accepting `GCA_` accessions with `version_status=latest`. Each assembly contributes once to its taxon and each ancestor. Merged taxon IDs are resolved; unresolved IDs are counted in a separate root branch. These counts describe genome assemblies, not all GenBank nucleotide records. An assembly counts as having annotations when it occurs in the publication inventory; this includes partial assemblies and does not imply full base coverage. Exact accession versions are matched to the NCBI snapshot. Published versions outside that snapshot are reported separately and excluded from chart percentages.
23
 
24
- Click sectors to expand the loaded chart. Use the child-group menu or scientific-name/taxon-ID search to load another subtree, and the parent/home buttons to return. Each chart loads three descendant levels and the eight largest children per node; smaller children are combined into an accurately counted “Other taxa” sector. Search can reach those taxa individually. Hover percentages refer to the selected group; the group heading also shows its share of the full snapshot.
 
 
 
 
25
 
26
  ### Refresh the taxonomy snapshot
27
 
 
17
 
18
  ## GenBank taxonomy
19
 
20
+ The landing page opens with an interactive **tree of eukaryotic life**, using NCBI's current GenBank assembly summary and taxonomy. Curved branches and nodes are colored by the fraction of assemblies with published annotations: gray for none found in the inventory, increasingly dark teal for higher percentages. Counts and percentages appear beside the groups, with details on hover. Annotation lookup sits below the graphic and searches its existing smaller index.
21
 
22
+ The viewer is restricted to **Eukaryota (NCBI taxid 2759) and its descendants**, including search, breadcrumbs, and parent navigation. The model predicts eukaryotic annotations; bacteria, archaea, and viruses are outside this display. The current eukaryotic snapshot contains **70,395 assemblies**, of which **17,561 (24.9%)** have published annotations. The underlying SQLite snapshot retains the full NCBI inventory for refresh/provenance, while the interface uses only the eukaryotic subtree and its denominators. Assemblies with unresolved taxonomy cannot be assigned to that subtree and are excluded.
23
 
24
+ The inventory accepts `GCA_` accessions with `version_status=latest`. Each assembly contributes once to its taxon and each ancestor. These counts describe genome assemblies, not all GenBank nucleotide records. An assembly counts as having annotations when it occurs in the publication inventory; this includes partial assemblies and does not imply full base coverage. Exact accession versions are matched to the NCBI snapshot. Published versions outside that snapshot are excluded from percentages.
25
+
26
+ Click a group to unfold its direct lineages, and use breadcrumbs, parent navigation, or shortcuts to return. Nodes support Enter/Space keyboard navigation. The opening view expands the actual animal/fungal ancestor, Opisthokonta, alongside green plants, SAR, and the remaining eukaryotic lineages. Other views show six direct lineages and an expandable remainder. “Other lineages” is an explicitly labeled display aggregate, not an invented clade; its counts sum the remaining siblings. Repeated expansion reaches all siblings without truncating them. Scientific-name/taxon-ID search also reaches individual taxa. Branch lengths, spacing, and widths are illustrative and do not encode time or abundance. Mobile users can scroll the tree horizontally.
27
+
28
+ The graphic uses server-rendered SVG/HTML with scoped styles in `atlas.css` and delegated click/keyboard handlers in `atlas.js`; no external graphics library or image assets are required. Include these files when deploying.
29
 
30
  ### Refresh the taxonomy snapshot
31
 
app.py CHANGED
@@ -119,48 +119,45 @@ def build_app(catalog=None):
119
  return str(target)
120
 
121
  with gr.Blocks(title="GenBank Annotation Explorer", delete_cache=(3600, 3600)) as demo:
122
- gr.Markdown("# GenBank Annotation Explorer\nExplore predicted coding regions by **assembly or contig accession**.")
123
- with gr.Tabs():
124
- with gr.Tab("GenBank taxonomy"):
125
- build_taxonomy_tab()
126
- with gr.Tab("Annotation lookup"):
127
- gr.Markdown(f"**Prototype {scope} · {len(catalog.records):,} segments · "
128
- f"{len(catalog.manifest['assemblies']):,} assemblies · {catalog.manifest['bases']:,} bases**\n\n"
129
- "Source: [HuggingFaceBio/genbank-annotations](https://huggingface.co/buckets/HuggingFaceBio/genbank-annotations). "
130
- f"These are model-predicted CDS probabilities, not curated gene features. Search covers the {scope} only. "
131
- + (f"Annotations load on demand from **{len(catalog.manifest['sources'])} bucket files**. "
132
- f"Index updated {catalog.manifest['created_at'][:10]}." if remote_mode else ""))
133
- with gr.Row():
134
- accession = gr.Textbox(label="Accession ID", placeholder="Assembly (GCA_…) or contig accession", scale=5)
135
- search_button = gr.Button("Find annotations", variant="primary", scale=1)
136
- examples = [first["assembly_accession"], first["record_name"]]
137
- if remote_mode:
138
- with closing(catalog.connect()) as conn:
139
- examples += [r[0] for r in conn.execute("SELECT record_name FROM segments WHERE id IN (SELECT min(id) FROM segments GROUP BY object_path)")]
140
- examples += ["JBPJTW010000350.1"]
141
- gr.Examples(examples=[[e] for e in dict.fromkeys(examples)], inputs=accession)
142
- status = gr.Markdown("Enter an accession or select an example. IDs are case-insensitive; version suffixes are optional.")
143
- results = gr.Dataframe(value=catalog.table([]), interactive=False, label="Matching segments")
144
- segment = gr.Dropdown(choices=[], label="Segment to explore", interactive=True)
145
- with gr.Row():
146
- start = gr.Number(label="Start (0-based, inclusive)", precision=0)
147
- end = gr.Number(label="End (exclusive)", precision=0)
148
- view = gr.Button("Update region")
149
- with gr.Row():
150
- mode = gr.Radio(["Probabilities", "Binary labels"], value="Probabilities", label="Viewer mode")
151
- threshold = gr.Slider(0, 1, value=0.5, step=0.01, label="CDS threshold (max strand P > threshold)")
152
- plot = gr.Plot(label="CDS tracks")
153
- note = gr.Markdown("Choose a segment to see its probability tracks.")
154
- with gr.Accordion("Segment metadata and provenance", open=False):
155
- metadata = gr.JSON(label="Source metadata")
156
- with gr.Row():
157
- download = gr.Button("Prepare segment download")
158
- file = gr.File(label="Original segment annotations (Parquet)", interactive=False)
159
- with gr.Accordion("Browse indexed accessions and coverage", open=False):
160
- gr.Markdown(f"Showing the first {len(all_ids):,} indexed segments. Search an accession to find other indexed records. "
161
- "An indexed file does not imply complete coverage of its assembly.")
162
- gr.Dataframe(value=catalog.table(all_ids), interactive=False)
163
- gr.JSON(value=catalog.manifest, label="Index provenance" if remote_mode else "Sample provenance")
164
  outputs = [status, results, segment, file]
165
  for event in (search_button.click, accession.submit):
166
  event(search, accession, outputs).then(select_segment, [segment, mode, threshold], [metadata, start, end, plot, note, file])
 
119
  return str(target)
120
 
121
  with gr.Blocks(title="GenBank Annotation Explorer", delete_cache=(3600, 3600)) as demo:
122
+ build_taxonomy_tab()
123
+ gr.Markdown("## Find genome annotations\nLook up an assembly or contig accession to explore predicted coding regions.")
124
+ gr.Markdown(f"**Prototype {scope} · {len(catalog.records):,} segments · "
125
+ f"{len(catalog.manifest['assemblies']):,} assemblies · {catalog.manifest['bases']:,} bases**\n\n"
126
+ "Source: [HuggingFaceBio/genbank-annotations](https://huggingface.co/buckets/HuggingFaceBio/genbank-annotations). "
127
+ f"These are model-predicted CDS probabilities, not curated gene features. Search covers the {scope} only. "
128
+ + (f"Annotations load on demand from **{len(catalog.manifest['sources'])} bucket files**. "
129
+ f"Index updated {catalog.manifest['created_at'][:10]}." if remote_mode else ""))
130
+ with gr.Row():
131
+ accession = gr.Textbox(label="Accession ID", placeholder="Assembly (GCA_…) or contig accession", scale=5)
132
+ search_button = gr.Button("Find annotations", variant="primary", scale=1)
133
+ examples = [first["assembly_accession"], first["record_name"]]
134
+ if remote_mode:
135
+ with closing(catalog.connect()) as conn:
136
+ examples += [r[0] for r in conn.execute("SELECT record_name FROM segments WHERE id IN (SELECT min(id) FROM segments GROUP BY object_path)")]
137
+ examples += ["JBPJTW010000350.1"]
138
+ gr.Examples(examples=[[e] for e in dict.fromkeys(examples)], inputs=accession)
139
+ status = gr.Markdown("Enter an accession or select an example. IDs are case-insensitive; version suffixes are optional.")
140
+ results = gr.Dataframe(value=catalog.table([]), interactive=False, label="Matching segments")
141
+ segment = gr.Dropdown(choices=[], label="Segment to explore", interactive=True)
142
+ with gr.Row():
143
+ start = gr.Number(label="Start (0-based, inclusive)", precision=0)
144
+ end = gr.Number(label="End (exclusive)", precision=0)
145
+ view = gr.Button("Update region")
146
+ with gr.Row():
147
+ mode = gr.Radio(["Probabilities", "Binary labels"], value="Probabilities", label="Viewer mode")
148
+ threshold = gr.Slider(0, 1, value=0.5, step=0.01, label="CDS threshold (max strand P > threshold)")
149
+ plot = gr.Plot(label="CDS tracks")
150
+ note = gr.Markdown("Choose a segment to see its probability tracks.")
151
+ with gr.Accordion("Segment metadata and provenance", open=False):
152
+ metadata = gr.JSON(label="Source metadata")
153
+ with gr.Row():
154
+ download = gr.Button("Prepare segment download")
155
+ file = gr.File(label="Original segment annotations (Parquet)", interactive=False)
156
+ with gr.Accordion("Browse indexed accessions and coverage", open=False):
157
+ gr.Markdown(f"Showing the first {len(all_ids):,} indexed segments. Search an accession to find other indexed records. "
158
+ "An indexed file does not imply complete coverage of its assembly.")
159
+ gr.Dataframe(value=catalog.table(all_ids), interactive=False)
160
+ gr.JSON(value=catalog.manifest, label="Index provenance" if remote_mode else "Sample provenance")
 
 
 
161
  outputs = [status, results, segment, file]
162
  for event in (search_button.click, accession.submit):
163
  event(search, accession, outputs).then(select_segment, [segment, mode, threshold], [metadata, start, end, plot, note, file])
atlas.css ADDED
@@ -0,0 +1,59 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ .atlas { --ink:#173c30; --muted:#647467; position:relative; overflow:hidden; color:var(--ink); background:#f7f8f0; border:1px solid #e0e6d8; border-radius:24px; padding:32px 30px 18px; font-family:Arial,Helvetica,sans-serif; box-shadow:0 12px 50px #234b2910; }
2
+ .atlas * { box-sizing:border-box; }
3
+ .atlas-header { display:flex; justify-content:space-between; align-items:center; gap:28px; }
4
+ .atlas-kicker { font-size:10px; font-weight:700; letter-spacing:1.5px; line-height:1.6; text-transform:uppercase; color:#527261; }
5
+ .atlas-kicker span { padding:0 8px; color:#9aaa95; }
6
+ .atlas h1 { font:400 clamp(29px,3.8vw,47px)/1.08 Georgia,'Times New Roman',serif; letter-spacing:-1.5px; margin:12px 0; color:var(--ink); }
7
+ .atlas h1 span { color:#68a788; }
8
+ .atlas-header p { margin:0; color:var(--muted); font-size:14px; line-height:1.6; }
9
+ .atlas-summary-block { min-width:270px; padding-left:26px; border-left:1px solid #dbe3d3; }
10
+ .atlas-summary { display:flex; align-items:center; gap:12px; margin-top:8px; }
11
+ .atlas-summary strong { font-size:33px; font-weight:500; letter-spacing:-1.4px; font-variant-numeric:tabular-nums; }
12
+ .atlas-summary span { font-size:11px; line-height:1.6; color:var(--muted); }
13
+ .atlas-badge { padding:7px 9px; font-size:13px; background:#dfeedd; color:#285b40; border-radius:8px; white-space:nowrap; }
14
+ .atlas button { font:inherit; cursor:pointer; }
15
+ .atlas-nav { display:flex; justify-content:space-between; align-items:center; gap:12px; margin:25px 0 14px; }
16
+ .atlas-shortcuts { display:flex; flex-wrap:wrap; gap:7px; }
17
+ .atlas-shortcuts button { border:1px solid #cfdcc9; background:#ffffff80; border-radius:30px; padding:8px 15px; color:#315641; font-size:12px; transition:background .15s; }
18
+ .atlas-shortcuts button:hover { background:#dfeedd; }
19
+ .atlas .atlas-back { color:#647467; background:transparent; border:0; font-size:12px; padding:8px; white-space:nowrap; }
20
+ .atlas-breadcrumb { display:flex; align-items:center; flex-wrap:wrap; gap:7px; color:#6c7d6a; font-size:11px; min-height:20px; }
21
+ .atlas-breadcrumb button { border:0; background:none; color:inherit; padding:2px 0; }
22
+ .atlas-breadcrumb button:hover { text-decoration:underline; }
23
+ .crumb-divider { opacity:.4; }
24
+ .tree-scroll { overflow-x:auto; overscroll-behavior-x:contain; margin:0 -5px; }
25
+ .life-tree { display:block; width:100%; min-width:830px; height:auto; overflow:visible; }
26
+ .tree-branch-under { fill:none; stroke:#e4e9dd; stroke-width:9; stroke-linecap:round; }
27
+ .tree-branch { fill:none; stroke-width:4; stroke-linecap:round; }
28
+ .tree-node { cursor:pointer; }
29
+ .tree-hit { fill:transparent; transition:fill .15s; }
30
+ .tree-node:hover .tree-hit,.tree-node:focus .tree-hit { fill:#e5ecdd; }
31
+ .tree-node:focus { outline:none; }
32
+ .tree-node:focus .tree-dot { stroke:#173c30; stroke-width:3; }
33
+ .tree-dot { stroke:#f7f8f0; stroke-width:3; }
34
+ .tree-label { font:600 17px Arial,Helvetica,sans-serif; fill:#254735; }
35
+ .tree-internal { font-size:14px; }
36
+ .tree-count { font:12px Arial,Helvetica,sans-serif; fill:#697966; }
37
+ .tree-percent { font:500 20px Georgia,'Times New Roman',serif; fill:#28543d; }
38
+ .atlas-footer { display:flex; align-items:center; flex-wrap:wrap; gap:15px; justify-content:space-between; border-top:1px solid #dde4d5; padding-top:14px; color:#6c7a66; font-size:11px; line-height:1.6; }
39
+ .atlas-legend { display:flex; gap:7px; align-items:center; }
40
+ .atlas-zero { width:8px; height:8px; border-radius:50%; background:#d5d9d0; }
41
+ .atlas-gradient { display:block; width:60px; height:7px; border-radius:10px; background:linear-gradient(90deg,#badbc8,#40916f,#0f4e3b); }
42
+ .atlas-date { opacity:.8; }
43
+ .atlas-footnote { font-size:10px; line-height:1.6; color:#77816e; margin-top:12px; max-width:860px; }
44
+ .atlas-tooltip { position:absolute; z-index:5; pointer-events:none; max-width:290px; padding:12px 15px; border-radius:12px; color:#f5f8ef; background:#1d4334; font-size:12px; line-height:1.7; box-shadow:0 5px 20px #18372122; }
45
+ .atlas-tooltip[hidden] { display:none; }
46
+ .atlas button:focus-visible { outline:2px solid #327555; outline-offset:3px; }
47
+ .atlas-leaf-note { color:#647467; font-size:13px; text-align:center; margin:0 0 20px; }
48
+ .atlas-mobile-hint { display:none; }
49
+ @media(max-width:800px) {
50
+ .atlas { padding:22px 16px 16px; border-radius:18px; }
51
+ .atlas-header { align-items:flex-start; flex-direction:column; gap:18px; }
52
+ .atlas-summary-block { border-left:0; padding:0; min-width:0; }
53
+ .atlas-summary { flex-wrap:wrap; }
54
+ .atlas h1 { font-size:35px; }
55
+ .atlas-nav { flex-wrap:wrap; margin-top:18px; }
56
+ .atlas-mobile-hint { display:inline; }
57
+ .atlas-footer { gap:9px; }
58
+ }
59
+ @media(prefers-reduced-motion:reduce) { .atlas * { transition:none!important; } }
atlas.js ADDED
@@ -0,0 +1,28 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ // Delegate to the component root so navigation still works after HTML updates.
2
+ function activate(event) {
3
+ const target = event.target.closest('[data-taxid]');
4
+ if (!target || !element.contains(target)) return;
5
+ if (event.type === 'keydown' && !['Enter', ' '].includes(event.key)) return;
6
+ // Native buttons already synthesize a click on keyboard activation.
7
+ if (event.type === 'keydown' && target.tagName.toLowerCase() === 'button') return;
8
+ event.preventDefault();
9
+ trigger('click', {taxid: Number(target.dataset.taxid), offset: Number(target.dataset.offset || 0)});
10
+ }
11
+ element.addEventListener('click', activate);
12
+ element.addEventListener('keydown', activate);
13
+ element.addEventListener('pointermove', (event) => {
14
+ const node = event.target.closest('[data-detail]');
15
+ const tooltip = element.querySelector('.atlas-tooltip');
16
+ const atlas = element.querySelector('.atlas');
17
+ if (!tooltip || !atlas) return;
18
+ if (!node || event.pointerType === 'touch') { tooltip.hidden = true; return; }
19
+ tooltip.textContent = node.dataset.detail;
20
+ tooltip.hidden = false;
21
+ const bounds = atlas.getBoundingClientRect();
22
+ tooltip.style.left = Math.max(8, Math.min(event.clientX - bounds.left + 15, bounds.width - 305)) + 'px';
23
+ tooltip.style.top = Math.max(8, Math.min(event.clientY - bounds.top + 18, bounds.height - tooltip.offsetHeight - 8)) + 'px';
24
+ });
25
+ element.addEventListener('pointerleave', () => {
26
+ const tooltip = element.querySelector('.atlas-tooltip');
27
+ if (tooltip) tooltip.hidden = true;
28
+ });
taxonomy.py CHANGED
@@ -1,13 +1,34 @@
1
  """Read-only taxonomy navigation, independent of the annotation lookup index."""
2
  from contextlib import closing
 
3
  import json
4
  from pathlib import Path
5
  import sqlite3
6
 
7
  import gradio as gr
8
- import plotly.graph_objects as go
9
 
10
- DATABASE = Path(__file__).resolve().parent / "data/taxonomy.sqlite"
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
11
 
12
 
13
  class Taxonomy:
@@ -15,6 +36,8 @@ class Taxonomy:
15
  self.path = Path(path)
16
  with closing(self.connect()) as conn:
17
  self.metadata = json.loads(conn.execute("SELECT value FROM metadata").fetchone()[0])
 
 
18
  self.coverage = self.metadata.get("coverage")
19
 
20
  def connect(self):
@@ -24,129 +47,214 @@ class Taxonomy:
24
 
25
  def search(self, query):
26
  query = str(query or "").strip()
 
 
27
  with closing(self.connect()) as conn:
28
  if query.lstrip("-").isdigit():
29
- rows = conn.execute("SELECT * FROM taxa WHERE taxid=?", (int(query),)).fetchall()
30
  else:
31
  pattern = "%" + query.replace("\\", "\\\\").replace("%", "\\%").replace("_", "\\_") + "%"
32
- rows = conn.execute("SELECT * FROM taxa WHERE name LIKE ? ESCAPE '\\' ORDER BY total_count DESC LIMIT 100", (pattern,)).fetchall()
33
  return [(f"{r['name']} · {r['total_count']:,} assemblies · taxid {r['taxid']}", str(r['taxid'])) for r in rows]
34
 
35
- def view(self, taxid):
 
 
 
36
  with closing(self.connect()) as conn:
37
- root = conn.execute("SELECT * FROM taxa WHERE taxid=?", (int(taxid),)).fetchone()
38
- if root is None:
39
- raise ValueError("Taxon is absent from this assembly snapshot")
40
- ids, labels, parents, values, details, colors = [], [], [], [], [], []
41
-
42
- def add(key, label, parent, count, rank, covered):
43
- ids.append(str(key)); labels.append(label); parents.append(str(parent))
44
- values.append(count)
45
- percent = 100 * covered / count if count else 0
46
- colors.append(percent)
47
- details.append([rank, count / root['total_count'] * 100, covered, percent])
48
-
49
- def visit(row, parent="", depth=0):
50
- key = row['taxid']
51
- add(key, row['name'], parent, row['total_count'], row['rank'], row['covered_total'] if self.coverage else 0)
52
- if depth >= 3:
53
- return
54
- children = conn.execute("SELECT * FROM taxa WHERE parent_id=? AND taxid!=? ORDER BY total_count DESC", (key, key)).fetchall()
55
- # At most 8 children per node; exact residual counts stay visible.
56
- for child in children[:8]:
57
- visit(child, key, depth + 1)
58
- other = sum(c['total_count'] for c in children[8:])
59
- if other:
60
- other_covered = sum(c['covered_total'] for c in children[8:]) if self.coverage else 0
61
- add(f"other-{key}", f"Other taxa ({len(children) - 8:,})", key, other, "Grouped for display; search to explore", other_covered)
62
- if row['direct_count'] and children:
63
- add(f"direct-{key}", "Assigned directly to this taxon", key, row['direct_count'], "direct assignments", row['covered_direct'] if self.coverage else 0)
64
-
65
- visit(root)
66
- children = conn.execute("SELECT * FROM taxa WHERE parent_id=? AND taxid!=? ORDER BY total_count DESC LIMIT 200", (root['taxid'], root['taxid'])).fetchall()
67
- lineage, current = [], root
68
- while True:
69
- lineage.append(current['name'])
70
- if current['taxid'] == 1:
71
- break
72
- current = conn.execute("SELECT * FROM taxa WHERE taxid=?", (current['parent_id'],)).fetchone()
73
- marker = dict(colors=colors, cmin=0, cmax=100, showscale=True,
74
- colorscale=[[0, "#e2e8f0"], [0.000001, "#ccece6"], [0.1, "#80cdc1"], [0.5, "#279e91"], [1, "#005a50"]],
75
- colorbar=dict(title="Assemblies with<br>annotations (%)", tickvals=[0, 25, 50, 75, 100]),
76
- line=dict(color="white", width=1)) if self.coverage else {}
77
- hover = "<b>%{label}</b><br>%{customdata[0]}<br>%{value:,} assemblies<br>%{customdata[1]:.2f}% of selected group"
78
- if self.coverage:
79
- hover += "<br><b>%{customdata[2]:,} with published annotations</b><br>%{customdata[3]:.2f}% of assemblies in this group"
80
- figure = go.Figure(go.Sunburst(ids=ids, labels=labels, parents=parents, values=values,
81
- branchvalues="total", customdata=details, sort=False,
82
- marker=marker, hovertemplate=hover + "<extra></extra>"))
83
- figure.update_layout(height=620, margin=dict(t=10, b=10, l=10, r=10), template="plotly_white")
84
- count = root['total_count']
85
- note = f"### {root['name']}\n**{count:,} assemblies** · {count / self.metadata['assembly_count']:.2%} of this GenBank assembly snapshot\n\n" + " → ".join(reversed(lineage))
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
86
  if self.coverage:
87
- note += f"\n\n**{root['covered_total']:,} / {count:,} assemblies with published annotations ({root['covered_total'] / count:.2%})**. Assemblies may be partially annotated."
88
- choices = [(f"{r['name']} · {r['total_count']:,}", str(r['taxid'])) for r in children]
89
- return figure, note, choices, str(root['parent_id'])
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
90
 
91
 
92
  def build_taxonomy_tab():
 
93
  if not DATABASE.exists():
94
- gr.Markdown("Taxonomy snapshot unavailable. Run `python refresh_taxonomy.py --download` to create it.")
95
  return
96
  taxonomy = Taxonomy()
97
- meta = taxonomy.metadata
98
- gr.Markdown(f"## GenBank genome assemblies\n**{meta['assembly_count']:,} assemblies** · Snapshot built **{meta['created_at'][:10]}**\n\n"
99
- "Explore the NCBI taxonomy by assembly count. This inventory covers current GenBank genome assemblies; "
100
- "it does not count every nucleotide submission.")
101
- if taxonomy.coverage:
102
- coverage = taxonomy.coverage
103
- gr.Markdown(f"**Annotation inventory updated {coverage['created_at'][:10]}** · "
104
- f"**{coverage['matched_current_assemblies']:,} assemblies** have published annotations\n\n"
105
- "**Area = assembly count. Color = percentage of assemblies with published annotations.** "
106
- "Gray means no published annotations found in this inventory; darker teal means a higher fraction. "
107
- "An assembly counts once if it has annotations, including partial assemblies. This is not the percentage of bases annotated. "
108
- "The Annotation lookup tab currently searches a smaller subset.")
109
- if coverage['unmatched_assembly_versions']:
110
- gr.Markdown(f"{coverage['unmatched_assembly_versions']:,} published assembly versions are outside the current GenBank snapshot "
111
- "and are excluded from the chart's percentages. Matching uses exact accession versions.")
112
- else:
113
- gr.Markdown("Annotation coverage inventory is unavailable; colors distinguish taxonomic branches only.")
114
- initial, initial_note, initial_choices, _ = taxonomy.view("1")
115
- selected = gr.State("1")
116
- parent = gr.State("1")
117
- with gr.Row():
118
- home = gr.Button("All GenBank assemblies")
119
- up = gr.Button("Parent group")
120
- child = gr.Dropdown(choices=initial_choices, label="Explore a child group (largest 200)", interactive=True)
121
- with gr.Row():
122
- query = gr.Textbox(label="Find a taxon", placeholder="Scientific name or NCBI taxon ID")
123
- find = gr.Button("Search taxonomy")
124
- matches = gr.Dropdown(choices=[], label="Taxon search results (up to 100, largest first)", interactive=True)
125
- search_status = gr.Markdown()
126
- note = gr.Markdown(initial_note)
127
- chart = gr.Plot(value=initial, label="GenBank taxonomy")
128
- gr.Markdown("Click chart sectors to expand the displayed branches; click the center to zoom out. "
129
- "Use **Explore a child group** or **Find a taxon** to load deeper branches. "
130
- "Each view includes three descendant levels and the eight largest children per node. "
131
- "**Other taxa** preserves the remaining assembly counts and combines their annotation counts before calculating its percentage.")
132
- with gr.Accordion("Snapshot sources and scope", open=False):
133
- gr.Markdown("Source: [NCBI GenBank assembly summary](https://ftp.ncbi.nlm.nih.gov/genomes/ASSEMBLY_REPORTS/assembly_summary_genbank.txt) "
134
- "and [NCBI Taxonomy](https://ftp.ncbi.nlm.nih.gov/pub/taxonomy/taxdump.tar.gz). "
135
- "Counts roll up each assembly's taxon through its ancestors. Merged taxon IDs are resolved; unresolved IDs remain in an explicit group.")
136
- gr.JSON(meta)
137
-
138
- def taxonomy_view(taxid):
139
- figure, text, choices, parent_id = taxonomy.view(taxid or "1")
140
- return figure, text, gr.Dropdown(choices=choices, value=None), str(taxid or "1"), parent_id
141
-
142
- def taxonomy_search(text):
143
- choices = taxonomy.search(text) if str(text or "").strip() else []
144
- return gr.Dropdown(choices=choices, value=None), f"{len(choices)} matching taxa shown." if choices else "No matching taxa. Try a scientific name or taxon ID."
145
-
146
- outputs = [chart, note, child, selected, parent]
147
- child.input(taxonomy_view, child, outputs)
148
- matches.input(taxonomy_view, matches, outputs)
149
- home.click(lambda: taxonomy_view("1"), outputs=outputs)
150
- up.click(taxonomy_view, parent, outputs)
151
- find.click(taxonomy_search, query, [matches, search_status])
152
- query.submit(taxonomy_search, query, [matches, search_status])
 
1
  """Read-only taxonomy navigation, independent of the annotation lookup index."""
2
  from contextlib import closing
3
+ from html import escape
4
  import json
5
  from pathlib import Path
6
  import sqlite3
7
 
8
  import gradio as gr
 
9
 
10
+ ROOT = Path(__file__).resolve().parent
11
+ DATABASE = ROOT / "data/taxonomy.sqlite"
12
+ EUKARYOTA = 2759
13
+ EUK_TREE = """WITH RECURSIVE euk(taxid) AS (
14
+ SELECT 2759 UNION ALL
15
+ SELECT t.taxid FROM taxa t JOIN euk e ON t.parent_id=e.taxid
16
+ WHERE t.taxid != t.parent_id
17
+ ) """
18
+ DISPLAY_NAMES = {2759: "Eukaryotes", 33208: "Animals", 33090: "Green plants",
19
+ 4751: "Fungi", 33154: "Animals + fungi", 2698737: "SAR lineages",
20
+ 2763: "Red algae", 3041: "Green algae"}
21
+
22
+
23
+ def coverage_color(percent):
24
+ if percent <= 0:
25
+ return "#d5d9d0"
26
+ stops = [(0, (186, 219, 200)), (50, (64, 145, 111)), (100, (15, 78, 59))]
27
+ for (a, low), (b, high) in zip(stops, stops[1:]):
28
+ if percent <= b:
29
+ fraction = (percent - a) / (b - a)
30
+ return "#" + "".join(f"{round(x + fraction * (y - x)):02x}" for x, y in zip(low, high))
31
+ return "#0f4e3b"
32
 
33
 
34
  class Taxonomy:
 
36
  self.path = Path(path)
37
  with closing(self.connect()) as conn:
38
  self.metadata = json.loads(conn.execute("SELECT value FROM metadata").fetchone()[0])
39
+ self.eukaryote_ids = frozenset(r[0] for r in conn.execute(EUK_TREE + "SELECT taxid FROM euk"))
40
+ self.eukaryotes = dict(conn.execute("SELECT * FROM taxa WHERE taxid=?", (EUKARYOTA,)).fetchone())
41
  self.coverage = self.metadata.get("coverage")
42
 
43
  def connect(self):
 
47
 
48
  def search(self, query):
49
  query = str(query or "").strip()
50
+ aliases = {"animals": "33208", "plants": "33090", "green plants": "33090", "eukaryotes": "2759"}
51
+ query = aliases.get(query.casefold(), query)
52
  with closing(self.connect()) as conn:
53
  if query.lstrip("-").isdigit():
54
+ rows = conn.execute(EUK_TREE + "SELECT taxa.* FROM taxa JOIN euk USING(taxid) WHERE taxid=?", (int(query),)).fetchall()
55
  else:
56
  pattern = "%" + query.replace("\\", "\\\\").replace("%", "\\%").replace("_", "\\_") + "%"
57
+ rows = conn.execute(EUK_TREE + "SELECT taxa.* FROM taxa JOIN euk USING(taxid) WHERE name LIKE ? ESCAPE '\\' ORDER BY total_count DESC LIMIT 100", (pattern,)).fetchall()
58
  return [(f"{r['name']} · {r['total_count']:,} assemblies · taxid {r['taxid']}", str(r['taxid'])) for r in rows]
59
 
60
+ def view(self, taxid=EUKARYOTA, offset=0):
61
+ taxid, offset = int(taxid), int(offset)
62
+ if taxid not in self.eukaryote_ids or offset < 0:
63
+ raise ValueError("Choose a eukaryotic taxon from this snapshot.")
64
  with closing(self.connect()) as conn:
65
+ def children(t):
66
+ return [dict(r) for r in conn.execute("SELECT * FROM taxa WHERE parent_id=? AND taxid!=? ORDER BY total_count DESC, taxid", (t, t))]
67
+
68
+ def node(row):
69
+ return dict(taxid=row['taxid'], offset=0, name=row['name'],
70
+ label=DISPLAY_NAMES.get(row['taxid'], row['name']),
71
+ total=row['total_count'], covered=row.get('covered_total', 0), children=[])
72
+
73
+ def remainder(rows, parent, start):
74
+ return dict(taxid=parent, offset=start, name=f"Other lineages · {len(rows):,} groups (display aggregate)",
75
+ label=f"Other lineages ({len(rows):,})", total=sum(r['total_count'] for r in rows),
76
+ covered=sum(r.get('covered_total', 0) for r in rows), children=[], aggregate=True)
77
+
78
+ row = dict(conn.execute("SELECT * FROM taxa WHERE taxid=?", (taxid,)).fetchone())
79
+ all_children = children(taxid)
80
+ if offset and offset >= len(all_children):
81
+ raise ValueError("This group has no further lineages.")
82
+ root = remainder(all_children[offset:], taxid, offset) if offset else node(row)
83
+ if offset:
84
+ root['label'] = "More lineages"
85
+ visible = all_children[offset:]
86
+ overview = taxid == EUKARYOTA and offset == 0
87
+ limit = 3 if overview else 6
88
+ root['children'] = [node(r) for r in visible[:limit]]
89
+ if len(visible) > limit:
90
+ root['children'].append(remainder(visible[limit:], taxid, offset + limit))
91
+ if not offset and row['direct_count'] and all_children:
92
+ root['children'].append(dict(taxid=taxid, offset=0, name="Assemblies assigned directly to this taxon",
93
+ label="Direct assignments", total=row['direct_count'],
94
+ covered=row.get('covered_direct', 0), children=[], direct=True))
95
+ if overview:
96
+ for item in root['children']:
97
+ if item['taxid'] == 33154 and not item.get('aggregate'):
98
+ relatives = children(33154)
99
+ item['children'] = [node(r) for r in relatives[:2]]
100
+ if len(relatives) > 2:
101
+ item['children'].append(remainder(relatives[2:], 33154, 2))
102
+ lineage = [row]
103
+ while lineage[-1]['taxid'] != EUKARYOTA:
104
+ lineage.append(dict(conn.execute("SELECT * FROM taxa WHERE taxid=?", (lineage[-1]['parent_id'],)).fetchone()))
105
+ parent = taxid if offset else row['parent_id'] if taxid != EUKARYOTA else EUKARYOTA
106
+ return self.render(root, list(reversed(lineage)), parent)
107
+
108
+ def render(self, root, lineage, parent):
109
+ leaves = []
110
+
111
+ def position(node, depth=0):
112
+ node['depth'] = depth
113
+ if node['children']:
114
+ for child in node['children']:
115
+ position(child, depth + 1)
116
+ node['y'] = (node['children'][0]['y'] + node['children'][-1]['y']) / 2
117
+ else:
118
+ node['y'] = 64 + len(leaves) * 67
119
+ leaves.append(node)
120
+ node['x'] = 80 if depth == 0 else 335 if node['children'] else 610
121
+
122
+ position(root)
123
+ height = max(230, 64 + len(leaves) * 67)
124
+ if not root['children']:
125
+ root['y'] = height / 2
126
+ paths, nodes = [], []
127
+
128
+ def draw(node):
129
+ x, y = node['x'], node['y']
130
+ percent = 100 * node['covered'] / node['total'] if self.coverage and node['total'] else 0
131
+ color = coverage_color(percent) if self.coverage else "#d5d9d0"
132
+ for child in node['children']:
133
+ cx, cy = child['x'], child['y']
134
+ cp = 100 * child['covered'] / child['total'] if self.coverage and child['total'] else 0
135
+ bend = (x + cx) / 2
136
+ curve = f"M{x},{y} C{bend},{y} {bend},{cy} {cx},{cy}"
137
+ paths.append(f'<path d="{curve}" class="tree-branch-under"/><path d="{curve}" stroke="{coverage_color(cp) if self.coverage else color}" class="tree-branch"/>')
138
+ draw(child)
139
+ tip = not node['children'] and node['depth'] > 0
140
+ label = escape(node['label'])
141
+ stats = f"{node['covered']:,} / {node['total']:,}" if self.coverage else f"{node['total']:,}"
142
+ coverage_text = f"{percent:.1f}%" if self.coverage else "—"
143
+ detail = (f"{node['name']} · {node['covered']:,} of {node['total']:,} assemblies have published annotations ({percent:.2f}%). Includes partial assemblies."
144
+ if self.coverage else f"{node['name']} · {node['total']:,} assemblies. Coverage inventory unavailable.")
145
+ action = "" if node.get('direct') else f'data-taxid="{node["taxid"]}" data-offset="{node["offset"]}" role="button" tabindex="0"'
146
+ if node.get('aggregate'):
147
+ detail += " Display aggregate, not a taxonomic clade. Activate to see its lineages."
148
+ elif not node.get('direct'):
149
+ detail += " Activate to explore this group."
150
+ nodes.append(f'<g class="tree-node" {action} aria-label="{escape(detail, quote=True)}" data-detail="{escape(detail, quote=True)}"><title>{escape(detail)}</title>')
151
+ if tip:
152
+ nodes.append(f'<rect x="{x-20}" y="{y-27}" width="425" height="56" rx="14" class="tree-hit"/>')
153
+ else:
154
+ nodes.append(f'<rect x="{max(0,x-78)}" y="{y-46}" width="156" height="88" rx="14" class="tree-hit"/>')
155
+ nodes.append(f'<circle cx="{x}" cy="{y}" r="13" fill="{color}" class="tree-dot"/><circle cx="{x}" cy="{y}" r="4" fill="#fafbf5"/>')
156
+ if tip:
157
+ label = escape(node['label'] if len(node['label']) <= 27 else node['label'][:25] + "…")
158
+ suffix = "annotated" if self.coverage else "assemblies"
159
+ nodes.append(f'<text x="{x+25}" y="{y-3}" class="tree-label">{label}</text>'
160
+ f'<text x="{x+25}" y="{y+18}" class="tree-count">{stats} {suffix}</text>'
161
+ f'<text x="1010" y="{y+3}" text-anchor="end" class="tree-percent">{coverage_text}</text>')
162
+ else:
163
+ label = label if len(node['label']) <= 23 else escape(node['label'][:21] + "…")
164
+ nodes.append(f'<text x="{x}" y="{y-27}" text-anchor="middle" class="tree-label tree-internal">{label}</text>'
165
+ f'<text x="{x}" y="{y+33}" text-anchor="middle" class="tree-count">{coverage_text} annotated</text>')
166
+ nodes.append('</g>')
167
+
168
+ draw(root)
169
+ svg = (f'<svg viewBox="0 0 1040 {height}" class="life-tree" aria-label="Eukaryotic taxonomy and annotation coverage">'
170
+ + ''.join(paths) + ''.join(nodes) + '</svg>')
171
+ total, covered = root['total'], root['covered']
172
+ percent = 100 * covered / total if self.coverage and total else 0
173
+ selected_name = root['label'] if not root.get('aggregate') else f"Other lineages of {lineage[-1]['name']}"
174
+ breadcrumbs = ' <span class="crumb-divider">/</span> '.join(
175
+ f'<button data-taxid="{r["taxid"]}" data-offset="0">{escape(DISPLAY_NAMES.get(r["taxid"], r["name"]))}</button>' for r in lineage)
176
+ if root.get('aggregate'):
177
+ breadcrumbs += ' <span class="crumb-divider">/</span> <span>Other lineages</span>'
178
+ stamp = (self.coverage or self.metadata)['created_at'][:10]
179
  if self.coverage:
180
+ summary = (f'<div class="atlas-kicker">{escape(selected_name)} · ASSEMBLY COVERAGE</div>'
181
+ f'<div class="atlas-summary"><strong>{covered:,}</strong><span>of {total:,}<br>assemblies annotated</span>'
182
+ f'<b class="atlas-badge">{percent:.1f}%</b></div>')
183
+ else:
184
+ summary = f'<div class="atlas-kicker">{escape(selected_name)}</div><div class="atlas-summary"><strong>{total:,}</strong><span>GenBank assemblies<br>Coverage unavailable</span></div>'
185
+ leaf_note = '<p class="atlas-leaf-note">This is a terminal taxon in the assembly snapshot. Use the breadcrumb to explore its relatives.</p>' if not root['children'] else ''
186
+ return f'''<section class="atlas" aria-label="Tree of eukaryotic life">
187
+ <header class="atlas-header">
188
+ <div><div class="atlas-kicker">HUGGING FACE BIO <span> / </span> GENOME ATLAS</div>
189
+ <h1>The tree of eukaryotic life<span>.</span></h1>
190
+ <p>Follow the branches. Discover where we’ve annotated.</p></div>
191
+ <div class="atlas-summary-block">{summary}</div>
192
+ </header>
193
+ <nav class="atlas-nav" aria-label="Explore major lineages">
194
+ <div class="atlas-shortcuts"><button data-taxid="2759" data-offset="0">All eukaryotes</button>
195
+ <button data-taxid="33208" data-offset="0">Animals</button><button data-taxid="33090" data-offset="0">Green plants</button>
196
+ <button data-taxid="4751" data-offset="0">Fungi</button></div>
197
+ <button class="atlas-back" data-taxid="{parent}" data-offset="0">← Parent group</button>
198
+ </nav>
199
+ <div class="atlas-breadcrumb">{breadcrumbs}</div>
200
+ <div class="tree-scroll" tabindex="0" aria-label="Interactive tree. Scroll horizontally on small screens.">{svg}</div>
201
+ {leaf_note}<div class="atlas-tooltip" role="tooltip" hidden></div>
202
+ <footer class="atlas-footer"><div class="atlas-legend"><span>Coverage</span><i class="atlas-zero"></i><span>None</span>
203
+ <i class="atlas-gradient"></i><span>Low → 100%</span></div>
204
+ <span>Click a group to unfold its lineages <span class="atlas-mobile-hint">· Swipe to explore</span></span>
205
+ <span class="atlas-date">Updated {stamp}</span></footer>
206
+ <div class="atlas-footnote">Coverage counts assemblies with published annotations, including partial assemblies. Branch lengths and spacing are for readability; they do not encode time or assembly counts.</div>
207
+ </section>'''
208
 
209
 
210
  def build_taxonomy_tab():
211
+ """Render the landing graphic before lookup (name retained for imports)."""
212
  if not DATABASE.exists():
213
+ gr.Markdown("The eukaryotic tree will appear when the taxonomy snapshot is available.")
214
  return
215
  taxonomy = Taxonomy()
216
+ tree = gr.HTML(taxonomy.view(), css_template=(ROOT / "atlas.css").read_text(),
217
+ js_on_load=(ROOT / "atlas.js").read_text(), apply_default_css=False,
218
+ elem_id="eukaryotic-atlas")
219
+
220
+ def explore_tree(evt: gr.EventData):
221
+ try:
222
+ return taxonomy.view(evt.taxid, evt.offset)
223
+ except (ValueError, TypeError, AttributeError) as exc:
224
+ raise gr.Error("Choose a eukaryotic group in this snapshot.") from exc
225
+
226
+ tree.click(explore_tree, outputs=tree, show_progress="minimal", concurrency_limit=1)
227
+ with gr.Accordion("Find a lineage", open=False):
228
+ with gr.Row():
229
+ query = gr.Textbox(label="Eukaryotic taxon", placeholder="Scientific name, taxon ID, or a group such as animals")
230
+ find = gr.Button("Search lineages")
231
+ matches = gr.Dropdown(choices=[], label="Matching lineages", interactive=True)
232
+ status = gr.Markdown()
233
+
234
+ def taxonomy_search(text):
235
+ choices = taxonomy.search(text) if str(text or '').strip() else []
236
+ return gr.Dropdown(choices=choices, value=None), f"{len(choices)} results (up to 100, largest first)." if choices else "No matching eukaryotic taxa in this snapshot."
237
+
238
+ def taxonomy_view(taxid):
239
+ return taxonomy.view(taxid or EUKARYOTA)
240
+
241
+ matches.input(taxonomy_view, matches, tree)
242
+ find.click(taxonomy_search, query, [matches, status])
243
+ query.submit(taxonomy_search, query, [matches, status])
244
+ with gr.Accordion("About the tree and coverage", open=False):
245
+ gr.Markdown("This tree follows **NCBI Taxonomy within Eukaryota**. Animals and fungi share the Opisthokonta branch; "
246
+ "green plants include green algae. ‘Other lineages’ combines the remaining siblings for display and can be expanded. "
247
+ "Each view shows up to six direct lineages plus any remainder. The opening view also opens the animal/fungal branch. "
248
+ "The tree layout is illustrative; **counts and colors use the actual assembly inventory**.\n\n"
249
+ "Coverage means the fraction of current GenBank assembly versions with published annotations, including partial assemblies. "
250
+ "It does not measure the fraction of bases annotated. Parent counts include descendants once each. "
251
+ "Exact accession versions are matched. The accession lookup below currently searches a smaller indexed subset.\n\n"
252
+ "Sources: [NCBI assembly summary](https://ftp.ncbi.nlm.nih.gov/genomes/ASSEMBLY_REPORTS/assembly_summary_genbank.txt), "
253
+ "[NCBI Taxonomy](https://ftp.ncbi.nlm.nih.gov/pub/taxonomy/taxdump.tar.gz), "
254
+ "and [published annotations](https://huggingface.co/buckets/HuggingFaceBio/genbank-annotations).")
255
+ coverage = taxonomy.coverage or {}
256
+ gr.JSON({"taxonomy_updated": taxonomy.metadata['created_at'], "coverage_updated": coverage.get('created_at'),
257
+ "display_scope": "Eukaryota (NCBI taxid 2759) and its descendants only",
258
+ "inventory_method": coverage.get('method'),
259
+ "published_versions_outside_current_GenBank_snapshot": coverage.get('unmatched_assembly_versions'),
260
+ "sources": taxonomy.metadata['sources']}, label="Snapshot provenance")