tianlong12 commited on
Commit
520b9c6
·
verified ·
1 Parent(s): 1b5a405

Update app.py

Browse files
Files changed (1) hide show
  1. app.py +114 -124
app.py CHANGED
@@ -1,23 +1,29 @@
1
- import random
 
2
  import time
3
  import json
4
- import re
5
- import aiohttp
6
- import requests
7
  import asyncio
 
 
 
8
  from flask import Flask, request, Response
9
  from flask_cors import CORS
10
- import uuid
11
 
12
  app = Flask(__name__)
13
- CORS(app)
14
 
 
15
  MAGAI_TOKEN = {
16
  "cookie": "_fbp=fb.1.1722349051350.28463402121267809;soquick-mobile_u1main=1722349236461x685414888067651300;intercom-id-jnjoad6e=cbbd8fc9-a010-4e8c-8e7e-9cffccd3abea;soquick-mobile_live_u2main.sig=HuQePfrEHGidu4eRyfiZkcL1_2E;__stripe_mid=7767e1a3-e87f-4456-b073-6c8b7ae9e82119b00d;__stripe_sid=99c612a5-a12a-426f-baa5-e61471a013f140c482;_ga=GA1.1.242967908.1722349051;_ga_GFQ25YSHT2=GS1.1.1726123356.1.0.1726123393.0.0.0;_ga_N5J29RVHDJ=GS1.1.1726123395.4.1.1726124637.0.0.0;intercom-device-id-jnjoad6e=35ee824e-f7f6-415d-8698-bd822cb46d3a;intercom-session-jnjoad6e=SXlhUDdqa0E5YTlmUVA2QXk3K3hBSXFNSnRzL2x0cEtvVDF3U1k3UlRCQmhPRVdUcktDYkpwVXpiZFA1SzhUSi0tTFlCazFUamcxbExFRU1LTVlWSitVQT09--40f0dca176cfb28add2903465c54bcee4f33de2b;soquick-mobile_live_u2main=bus|1722349236461x685414888067651300|1726123417637x655253536227564700",
17
  "app_last_change": "21388518093",
18
  "current_page_item": "1348695171700984260__LOOKUP__1726124636560x692535552825360400",
19
  "current_user": "1348695171700984260__LOOKUP__1722349236461x685414888067651300",
20
  }
 
 
 
 
21
 
