File size: 5,176 Bytes
db96ac6
eb3c302
c338f24
c50e236
69847f4
926730e
69847f4
926730e
 
c031cee
81ecad1
c338f24
fbc6ce1
 
 
f01f657
fbc6ce1
 
926730e
c50e236
 
 
 
476a74f
c50e236
c0f152a
 
 
 
476a74f
 
 
 
 
 
 
 
 
 
 
 
 
 
fbc6ce1
476a74f
 
 
 
041821c
 
f383954
 
33361c4
f383954
33361c4
f383954
 
 
33361c4
 
 
f383954
c0f152a
 
 
3d77054
 
 
 
 
 
 
 
 
 
c0f152a
 
 
3d77054
c0f152a
926730e
476a74f
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
926730e
 
 
 
 
 
 
2deac23
21c4801
56c8a54
926730e
ee542af
926730e
2deac23
 
c031cee
926730e
 
 
2deac23
926730e
 
c50e236
 
 
 
 
 
 
 
 
 
 
 
cc6b7b4
c50e236
 
 
 
926730e
2deac23
21c4801
89f7adc
21c4801
926730e
 
c338f24
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
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
from flask import Flask, request, jsonify
import hmac, hashlib, secrets, time, os
from openai import OpenAI
from datetime import datetime, timedelta
import logging

logging.basicConfig(level=logging.INFO)
app = Flask(__name__)

# 🔑 Secret key for API authentication
SECRET_KEY = os.getenv("SECRET_KEY")
GITHUB_TOKEN = os.getenv("GITHUB_TOKEN")
SPECIAL_API_KEY = os.getenv("SPECIAL_API_KEY")
ENDPOINT = os.getenv("ENDPOINT")
SYSTEM_PROMPT = os.getenv("SYSTEM_PROMPT")
print(SYSTEM_PROMPT)

client = OpenAI(base_url=ENDPOINT,api_key=GITHUB_TOKEN)

# Track API statistics
api_usage = {}  # Stores {api_key: {"count": X, "reset_time": timestamp}}

# ✅ Request Limit Configuration
REQUEST_LIMIT = 10 # Max requests per day

# Track API statistics
request_count = 0
start_time = time.time()

# 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

def generate_response(query:str) -> str:
    try:
        model_name = "gpt-4o"
        response = client.chat.completions.create(
        messages=[{"role": "system","content": SYSTEM_PROMPT},{"role": "user","content": query}],temperature=0.7,max_tokens=4096,top_p=0.9,model=model_name,stream=False)
        return response.choices[0].message.content
    except:
        return "API Server is under maintenance. Please Try After Some Time Thank You for using TrueSyncAI Chat API. Have a great day."

@app.route('/')
def home():
    return """
    <html>
    <head>
        <title>TrueSyncAI</title>
    </head>
    <body style="text-align: center;">
        <h1>Welcome to TrueSyncAI</h1>
        <img src="https://huggingface.co/spaces/sujalrajpoot/truesyncai/resolve/main/TrueSyncAI.jpg" alt="TrueSyncAI Logo" width="500">
    </body>
    </html>
    """

@app.route('/status', methods=['GET'])
def status():
    global request_count
    uptime_seconds = int(time.time() - start_time)

    # Convert uptime to days, hours, minutes, and seconds
    days = uptime_seconds // 86400
    hours = (uptime_seconds % 86400) // 3600
    minutes = (uptime_seconds % 3600) // 60
    seconds = uptime_seconds % 60

    uptime_str = f"{days} days, {hours} hours, {minutes} minutes and {seconds} seconds"

    return jsonify({
        "status": "API is running",
        "total_requests": request_count,
        "uptime": uptime_str
    })

@app.route("/usage", methods=["GET"])
def usage():
    api_key = request.args.get("api_key")

    if not api_key or not validate_api_key(api_key):
        return jsonify({"error": "Invalid API Key"}), 401
    
    # Get usage data or return default values
    now = datetime.utcnow()
    user_data = api_usage.get(api_key, {"count": 0, "reset_time": now + timedelta(days=1)})
    
    remaining_requests = max(0, REQUEST_LIMIT - user_data["count"])
    reset_time = user_data["reset_time"].strftime("%Y-%m-%d %H:%M:%S UTC")

    return jsonify({
        "api_key": api_key,
        "requests_used": user_data["count"],
        "remaining_requests": remaining_requests,
        "reset_time": reset_time
    })

# 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}"
    return jsonify({"api_key": api_key})
    
# Chat Endpoint
@app.route("/v1/chat/completions", methods=["POST"])
def chat():
    global request_count
    data = request.json
    api_key = data.get("api_key")
    message = data.get("message", "").strip()
    logging.info(f"Request received: {data}")
    
    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
        
        # ✅ Apply Limit to the Specific API Key
    if api_key == SPECIAL_API_KEY:
        now = datetime.utcnow()
        user_data = api_usage.get(api_key, {"count": 0, "reset_time": now + timedelta(days=1)})
        
        # Reset count if the reset time has passed
        if now >= user_data["reset_time"]:
            user_data = {"count": 0, "reset_time": now + timedelta(days=1)}
        
        # Block requests if limit exceeded
        if user_data["count"] >= REQUEST_LIMIT:
            return jsonify({"error": "Request limit reached. This is a testing API key for developers. The limit resets daily. Please wait or use a different key."}), 429
        
        # Increase request count
        user_data["count"] += 1
        api_usage[api_key] = user_data  # Update storage
    
    # Basic AI response (Can integrate LLMs here)
    response = generate_response(message)
    request_count += 1
    return jsonify({"response": response})

if __name__ == "__main__":
    app.run(host="0.0.0.0", port=7860)  # Hugging Face Spaces default port