Zeeshan42 commited on
Commit
5e5ffa6
1 Parent(s): 18fd3f5

Update app.py

Browse files
Files changed (1) hide show
  1. app.py +120 -61
app.py CHANGED
@@ -1,64 +1,123 @@
1
  import gradio as gr
2
- from huggingface_hub import InferenceClient
3
-
4
- """
5
- For more information on `huggingface_hub` Inference API support, please check the docs: https://huggingface.co/docs/huggingface_hub/v0.22.2/en/guides/inference
6
- """
7
- client = InferenceClient("HuggingFaceH4/zephyr-7b-beta")
8
-
9
-
10
- def respond(
11
- message,
12
- history: list[tuple[str, str]],
13
- system_message,
14
- max_tokens,
15
- temperature,
16
- top_p,
17
- ):
18
- messages = [{"role": "system", "content": system_message}]
19
-
20
- for val in history:
21
- if val[0]:
22
- messages.append({"role": "user", "content": val[0]})
23
- if val[1]:
24
- messages.append({"role": "assistant", "content": val[1]})
25
-
26
- messages.append({"role": "user", "content": message})
27
-
28
- response = ""
29
-
30
- for message in client.chat_completion(
31
- messages,
32
- max_tokens=max_tokens,
33
- stream=True,
34
- temperature=temperature,
35
- top_p=top_p,
36
- ):
37
- token = message.choices[0].delta.content
38
-
39
- response += token
40
- yield response
41
-
42
-
43
- """
44
- For information on how to customize the ChatInterface, peruse the gradio docs: https://www.gradio.app/docs/chatinterface
45
- """
46
- demo = gr.ChatInterface(
47
- respond,
48
- additional_inputs=[
49
- gr.Textbox(value="You are a friendly Chatbot.", label="System message"),
50
- gr.Slider(minimum=1, maximum=2048, value=512, step=1, label="Max new tokens"),
51
- gr.Slider(minimum=0.1, maximum=4.0, value=0.7, step=0.1, label="Temperature"),
52
- gr.Slider(
53
- minimum=0.1,
54
- maximum=1.0,
55
- value=0.95,
56
- step=0.05,
57
- label="Top-p (nucleus sampling)",
58
- ),
59
- ],
60
- )
61
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
62
 
63
- if __name__ == "__main__":
64
- demo.launch()
 
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()