transcript / app.py
CORVO-AI's picture
Update app.py
98e48e0 verified
raw
history blame
2.69 kB
import requests
from flask import Flask, request, jsonify
from datetime import datetime
app = Flask(__name__)
# Your PythonAnywhere API endpoint
PYTHONANYWHERE_URL = "https://omarnuwara.pythonanywhere.com/get-response"
# URL of GitHub-hosted user database
USER_DB_URL = "https://raw.githubusercontent.com/omarnuwrar/api/refs/heads/main/user.json"
def get_users_from_db():
"""Fetch user data from the GitHub JSON file."""
response = requests.get(USER_DB_URL)
if response.status_code == 200:
return response.json()
else:
raise Exception("Failed to fetch the user database.")
def validate_token(token):
"""Validate the provided token."""
users = get_users_from_db()
for user in users:
if user["token"] == token:
expiration_time = datetime.fromisoformat(user["token_expiration_time"])
if datetime.now() < expiration_time:
return True, None # Token is valid, no error message
else:
return False, "Token has expired."
return False, "Token not found."
@app.route('/chat', methods=['POST'])
def chat():
try:
# Ensure the request contains JSON with "message" and "token" keys
if not request.is_json:
return jsonify({"error": "Request must be in JSON format."}), 400
user_input = request.json.get("message", "")
token = request.json.get("token", "")
if not user_input:
return jsonify({"error": "No message provided in the request."}), 400
if not token:
return jsonify({"error": "No token provided in the request."}), 400
# Validate token
token_valid, token_message = validate_token(token)
if not token_valid:
return jsonify({"error": "Invalid token.", "details": token_message}), 401
# Forward the message to the PythonAnywhere endpoint
data = {"message": [{"role": "user", "content": user_input}]}
response = requests.post(PYTHONANYWHERE_URL, json=data)
if response.status_code == 200:
response_json = response.json()
ai_response = response_json.get("response", "No 'response' key found in the JSON.")
ai_response = ai_response.encode('latin1').decode('utf-8', 'ignore')
return jsonify({"response": ai_response})
else:
return jsonify({
"error": "Error from PythonAnywhere",
"details": response.text
}), response.status_code
except Exception as e:
return jsonify({"error": "An error occurred", "details": str(e)}), 500
if __name__ == "__main__":
app.run(host="0.0.0.0", port=7860)