Muhammadidrees commited on
Commit
b4961fa
·
verified ·
1 Parent(s): f19b8f7

Update app.py

Browse files
Files changed (1) hide show
  1. app.py +93 -102
app.py CHANGED
@@ -2,123 +2,114 @@ import gradio as gr
2
  import torch
3
  from transformers import AutoTokenizer, AutoModelForCausalLM, pipeline
4
 
5
- HF_MODEL = "Muhammadidrees/bioLLM"
6
 
7
- # ---------------------------
8
- # Safe model/tokenizer loader
9
- # ---------------------------
10
- def load_model_and_tokenizer(model_name):
11
- try:
12
- tokenizer = AutoTokenizer.from_pretrained(model_name)
13
- except ImportError:
14
- # fallback if sacremoses is missing
15
- tokenizer = AutoTokenizer.from_pretrained(model_name, use_fast=False)
16
-
17
- model = AutoModelForCausalLM.from_pretrained(model_name, torch_dtype=torch.float32)
18
- pipe = pipeline("text-generation", model=model, tokenizer=tokenizer, device=0 if torch.cuda.is_available() else -1)
19
- return pipe, tokenizer
20
-
21
- pipe, tokenizer = load_model_and_tokenizer(HF_MODEL)
22
-
23
-
24
- # ---------------------------
25
- # Prompt template
26
- # ---------------------------
27
- def build_prompt(inputs):
28
- biomarkers = "\n".join([f"- {k}: {v}" for k, v in inputs.items() if k not in ["Age", "Weight", "Height", "Sex"]])
29
- demographics = f"Age: {inputs['Age']}, Sex: {inputs['Sex']}, Height: {inputs['Height']} cm, Weight: {inputs['Weight']} kg"
30
-
31
- prompt = f"""
32
- You are a biomedical AI assistant.
33
- You will generate a medical-style report based on the given biomarkers and demographics.
34
- Follow this structure exactly:
35
 
36
- ### Executive Summary
37
- (A concise summary of patient status)
38
 
39
- ### System-Specific Analysis
40
- (Explain implications for cardiovascular, renal, hepatic, metabolic, and immune systems)
 
41
 
42
- ### Personalized Action Plan
43
- (List lifestyle, dietary, and medical recommendations)
44
 
45
- ### Further Recommendations
46
- (Additional tests, follow-ups, or referrals)
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
47
 
48
- ### Biomarker Interpretation Table
49
- Generate a Markdown table with columns: Biomarker | Value | Status | Interpretation
50
 
51
- ---
52
- Patient Demographics:
53
- {demographics}
54
 
55
- Biomarkers:
56
- {biomarkers}
57
- """
58
- return prompt
59
 
 
 
 
60
 
61
- # ---------------------------
62
- # Gradio function
63
- # ---------------------------
64
- def generate_report(Age, Weight, Height, Sex,
65
- Albumin, Creatinine, Glucose, CRP, MCV,
66
- RDW, Hemoglobin, WBC, Platelets, Cholesterol):
67
-
68
- inputs = {
69
- "Age": Age, "Weight": Weight, "Height": Height, "Sex": Sex,
70
- "Albumin": Albumin, "Creatinine": Creatinine, "Glucose": Glucose, "CRP": CRP,
71
- "MCV": MCV, "RDW": RDW, "Hemoglobin": Hemoglobin, "WBC": WBC,
72
- "Platelets": Platelets, "Cholesterol": Cholesterol
73
- }
74
 
75
- prompt = build_prompt(inputs)
 
 
76
 
77
- output = pipe(prompt, max_new_tokens=1500, temperature=0.6, do_sample=True)[0]["generated_text"]
 
 
78
 
79
- return output
 
 
80
 
 
 
81
 
82
- # ---------------------------
83
- # Gradio UI
84
- # ---------------------------
85
- with gr.Blocks() as demo:
86
- gr.Markdown("# 🧬 BioLLM: Biomarker AI Report Generator")
87
- gr.Markdown("Provide biomarkers + demographics to generate an AI-based health report.")
88
 
89
- with gr.Row():
90
- with gr.Column():
91
- Age = gr.Number(label="Age", value=45)
92
- Sex = gr.Dropdown(["Male", "Female"], label="Sex", value="Male")
93
- Height = gr.Number(label="Height (cm)", value=175)
94
- Weight = gr.Number(label="Weight (kg)", value=75)
95
-
96
- with gr.Column():
97
- Albumin = gr.Textbox(label="Albumin (g/dL)", value="4.2")
98
- Creatinine = gr.Textbox(label="Creatinine (mg/dL)", value="1.0")
99
- Glucose = gr.Textbox(label="Glucose (mg/dL)", value="90")
100
- CRP = gr.Textbox(label="CRP (mg/L)", value="2.0")
101
- MCV = gr.Textbox(label="MCV (fL)", value="88")
102
- RDW = gr.Textbox(label="RDW (%)", value="12.5")
103
- Hemoglobin = gr.Textbox(label="Hemoglobin (g/dL)", value="14.0")
104
- WBC = gr.Textbox(label="WBC (10^3/uL)", value="6.5")
105
- Platelets = gr.Textbox(label="Platelets (10^3/uL)", value="250")
106
- Cholesterol = gr.Textbox(label="Cholesterol (mg/dL)", value="180")
107
-
108
- run_btn = gr.Button("🔍 Generate Report")
109
- output_box = gr.Markdown(label="AI-Generated Report")
110
-
111
- run_btn.click(
112
- generate_report,
113
- inputs=[Age, Weight, Height, Sex,
114
- Albumin, Creatinine, Glucose, CRP, MCV,
115
- RDW, Hemoglobin, WBC, Platelets, Cholesterol],
116
- outputs=[output_box]
117
  )
