Test1 / app.py
Kakitsu's picture
Create app.py
06aca98 verified
# 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)