Kakitsu commited on
Commit
06aca98
·
verified ·
1 Parent(s): a65a99f

Create app.py

Browse files
Files changed (1) hide show
  1. app.py +64 -0
app.py ADDED
@@ -0,0 +1,64 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # app.py
2
+ from flask import Flask, jsonify, request
3
+ import requests
4
+ import os # Ensure os module is imported to access environment variables
5
+
6
+ # Initialize Flask application
7
+ app = Flask(__name__)
8
+
9
+ # Define the Hugging Face model URL and API token from environment variable
10
+ model_name = "tanusrich/Mental_Health_Chatbot"
11
+ api_url = f"https://api-inference.huggingface.co/models/{model_name}"
12
+
13
+ # Get the Hugging Face API token from environment variables
14
+ api_token = os.getenv("HF_API_TOKEN") # 'HF_API_TOKEN' is the environment variable name
15
+
16
+ # Check if the API token is available
17
+ if api_token is None:
18
+ raise ValueError("Hugging Face API token is not set in the environment variables.")
19
+
20
+ # Set up headers for authentication
21
+ headers = {
22
+ "Authorization": f"Bearer {api_token}",
23
+ "Content-Type": "application/json"
24
+ }
25
+
26
+ # Function to call the Hugging Face API for multiple inputs (batch processing)
27
+ def chat_with_model(input_texts):
28
+ # Prepare the payload (multiple inputs in batch)
29
+ payload = {
30
+ "inputs": input_texts,
31
+ "parameters": {
32
+ "max_length": 50 # Reduce the maximum length to 50 tokens
33
+ }
34
+ }
35
+
36
+ # Send a POST request to the Hugging Face API
37
+ response = requests.post(api_url, headers=headers, json=payload)
38
+
39
+ # Check if the response is successful
40
+ if response.status_code == 200:
41
+ # Parse the response and return the generated text for each input
42
+ return [resp['generated_text'] for resp in response.json()]
43
+ else:
44
+ # If there's an error, return the error message
45
+ return f"Error: {response.status_code}, {response.text}"
46
+
47
+ @app.route('/')
48
+ def home():
49
+ return jsonify({"message": "Welcome to the Mental Health Therapy Chatbot!"})
50
+
51
+ @app.route('/chat', methods=['POST'])
52
+ def chat():
53
+ data = request.get_json() # Get the input from the POST request
54
+ user_inputs = data.get('inputs') # Get user inputs from the data (list of strings)
55
+
56
+ if user_inputs:
57
+ # Call the chatbot function with the batch of inputs
58
+ responses = chat_with_model(user_inputs)
59
+ return jsonify({"responses": responses})
60
+ else:
61
+ return jsonify({"error": "No inputs provided."}), 400
62
+
63
+ if __name__ == '__main__':
64
+ app.run(debug=False)