MiklX commited on
Commit
d5509b5
·
1 Parent(s): 16f2cf9

Update app.py

Browse files
Files changed (1) hide show
  1. app.py +62 -66
app.py CHANGED
@@ -1,65 +1,34 @@
1
- import asyncio
2
- from quart import Quart, request, jsonify
3
- import random
4
- from g4f import ChatCompletion
5
  import json
6
- import ast
7
- import re
8
- import html
9
-
10
- app = Quart(__name__)
11
-
12
-
13
- def decode_unicode_escape(input_text):
14
- try:
15
- decoded_json = json.loads('{"content": ' + input_text + '}')
16
- content = decoded_json["content"].encode("utf-8").decode("unicode-escape")
17
- return content.encode().decode('unicode_escape')
18
- except Exception as e:
19
- return str(e)
20
 
21
- def remove_repeated_quotes(text):
22
- # Заменяем повторяющиеся кавычки с эскейп-символами
23
- text = re.sub(r'(\\+")+', r'\1', text)
24
- # Заменяем повторяющиеся кавычки без эскейп-символов
25
- text = re.sub(r'(")+', r'\1', text)
26
- return text
27
 
28
-
29
- async def get_completion(model, prompt):
30
- response = await ChatCompletion.create_async(
31
- model=model,
32
- messages = ast.literal_eval(f"[{remove_repeated_quotes(prompt)}]")
33
- #messages=[{"role": "user", "content": prompt}],
34
- )
35
- return response
36
 
37
- @app.route('/chat/completions', methods=['POST'])
38
- async def chat_completions():
39
- try:
40
- app.config['QUART_ROUTE_TIMEOUT'] = 180
41
- app.config["JSON_AS_ASCII"] = False
42
- app.config["JSONIFY_MIMETYPE"] = "application/json; charset=utf-8"
43
 
44
- # Получаем данные из POST-запроса
45
- request_data = await request.get_data()
46
- request_data_str = request_data.decode('utf-8')
47
 
48
- # Извлекаем значение из JSON данных
49
- request_json = json.loads(request_data_str)
50
- user_message = request_json.get("message", "")
51
- model = request_json.get("model", "")
52
- password = request_json.get("password", "")
53
 
54
- # Проверяем код пароля
55
- if password != "P@ssw0rd":
56
- return jsonify({"error": "Unauthorized", "message": "Неверный код пароля"}), 401
57
 
58
- response = await get_completion(model, user_message)
 
59
 
60
- completion_id = random.randint(1, 100)
61
- completion_timestamp = '2022-01-01 12:00:00'
62
- data = {
63
  "id": f"chatcmpl-{completion_id}",
64
  "object": "chat.completion",
65
  "created": completion_timestamp,
@@ -78,22 +47,49 @@ async def chat_completions():
78
  "prompt_tokens": None,
79
  "completion_tokens": None,
80
  "total_tokens": None,
81
- }
82
  }
83
 
84
- # Экранирование HTML-символов в JSON-данных
85
- response = json.dumps(data, ensure_ascii=False).encode('utf-8')
86
- response = html.escape(response.decode('utf-8'))
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
87
 
88
- # Создайте объект Response с указанием заголовков и кодировки
89
- return app.response_class(response, content_type='application/json; charset=utf-8')
 
 
 
 
 
 
 
 
 
 
 
 
 
90
 
91
- except json.JSONDecodeError as e:
92
- return jsonify({"error": "Bad Request", "message": "Неверный формат JSON в запросе"}), 400
93
 
94
- except Exception as e:
95
- # Вернуть ошибку 500 с сообщением об ошибке
96
- return jsonify({"error": "Internal Server Error", "message": str(e)}), 500
97
 
98
- if __name__ == '__main__':
99
- app.run(host='0.0.0.0', port=7860, debug=True)
 
 
 
 
 
1
  import json
2
+ import random
3
+ import string
4
+ import time
5
+ from typing import Any
 
 
 
 
 
 
 
 
 
 
6
 
7
+ from flask import Flask, request
8
+ from flask_cors import CORS
 
 
 
 
9
 
10
+ from g4f import ChatCompletion, Provider
 
 
 
 
 
 
 
11
 
12
+ app = Flask(name)
13
+ CORS(app)
 
 
 
 
14
 
15
+ @app.route("/")
16
+ def main():
17
+ return """Just GPT3.5 api created by xtekky<br>See <a href='https://huggingface.co/spaces/ddosxd/gpt-3.5-ponos/blob/main/README.md'> for examples</a>"""
18
 
19
+ @app.route("/chat/completions", methods=["POST"])
20
+ def chat_completions():
21
+ model = request.get_json().get("model", "gpt-3.5-turbo")
22
+ stream = request.get_json().get("stream", False)
23
+ messages = request.get_json().get("messages")
24
 
25
+ response = ChatCompletion.create(model=model, stream=stream, messages=messages, provider=Provider.DeepAi)
 
 
26
 
27
+ completion_id = "".join(random.choices(string.ascii_letters + string.digits, k=28))
28
+ completion_timestamp = int(time.time())
29
 
30
+ if not stream:
31
+ return {
 
32
  "id": f"chatcmpl-{completion_id}",
33
  "object": "chat.completion",
34
  "created": completion_timestamp,
 
47
  "prompt_tokens": None,
48
  "completion_tokens": None,
49
  "total_tokens": None,
50
+ },
51
  }
52
 
53
+ def streaming():
54
+ for chunk in response:
55
+ completion_data = {
56
+ "id": f"chatcmpl-{completion_id}",
57
+ "object": "chat.completion.chunk",
58
+ "created": completion_timestamp,
59
+ "model": model,
60
+ "choices": [
61
+ {
62
+ "index": 0,
63
+ "delta": {
64
+ "content": chunk,
65
+ },
66
+ "finish_reason": None,
67
+ }
68
+ ],
69
+ }
70
+
71
+ content = json.dumps(completion_data, separators=(",", ":"))
72
+ yield f"data: {content}\n\n"
73
+ time.sleep(0.1)
74
 
75
+ end_completion_data: dict[str, Any] = {
76
+ "id": f"chatcmpl-{completion_id}",
77
+ "object": "chat.completion.chunk",
78
+ "created": completion_timestamp,
79
+ "model": model,
80
+ "choices": [
81
+ {
82
+ "index": 0,
83
+ "delta": {},
84
+ "finish_reason": "stop",
85
+ }
86
+ ],
87
+ }
88
+ content = json.dumps(end_completion_data, separators=(",", ":"))
89
+ yield f"data: {content}\n\n"
90
 
91
+ return app.response_class(streaming(), mimetype="text/event-stream")
 
92
 
 
 
 
93
 
94
+ if name == "main":
95
+ app.run(host="0.0.0.0", port=7860, debug=False)