einfy commited on
Commit
2b2e813
1 Parent(s): 456d67b

Create app.py

Browse files
Files changed (1) hide show
  1. app.py +62 -0
app.py ADDED
@@ -0,0 +1,62 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ import gradio as gr
2
+
3
+ def chat(user_input, history=[]):
4
+ """
5
+ Chat function that takes user input and conversation history,
6
+ returns the model response and updates the history. Handles potential
7
+ memory issues by clearing conversation history after a certain length.
8
+
9
+ Args:
10
+ user_input: String containing the user's message.
11
+ history: List of tuples containing conversation history
12
+ (user_message, model_response).
13
+
14
+ Returns:
15
+ A tuple containing the model response and updated history (limited length).
16
+ """
17
+ # Update history with user input
18
+ history.append((user_input, None))
19
+
20
+ # Clear conversation history if it exceeds a certain length (adjust as needed)
21
+ if len(history) > 10:
22
+ history = history[-5:] # Keep the most recent 5 interactions
23
+
24
+ # Access the loaded model (replace with appropriate error handling)
25
+ model = gr.get("chatbot_model")
26
+
27
+ # Generate response using the model (consider error handling and retries)
28
+ response = model(user_input, max_length=50, do_sample=True)[0]['generated_text']
29
+
30
+ # Update history with model response
31
+ history.append((None, response))
32
+
33
+ return response, history
34
+
35
+ # Attempt to load the model from Hugging Face (consider error handling)
36
+ try:
37
+ chatbot_model = gr.load("models/lucas-w/mental-health-chatbot-3")
38
+ except Exception as e:
39
+ print(f"Error loading model: {e}")
40
+ chatbot_model = None # Handle the case where model loading fails
41
+
42
+ # Launch the Gradio interface with error handling
43
+ if chatbot_model is not None:
44
+ interface = gr.Interface(
45
+ fn=chat,
46
+ inputs="textbox",
47
+ outputs="textbox",
48
+ interpretation="chat",
49
+ title="Mental Health Chatbot",
50
+ description="Talk to a mental health assistant",
51
+ elem_id="chat-container",
52
+ css="""
53
+ #chat-container {
54
+ height: 400px;
55
+ overflow-y: scroll;
56
+ }
57
+ """
58
+ )
59
+
60
+ interface.launch()
61
+ else:
62
+ print("Failed to launch chatbot. Please check model availability and error messages.")