import gradio as gr from transformers import pipeline import pandas as pd import PyPDF2 import pdfplumber import torch import timm from PIL import Image # Load pre-trained model for zero-shot classification classifier = pipeline("zero-shot-classification", model="facebook/bart-large-mnli") # Pre-trained model for X-ray analysis (example with a model from timm library) image_model = timm.create_model('resnet50', pretrained=True) image_model.eval() # Initialize patient database patients_db = [] # Disease and medication mapping with formulations and doctor recommendations disease_details = { "anemia": { "medication": "Iron supplements (e.g., Ferrous sulfate 325mg)", "precaution": "Increase intake of iron-rich foods like spinach, red meat, and beans.", "doctor": "Hematologist" }, "viral infection": { "medication": "Antiviral drugs (e.g., Oseltamivir 75mg for flu)", "precaution": "Rest, stay hydrated, avoid close contact with others, and wash hands frequently.", "doctor": "Infectious Disease Specialist" }, "liver disease": { "medication": "Hepatoprotective drugs (e.g., Ursodeoxycholic acid 300mg)", "precaution": "Avoid alcohol and maintain a balanced diet, avoid fatty foods.", "doctor": "Hepatologist" }, "kidney disease": { "medication": "Angiotensin-converting enzyme inhibitors (e.g., Lisinopril 10mg)", "precaution": "Monitor salt intake, stay hydrated, and avoid NSAIDs.", "doctor": "Nephrologist" }, "diabetes": { "medication": "Metformin (e.g., 500mg) or insulin therapy", "precaution": "Follow a low-sugar diet, monitor blood sugar levels, and exercise regularly.", "doctor": "Endocrinologist" }, "hypertension": { "medication": "Antihypertensive drugs (e.g., Amlodipine 5mg)", "precaution": "Reduce salt intake, manage stress, and avoid smoking.", "doctor": "Cardiologist" }, "COVID-19": { "medication": "Supportive care, antiviral drugs (e.g., Remdesivir 200mg in severe cases)", "precaution": "Follow isolation protocols, wear a mask, stay hydrated, and rest.", "doctor": "Infectious Disease Specialist" }, "pneumonia": { "medication": "Antibiotics (e.g., Amoxicillin 500mg or Azithromycin 250mg)", "precaution": "Rest, avoid smoking, stay hydrated, and get proper ventilation.", "doctor": "Pulmonologist" } } # Functions for various features def register_patient(name, age, gender): patient_id = len(patients_db) + 1 patients_db.append({ "ID": patient_id, "Name": name, "Age": age, "Gender": gender, "Symptoms": "", "Diagnosis": "", "Action Plan": "", "Medications": "", "Precautions": "", "Tests": "" }) return f"✅ Patient {name} registered successfully. Patient ID: {patient_id}" def analyze_report(patient_id, report_text): candidate_labels = list(disease_details.keys()) result = classifier(report_text, candidate_labels) diagnosis = result['labels'][0] # Update patient's diagnosis, medications, and precautions in the patient record medication = disease_details.get(diagnosis, {}).get("medication", "No medication found") precaution = disease_details.get(diagnosis, {}).get("precaution", "No precautions found") for patient in patients_db: if patient["ID"] == patient_id: patient["Diagnosis"] = diagnosis patient["Medications"] = medication patient["Precautions"] = precaution break return f"🔍 Diagnosis: {diagnosis}" def extract_pdf_report(pdf): text = "" with pdfplumber.open(pdf.name) as pdf_file: for page in pdf_file.pages: text += page.extract_text() return text def analyze_image(patient_id, img): image = Image.open(img).convert('RGB') transform = torch.nn.Sequential( torch.nn.Upsample(size=(224, 224)), torch.nn.Normalize(mean=[0.485, 0.456, 0.406], std=[0.229, 0.224, 0.225]) ) image_tensor = transform(torch.unsqueeze(torch.tensor(image), 0)) output = image_model(image_tensor) _, predicted = torch.max(output, 1) labels = {0: "Normal", 1: "Pneumonia", 2: "Liver Disorder", 3: "COVID-19"} diagnosis = labels.get(predicted.item(), "Unknown") # Update patient's diagnosis, medications, and precautions in the patient record medication = disease_details.get(diagnosis, {}).get("medication", "No medication found") precaution = disease_details.get(diagnosis, {}).get("precaution", "No precautions found") for patient in patients_db: if patient["ID"] == patient_id: patient["Diagnosis"] = diagnosis patient["Medications"] = medication patient["Precautions"] = precaution break return f"🔍 Diagnosis from image: {diagnosis}" def show_dashboard(): if not patients_db: return "No patient records available." return pd.DataFrame(patients_db) # New Spaces def doctor_space(patient_id): for patient in patients_db: if patient["ID"] == patient_id: diagnosis = patient["Diagnosis"] medication = patient["Medications"] precaution = patient["Precautions"] doctor = disease_details.get(diagnosis, {}).get("doctor", "No doctor available") return (f"🩺 Patient Name: {patient['Name']}\n" f"📋 Diagnosis: {diagnosis}\n" f"💊 Medications: {medication}\n" f"⚠️ Precautions: {precaution}\n" f"📄 Action Plan: {patient['Action Plan']}\n" f"👩‍⚕️ Recommended Doctor: {doctor}") return "Patient not found. Please check the ID." def pharmacist_space(patient_id): for patient in patients_db: if patient["ID"] == patient_id: diagnosis = patient["Diagnosis"] medication = patient["Medications"] return (f"💊 Patient Name: {patient['Name']}\n" f"📋 Prescribed Medications: {medication}") return "Patient not found. Please check the ID." # Gradio Interfaces patient_interface = gr.Interface(fn=register_patient, inputs=[gr.Textbox(label="Patient Name"), gr.Number(label="Age"), gr.Radio(label="Gender", choices=["Male", "Female", "Other"])], outputs="text") report_interface = gr.Interface(fn=analyze_report, inputs=[gr.Number(label="Patient ID"), gr.Textbox(label="Report Text")], outputs="text") pdf_report_interface = gr.Interface(fn=extract_pdf_report, inputs=gr.File(label="Upload PDF Report"), outputs="text") image_interface = gr.Interface(fn=analyze_image, inputs=[gr.Number(label="Patient ID"), gr.Image(type="filepath")], outputs="text") dashboard_interface = gr.Interface(fn=show_dashboard, inputs=None, outputs="dataframe") doctor_interface = gr.Interface(fn=doctor_space, inputs=gr.Number(label="Patient ID"), outputs="text") pharmacist_interface = gr.Interface(fn=pharmacist_space, inputs=gr.Number(label="Patient ID"), outputs="text") # Layout using Blocks with gr.Blocks() as demo: gr.Markdown("# Medical Report and Image Analyzer") with gr.TabItem("Patient Registration"): patient_interface.render() with gr.TabItem("Analyze Report (Text)"): report_interface.render() with gr.TabItem("Analyze Report (PDF)"): pdf_report_interface.render() with gr.TabItem("Analyze Image (X-ray/CT)"): image_interface.render() with gr.TabItem("Dashboard"): dashboard_interface.render() with gr.TabItem("Doctor Space"): doctor_interface.render() with gr.TabItem("Pharmacist Space"): pharmacist_interface.render() demo.launch(share=True)