22
  MAGAI_MAPPING = {
23
  "gpt-4o": "openai/gpt-4o",
@@ -39,7 +45,6 @@ def create_luid(separator="x"):
39
  def format_model_name(model_name):
40
  return re.sub(r"_+", "_", re.sub(r"[/:-]", "_", model_name))
41
 
42
-
43
  def find_token_in_object(obj):
44
  if isinstance(obj, dict):
45
  for key, value in obj.items():
@@ -50,24 +55,22 @@ def find_token_in_object(obj):
50
  return token
51
  return None
52
 
53
-
54
  def get_last_user_content(messages):
55
  for message in reversed(messages):
56
  if message["role"] == "user":
57
  return message["content"]
58
  return None
59
 
60
-
61
  async def get_token(model, message):
62
  server_call_id = generate_uuid()
63
- created_id = MAGAI_TOKEN["current_page_item"].split("__")[0]
64
- user_id = MAGAI_TOKEN["current_user"].split("__")[2]
65
  model_id = "0060f9accd1dbade552f65ac646fb3da"
66
  item_id = "bUNih7"
67
  element_id = "bUNib7"
68
 
69
  body = {
70
- "app_last_change": MAGAI_TOKEN["app_last_change"],
71
  "calls": [
72
  {
73
  "client_state": {
@@ -155,8 +158,8 @@ async def get_token(model, message):
155
  "cache": {
156
  f"{model_id}": format_model_name(model),
157
  "true": True,
158
- "CurrentPageItem": MAGAI_TOKEN["current_page_item"],
159
- "CurrentUser": MAGAI_TOKEN["current_user"],
160
  },
161
  "exists": {
162
  f"{model_id}": True,
@@ -193,7 +196,7 @@ async def get_token(model, message):
193
  "x-bubble-fiber-id": generate_uuid(),
194
  "x-bubble-pl": create_luid(),
195
  "accept": "application/json, text/javascript, */*; q=0.01",
196
- "cookie": MAGAI_TOKEN["cookie"],
197
  },
198
  json=body,
199
  ) as response:
@@ -211,126 +214,113 @@ async def get_token(model, message):
211
  if token:
212
  return token
213
 
214
-
215
  async def get_request_data(model, messages):
216
  if model not in MAGAI_MAPPING:
217
- return Response(
218
- json.dumps(
219
- {
220
- "error": {
221
- "message": "This model is currently unavailable. Please try again later or choose another model.",
222
- "code": "model_not_exists",
223
- }
224
- }
225
- ),
226
- status=400,
227
- mimetype="application/json",
228
- )
229
 
230
  last_user_message = get_last_user_content(messages)
231
- token = await get_token(MAGAI_MAPPING[model], last_user_message)
232
- headers = {
233
- "Content-Type": "application/json",
234
- "HTTP-Referer": "https://magai.co",
235
- "Origin": "https://app.magai.co",
236
- "Pragma": "no-cache",
237
- "Referer": "https://app.magai.co/",
238
- "Token": token,
239
- "User-Agent": "Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/500.00 (KHTML, like Gecko) Chrome/100.0.0.0 Safari/500.00",
240
- }
241
-
242
- json_data = {
243
- "model": MAGAI_MAPPING[model],
244
- "messages": [{"role": "system", "content": "You are a helpful assistant."}]
245
- + messages,
246
- "tools": [
247
- {
248
- "type": "function",
249
- "function": {
250
- "name": "get_actual_time_info",
251
- "description": "Returns actual information from web about prompt theme.",
252
- "parameters": {
253
- "type": "object",
254
- "properties": {
255
- "query": {
256
- "type": "string",
257
- "description": "The query string based on users prompt to search information about.",
258
- }
 
 
 
 
 
 
 
 
259
  },
260
- "required": ["query"],
261
  },
262
  },
263
- },
264
- {
265
- "type": "function",
266
- "function": {
267
- "name": "generate_image",
268
- "description": "Returns generated image URL.",
269
- "parameters": {
270
- "type": "object",
271
- "properties": {
272
- "query": {
273
- "type": "string",
274
- "description": "Prompt to image generation AI model, that describes what image to generate.",
275
- }
 
276
  },
277
- "required": ["query"],
278
  },
279
  },
280
- },
281
- ],
282
- "provider": {"data_collection": "deny"},
283
- "tool_choice": "auto",
284
- "stream": True,
285
- }
286
-
287
- response = requests.post(
288
- "https://live.proxy.magai.co:4430/opr/api/v1/chat/completions",
289
- headers=headers,
290
- json=json_data,
291
- )
292
- return response
293
-
294
-
295
- def format_response(response):
296
- content = ""
297
- for line in response.iter_lines():
298
- if line:
299
- decoded_line = line.decode("utf-8")
300
- if decoded_line.startswith("data:"):
301
- try:
302
- data = json.loads(decoded_line[5:].strip())
303
- if "choices" in data and len(data["choices"]) > 0:
304
- delta = data["choices"][0].get("delta", {})
305
- if "content" in delta:
306
- content += delta["content"]
307
- except json.JSONDecodeError:
308
- pass
309
- return content
310
-
311
 
312
  @app.route("/hf/v1/chat/completions", methods=["POST"])
313
- def chat_completions():
314
- data = request.json
315
- messages = data.get("messages", [])
316
- model = data.get("model", "claude-3.5-sonnet")
317
-
318
- async def process_request():
319
- response = await get_request_data(model, messages)
320
- return format_response(response)
321
-
322
- loop = asyncio.new_event_loop()
323
- asyncio.set_event_loop(loop)
324
- result = loop.run_until_complete(process_request())
325
-
326
- event_stream_response = ""
327
- for part in result:
328
- part = part.replace("\n", "\\n")
329
- event_stream_response += f'data:{{"id":"{uuid.uuid4()}","object":"chat.completion.chunk","created":{int(time.time())},"model":"{model}","system_fingerprint":"fp_45ah8ld5a7","choices":[{{"index":0,"delta":{{"content":"{part}"}},"logprobs":null,"finish_reason":null}}]}}\n\n'
330
- event_stream_response += "data:[DONE]\n"
331
-
332
- return Response(event_stream_response, mimetype="text/event-stream")
333
-
 
 
 
 
 
 
 
 
334
 
335
  if __name__ == "__main__":
336
- app.run(host="0.0.0.0", port=7860)
 
1
+
2
+ import os
3
  import time
4
  import json
5
+ import uuid
 
 
6
  import asyncio
7
+ import aiohttp
8
+ import random
9
+ import re
10
  from flask import Flask, request, Response
11
  from flask_cors import CORS
 
12
 
13
  app = Flask(__name__)
14
+ CORS(app, resources={r"/*": {"origins": "*"}})
15
 
16
+ # Load environment variables
17
  MAGAI_TOKEN = {
18
  "cookie": "_fbp=fb.1.1722349051350.28463402121267809;soquick-mobile_u1main=1722349236461x685414888067651300;intercom-id-jnjoad6e=cbbd8fc9-a010-4e8c-8e7e-9cffccd3abea;soquick-mobile_live_u2main.sig=HuQePfrEHGidu4eRyfiZkcL1_2E;__stripe_mid=7767e1a3-e87f-4456-b073-6c8b7ae9e82119b00d;__stripe_sid=99c612a5-a12a-426f-baa5-e61471a013f140c482;_ga=GA1.1.242967908.1722349051;_ga_GFQ25YSHT2=GS1.1.1726123356.1.0.1726123393.0.0.0;_ga_N5J29RVHDJ=GS1.1.1726123395.4.1.1726124637.0.0.0;intercom-device-id-jnjoad6e=35ee824e-f7f6-415d-8698-bd822cb46d3a;intercom-session-jnjoad6e=SXlhUDdqa0E5YTlmUVA2QXk3K3hBSXFNSnRzL2x0cEtvVDF3U1k3UlRCQmhPRVdUcktDYkpwVXpiZFA1SzhUSi0tTFlCazFUamcxbExFRU1LTVlWSitVQT09--40f0dca176cfb28add2903465c54bcee4f33de2b;soquick-mobile_live_u2main=bus|1722349236461x685414888067651300|1726123417637x655253536227564700",
19
  "app_last_change": "21388518093",
20
  "current_page_item": "1348695171700984260__LOOKUP__1726124636560x692535552825360400",
21
  "current_user": "1348695171700984260__LOOKUP__1722349236461x685414888067651300",
22
  }
23
+ MAGAI_COOKIE = MAGAI_TOKEN["cookie"]
24
+ MAGAI_APP_LAST_CHANGE = MAGAI_TOKEN["app_last_change"]
25
+ MAGAI_CURRENT_PAGE_ITEM = MAGAI_TOKEN["current_page_item"]
26
+ MAGAI_CURRENT_USER = MAGAI_TOKEN["current_user"]
27
 
28
  MAGAI_MAPPING = {
29
  "gpt-4o": "openai/gpt-4o",
 
45
  def format_model_name(model_name):
46
  return re.sub(r"_+", "_", re.sub(r"[/:-]", "_", model_name))
47
 
 
48
  def find_token_in_object(obj):
49
  if isinstance(obj, dict):
50
  for key, value in obj.items():
 
55
  return token
56
  return None
57
 
 
58
  def get_last_user_content(messages):
59
  for message in reversed(messages):
60
  if message["role"] == "user":
61
  return message["content"]
62
  return None
63
 
 
64
  async def get_token(model, message):
65
  server_call_id = generate_uuid()
66
+ created_id = MAGAI_CURRENT_PAGE_ITEM.split("__")[0]
67
+ user_id = MAGAI_CURRENT_USER.split("__")[2]
68
  model_id = "0060f9accd1dbade552f65ac646fb3da"
69
  item_id = "bUNih7"
70
  element_id = "bUNib7"
71
 
72
  body = {
73
+ "app_last_change": MAGAI_APP_LAST_CHANGE,
74
  "calls": [
75
  {
76
  "client_state": {
 
158
  "cache": {
159
  f"{model_id}": format_model_name(model),
160
  "true": True,
161
+ "CurrentPageItem": MAGAI_CURRENT_PAGE_ITEM,
162
+ "CurrentUser": MAGAI_CURRENT_USER,
163
  },
164
  "exists": {
165
  f"{model_id}": True,
 
196
  "x-bubble-fiber-id": generate_uuid(),
197
  "x-bubble-pl": create_luid(),
198
  "accept": "application/json, text/javascript, */*; q=0.01",
199
+ "cookie": MAGAI_COOKIE,
200
  },
201
  json=body,
202
  ) as response:
 
214
  if token:
215
  return token
216
 
 
217
  async def get_request_data(model, messages):
218
  if model not in MAGAI_MAPPING:
219
+ return None, "Model not available"
 
 
 
 
 
 
 
 
 
 
 
220
 
221
  last_user_message = get_last_user_content(messages)
222
+ if not last_user_message:
223
+ return None, "No user message found"
224
+
225
+ try:
226
+ token = await get_token(MAGAI_MAPPING[model], last_user_message)
227
+ if not token:
228
+ return None, "Failed to obtain token"
229
+
230
+ headers = {
231
+ "Content-Type": "application/json",
232
+ "HTTP-Referer": "https://magai.co",
233
+ "Origin": "https://app.magai.co",
234
+ "Pragma": "no-cache",
235
+ "Referer": "https://app.magai.co/",
236
+ "Token": token,
237
+ "User-Agent": "Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/500.00 (KHTML, like Gecko) Chrome/100.0.0.0 Safari/500.00",
238
+ }
239
+
240
+ json_data = {
241
+ "model": MAGAI_MAPPING[model],
242
+ "messages": [{"role": "system", "content": "You are a helpful assistant."}] + messages,
243
+ "tools": [
244
+ {
245
+ "type": "function",
246
+ "function": {
247
+ "name": "get_actual_time_info",
248
+ "description": "Returns actual information from web about prompt theme.",
249
+ "parameters": {
250
+ "type": "object",
251
+ "properties": {
252
+ "query": {
253
+ "type": "string",
254
+ "description": "The query string based on users prompt to search information about.",
255
+ }
256
+ },
257
+ "required": ["query"],
258
  },
 
259
  },
260
  },
261
+ {
262
+ "type": "function",
263
+ "function": {
264
+ "name": "generate_image",
265
+ "description": "Returns generated image URL.",
266
+ "parameters": {
267
+ "type": "object",
268
+ "properties": {
269
+ "query": {
270
+ "type": "string",
271
+ "description": "Prompt to image generation AI model, that describes what image to generate.",
272
+ }
273
+ },
274
+ "required": ["query"],
275
  },
 
276
  },
277
  },
278
+ ],
279
+ "provider": {"data_collection": "deny"},
280
+ "tool_choice": "auto",
281
+ "stream": True,
282
+ }
283
+
284
+ async with aiohttp.ClientSession() as session:
285
+ async with session.post(
286
+ "https://live.proxy.magai.co:4430/opr/api/v1/chat/completions",
287
+ headers=headers,
288
+ json=json_data,
289
+ ) as response:
290
+ return response, None
291
+ except Exception as e:
292
+ return None, str(e)
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
293
 
294
  @app.route("/hf/v1/chat/completions", methods=["POST"])
295
+ async def chat_completions():
296
+ try:
297
+ data = request.json
298
+ messages = data.get("messages", [])
299
+ model = data.get("model", "claude-3.5-sonnet")
300
+
301
+ response, error = await get_request_data(model, messages)
302
+ if error:
303
+ return Response(json.dumps({"error": error}), status=400, mimetype="application/json")
304
+
305
+ async def generate():
306
+ async for line in response.content:
307
+ if line:
308
+ decoded_line = line.decode("utf-8")
309
+ if decoded_line.startswith("data:"):
310
+ try:
311
+ data = json.loads(decoded_line[5:].strip())
312
+ if "choices" in data and len(data["choices"]) > 0:
313
+ delta = data["choices"][0].get("delta", {})
314
+ if "content" in delta:
315
+ content = delta["content"].replace("\n", "\\n")
316
+ yield f'data:{{"id":"{uuid.uuid4()}","object":"chat.completion.chunk","created":{int(time.time())},"model":"{model}","system_fingerprint":"fp_45ah8ld5a7","choices":[{{"index":0,"delta":{{"content":"{content}"}},"logprobs":null,"finish_reason":null}}]}}\n\n'
317
+ except json.JSONDecodeError:
318
+ pass
319
+ yield "data:[DONE]\n"
320
+
321
+ return Response(generate(), mimetype="text/event-stream")
322
+ except Exception as e:
323
+ return Response(json.dumps({"error": str(e)}), status=500, mimetype="application/json")
324
 
325
  if __name__ == "__main__":
326
+ app.run(host="0.0.0.0", port=7860)