truesyncai / app.py
sujalrajpoot's picture
Create app.py
926730e verified
raw
history blame
1.77 kB
from flask import Flask, request, jsonify
import hmac, hashlib, secrets, time
app = Flask(__name__)
# 🔑 Secret key for API authentication (Load from environment in production)
SECRET_KEY = "MySuperSecretKey_TrueSyncAI"
# Store API keys temporarily (use a database for real applications)
API_KEYS = {}
# Generate API Key
@app.route("/generate_api_key", methods=["POST"])
def generate_api_key():
random_part = secrets.token_hex(16)
signature = hmac.new(SECRET_KEY.encode(), random_part.encode(), hashlib.sha256).hexdigest()[:16]
api_key = f"TrueSyncAI-{random_part}-{signature}"
# Store the key with a timestamp
API_KEYS[api_key] = time.time()
return jsonify({"api_key": api_key})
# Validate API Key
def validate_api_key(api_key):
parts = api_key.split("-")
if len(parts) != 3 or parts[0] != "TrueSyncAI":
return False
random_part, received_signature = parts[1], parts[2]
expected_signature = hmac.new(SECRET_KEY.encode(), random_part.encode(), hashlib.sha256).hexdigest()[:16]
return expected_signature == received_signature and api_key in API_KEYS
# Chat Endpoint
@app.route("/chat", methods=["POST"])
def chat():
data = request.json
api_key = data.get("api_key")
message = data.get("message", "").strip()
if not api_key or not validate_api_key(api_key):
return jsonify({"error": "Invalid API Key"}), 401
if not message:
return jsonify({"error": "Message cannot be empty"}), 400
# Basic AI response (Can integrate LLMs here)
response = f"TrueSyncAI: You said '{message}', but I'm still learning!"
return jsonify({"response": response})
if __name__ == "__main__":
app.run(host="0.0.0.0", port=7860) # Hugging Face Spaces default port