Spaces:
Sleeping
Sleeping
Update app.py
Browse files1 unmodified line234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241 unmodified lineimport torchfrom transformers import AutoTokenizer, AutoModelForCausalLM, pipelineHF_MODEL = "Muhammadidrees/bioLLM"# ---------------------------# Safe model/tokenizer loader# ---------------------------def load_model_and_tokenizer(model_name):try:tokenizer = AutoTokenizer.from_pretrained(model_name)except ImportError:# fallback if sacremoses is missingtokenizer = AutoTokenizer.from_pretrained(model_name, use_fast=False)model = AutoModelForCausalLM.from_pretrained(model_name, torch_dtype=torch.float32)pipe = pipeline("text-generation", model=model, tokenizer=tokenizer, device=0 if torch.cuda.is_available() else -1)return pipe, tokenizerpipe, tokenizer = load_model_and_tokenizer(HF_MODEL)# ---------------------------# Prompt template# ---------------------------def build_prompt(inputs):biomarkers = "\n".join([f"- {k}: {v}" for k, v in inputs.items() if k not in ["Age", "Weight", "Height", "Sex"]])demographics = f"Age: {inputs['Age']}, Sex: {inputs['Sex']}, Height: {inputs['Height']} cm, Weight: {inputs['Weight']} kg"prompt = f"""You are a biomedical AI assistant.You will generate a medical-style report based on the given biomarkers and demographics.Follow this structure exactly:### Executive Summary(A concise summary of patient status)### System-Specific Analysis(Explain implications for cardiovascular, renal, hepatic, metabolic, and immune systems)### Personalized Action Plan(List lifestyle, dietary, and medical recommendations)### Further Recommendations(Additional tests, follow-ups, or referrals)### Biomarker Interpretation TableGenerate a Markdown table with columns: Biomarker | Value | Status | Interpretation---Patient Demographics:{demographics}Biomarkers:{biomarkers}"""return prompt# ---------------------------# Gradio function# ---------------------------def generate_report(Age, Weight, Height, Sex,Albumin, Creatinine, Glucose, CRP, MCV,RDW, Hemoglobin, WBC, Platelets, Cholesterol):inputs = {"Age": Age, "Weight": Weight, "Height": Height, "Sex": Sex,"Albumin": Albumin, "Creatinine": Creatinine, "Glucose": Glucose, "CRP": CRP,"MCV": MCV, "RDW": RDW, "Hemoglobin": Hemoglobin, "WBC": WBC,"Platelets": Platelets, "Cholesterol": Cholesterol}prompt = build_prompt(inputs)output = pipe(prompt, max_new_tokens=1500, temperature=0.6, do_sample=True)[0]["generated_text"]return output# ---------------------------# Gradio UI# ---------------------------with gr.Blocks() as demo:gr.Markdown("# 🧬 BioLLM: Biomarker AI Report Generator")gr.Markdown("Provide biomarkers + demographics to generate an AI-based health report.")with gr.Row():with gr.Column():Age = gr.Number(label="Age", value=45)Sex = gr.Dropdown(["Male", "Female"], label="Sex", value="Male")Height = gr.Number(label="Height (cm)", value=175)Weight = gr.Number(label="Weight (kg)", value=75)with gr.Column():Albumin = gr.Textbox(label="Albumin (g/dL)", value="4.2")Creatinine = gr.Textbox(label="Creatinine (mg/dL)", value="1.0")Glucose = gr.Textbox(label="Glucose (mg/dL)", value="90")CRP = gr.Textbox(label="CRP (mg/L)", value="2.0")MCV = gr.Textbox(label="MCV (fL)", value="88")RDW = gr.Textbox(label="RDW (%)", value="12.5")Hemoglobin = gr.Textbox(label="Hemoglobin (g/dL)", value="14.0")WBC = gr.Textbox(label="WBC (10^3/uL)", value="6.5")Platelets = gr.Textbox(label="Platelets (10^3/uL)", value="250")Cholesterol = gr.Textbox(label="Cholesterol (mg/dL)", value="180")run_btn = gr.Button("🔍 Generate Report")output_box = gr.Markdown(label="AI-Generated Report")run_btn.click(generate_report,inputs=[Age, Weight, Height, Sex,Albumin, Creatinine, Glucose, CRP, MCV,RDW, Hemoglobin, WBC, Platelets, Cholesterol],outputs=[output_box])# ---------------------------# Run app# ---------------------------if __name__ == "__main__":demo.launch()1 unmodified line234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151 unmodified lineimport torchfrom transformers import AutoTokenizer, AutoModelForCausalLM, pipelineMODEL_ID = "Muhammadidrees/bioLLM"#import gradio as grfrom transformers import AutoTokenizer, AutoModelForCausalLM, pipeline# Load your model from Hugging Face Hub# MODEL_ID = "Muhammadidrees/MedicalInsights"tokenizer = AutoTokenizer.from_pretrained(MODEL_ID)model = AutoModelForCausalLM.from_pretrained(MODEL_ID, device_map="auto")pipe = pipeline("text-generation", model=model, tokenizer=tokenizer)# Function to build structured input and query the LLMdef analyze(albumin, creatinine, glucose, crp, mcv, rdw, alp,wbc, lymph, age, gender, height, weight):# Calculate BMI (hidden from user, only passed to LLM)try:height_m = height / 100 # cm → mbmi = round(weight / (height_m ** 2), 2)except Exception:bmi = "N/A"# System-style instructionsystem_prompt = ("You are an advanced AI medical assistant. ""Analyze the patient’s biomarkers and demographics. ""Provide a structured assessment including: """"Executive Summary,System-Specific Analysis,Personalized Action Plan,Interaction Alerts,Longevity Metrics,Enhanced AI Insights & Longitudinal Risk""" )# Construct patient profile inputpatient_input = f"""Patient Profile:- Age: {age}- Gender: {gender}- Height: {height} cm- Weight: {weight} kg- BMI: {bmi}Lab Values:- Albumin: {albumin} g/dL- Creatinine: {creatinine} mg/dL- Glucose: {glucose} mg/dL- C-Reactive Protein: {crp} mg/L- Mean Cell Volume: {mcv} fL- Red Cell Distribution Width: {rdw} %- Alkaline Phosphatase: {alp} U/L- White Blood Cell Count: {wbc} K/uL- Lymphocyte Percentage: {lymph} %"""prompt = system_prompt + "\n" + patient_input# Call LLM (exclude echoed input)result = pipe(prompt,max_new_tokens=2000,do_sample=True,temperature=0.6,return_full_text=False)return result[0]["generated_text"].strip()# Build Gradio UIwith gr.Blocks() as demo:gr.Markdown("## 🧪 Medical Insights AI — Enter Patient Data")with gr.Row():albumin = gr.Number(label="Albumin (g/dL)")wbc = gr.Number(label="White Blood Cell Count (K/uL)")with gr.Row():creatinine = gr.Number(label="Creatinine (mg/dL)")lymph = gr.Number(label="Lymphocyte Percentage (%)")with gr.Row():glucose = gr.Number(label="Glucose (mg/dL)")age = gr.Number(label="Age (years)")with gr.Row():crp = gr.Number(label="C-Reactive Protein (mg/L)")gender = gr.Dropdown(choices=["Male", "Female"], label="Gender")with gr.Row():mcv = gr.Number(label="Mean Cell Volume (fL)")height = gr.Number(label="Height (cm)")with gr.Row():rdw = gr.Number(label="Red Cell Distribution Width (%)")weight = gr.Number(label="Weight (kg)")with gr.Row():alp = gr.Number(label="Alkaline Phosphatase (U/L)")analyze_btn = gr.Button("🔎 Analyze")output = gr.Textbox(label="AI Medical Assessment", lines=12)# Run analysisanalyze_btn.click(fn=analyze,inputs=[albumin, creatinine, glucose, crp, mcv, rdw, alp,wbc, lymph, age, gender, height, weight],outputs=output)demo.launch()
app.py+93-102