Spaces:
Sleeping
Sleeping
Update app.py
Browse files
app.py
CHANGED
|
@@ -1,158 +1,54 @@
|
|
| 1 |
-
import requests
|
| 2 |
from flask import Flask, request, jsonify
|
| 3 |
-
|
| 4 |
import json
|
| 5 |
|
| 6 |
app = Flask(__name__)
|
| 7 |
-
# URLs
|
| 8 |
-
SEPTIMIUS_JSON_URL = "https://corvo-ai-septimius.hf.space/read_Septimius_json"
|
| 9 |
-
|
| 10 |
-
# Brain Inc API Details
|
| 11 |
-
BRAININC_API_URL = "https://api.braininc.net/stream/bas-demo-v4/nlp/completions_generation"
|
| 12 |
-
BRAININC_API_TOKEN = "token 72ec00483379076f580eb8126f29da802a5140c3" # Replace if needed
|
| 13 |
-
|
| 14 |
-
def is_token_valid(token):
|
| 15 |
-
"""
|
| 16 |
-
Check if the token is valid and not expired by reading from Septimius.json.
|
| 17 |
-
"""
|
| 18 |
-
try:
|
| 19 |
-
# Fetch the current Septimius.json data
|
| 20 |
-
response = requests.get(SEPTIMIUS_JSON_URL)
|
| 21 |
-
if response.status_code == 200:
|
| 22 |
-
json_data = response.json()
|
| 23 |
-
|
| 24 |
-
if json_data.get("success"):
|
| 25 |
-
# Check if the token exists and is not expired
|
| 26 |
-
for entry in json_data["data"]:
|
| 27 |
-
if entry.get("token") == token:
|
| 28 |
-
# Parse the expiration date and compare it with the current date
|
| 29 |
-
expired_date = entry.get("expired_date")
|
| 30 |
-
if expired_date and datetime.fromisoformat(expired_date) > datetime.now():
|
| 31 |
-
return True # Token is valid
|
| 32 |
-
else:
|
| 33 |
-
return False # Token is expired
|
| 34 |
-
|
| 35 |
-
return False # Token not found
|
| 36 |
-
else:
|
| 37 |
-
print(f"Error fetching Septimius.json (Status Code: {response.status_code})")
|
| 38 |
-
return False
|
| 39 |
-
except requests.exceptions.RequestException as e:
|
| 40 |
-
print(f"Error connecting to Septimius API: {e}")
|
| 41 |
-
return False
|
| 42 |
-
|
| 43 |
-
|
| 44 |
-
def generate_ai_response(message):
|
| 45 |
-
"""
|
| 46 |
-
Generate AI response using Brain Inc API.
|
| 47 |
-
"""
|
| 48 |
-
headers = {
|
| 49 |
-
"Authorization": f"{BRAININC_API_TOKEN}",
|
| 50 |
-
"Content-Type": "application/json;charset=UTF-8",
|
| 51 |
-
}
|
| 52 |
-
|
| 53 |
-
payload = {
|
| 54 |
-
"identifier_type": "object_id",
|
| 55 |
-
"identifier_value": "4775260",
|
| 56 |
-
"pubsub_topic": "/studios/516104/wsuid_4647155_new-edge-112_nodeid_editor-111/textGenStream/1722445975926",
|
| 57 |
-
"stream": True,
|
| 58 |
-
"variables": {
|
| 59 |
-
"Input": f"you are AI Model (ALEX-9) Created By Libyan Team\n\nBoss : MR Omar Nuwara\n\nyour task is chat with user and help him in many tasks and NOTE: you are not from open ai you are from Libyan Team and your name (ALEX-9)\n\nNow Here the chat:{message}",
|
| 60 |
-
"User Input":f"you are AI Model (ALEX-9) Created By Libyan Team\n\nBoss : MR Omar Nuwara\n\nyour task is chat with user and help him in many tasks and NOTE: you are not from open ai you are from Libyan Team and your name (ALEX-9)\n\nNow Here the chat:{message}",
|
| 61 |
-
"input":f"you are AI Model (ALEX-9) Created By Libyan Team\n\nBoss : MR Omar Nuwara\n\nyour task is chat with user and help him in many tasks and NOTE: you are not from open ai you are from Libyan Team and your name (ALEX-9)\n\nNow Here the chat:{message}",
|
| 62 |
-
}
|
| 63 |
-
}
|
| 64 |
-
|
| 65 |
-
|
| 66 |
-
try:
|
| 67 |
-
response = requests.post(BRAININC_API_URL, headers=headers, json=payload)
|
| 68 |
-
combined_content = ""
|
| 69 |
-
|
| 70 |
-
for line in response.text.splitlines():
|
| 71 |
-
if line.startswith('data: '):
|
| 72 |
-
json_data = line[6:].strip()
|
| 73 |
-
try:
|
| 74 |
-
data = json.loads(json_data)
|
| 75 |
-
delta_content = data.get('choices')[0].get('delta').get('content', '')
|
| 76 |
-
combined_content += delta_content
|
| 77 |
-
except json.JSONDecodeError:
|
| 78 |
-
continue
|
| 79 |
-
|
| 80 |
-
return combined_content
|
| 81 |
-
except requests.exceptions.RequestException as e:
|
| 82 |
-
print(f"Error connecting to Brain Inc API: {e}")
|
| 83 |
-
return "Error generating response"
|
| 84 |
-
|
| 85 |
-
|
| 86 |
-
@app.route('/chat', methods=['POST'])
|
| 87 |
-
def chat():
|
| 88 |
-
try:
|
| 89 |
-
# Ensure the request contains JSON and the required keys
|
| 90 |
-
request_data = request.json if request.is_json else None
|
| 91 |
-
token = request_data.get("token") if request_data else None
|
| 92 |
-
message = request_data.get("message") if request_data else None
|
| 93 |
-
|
| 94 |
-
# Error Handling for Missing Parameters
|
| 95 |
-
if not token:
|
| 96 |
-
return jsonify({"error": "Token Not Provided", "details": "Please provide a valid token in the request body."}), 400
|
| 97 |
-
if not message:
|
| 98 |
-
return jsonify({"error": "Message Not Provided", "details": "Please provide a message in the request body."}), 400
|
| 99 |
-
|
| 100 |
-
# Check if the token is valid
|
| 101 |
-
if not is_token_valid(token):
|
| 102 |
-
# Enhanced Error Response for Token Validation
|
| 103 |
-
if token_expired(token):
|
| 104 |
-
return jsonify({"error": "Token Expired", "details": "Your token has expired. Please renew your subscription to continue."}), 403
|
| 105 |
-
elif token_not_found(token):
|
| 106 |
-
return jsonify({"error": "Token Not Found", "details": "The provided token does not exist. Please check your token or subscribe to the service."}), 403
|
| 107 |
-
else:
|
| 108 |
-
return jsonify({"error": "Invalid Token", "details": "The provided token is invalid. Please check your token or contact support."}), 403
|
| 109 |
-
|
| 110 |
-
# Generate AI response using Brain Inc API
|
| 111 |
-
ai_response = generate_ai_response(message)
|
| 112 |
-
if ai_response == "Error generating response":
|
| 113 |
-
return jsonify({"error": "AI Response Generation Failed", "details": "Failed to generate a response from the AI service. Please try again later."}), 500
|
| 114 |
-
else:
|
| 115 |
-
return jsonify({"response": ai_response})
|
| 116 |
-
|
| 117 |
-
except requests.exceptions.RequestException as e:
|
| 118 |
-
# Catch API Request Exceptions
|
| 119 |
-
return jsonify({"error": "API Request Error", "details": str(e)}), 500
|
| 120 |
-
except Exception as e:
|
| 121 |
-
# Catch Any Unexpected Errors
|
| 122 |
-
return jsonify({"error": "An Unexpected Error Occurred", "details": str(e)}), 500
|
| 123 |
-
|
| 124 |
-
|
| 125 |
-
# Helper functions for more specific token error handling
|
| 126 |
-
def token_expired(token):
|
| 127 |
-
try:
|
| 128 |
-
response = requests.get(SEPTIMIUS_JSON_URL)
|
| 129 |
-
if response.status_code == 200:
|
| 130 |
-
json_data = response.json()
|
| 131 |
-
if json_data.get("success"):
|
| 132 |
-
for entry in json_data["data"]:
|
| 133 |
-
if entry.get("token") == token:
|
| 134 |
-
expired_date = entry.get("expired_date")
|
| 135 |
-
if expired_date and datetime.fromisoformat(expired_date) <= datetime.now():
|
| 136 |
-
return True
|
| 137 |
-
except Exception as e:
|
| 138 |
-
print(f"Error checking token expiration: {e}")
|
| 139 |
-
return False
|
| 140 |
-
|
| 141 |
-
|
| 142 |
-
def token_not_found(token):
|
| 143 |
-
try:
|
| 144 |
-
response = requests.get(SEPTIMIUS_JSON_URL)
|
| 145 |
-
if response.status_code == 200:
|
| 146 |
-
json_data = response.json()
|
| 147 |
-
if json_data.get("success"):
|
| 148 |
-
for entry in json_data["data"]:
|
| 149 |
-
if entry.get("token") == token:
|
| 150 |
-
return False # Token found
|
| 151 |
-
return True # Token not found in the loop
|
| 152 |
-
except Exception as e:
|
| 153 |
-
print(f"Error checking token existence: {e}")
|
| 154 |
-
return True # Assume not found if an error occurs
|
| 155 |
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|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|
|
|
| 6 |
|
| 7 |
+
# Headers for you.com API (with empty cookie)
|
| 8 |
+
headers = {
|
| 9 |
+
"cookie": "",
|
| 10 |
+
"User-Agent": "Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/130.0.0.0 Safari/537.36"
|
| 11 |
+
}
|
| 12 |
+
|
| 13 |
+
def get_ai_response(user_message, chat_history, ID):
|
| 14 |
+
if not user_message:
|
| 15 |
+
return "User message is required"
|
| 16 |
+
|
| 17 |
+
# Construct the URL for you.com API request
|
| 18 |
+
url = f"https://you.com/api/streamingSearch?page=1&count=10&safeSearch=Moderate&enable_worklow_generation_ux=true&domain=youchat&use_personalization_extraction=false&traceId=&selectedChatMode={ID}&q=CHAT:{chat_history} user:{user_message}"
|
| 19 |
+
|
| 20 |
+
# Send the request to you.com
|
| 21 |
+
response = requests.get(url, headers=headers, stream=True)
|
| 22 |
+
|
| 23 |
+
# Process the response
|
| 24 |
+
model_response = ""
|
| 25 |
+
for line in response.iter_lines():
|
| 26 |
+
if line:
|
| 27 |
+
decoded_line = line.decode('utf-8')
|
| 28 |
+
if 'youChatToken' in decoded_line and 'data: 'n decoded_line:
|
| 29 |
+
data = json.loads(decoded_line.split('data: ')[1])
|
| 30 |
+
model_response += data["youChatToken"]
|
| 31 |
+
|
| 32 |
+
# Clean up the response text
|
| 33 |
+
model_response = model_response.replace(
|
| 34 |
+
"#### You've hit your free quota for the Custom Agent. For more usage of the Custom Agent, learn more at: https://you.com/plans.\n\nAnswering your question without the Custom Agent:\n",
|
| 35 |
+
""
|
| 36 |
+
).replace("AI CORVO: ", "").replace("Ana: ", "").strip()
|
| 37 |
+
|
| 38 |
+
return model_response
|
| 39 |
+
|
| 40 |
+
@app.route('/ai-response', methods=['POST'])
|
| 41 |
+
def ai_response_endpoint():
|
| 42 |
+
data = request.json
|
| 43 |
+
if 'ID' not in data or 'user_message' not in data:
|
| 44 |
+
return jsonify({"error": "Missing required parameters: ID and/or user_message"}), 400
|
| 45 |
+
|
| 46 |
+
ID = data['ID']
|
| 47 |
+
user_message = data['user_message']
|
| 48 |
+
chat_history = data.get('chat_history', "") # Optional parameter, defaults to empty string if not provided
|
| 49 |
+
|
| 50 |
+
response = get_ai_response(user_message, chat_history, ID)
|
| 51 |
+
return jsonify({"response": response})
|
| 52 |
|
| 53 |
if __name__ == "__main__":
|
| 54 |
app.run(host="0.0.0.0", port=7860)
|