118
 
119
-
120
- # ---------------------------
121
- # Run app
122
- # ---------------------------
123
- if __name__ == "__main__":
124
- demo.launch()
 
2
  import torch
3
  from transformers import AutoTokenizer, AutoModelForCausalLM, pipeline
4
 
5
+ MODEL_ID = "Muhammadidrees/bioLLM"
6
 
7
+ #import gradio as gr
8
+ from transformers import AutoTokenizer, AutoModelForCausalLM, pipeline
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
9
 
10
+ # Load your model from Hugging Face Hub
11
+ # MODEL_ID = "Muhammadidrees/MedicalInsights"
12
 
13
+ tokenizer = AutoTokenizer.from_pretrained(MODEL_ID)
14
+ model = AutoModelForCausalLM.from_pretrained(MODEL_ID, device_map="auto")
15
+ pipe = pipeline("text-generation", model=model, tokenizer=tokenizer)
16
 
 
 
17
 
18
+ # Function to build structured input and query the LLM
19
+ def analyze(
20
+ albumin, creatinine, glucose, crp, mcv, rdw, alp,
21
+ wbc, lymph, age, gender, height, weight
22
+ ):
23
+ # Calculate BMI (hidden from user, only passed to LLM)
24
+ try:
25
+ height_m = height / 100 # cm → m
26
+ bmi = round(weight / (height_m ** 2), 2)
27
+ except Exception:
28
+ bmi = "N/A"
29
+
30
+ # System-style instruction
31
+ system_prompt = (
32
+ "You are an advanced AI medical assistant. "
33
+ "Analyze the patient’s biomarkers and demographics. "
34
+ "Provide a structured assessment including: "
35
+ """Executive Summary,System-Specific Analysis,Personalized Action Plan,Interaction Alerts,Longevity Metrics,Enhanced AI Insights & Longitudinal Risk
36
+
37
+ """ )
38
+
39
+ # Construct patient profile input
40
+ patient_input = f"""
41
+ Patient Profile:
42
+ - Age: {age}
43
+ - Gender: {gender}
44
+ - Height: {height} cm
45
+ - Weight: {weight} kg
46
+ - BMI: {bmi}
47
+
48
+ Lab Values:
49
+ - Albumin: {albumin} g/dL
50
+ - Creatinine: {creatinine} mg/dL
51
+ - Glucose: {glucose} mg/dL
52
+ - C-Reactive Protein: {crp} mg/L
53
+ - Mean Cell Volume: {mcv} fL
54
+ - Red Cell Distribution Width: {rdw} %
55
+ - Alkaline Phosphatase: {alp} U/L
56
+ - White Blood Cell Count: {wbc} K/uL
57
+ - Lymphocyte Percentage: {lymph} %
58
+ """
59
+
60
+ prompt = system_prompt + "\n" + patient_input
61
+
62
+ # Call LLM (exclude echoed input)
63
+ result = pipe(
64
+ prompt,
65
+ max_new_tokens=2000,
66
+ do_sample=True,
67
+ temperature=0.6,
68
+ return_full_text=False
69
+ )
70
+ return result[0]["generated_text"].strip()
71
 
 
 
72
 
73
+ # Build Gradio UI
74
+ with gr.Blocks() as demo:
75
+ gr.Markdown("## 🧪 Medical Insights AI — Enter Patient Data")
76
 
77
+ with gr.Row():
78
+ albumin = gr.Number(label="Albumin (g/dL)")
79
+ wbc = gr.Number(label="White Blood Cell Count (K/uL)")
 
80
 
81
+ with gr.Row():
82
+ creatinine = gr.Number(label="Creatinine (mg/dL)")
83
+ lymph = gr.Number(label="Lymphocyte Percentage (%)")
84
 
85
+ with gr.Row():
86
+ glucose = gr.Number(label="Glucose (mg/dL)")
87
+ age = gr.Number(label="Age (years)")
 
 
 
 
 
 
 
 
 
 
88
 
89
+ with gr.Row():
90
+ crp = gr.Number(label="C-Reactive Protein (mg/L)")
91
+ gender = gr.Dropdown(choices=["Male", "Female"], label="Gender")
92
 
93
+ with gr.Row():
94
+ mcv = gr.Number(label="Mean Cell Volume (fL)")
95
+ height = gr.Number(label="Height (cm)")
96
 
97
+ with gr.Row():
98
+ rdw = gr.Number(label="Red Cell Distribution Width (%)")
99
+ weight = gr.Number(label="Weight (kg)")
100
 
101
+ with gr.Row():
102
+ alp = gr.Number(label="Alkaline Phosphatase (U/L)")
103
 
104
+ analyze_btn = gr.Button("🔎 Analyze")
105
+ output = gr.Textbox(label="AI Medical Assessment", lines=12)
 
 
 
 
106
 
107
+ # Run analysis
108
+ analyze_btn.click(
109
+ fn=analyze,
110
+ inputs=[albumin, creatinine, glucose, crp, mcv, rdw, alp,
111
+ wbc, lymph, age, gender, height, weight],
112
+ outputs=output
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
113
  )
114
 
115
+ demo.launch()