evidence index loads in the background, in parallel, with retry
Browse files- app/app.py +3 -1
- app/draiml/rag.py +8 -6
- app/draiml/state.py +36 -11
- app/manifest.json +1 -1
- app/views/consult.py +3 -2
- scripts/build_index.py +3 -0
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 |
-
|
| 179 |
-
|
| 180 |
-
|
| 181 |
-
|
| 182 |
-
|
| 183 |
-
|
|
|
|
| 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 |
-
|
|
|
|
|
|
|
|
|
|
| 9 |
|
| 10 |
|
| 11 |
-
async def
|
| 12 |
global _index
|
| 13 |
-
|
| 14 |
-
|
| 15 |
-
|
| 16 |
-
|
| 17 |
-
|
| 18 |
-
|
| 19 |
-
|
| 20 |
-
|
| 21 |
-
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 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": "
|
| 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 |
-
|
| 70 |
-
|
|
|
|
| 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)
|