Spaces:
Running
Running
Create app.py
Browse files
app.py
ADDED
@@ -0,0 +1,51 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
1 |
+
from flask import Flask, request, jsonify
|
2 |
+
import hmac, hashlib, secrets, time
|
3 |
+
|
4 |
+
app = Flask(__name__)
|
5 |
+
|
6 |
+
# 🔑 Secret key for API authentication (Load from environment in production)
|
7 |
+
SECRET_KEY = "MySuperSecretKey_TrueSyncAI"
|
8 |
+
|
9 |
+
# Store API keys temporarily (use a database for real applications)
|
10 |
+
API_KEYS = {}
|
11 |
+
|
12 |
+
# Generate API Key
|
13 |
+
@app.route("/generate_api_key", methods=["POST"])
|
14 |
+
def generate_api_key():
|
15 |
+
random_part = secrets.token_hex(16)
|
16 |
+
signature = hmac.new(SECRET_KEY.encode(), random_part.encode(), hashlib.sha256).hexdigest()[:16]
|
17 |
+
api_key = f"TrueSyncAI-{random_part}-{signature}"
|
18 |
+
|
19 |
+
# Store the key with a timestamp
|
20 |
+
API_KEYS[api_key] = time.time()
|
21 |
+
return jsonify({"api_key": api_key})
|
22 |
+
|
23 |
+
# Validate API Key
|
24 |
+
def validate_api_key(api_key):
|
25 |
+
parts = api_key.split("-")
|
26 |
+
if len(parts) != 3 or parts[0] != "TrueSyncAI":
|
27 |
+
return False
|
28 |
+
|
29 |
+
random_part, received_signature = parts[1], parts[2]
|
30 |
+
expected_signature = hmac.new(SECRET_KEY.encode(), random_part.encode(), hashlib.sha256).hexdigest()[:16]
|
31 |
+
return expected_signature == received_signature and api_key in API_KEYS
|
32 |
+
|
33 |
+
# Chat Endpoint
|
34 |
+
@app.route("/chat", methods=["POST"])
|
35 |
+
def chat():
|
36 |
+
data = request.json
|
37 |
+
api_key = data.get("api_key")
|
38 |
+
message = data.get("message", "").strip()
|
39 |
+
|
40 |
+
if not api_key or not validate_api_key(api_key):
|
41 |
+
return jsonify({"error": "Invalid API Key"}), 401
|
42 |
+
|
43 |
+
if not message:
|
44 |
+
return jsonify({"error": "Message cannot be empty"}), 400
|
45 |
+
|
46 |
+
# Basic AI response (Can integrate LLMs here)
|
47 |
+
response = f"TrueSyncAI: You said '{message}', but I'm still learning!"
|
48 |
+
return jsonify({"response": response})
|
49 |
+
|
50 |
+
if __name__ == "__main__":
|
51 |
+
app.run(host="0.0.0.0", port=7860) # Hugging Face Spaces default port
|