Gregory-L commited on
Commit
19ba89e
·
verified ·
1 Parent(s): 2673d16

evidence index loads in the background, in parallel, with retry

Browse files
app/app.py CHANGED
@@ -3,7 +3,7 @@ import os
3
 
4
  import streamlit as st
5
 
6
- from draiml import __version__
7
 
8
  st.set_page_config(page_title="drAIML — open healthcare consultation", page_icon="⚕️", layout="wide")
9
 
@@ -12,6 +12,8 @@ if "hf_token" not in st.session_state: # token handed over by the page's "Sign
12
  st.session_state.hf_user = os.environ.get("HF_USER") or ""
13
  st.session_state.hf_oauth = bool(st.session_state.hf_token)
14
 
 
 
15
  pages = [
16
  st.Page("views/consult.py", title="Consultation", icon="🩺", default=True),
17
  st.Page("views/evidence.py", title="Evidence search", icon="🔎"),
 
3
 
4
  import streamlit as st
5
 
6
+ from draiml import __version__, state
7
 
8
  st.set_page_config(page_title="drAIML — open healthcare consultation", page_icon="⚕️", layout="wide")
9
 
 
12
  st.session_state.hf_user = os.environ.get("HF_USER") or ""
13
  st.session_state.hf_oauth = bool(st.session_state.hf_token)
14
 
15
+ state.start_loading() # fetch the evidence index in the background while the visitor reads/types
16
+
17
  pages = [
18
  st.Page("views/consult.py", title="Consultation", icon="🩺", default=True),
19
  st.Page("views/evidence.py", title="Evidence search", icon="🔎"),
app/draiml/rag.py CHANGED
@@ -174,13 +174,15 @@ async def search(index: EvidenceIndex, query: str, k: int = 6, token: str | None
174
 
175
 
176
  async def load(base: str = BASE) -> EvidenceIndex:
 
177
  meta = json.loads(await net.get_bytes(f"{base}/meta.json"))
178
- payload = json.loads(gzip.decompress(await net.get_bytes(f"{base}/passages.json.gz")))
179
- emb = scale = None
180
- if meta.get("dim"):
181
- emb = np.load(io.BytesIO(await net.get_bytes(f"{base}/emb_int8.npy")))
182
- scale = np.load(io.BytesIO(await net.get_bytes(f"{base}/emb_scale.npy")))
183
- arrays = read_bm25(await net.get_bytes(f"{base}/bm25.npz")) if meta.get("bm25") else None
 
184
  return EvidenceIndex(payload, emb, scale, meta, bm25=arrays)
185
 
186
 
 
174
 
175
 
176
  async def load(base: str = BASE) -> EvidenceIndex:
177
+ import asyncio
178
  meta = json.loads(await net.get_bytes(f"{base}/meta.json"))
179
+ names = ["passages.json.gz"] + (["bm25.npz"] if meta.get("bm25") else []) + \
180
+ (["emb_int8.npy", "emb_scale.npy"] if meta.get("dim") else [])
181
+ blobs = dict(zip(names, await asyncio.gather(*(net.get_bytes(f"{base}/{n}") for n in names))))
182
+ payload = json.loads(gzip.decompress(blobs["passages.json.gz"]))
183
+ emb = np.load(io.BytesIO(blobs["emb_int8.npy"])) if "emb_int8.npy" in blobs else None
184
+ scale = np.load(io.BytesIO(blobs["emb_scale.npy"])) if "emb_scale.npy" in blobs else None
185
+ arrays = read_bm25(blobs["bm25.npz"]) if "bm25.npz" in blobs else None
186
  return EvidenceIndex(payload, emb, scale, meta, bm25=arrays)
187
 
188
 
app/draiml/state.py CHANGED
@@ -3,22 +3,47 @@ from __future__ import annotations
3
 
4
  import streamlit as st
5
 
 
 
6
  from . import rag
7
 
8
- _index: rag.EvidenceIndex | None = None # module global: survives reruns in the stlite worker
 
 
 
9
 
10
 
11
- async def evidence_index() -> rag.EvidenceIndex | None:
12
  global _index
13
- if _index is None:
14
- with st.spinner("Loading the evidence index (≈18 MB, once per visit)…"):
15
- try:
16
- _index = await rag.load()
17
- except Exception as e: # offline, Hub hiccup — consultation still works without evidence
18
- st.warning(f"Evidence index unavailable ({e}); answering without citations.")
19
- st.exception(e)
20
- return None
21
- return _index
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
22
 
23
 
24
  def init():
 
3
 
4
  import streamlit as st
5
 
6
+ import asyncio
7
+
8
  from . import rag
9
 
10
+ # Module globals survive Streamlit reruns inside the stlite worker. The download starts in the background
11
+ # as soon as the app opens and is shielded, so a rerun (navigating, typing) never cancels it.
12
+ _index: rag.EvidenceIndex | None = None
13
+ _task: asyncio.Future | None = None
14
 
15
 
16
+ async def _load_with_retry():
17
  global _index
18
+ last = None
19
+ for attempt in range(3):
20
+ try:
21
+ _index = await rag.load()
22
+ return _index
23
+ except Exception as e: # flaky network: back off and retry
24
+ last = e
25
+ await asyncio.sleep(2 * (attempt + 1))
26
+ raise last
27
+
28
+
29
+ def start_loading():
30
+ global _task
31
+ if _index is None and (_task is None or (_task.done() and (_task.cancelled() or _task.exception() is not None))):
32
+ _task = asyncio.ensure_future(_load_with_retry())
33
+
34
+
35
+ async def evidence_index() -> rag.EvidenceIndex | None:
36
+ if _index is not None:
37
+ return _index
38
+ start_loading()
39
+ with st.spinner("Loading the evidence index (≈15 MB, once per visit)…"):
40
+ try:
41
+ return await asyncio.shield(_task)
42
+ except asyncio.CancelledError:
43
+ raise
44
+ except Exception as e: # offline, Hub hiccup — consultation still works without evidence
45
+ st.warning(f"Evidence index unavailable ({type(e).__name__}: {e}); answering without citations.")
46
+ return None
47
 
48
 
49
  def init():
app/manifest.json CHANGED
@@ -1,5 +1,5 @@
1
  {
2
- "build": "4cc1e9e219d5",
3
  "requirements": [],
4
  "files": [
5
  "app.py",
 
1
  {
2
+ "build": "616f192b84dc",
3
  "requirements": [],
4
  "files": [
5
  "app.py",
app/views/consult.py CHANGED
@@ -66,8 +66,9 @@ with st.sidebar:
66
  if c1.button("Clear", use_container_width=True):
67
  ss.history = []
68
  st.rerun()
69
- c2.download_button("Transcript", consult.transcript_markdown(ss.history), "draiml-consultation.md",
70
- "text/markdown", use_container_width=True, disabled=not ss.history)
 
71
 
72
 
73
  def render_extras(m: dict):
 
66
  if c1.button("Clear", use_container_width=True):
67
  ss.history = []
68
  st.rerun()
69
+ if ss.history:
70
+ c2.download_button("Transcript", consult.transcript_markdown(ss.history), "draiml-consultation.md",
71
+ "text/markdown", use_container_width=True)
72
 
73
 
74
  def render_extras(m: dict):
scripts/build_index.py CHANGED
@@ -109,6 +109,9 @@ def main():
109
  old = json.load(f)
110
  passages, sources = old["passages"], old["sources"]
111
  print(f"reusing {len(passages)} passages")
 
 
 
112
  for repo, fn, n in ([] if passages else SOURCES):
113
  info = api.dataset_info(repo)
114
  ok, lic = is_open_dataset(info)
 
109
  old = json.load(f)
110
  passages, sources = old["passages"], old["sources"]
111
  print(f"reusing {len(passages)} passages")
112
+ for p in passages: # keep the browser download small: ~1000 chars is plenty for a cited passage
113
+ if len(p[0]) > 1000:
114
+ p[0] = p[0][:1000].rsplit(" ", 1)[0] + " …"
115
  for repo, fn, n in ([] if passages else SOURCES):
116
  info = api.dataset_info(repo)
117
  ok, lic = is_open_dataset(info)