File size: 4,257 Bytes
a2c4a4a
 
c5857d8
7271724
4eaa6ce
a2c4a4a
 
 
c5857d8
4eaa6ce
 
 
 
 
 
 
a2c4a4a
 
 
 
 
4eaa6ce
a2c4a4a
bdb0a6e
4eaa6ce
 
 
 
a2c4a4a
4eaa6ce
 
a2c4a4a
 
 
 
 
 
 
 
 
4eaa6ce
a2c4a4a
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
4eaa6ce
a2c4a4a
 
 
 
 
 
 
 
 
 
 
 
 
 
4eaa6ce
a2c4a4a
4eaa6ce
 
a2c4a4a
 
 
 
4eaa6ce
 
 
 
a2c4a4a
 
 
 
4eaa6ce
938d757
a2c4a4a
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
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()