CORVO-AI commited on
Commit
dc76955
·
verified ·
1 Parent(s): 678d88b

Update app.py

Browse files
Files changed (1) hide show
  1. app.py +19 -33
app.py CHANGED
@@ -1,48 +1,39 @@
1
  import requests
2
  from flask import Flask, request, jsonify
3
  from datetime import datetime
4
- import json
5
 
6
  app = Flask(__name__)
7
 
8
  # Your PythonAnywhere API endpoint
9
  PYTHONANYWHERE_URL = "https://omarnuwara.pythonanywhere.com/get-response"
10
 
11
- # URL of the GitHub-hosted JSON database
12
  USER_DB_URL = "https://raw.githubusercontent.com/omarnuwrar/api/refs/heads/main/user.json"
13
 
14
  def get_users_from_db():
15
  """Fetch user data from the GitHub JSON file."""
16
- try:
17
- response = requests.get(USER_DB_URL)
18
- if response.status_code == 200:
19
- return response.json()
20
- else:
21
- raise Exception("Failed to fetch the user database.")
22
- except Exception as e:
23
- raise Exception(f"Error fetching user database: {str(e)}")
24
 
25
  def validate_token(token):
26
- """Validate the token from the GitHub-hosted database."""
27
- try:
28
- users = get_users_from_db()
29
- # Look for the token in the database
30
- for user in users:
31
- if user["token"] == token:
32
- # Check if the token is expired
33
- expiration_time = datetime.fromisoformat(user["token_expiration_time"])
34
- if datetime.now() < expiration_time:
35
- return True, None # Token is valid
36
- else:
37
- return False, "Token is expired."
38
- return False, "Token not found." # Token not found in the database
39
- except Exception as e:
40
- return False, f"Error validating token: {str(e)}"
41
 
42
  @app.route('/chat', methods=['POST'])
43
  def chat():
44
  try:
45
- # Ensure the request contains JSON and a "message" and "token" key
46
  if not request.is_json:
47
  return jsonify({"error": "Request must be in JSON format."}), 400
48
 
@@ -55,31 +46,26 @@ def chat():
55
  if not token:
56
  return jsonify({"error": "No token provided in the request."}), 400
57
 
58
- # Validate the token
59
  token_valid, token_message = validate_token(token)
60
  if not token_valid:
61
  return jsonify({"error": "Invalid token.", "details": token_message}), 401
62
 
63
- # Create the payload to send to PythonAnywhere
64
  data = {"message": user_input}
65
-
66
- # Forward the request to PythonAnywhere
67
  response = requests.post(PYTHONANYWHERE_URL, json=data)
68
 
69
  if response.status_code == 200:
70
  response_json = response.json()
71
  ai_response = response_json.get("response", "No 'response' key found in the JSON.")
72
- ai_response = ai_response.encode('latin1').decode('utf-8', 'ignore')
73
  return jsonify({"response": ai_response})
74
  else:
75
- # Handle errors from PythonAnywhere
76
  return jsonify({
77
  "error": "Error from PythonAnywhere",
78
  "details": response.text
79
  }), response.status_code
80
 
81
  except Exception as e:
82
- # Catch any unexpected errors
83
  return jsonify({"error": "An error occurred", "details": str(e)}), 500
84
 
85
  if __name__ == "__main__":
 
1
  import requests
2
  from flask import Flask, request, jsonify
3
  from datetime import datetime
 
4
 
5
  app = Flask(__name__)
6
 
7
  # Your PythonAnywhere API endpoint
8
  PYTHONANYWHERE_URL = "https://omarnuwara.pythonanywhere.com/get-response"
9
 
10
+ # URL of GitHub-hosted user database
11
  USER_DB_URL = "https://raw.githubusercontent.com/omarnuwrar/api/refs/heads/main/user.json"
12
 
13
  def get_users_from_db():
14
  """Fetch user data from the GitHub JSON file."""
15
+ response = requests.get(USER_DB_URL)
16
+ if response.status_code == 200:
17
+ return response.json()
18
+ else:
19
+ raise Exception("Failed to fetch the user database.")
 
 
 
20
 
21
  def validate_token(token):
22
+ """Validate the provided token."""
23
+ users = get_users_from_db()
24
+ for user in users:
25
+ if user["token"] == token:
26
+ expiration_time = datetime.fromisoformat(user["token_expiration_time"])
27
+ if datetime.now() < expiration_time:
28
+ return True
29
+ else:
30
+ return False, "Token has expired."
31
+ return False, "Token not found."
 
 
 
 
 
32
 
33
  @app.route('/chat', methods=['POST'])
34
  def chat():
35
  try:
36
+ # Ensure the request contains JSON with "message" and "token" keys
37
  if not request.is_json:
38
  return jsonify({"error": "Request must be in JSON format."}), 400
39
 
 
46
  if not token:
47
  return jsonify({"error": "No token provided in the request."}), 400
48
 
49
+ # Validate token
50
  token_valid, token_message = validate_token(token)
51
  if not token_valid:
52
  return jsonify({"error": "Invalid token.", "details": token_message}), 401
53
 
54
+ # Forward the message to the PythonAnywhere endpoint
55
  data = {"message": user_input}
 
 
56
  response = requests.post(PYTHONANYWHERE_URL, json=data)
57
 
58
  if response.status_code == 200:
59
  response_json = response.json()
60
  ai_response = response_json.get("response", "No 'response' key found in the JSON.")
 
61
  return jsonify({"response": ai_response})
62
  else:
 
63
  return jsonify({
64
  "error": "Error from PythonAnywhere",
65
  "details": response.text
66
  }), response.status_code
67
 
68
  except Exception as e:
 
69
  return jsonify({"error": "An error occurred", "details": str(e)}), 500
70
 
71
  if __name__ == "__main__":