NeuroMedix / app.py
REALME5-pro's picture
Update app.py
a2c4a4a verified
import gradio as gr
from huggingface_hub import InferenceClient
from fastai.text.all import *
from transformers import AutoTokenizer, AutoModelForSequenceClassification
import torch
# Initialize Hugging Face Client
client = InferenceClient("HuggingFaceH4/zephyr-7b-beta")
# Load the medical model
medical_learn = load_learner('model.pkl')
# Medical model configuration
medical_categories = ['Allergy', 'Anemia', 'Bronchitis', 'Diabetes', 'Diarrhea', 'Fatigue', 'Flu', 'Malaria', 'Stress']
def classify_medical_text(txt):
try:
pred, idx, probs = medical_learn.predict(txt)
return dict(zip(medical_categories, map(float, probs)))
except Exception as e:
return {"error": str(e)}
# Load the psychiatric model
psychiatric_model_name = "nlp4good/psych-search" # Replace with the appropriate model
psychiatric_tokenizer = AutoTokenizer.from_pretrained(psychiatric_model_name)
psychiatric_model = AutoModelForSequenceClassification.from_pretrained(psychiatric_model_name)
# Psychiatric model configuration
psychiatric_labels = ['Depression', 'Anxiety', 'Bipolar Disorder', 'PTSD', 'OCD', 'Stress', 'Schizophrenia']
def classify_psychiatric_text(txt):
try:
inputs = psychiatric_tokenizer(txt, return_tensors="pt", truncation=True, padding=True)
with torch.no_grad():
outputs = psychiatric_model(**inputs)
logits = outputs.logits
probabilities = torch.softmax(logits, dim=1).squeeze().tolist()
return dict(zip(psychiatric_labels, probabilities))
except Exception as e:
return {"error": str(e)}
# Chat-based Interface
def respond(
message,
history: list[tuple[str, str]],
system_message,
max_tokens,
temperature,
top_p,
):
messages = [{"role": "system", "content": system_message}]
for val in history:
if val[0]:
messages.append({"role": "user", "content": val[0]})
if val[1]:
messages.append({"role": "assistant", "content": val[1]})
messages.append({"role": "user", "content": message})
response = ""
try:
for message in client.chat_completion(
messages,
max_tokens=max_tokens,
stream=True,
temperature=temperature,
top_p=top_p,
):
token = message.choices[0].delta.content
response += token
yield response
except Exception as e:
yield f"Error: {str(e)}"
# Gradio Interfaces
medical_interface = gr.Interface(
fn=classify_medical_text,
inputs=gr.Textbox(lines=2, label="Describe your symptoms in detail"),
outputs=gr.Label(label="Medical Diagnosis"),
examples=["I feel short of breath and have a high fever.", "My throat hurts and I keep sneezing.", "I am always thirsty."],
description="Identify potential medical conditions based on symptoms."
)
psychiatric_interface = gr.Interface(
fn=classify_psychiatric_text,
inputs=gr.Textbox(lines=2, label="Describe your mental health concerns in detail"),
outputs=gr.Label(label="Psychiatric Analysis"),
examples=["I feel hopeless and have no energy.", "I am unable to concentrate and feel anxious all the time.", "I have recurring intrusive thoughts."],
description="Analyze potential mental health concerns based on input."
)
chat_interface = gr.ChatInterface(
respond,
additional_inputs=[
gr.Textbox(value="You are a friendly Chatbot.", label="System message"),
gr.Slider(minimum=1, maximum=2048, value=512, step=1, label="Max new tokens"),
gr.Slider(minimum=0.1, maximum=4.0, value=0.7, step=0.1, label="Temperature"),
gr.Slider(minimum=0.1, maximum=1.0, value=0.95, step=0.05, label="Top-p (nucleus sampling)"),
],
description="Chat with an AI assistant for general inquiries or extended conversation."
)
# Unified Gradio App with Tabs
with gr.Blocks() as app:
gr.Markdown("# Unified Medical and Psychiatric Assistant")
with gr.Tab("Chat Assistant"):
chat_interface.render()
with gr.Tab("Medical Diagnosis"):
medical_interface.render()
with gr.Tab("Psychiatric Analysis"):
psychiatric_interface.render()
# Launch the App
if __name__ == "__main__":
app.launch()