safwansajad commited on
Commit
6d5d5a4
·
verified ·
1 Parent(s): 7d4edac

Update app.py

Browse files
Files changed (1) hide show
  1. app.py +18 -75
app.py CHANGED
@@ -1,102 +1,45 @@
1
  import gradio as gr
2
  from transformers import pipeline, AutoModelForCausalLM, AutoTokenizer
 
3
 
4
  # Load models
5
  chatbot_model = "microsoft/DialoGPT-medium"
6
- tokenizer = AutoTokenizer.from_pretrained(chatbot_model)
7
- model = AutoModelForCausalLM.from_pretrained(chatbot_model)
8
- emotion_pipeline = pipeline("text-classification", model="j-hartmann/emotion-english-distilroberta-base")
9
-
10
- # Store chat histories
11
- chat_histories = {}
12
-
13
  def chatbot_response(message, session_id="default"):
14
- """Core function that handles both chat and emotion analysis"""
15
  if session_id not in chat_histories:
16
  chat_histories[session_id] = []
17
-
18
- # Generate chatbot response
19
  input_ids = tokenizer.encode(message + tokenizer.eos_token, return_tensors="pt")
20
  output = model.generate(input_ids, max_length=200, pad_token_id=tokenizer.eos_token_id)
21
  response = tokenizer.decode(output[:, input_ids.shape[-1]:][0], skip_special_tokens=True)
22
-
23
  # Detect emotion
24
  emotion_result = emotion_pipeline(message)
25
  emotion = emotion_result[0]["label"]
26
  score = float(emotion_result[0]["score"])
27
-
28
  # Store history
29
  chat_histories[session_id].append((message, response))
30
  return response, emotion, score
31
 
32
- # ------------------ API Interface ------------------
33
- def api_predict(message: str, session_id: str = "default"):
34
- """Endpoint for /predict that returns JSON"""
35
- response, emotion, score = chatbot_response(message, session_id)
36
- return {
37
- "response": response,
38
- "emotion": emotion,
39
- "score": score,
40
- "session_id": session_id
41
- }
42
-
43
- # ------------------ Web Interface ------------------
44
- with gr.Blocks(title="Mental Health Chatbot") as web_interface:
45
  gr.Markdown("# 🤖 Mental Health Chatbot")
46
-
47
  with gr.Row():
48
- with gr.Column():
49
- chatbot = gr.Chatbot(height=400)
50
- msg = gr.Textbox(placeholder="Type your message...", label="You")
51
- with gr.Row():
52
- session_id = gr.Textbox(label="Session ID", value="default")
53
- submit_btn = gr.Button("Send", variant="primary")
54
- clear_btn = gr.Button("Clear")
55
-
56
- with gr.Column():
57
- emotion_out = gr.Textbox(label="Detected Emotion")
58
- score_out = gr.Number(label="Confidence Score")
59
 
60
- def respond(message, chat_history, session_id):
61
- response, emotion, score = chatbot_response(message, session_id)
62
- chat_history.append((message, response))
63
- return "", chat_history, emotion, score
 
 
 
 
 
64
 
65
- submit_btn.click(
66
- respond,
67
- [msg, chatbot, session_id],
68
- [msg, chatbot, emotion_out, score_out]
69
- )
70
- msg.submit(
71
- respond,
72
- [msg, chatbot, session_id],
73
- [msg, chatbot, emotion_out, score_out]
74
- )
75
- clear_btn.click(
76
- lambda s_id: ([], "", 0.0) if s_id in chat_histories else ([], "", 0.0),
77
- [session_id],
78
- [chatbot, emotion_out, score_out]
79
- )
80
 
81
- # ------------------ Mount Interfaces ------------------
82
- app = gr.mount_gradio_app(
83
- gr.routes.App(),
84
- web_interface,
85
- path="/"
86
- )
87
 
88
- app = gr.mount_gradio_app(
89
- app,
90
- gr.Interface(
91
- fn=api_predict,
92
- inputs=[gr.Textbox(), gr.Textbox()],
93
- outputs=gr.JSON(),
94
- title="API Predict",
95
- description="Use this endpoint for programmatic access"
96
- ),
97
- path="/predict"
98
- )
99
 
100
- # ------------------ Launch ------------------
101
  if __name__ == "__main__":
102
- app.launch(show_api=False) # We manually mounted our API
 
1
  import gradio as gr
2
  from transformers import pipeline, AutoModelForCausalLM, AutoTokenizer
3
+ import json
4
 
5
  # Load models
6
  chatbot_model = "microsoft/DialoGPT-medium"
 
 
 
 
 
 
 
7
  def chatbot_response(message, session_id="default"):
 
8
  if session_id not in chat_histories:
9
  chat_histories[session_id] = []
10
+
11
+ # Generate response
12
  input_ids = tokenizer.encode(message + tokenizer.eos_token, return_tensors="pt")
13
  output = model.generate(input_ids, max_length=200, pad_token_id=tokenizer.eos_token_id)
14
  response = tokenizer.decode(output[:, input_ids.shape[-1]:][0], skip_special_tokens=True)
15
+
16
  # Detect emotion
17
  emotion_result = emotion_pipeline(message)
18
  emotion = emotion_result[0]["label"]
19
  score = float(emotion_result[0]["score"])
20
+
21
  # Store history
22
  chat_histories[session_id].append((message, response))
23
  return response, emotion, score
24
 
25
+ # Gradio Interface (Primary for Spaces)
26
+ with gr.Blocks() as demo:
 
 
 
 
 
 
 
 
 
 
 
27
  gr.Markdown("# 🤖 Mental Health Chatbot")
 
28
  with gr.Row():
 
 
 
 
 
 
 
 
 
 
 
29
 
30
+ btn.click(respond, [msg, chatbot, session_id], [msg, chatbot, emotion_out, score_out])
31
+ msg.submit(respond, [msg, chatbot, session_id], [msg, chatbot, emotion_out, score_out])
32
+ clear_btn.click(lambda s_id: ([], "", 0.0) if s_id in chat_histories else ([], "", 0.0),
33
+ inputs=[session_id],
34
+ outputs=[chatbot, emotion_out, score_out])
35
+
36
+
37
+
38
+
39
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
40
 
 
 
 
 
 
 
41
 
 
 
 
 
 
 
 
 
 
 
 
42
 
43
+ # For Hugging Face Spaces, Gradio must be the main interface
44
  if __name__ == "__main__":
45
+ demo.launch()