Spaces:
Runtime error
Runtime error
Update app.py
Browse files
app.py
CHANGED
@@ -1,64 +1,123 @@
|
|
1 |
import gradio as gr
|
2 |
-
from
|
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 |
-
step=0.05,
|
57 |
-
label="Top-p (nucleus sampling)",
|
58 |
-
),
|
59 |
-
],
|
60 |
-
)
|
61 |
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
62 |
|
63 |
-
|
64 |
-
|
|
|
1 |
import gradio as gr
|
2 |
+
from datasets import load_dataset
|
3 |
+
from transformers import T5ForConditionalGeneration, T5Tokenizer, AutoTokenizer, AutoModelForSequenceClassification
|
4 |
+
import random
|
5 |
+
import torch
|
6 |
+
import groq # Assuming you are using the Groq library
|
7 |
+
import os
|
8 |
+
from dotenv import load_dotenv
|
9 |
+
from huggingface_hub import login
|
10 |
+
|
11 |
+
# Load environment variables from .env file
|
12 |
+
load_dotenv()
|
13 |
+
HUGGING_FACE_TOKEN = os.getenv("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")
|
14 |
+
|
15 |
+
# Authenticate with Hugging Face (use your token)
|
16 |
+
login(HUGGING_FACE_TOKEN)
|
17 |
+
|
18 |
+
# Load the mental health counseling conversations dataset
|
19 |
+
ds = load_dataset("Amod/mental_health_counseling_conversations")
|
20 |
+
context = ds["train"]["Context"]
|
21 |
+
response = ds["train"]["Response"]
|
22 |
+
|
23 |
+
GROQ_API_KEY = "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"
|
24 |
+
|
25 |
+
client = groq.Groq(api_key=GROQ_API_KEY)
|
26 |
+
|
27 |
+
# Load FLAN-T5 model and tokenizer for primary RAG
|
28 |
+
flan_tokenizer = T5Tokenizer.from_pretrained("google/flan-t5-small")
|
29 |
+
flan_model = T5ForConditionalGeneration.from_pretrained("google/flan-t5-small")
|
30 |
+
|
31 |
+
# Load sentiment analysis model
|
32 |
+
sentiment_tokenizer = AutoTokenizer.from_pretrained("distilbert-base-uncased-finetuned-sst-2-english")
|
33 |
+
sentiment_model = AutoModelForSequenceClassification.from_pretrained("distilbert-base-uncased-finetuned-sst-2-english")
|
34 |
+
|
35 |
+
# Groq client setup (assuming you have an API key)
|
36 |
+
client = groq.Groq(api_key=GROQ_API_KEY) # Corrected Groq client initialization
|
37 |
+
# Function for sentiment analysis
|
38 |
+
def analyze_sentiment(text):
|
39 |
+
inputs = sentiment_tokenizer(text, return_tensors="pt")
|
40 |
+
outputs = sentiment_model(**inputs)
|
41 |
+
probs = torch.nn.functional.softmax(outputs.logits, dim=-1)
|
42 |
+
sentiment = "positive" if torch.argmax(probs) == 1 else "negative"
|
43 |
+
confidence = probs.max().item()
|
44 |
+
return sentiment, confidence
|
45 |
+
|
46 |
+
# Function to generate response based on sentiment and user input
|
47 |
+
def generate_response(sentiment, user_input):
|
48 |
+
prompt = f"The user feels {sentiment}. Respond with supportive advice based on: {user_input}"
|
49 |
+
inputs = flan_tokenizer(prompt, return_tensors="pt")
|
50 |
+
response = flan_model.generate(**inputs, max_length=150)
|
51 |
+
return flan_tokenizer.decode(response[0], skip_special_tokens=True)
|
52 |
+
# Main chatbot function
|
53 |
+
def chatbot(user_input):
|
54 |
+
if not user_input.strip():
|
55 |
+
return "Please enter a question or concern to receive guidance."
|
|
|
|
|
|
|
|
|
|
|
56 |
|
57 |
+
# Word count limit
|
58 |
+
word_count = len(user_input.split())
|
59 |
+
max_words = 50
|
60 |
+
remaining_words = max_words - word_count
|
61 |
+
if remaining_words < 0:
|
62 |
+
return f"Your input is too long. Please limit it to {max_words} words."
|
63 |
+
|
64 |
+
# Sentiment analysis
|
65 |
+
sentiment, confidence = analyze_sentiment(user_input)
|
66 |
+
|
67 |
+
# Groq API fallback for a personalized response
|
68 |
+
try:
|
69 |
+
brief_response = client.chat.completions.create(
|
70 |
+
messages=[{
|
71 |
+
"role": "user",
|
72 |
+
"content": user_input,
|
73 |
+
}],
|
74 |
+
model="llama3-8b-8192", # Change model if needed
|
75 |
+
)
|
76 |
+
brief_response = brief_response.choices[0].message.content
|
77 |
+
except Exception as e:
|
78 |
+
brief_response = None
|
79 |
+
|
80 |
+
if brief_response:
|
81 |
+
return f"**Personalized Response from Groq:** {brief_response}"
|
82 |
+
|
83 |
+
# Fallback to FLAN-T5 model for response generation
|
84 |
+
response_text = generate_response(sentiment, user_input)
|
85 |
+
def generate_response(user_input):
|
86 |
+
# Generate response using FLAN-T5
|
87 |
+
inputs = flan_tokenizer.encode("summarize: " + user_input, return_tensors="pt", max_length=512, truncation=True)
|
88 |
+
summary_ids = flan_model.generate(inputs, max_length=100, num_beams=4, early_stopping=True)
|
89 |
+
generated_response = flan_tokenizer.decode(summary_ids[0], skip_special_tokens=True)
|
90 |
+
|
91 |
+
if not generated_response:
|
92 |
+
return "I'm sorry, I don't have information specific to your concern. Please consult a professional."
|
93 |
+
|
94 |
+
# Final response with different sources
|
95 |
+
complete_response = (
|
96 |
+
f"**Sentiment Analysis:** {sentiment} (Confidence: {confidence:.2f})\n\n"
|
97 |
+
f"**Generated Response:**\n{generated_response}\n\n"
|
98 |
+
f"**Contextual Information:**\n{context_text}\n\n"
|
99 |
+
f"**Additional Dataset Response:**\n{dataset_response}\n\n"
|
100 |
+
f"Words entered: {word_count}, Words remaining: {remaining_words}"
|
101 |
+
)
|
102 |
+
|
103 |
+
return complete_response
|
104 |
+
|
105 |
+
# Example call to the function
|
106 |
+
response = generate_response("This is an example input.")
|
107 |
+
print(response)
|
108 |
+
# Set up Gradio interface
|
109 |
+
interface = gr.Interface(
|
110 |
+
fn=chatbot,
|
111 |
+
inputs=gr.Textbox(
|
112 |
+
label="Ask your question:",
|
113 |
+
placeholder="Describe how you're feeling today...",
|
114 |
+
lines=4
|
115 |
+
),
|
116 |
+
outputs=gr.Markdown(label="Psychologist Assistant Response"),
|
117 |
+
title="Virtual Psychiatrist Assistant",
|
118 |
+
description="Enter your mental health concerns, and receive guidance and responses from a trained assistant.",
|
119 |
+
theme="huggingface"
|
120 |
+
)
|
121 |
|
122 |
+
# Launch the app
|
123 |
+
interface.launch()
|