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

Update app.py

Browse files
Files changed (1) hide show
  1. app.py +37 -42
app.py CHANGED
@@ -1,45 +1,40 @@
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()
 
1
  import gradio as gr
2
+ import requests
3
+
4
+ # Define the sentiment analysis function that communicates with the Hugging Face model API
5
+ def analyze_sentiment(message: str):
6
+ try:
7
+ # Send request to the Hugging Face Space for sentiment analysis
8
+ response = requests.post(
9
+ 'https://safwansajad-emotion-detection-gpt.hf.space/predict',
10
+ json={'text': message},
11
+ headers={'Content-Type': 'application/json'}
12
+ )
13
+
14
+ # Extract the sentiment and score from the response
15
+ data = response.json()
16
+
17
+ # Return the label and score in the format expected by your app
18
+ if 'emotion' in data and 'score' in data:
19
+ return [{"label": data['emotion'], "score": data['score']}]
20
+ else:
21
+ return [{"label": "Unknown", "score": 0}]
22
 
23
+ except Exception as e:
24
+ print(f"Error during sentiment analysis: {e}")
25
+ return [{"label": "Error", "score": 0}]
26
+
27
+ # Set up Gradio interface
28
+ iface = gr.Interface(
29
+ fn=analyze_sentiment, # Function to be called
30
+ inputs=gr.Textbox(label="Enter your message", placeholder="How are you feeling today?", lines=2), # User input
31
+ outputs=gr.JSON(), # Output in JSON format (label and score)
32
+ live=True, # Enables live input processing
33
+ title="Sentiment Analysis with SerenityAI", # Title of the interface
34
+ description="Enter a message and get feedback about your emotional state. Your feelings matter!",
35
+ theme="huggingface", # Optionally set the theme to Hugging Face's style
36
+ )
37
+
38
+ # Launch the Gradio app
 
 
 
 
 
 
 
 
 
 
 
 
39
  if __name__ == "__main__":
40
+ iface.launch(share=True) # share=True gives you a public link