Hivra commited on
Commit
c3cac89
·
verified ·
1 Parent(s): 7213352

Upload 5 files

Browse files
Files changed (5) hide show
  1. Dockerfile +24 -0
  2. main.py +151 -0
  3. requirements.txt +3 -0
  4. space_checker.py +13 -0
  5. start.sh +5 -0
Dockerfile ADDED
@@ -0,0 +1,24 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # read the doc: https://huggingface.co/docs/hub/spaces-sdks-docker
2
+ # you will also find guides on how best to write your Dockerfile
3
+
4
+ FROM python:3.9
5
+
6
+ WORKDIR /code
7
+
8
+ COPY ./main.py /code/main.py
9
+
10
+ COPY ./space_checker.py /code/space_checker.py
11
+
12
+ COPY ./requirements.txt /code/requirements.txt
13
+
14
+ COPY ./start.sh /code/start.sh
15
+
16
+ COPY . .
17
+
18
+ RUN pip install -r /code/requirements.txt
19
+
20
+ RUN chmod +x start.sh
21
+
22
+ RUN sed -i 's/\r$//' start.sh
23
+
24
+ CMD ["bash","start.sh"]
main.py ADDED
@@ -0,0 +1,151 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ import gevent.pywsgi
2
+ from gevent import monkey;monkey.patch_all()
3
+ from flask import Flask, request, Response, jsonify
4
+ import argparse
5
+ import requests
6
+ import random
7
+ import string
8
+ import time
9
+ import json
10
+ import os
11
+
12
+ app = Flask(__name__)
13
+ app.json.sort_keys = False
14
+
15
+ parser = argparse.ArgumentParser(description="An example of Qwen demo with a similar API to OAI.")
16
+ parser.add_argument("--host", type=str, help="Set the ip address.(default: 0.0.0.0)", default='0.0.0.0')
17
+ parser.add_argument("--port", type=int, help="Set the port.(default: 7860)", default=7860)
18
+ args = parser.parse_args()
19
+
20
+ base_url = os.getenv('MODEL_BASE_URL')
21
+
22
+ @app.route('/api/v1/models', methods=["GET", "POST"])
23
+ @app.route('/v1/models', methods=["GET", "POST"])
24
+ def model_list():
25
+ time_now = int(time.time())
26
+ model_list = {
27
+ "object": "list",
28
+ "data": [
29
+ {
30
+ "id": "qwen-2-5",
31
+ "object": "model",
32
+ "created": time_now,
33
+ "owned_by": "tastypear"
34
+ },
35
+ {
36
+ "id": "gpt-3.5-turbo",
37
+ "object": "model",
38
+ "created": time_now,
39
+ "owned_by": "tastypear"
40
+ }
41
+ ]
42
+ }
43
+ return jsonify(model_list)
44
+
45
+ @app.route("/", methods=["GET"])
46
+ def index():
47
+ return Response(f'QW2.5 ᴍᴀx OpenAI Compatible API<br><br>'+
48
+ f'Set "{os.getenv("SPACE_URL")}/api" as proxy (or API Domain) in your Chatbot.<br><br>'+
49
+ f'The complete API is: {os.getenv("SPACE_URL")}/api/v1/chat/completions')
50
+
51
+ @app.route("/api/v1/chat/completions", methods=["POST", "OPTIONS"])
52
+ @app.route("/v1/chat/completions", methods=["POST", "OPTIONS"])
53
+ def chat_completions():
54
+
55
+ if request.method == "OPTIONS":
56
+ return Response(
57
+ headers={
58
+ "Access-Control-Allow-Origin": "*",
59
+ "Access-Control-Allow-Headers": "*",
60
+ }
61
+ )
62
+
63
+ data = request.get_json()
64
+
65
+ # reorganize data
66
+ system = "You are a helpful assistant."
67
+ chat_history = []
68
+ prompt = ""
69
+
70
+ if "messages" in data:
71
+ messages = data["messages"]
72
+ message_size = len(messages)
73
+
74
+ prompt = messages[-1].get("content")
75
+ for i in range(message_size - 1):
76
+ role_this = messages[i].get("role")
77
+ role_next = messages[i + 1].get("role")
78
+ if role_this == "system":
79
+ system = messages[i].get("content")
80
+ elif role_this == "user":
81
+ if role_next == "assistant":
82
+ chat_history.append(
83
+ [messages[i].get("content"), messages[i + 1].get("content")]
84
+ )
85
+ else:
86
+ chat_history.append([messages[i].get("content"), " "])
87
+
88
+ # gen a random char(11) hash
89
+ chars = string.ascii_lowercase + string.digits
90
+ session_hash = "".join(random.choice(chars) for _ in range(11))
91
+
92
+ json_prompt = {
93
+ "data": [prompt, chat_history, system],
94
+ "fn_index": 0,
95
+ "session_hash": session_hash,
96
+ "trigger_id": 11,
97
+ }
98
+
99
+ def generate():
100
+ response = requests.post(f"{base_url}/gradio_api/queue/join", json=json_prompt)
101
+ url = f"{base_url}/gradio_api/queue/data?session_hash={session_hash}"
102
+ data = requests.get(url, stream=True)
103
+
104
+ time_now = int(time.time())
105
+
106
+ for line in data.iter_lines():
107
+ if line:
108
+ decoded_line = line.decode("utf-8")
109
+ json_line = json.loads(decoded_line[6:])
110
+ if json_line["msg"] == "process_starts":
111
+ res_data = gen_res_data({}, time_now=time_now, start=True)
112
+ yield f"data: {json.dumps(res_data)}\n\n"
113
+ elif json_line["msg"] == "process_generating":
114
+ res_data = gen_res_data(json_line, time_now=time_now)
115
+ yield f"data: {json.dumps(res_data)}\n\n"
116
+ elif json_line["msg"] == "process_completed":
117
+ yield "data: [DONE]"
118
+
119
+ return Response(
120
+ generate(),
121
+ mimetype="text/event-stream",
122
+ headers={
123
+ "Access-Control-Allow-Origin": "*",
124
+ "Access-Control-Allow-Headers": "*",
125
+ },
126
+ )
127
+
128
+
129
+ def gen_res_data(data, time_now=0, start=False):
130
+ res_data = {
131
+ "id": "chatcmpl",
132
+ "object": "chat.completion.chunk",
133
+ "created": time_now,
134
+ "model": "qwen-2-5",
135
+ "choices": [{"index": 0, "finish_reason": None}],
136
+ }
137
+
138
+ if start:
139
+ res_data["choices"][0]["delta"] = {"role": "assistant", "content": ""}
140
+ else:
141
+ chat_pair = data["output"]["data"][1]
142
+ if chat_pair == []:
143
+ res_data["choices"][0]["finish_reason"] = "stop"
144
+ else:
145
+ res_data["choices"][0]["delta"] = {"content": chat_pair[-1][-1]}
146
+ return res_data
147
+
148
+
149
+ if __name__ == "__main__":
150
+ # app.run(host=args.host, port=args.port, debug=True)
151
+ gevent.pywsgi.WSGIServer((args.host, args.port), app).serve_forever()
requirements.txt ADDED
@@ -0,0 +1,3 @@
 
 
 
 
1
+ flask
2
+ requests
3
+ gevent
space_checker.py ADDED
@@ -0,0 +1,13 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ import requests
2
+ import time
3
+ import os
4
+
5
+ space_url = os.getenv('SPACE_URL')
6
+
7
+ def fetch_url(url):
8
+ response = requests.get(url)
9
+ print(response.text)
10
+
11
+ while True:
12
+ fetch_url(space_url)
13
+ time.sleep(3600)
start.sh ADDED
@@ -0,0 +1,5 @@
 
 
 
 
 
 
1
+ #!/bin/bash
2
+ python -m http.server 7860 & kill $!
3
+ python main.py &
4
+ python space_checker.py &
5
+ wait