Spaces:
Runtime error
Runtime error
Create app.py
Browse files
app.py
ADDED
|
@@ -0,0 +1,46 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
import gradio as gr
|
| 2 |
+
from sentence_transformers import SentenceTransformer, util
|
| 3 |
+
from transformers import pipeline
|
| 4 |
+
|
| 5 |
+
# --- MODELS ---
|
| 6 |
+
embedder = SentenceTransformer("all-MiniLM-L6-v2")
|
| 7 |
+
llm = pipeline("text-generation", model="gpt2", max_new_tokens=60)
|
| 8 |
+
|
| 9 |
+
# --- RULE-BASED FUNCTION ---
|
| 10 |
+
def rule_based(text):
|
| 11 |
+
if "anaemia" in text.lower() or "anemia" in text.lower():
|
| 12 |
+
return "✅ Anaemia detected (keyword match)"
|
| 13 |
+
else:
|
| 14 |
+
return "❌ Anaemia not detected (no keyword match)"
|
| 15 |
+
|
| 16 |
+
# --- MACHINE LEARNING FUNCTION ---
|
| 17 |
+
reference_text = "Patient diagnosed with anaemia and low haemoglobin."
|
| 18 |
+
ref_emb = embedder.encode(reference_text, convert_to_tensor=True)
|
| 19 |
+
|
| 20 |
+
def ml_based(text):
|
| 21 |
+
emb = embedder.encode(text, convert_to_tensor=True)
|
| 22 |
+
score = util.cos_sim(emb, ref_emb).item()
|
| 23 |
+
return f"Similarity to anaemia reference: {score:.2f}\n" + \
|
| 24 |
+
("✅ Anaemia likely" if score > 0.45 else "❌ Anaemia unlikely")
|
| 25 |
+
|
| 26 |
+
# --- AI / FOUNDATION MODEL FUNCTION ---
|
| 27 |
+
def ai_based(text):
|
| 28 |
+
prompt = f"Determine if the following note suggests anaemia:\n\n{text}\n\nAnswer clearly with reasoning."
|
| 29 |
+
result = llm(prompt)[0]["generated_text"]
|
| 30 |
+
return result
|
| 31 |
+
|
| 32 |
+
# --- GRADIO UI ---
|
| 33 |
+
with gr.Blocks(title="Rule-Based vs Machine Learning vs AI") as demo:
|
| 34 |
+
gr.Markdown("# 🔍 Clinical Text Understanding Demo\nCompare rule-based, ML, and AI approaches for detecting **anaemia**.")
|
| 35 |
+
text_input = gr.Textbox(label="Enter clinical note", lines=4)
|
| 36 |
+
rb_output = gr.Textbox(label="Rule-Based Result")
|
| 37 |
+
ml_output = gr.Textbox(label="Machine Learning Result")
|
| 38 |
+
ai_output = gr.Textbox(label="AI (LLM) Result")
|
| 39 |
+
|
| 40 |
+
def process(text):
|
| 41 |
+
return rule_based(text), ml_based(text), ai_based(text)
|
| 42 |
+
|
| 43 |
+
btn = gr.Button("Run All")
|
| 44 |
+
btn.click(process, inputs=text_input, outputs=[rb_output, ml_output, ai_output])
|
| 45 |
+
|
| 46 |
+
demo.launch()
|