File size: 2,241 Bytes
06aca98
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
# app.py
from flask import Flask, jsonify, request
import requests
import os  # Ensure os module is imported to access environment variables

# Initialize Flask application
app = Flask(__name__)

# Define the Hugging Face model URL and API token from environment variable
model_name = "tanusrich/Mental_Health_Chatbot"
api_url = f"https://api-inference.huggingface.co/models/{model_name}"

# Get the Hugging Face API token from environment variables
api_token = os.getenv("HF_API_TOKEN")  # 'HF_API_TOKEN' is the environment variable name

# Check if the API token is available
if api_token is None:
    raise ValueError("Hugging Face API token is not set in the environment variables.")

# Set up headers for authentication
headers = {
    "Authorization": f"Bearer {api_token}",
    "Content-Type": "application/json"
}

# Function to call the Hugging Face API for multiple inputs (batch processing)
def chat_with_model(input_texts):
    # Prepare the payload (multiple inputs in batch)
    payload = {
        "inputs": input_texts,
        "parameters": {
            "max_length": 50  # Reduce the maximum length to 50 tokens
        }
    }

    # Send a POST request to the Hugging Face API
    response = requests.post(api_url, headers=headers, json=payload)

    # Check if the response is successful
    if response.status_code == 200:
        # Parse the response and return the generated text for each input
        return [resp['generated_text'] for resp in response.json()]
    else:
        # If there's an error, return the error message
        return f"Error: {response.status_code}, {response.text}"

@app.route('/')
def home():
    return jsonify({"message": "Welcome to the Mental Health Therapy Chatbot!"})

@app.route('/chat', methods=['POST'])
def chat():
    data = request.get_json()  # Get the input from the POST request
    user_inputs = data.get('inputs')  # Get user inputs from the data (list of strings)

    if user_inputs:
        # Call the chatbot function with the batch of inputs
        responses = chat_with_model(user_inputs)
        return jsonify({"responses": responses})
    else:
        return jsonify({"error": "No inputs provided."}), 400

if __name__ == '__main__':
    app.run(debug=False)