Upload 4 files
Browse files- LICENSE +21 -0
- app.py +195 -0
- packages.txt +6 -0
- requirements.txt +11 -0
LICENSE
ADDED
|
@@ -0,0 +1,21 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
MIT License
|
| 2 |
+
|
| 3 |
+
Copyright (c) 2026 Imene Guizani
|
| 4 |
+
|
| 5 |
+
Permission is hereby granted, free of charge, to any person obtaining a copy
|
| 6 |
+
of this software and associated documentation files (the "Software"), to deal
|
| 7 |
+
in the Software without restriction, including without limitation the rights
|
| 8 |
+
to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
|
| 9 |
+
copies of the Software, and to permit persons to whom the Software is
|
| 10 |
+
furnished to do so, subject to the following conditions:
|
| 11 |
+
|
| 12 |
+
The above copyright notice and this permission notice shall be included in all
|
| 13 |
+
copies or substantial portions of the Software.
|
| 14 |
+
|
| 15 |
+
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
|
| 16 |
+
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
|
| 17 |
+
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
|
| 18 |
+
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
|
| 19 |
+
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
|
| 20 |
+
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
|
| 21 |
+
SOFTWARE.
|
app.py
ADDED
|
@@ -0,0 +1,195 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|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
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
"""LabLens web app (Gradio). Runs locally or as a Hugging Face Space.
|
| 2 |
+
|
| 3 |
+
Flow: upload -> read (deterministic extraction + flags) -> you check the table -> explain.
|
| 4 |
+
The check step is deliberate: OCR can misread a digit, and a human glance is the cheapest
|
| 5 |
+
safety net there is.
|
| 6 |
+
"""
|
| 7 |
+
from __future__ import annotations
|
| 8 |
+
|
| 9 |
+
import html
|
| 10 |
+
from pathlib import Path
|
| 11 |
+
|
| 12 |
+
import gradio as gr
|
| 13 |
+
|
| 14 |
+
from lablens.catalog import load_catalog, match_test_name
|
| 15 |
+
from lablens.explain import explain, llm_available, render_markdown
|
| 16 |
+
from lablens.extract import extract
|
| 17 |
+
from lablens.flagger import flag_all
|
| 18 |
+
from lablens.i18n import CHECK_NOTE, DISCLAIMER, FLAG_LABEL, GENERIC_RANGE, LANGS, RTL, URGENT, t
|
| 19 |
+
from lablens.models import Flag, Result
|
| 20 |
+
|
| 21 |
+
SAMPLES = Path(__file__).parent / "samples"
|
| 22 |
+
HEADERS = ["Test", "Value", "Unit", "Range low", "Range high"]
|
| 23 |
+
LANG_CHOICES = [(v, k) for k, v in LANGS.items()]
|
| 24 |
+
catalog = load_catalog()
|
| 25 |
+
|
| 26 |
+
FLAG_COLOR = {
|
| 27 |
+
"normal": "ok", "low": "warn", "high": "warn", "critical_low": "crit", "critical_high": "crit",
|
| 28 |
+
"unknown": "muted", "check": "check",
|
| 29 |
+
}
|
| 30 |
+
|
| 31 |
+
|
| 32 |
+
def _num(x):
|
| 33 |
+
if x is None:
|
| 34 |
+
return None
|
| 35 |
+
s = str(x).strip().replace(",", ".")
|
| 36 |
+
if s in ("", "nan", "None", "-"):
|
| 37 |
+
return None
|
| 38 |
+
try:
|
| 39 |
+
return float(s)
|
| 40 |
+
except ValueError:
|
| 41 |
+
return None
|
| 42 |
+
|
| 43 |
+
|
| 44 |
+
def read_report(file, lang):
|
| 45 |
+
if file is None:
|
| 46 |
+
return gr.update(value=[]), "Upload a report or pick a sample first.", None
|
| 47 |
+
path = file if isinstance(file, str) else file.name
|
| 48 |
+
results, unmatched, detected, method = extract(path)
|
| 49 |
+
analysis = flag_all(results, method=method)
|
| 50 |
+
rows = [[catalog[r.test_key].display["en"], r.value, r.unit or "", r.ref_low, r.ref_high]
|
| 51 |
+
for r in analysis.results]
|
| 52 |
+
n_check = sum(r.flag == Flag.CHECK for r in analysis.results)
|
| 53 |
+
how = "the PDF's text" if method == "pdf-text" else "the photo (OCR)"
|
| 54 |
+
status = (f"Read **{len(rows)} results** from {how}. "
|
| 55 |
+
"Compare the table with your report, fix anything that's wrong, then press **Explain**.")
|
| 56 |
+
if n_check:
|
| 57 |
+
status += f"\n\n⚠️ {t(CHECK_NOTE, lang)}"
|
| 58 |
+
if unmatched:
|
| 59 |
+
status += f"\n\n<details><summary>{len(unmatched)} line(s) with numbers I couldn't match to a test</summary>\n\n" + \
|
| 60 |
+
"\n".join(f"- `{html.escape(u)}`" for u in unmatched[:15]) + "\n</details>"
|
| 61 |
+
return gr.update(value=rows), status, detected
|
| 62 |
+
|
| 63 |
+
|
| 64 |
+
def _rows_to_results(rows) -> list[Result]:
|
| 65 |
+
out = []
|
| 66 |
+
data = rows.values.tolist() if hasattr(rows, "values") else (rows or [])
|
| 67 |
+
for row in data:
|
| 68 |
+
if not row or not str(row[0]).strip():
|
| 69 |
+
continue
|
| 70 |
+
key, score = match_test_name(str(row[0]))
|
| 71 |
+
value = _num(row[1])
|
| 72 |
+
if key is None or value is None:
|
| 73 |
+
continue
|
| 74 |
+
lo, hi = _num(row[3]), _num(row[4])
|
| 75 |
+
out.append(Result(test_key=key, raw_name=str(row[0]), value=value, unit=str(row[2] or "") or None,
|
| 76 |
+
ref_low=lo, ref_high=hi,
|
| 77 |
+
ref_source="report" if (lo is not None or hi is not None) else "none",
|
| 78 |
+
match_score=score))
|
| 79 |
+
return out
|
| 80 |
+
|
| 81 |
+
|
| 82 |
+
def _results_table(analysis, lang) -> str:
|
| 83 |
+
rtl = ' dir="rtl"' if lang in RTL else ""
|
| 84 |
+
trs = []
|
| 85 |
+
for r in analysis.results:
|
| 86 |
+
td = catalog[r.test_key]
|
| 87 |
+
name = html.escape(td.display.get(lang) or td.display["en"])
|
| 88 |
+
if r.ref_low is not None and r.ref_high is not None:
|
| 89 |
+
rng = f"{r.ref_low:g} – {r.ref_high:g}"
|
| 90 |
+
elif r.ref_high is not None:
|
| 91 |
+
rng = f"< {r.ref_high:g}"
|
| 92 |
+
elif r.ref_low is not None:
|
| 93 |
+
rng = f"> {r.ref_low:g}"
|
| 94 |
+
else:
|
| 95 |
+
rng = "—"
|
| 96 |
+
if r.ref_source == "catalog":
|
| 97 |
+
rng += f'<div class="ll-note">{html.escape(t(GENERIC_RANGE, lang))}</div>'
|
| 98 |
+
label = html.escape(t(FLAG_LABEL[r.flag.value], lang))
|
| 99 |
+
trs.append(f'<tr><td>{name}</td><td class="ll-num">{r.value:g} <span class="ll-unit">{html.escape(r.unit or "")}</span></td>'
|
| 100 |
+
f'<td class="ll-num">{rng}</td><td><span class="ll-badge ll-{FLAG_COLOR[r.flag.value]}">{label}</span></td></tr>')
|
| 101 |
+
return f'<table class="ll-table"{rtl}><tbody>{"".join(trs)}</tbody></table>'
|
| 102 |
+
|
| 103 |
+
|
| 104 |
+
def run_explain(rows, lang):
|
| 105 |
+
results = _rows_to_results(rows)
|
| 106 |
+
if not results:
|
| 107 |
+
return "", "", "Nothing to explain yet: read a report first.", ""
|
| 108 |
+
analysis = flag_all(results)
|
| 109 |
+
rtl = ' dir="rtl"' if lang in RTL else ""
|
| 110 |
+
banner = ""
|
| 111 |
+
if analysis.urgent:
|
| 112 |
+
banner = f'<div class="ll-urgent"{rtl}>🚨 {_md_bold(t(URGENT, lang))}</div>'
|
| 113 |
+
if any(r.flag == Flag.CHECK for r in analysis.results):
|
| 114 |
+
banner += f'<div class="ll-check"{rtl}>⚠️ {html.escape(t(CHECK_NOTE, lang))}</div>'
|
| 115 |
+
exp, source = explain(analysis, lang)
|
| 116 |
+
md = render_markdown(analysis, exp, lang)
|
| 117 |
+
note = ("Explanation written by an open model, grounded in the LabLens knowledge base and checked by guardrails."
|
| 118 |
+
if source == "llm" else
|
| 119 |
+
"Explanation from the LabLens knowledge base (AI model not configured or unavailable).")
|
| 120 |
+
return banner, _results_table(analysis, lang), md, f"<small>{note} {html.escape(t(DISCLAIMER, lang))}</small>"
|
| 121 |
+
|
| 122 |
+
|
| 123 |
+
def _md_bold(s: str) -> str:
|
| 124 |
+
s = html.escape(s)
|
| 125 |
+
import re
|
| 126 |
+
return re.sub(r"\*\*(.+?)\*\*", r"<strong>\1</strong>", s)
|
| 127 |
+
|
| 128 |
+
|
| 129 |
+
def load_sample(name):
|
| 130 |
+
return str(SAMPLES / name)
|
| 131 |
+
|
| 132 |
+
|
| 133 |
+
CSS = """
|
| 134 |
+
:root { --ll-ink:#14213d; --ll-accent:#0f766e; }
|
| 135 |
+
.gradio-container { max-width: 1080px !important; margin: auto; }
|
| 136 |
+
#ll-hero h1 { font-size: 2.1rem; margin-bottom: .2rem; letter-spacing: -0.02em; }
|
| 137 |
+
#ll-hero p { font-size: 1.02rem; opacity: .85; margin-top: 0; }
|
| 138 |
+
.ll-pill { display:inline-block; padding:.18rem .6rem; border-radius:999px; font-size:.78rem;
|
| 139 |
+
background: color-mix(in srgb, var(--ll-accent) 14%, transparent); color: var(--ll-accent);
|
| 140 |
+
margin-right:.35rem; font-weight:600; }
|
| 141 |
+
.ll-table { width:100%; border-collapse:collapse; font-size:.95rem; }
|
| 142 |
+
.ll-table td { padding:.55rem .6rem; border-bottom:1px solid color-mix(in srgb, currentColor 12%, transparent); vertical-align: top; }
|
| 143 |
+
.ll-num { font-variant-numeric: tabular-nums; white-space: nowrap; }
|
| 144 |
+
.ll-unit { opacity:.65; font-size:.85em; }
|
| 145 |
+
.ll-note { font-size:.75rem; opacity:.65; white-space: normal; }
|
| 146 |
+
.ll-badge { padding:.15rem .55rem; border-radius:6px; font-size:.82rem; font-weight:600; white-space:nowrap; }
|
| 147 |
+
.ll-ok { background:#dcfce7; color:#14532d; }
|
| 148 |
+
.ll-warn { background:#fef3c7; color:#78350f; }
|
| 149 |
+
.ll-crit { background:#fee2e2; color:#7f1d1d; }
|
| 150 |
+
.ll-check { background:#e0e7ff; color:#312e81; padding:.7rem .9rem; border-radius:10px; margin:.4rem 0; }
|
| 151 |
+
.ll-muted { background:#e5e7eb; color:#374151; }
|
| 152 |
+
.ll-urgent { background:#fee2e2; color:#7f1d1d; border:2px solid #dc2626; padding:.9rem 1rem;
|
| 153 |
+
border-radius:12px; font-size:1.02rem; margin:.4rem 0; }
|
| 154 |
+
"""
|
| 155 |
+
|
| 156 |
+
with gr.Blocks(title="LabLens") as demo:
|
| 157 |
+
gr.HTML(
|
| 158 |
+
'<div id="ll-hero"><h1>🔬 LabLens</h1>'
|
| 159 |
+
"<p>Understand your blood test in plain language — English, Français, العربية, or Tounsi.</p>"
|
| 160 |
+
'<span class="ll-pill">Flags by fixed medical rules, not AI</span>'
|
| 161 |
+
'<span class="ll-pill">Your image and name never reach the AI</span>'
|
| 162 |
+
'<span class="ll-pill">You check every value</span></div>'
|
| 163 |
+
)
|
| 164 |
+
with gr.Row():
|
| 165 |
+
with gr.Column(scale=5):
|
| 166 |
+
file = gr.File(label="Lab report (photo or PDF)", file_types=["image", ".pdf"], type="filepath")
|
| 167 |
+
with gr.Row():
|
| 168 |
+
s1 = gr.Button("Sample: English PDF", size="sm")
|
| 169 |
+
s2 = gr.Button("Sample: French photo", size="sm")
|
| 170 |
+
s3 = gr.Button("Sample: urgent value", size="sm")
|
| 171 |
+
lang = gr.Dropdown(LANG_CHOICES, value="en", label="Explain in")
|
| 172 |
+
read_btn = gr.Button("1 · Read report", variant="primary")
|
| 173 |
+
with gr.Column(scale=7):
|
| 174 |
+
status = gr.Markdown("Upload a report to begin.")
|
| 175 |
+
table = gr.Dataframe(headers=HEADERS, datatype=["str", "number", "str", "number", "number"],
|
| 176 |
+
interactive=True, label="What I read — edit anything that's wrong",
|
| 177 |
+
row_count=(0, "dynamic"), column_count=(5, "fixed"))
|
| 178 |
+
explain_btn = gr.Button("2 · Explain my results", variant="primary")
|
| 179 |
+
|
| 180 |
+
detected = gr.State(None)
|
| 181 |
+
banner = gr.HTML()
|
| 182 |
+
results_html = gr.HTML()
|
| 183 |
+
explanation = gr.Markdown()
|
| 184 |
+
footnote = gr.HTML(f"<small>{t(DISCLAIMER, 'en')} Synthetic sample reports only — fictional patients and labs.</small>")
|
| 185 |
+
|
| 186 |
+
s1.click(lambda: load_sample("sample_en_report.pdf"), outputs=file)
|
| 187 |
+
s2.click(lambda: (load_sample("sample_fr_photo.png"), "fr"), outputs=[file, lang])
|
| 188 |
+
s3.click(lambda: (load_sample("sample_fr_urgent.png"), "darija"), outputs=[file, lang])
|
| 189 |
+
read_btn.click(read_report, [file, lang], [table, status, detected])
|
| 190 |
+
explain_btn.click(run_explain, [table, lang], [banner, results_html, explanation, footnote])
|
| 191 |
+
lang.change(lambda l: gr.update(rtl=l in RTL), lang, explanation)
|
| 192 |
+
|
| 193 |
+
if __name__ == "__main__":
|
| 194 |
+
print("LLM configured:", llm_available())
|
| 195 |
+
demo.launch(css=CSS, theme=gr.themes.Soft(primary_hue="teal"))
|
packages.txt
ADDED
|
@@ -0,0 +1,6 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
tesseract-ocr
|
| 2 |
+
tesseract-ocr-eng
|
| 3 |
+
tesseract-ocr-fra
|
| 4 |
+
tesseract-ocr-ara
|
| 5 |
+
poppler-utils
|
| 6 |
+
fonts-dejavu-core
|
requirements.txt
ADDED
|
@@ -0,0 +1,11 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
gradio>=5.0
|
| 2 |
+
openai>=1.40
|
| 3 |
+
pydantic>=2.6
|
| 4 |
+
pyyaml>=6.0
|
| 5 |
+
rapidfuzz>=3.6
|
| 6 |
+
pdfplumber>=0.11
|
| 7 |
+
pytesseract>=0.3.10
|
| 8 |
+
opencv-python-headless>=4.9
|
| 9 |
+
numpy>=1.26
|
| 10 |
+
pillow>=10.0
|
| 11 |
+
reportlab>=4.0
|