Update app.py
Browse files
app.py
CHANGED
@@ -1,34 +1,29 @@
|
|
1 |
-
from
|
|
|
2 |
import json
|
3 |
-
|
4 |
-
import
|
5 |
-
import ssl
|
6 |
-
import logging
|
7 |
|
8 |
-
|
9 |
-
logging.basicConfig(level=logging.INFO)
|
10 |
-
logger = logging.getLogger(__name__)
|
11 |
|
12 |
-
|
13 |
-
|
14 |
-
|
15 |
-
self.send_error(404, "Not Found")
|
16 |
-
return
|
17 |
-
|
18 |
-
content_length = int(self.headers['Content-Length'])
|
19 |
-
post_data = self.rfile.read(content_length)
|
20 |
-
body = json.loads(post_data.decode('utf-8'))
|
21 |
|
|
|
|
|
|
|
|
|
22 |
model = body.get('model')
|
23 |
messages = body.get('messages')
|
24 |
stream = body.get('stream', False)
|
25 |
|
26 |
if not model or not messages or len(messages) == 0:
|
27 |
-
|
28 |
-
return
|
29 |
|
30 |
prompt = messages[-1]['content']
|
31 |
-
new_url = f
|
|
|
32 |
new_request_body = {
|
33 |
"prompt": prompt,
|
34 |
"image_size": "1024x1024",
|
@@ -37,92 +32,79 @@ class ChatCompletionsHandler(BaseHTTPRequestHandler):
|
|
37 |
"guidance_scale": 1
|
38 |
}
|
39 |
|
40 |
-
|
41 |
-
|
42 |
-
|
43 |
-
|
44 |
-
|
45 |
-
|
46 |
-
|
47 |
-
method='POST')
|
48 |
-
|
49 |
-
ctx = ssl.create_default_context()
|
50 |
-
ctx.check_hostname = False
|
51 |
-
ctx.verify_mode = ssl.CERT_NONE
|
52 |
-
|
53 |
-
try:
|
54 |
-
with urllib.request.urlopen(req, context=ctx) as response:
|
55 |
-
response_body = json.loads(response.read().decode('utf-8'))
|
56 |
-
|
57 |
-
logger.info(f"API Response: {response_body}") # 记录 API 响应
|
58 |
-
|
59 |
-
if 'images' not in response_body or not response_body['images']:
|
60 |
-
raise ValueError("No images in the response")
|
61 |
-
|
62 |
-
image_url = response_body['images'][0].get('url')
|
63 |
-
if not image_url:
|
64 |
-
raise ValueError("No URL in the image response")
|
65 |
-
|
66 |
-
unique_id = int(datetime.now().timestamp() * 1000)
|
67 |
-
current_timestamp = int(unique_id / 1000)
|
68 |
-
|
69 |
-
if stream:
|
70 |
-
response_payload = {
|
71 |
-
"id": unique_id,
|
72 |
-
"object": "chat.completion.chunk",
|
73 |
-
"created": current_timestamp,
|
74 |
-
"model": model,
|
75 |
-
"choices": [
|
76 |
-
{
|
77 |
-
"index": 0,
|
78 |
-
"delta": {
|
79 |
-
"content": f""
|
80 |
-
},
|
81 |
-
"finish_reason": "stop"
|
82 |
-
}
|
83 |
-
]
|
84 |
-
}
|
85 |
-
self.send_response(200)
|
86 |
-
self.send_header('Content-Type', 'text/event-stream')
|
87 |
-
self.end_headers()
|
88 |
-
self.wfile.write(f"data: {json.dumps(response_payload)}\n\n".encode('utf-8'))
|
89 |
else:
|
90 |
-
|
91 |
-
|
92 |
-
|
93 |
-
|
94 |
-
|
95 |
-
|
96 |
-
|
97 |
-
|
98 |
-
|
99 |
-
|
100 |
-
|
101 |
-
|
102 |
-
|
103 |
-
|
104 |
-
|
105 |
-
|
106 |
-
|
107 |
-
|
108 |
-
|
109 |
-
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
110 |
}
|
|
|
|
|
|
|
|
|
|
|
111 |
}
|
112 |
-
|
113 |
-
|
114 |
-
|
115 |
-
self.wfile.write(json.dumps(response_payload).encode('utf-8'))
|
116 |
-
|
117 |
-
except Exception as e:
|
118 |
-
logger.error(f"Error occurred: {str(e)}")
|
119 |
-
self.send_error(500, f"Internal Server Error: {str(e)}")
|
120 |
|
121 |
-
|
122 |
-
|
123 |
-
httpd = server_class(server_address, handler_class)
|
124 |
-
logger.info(f"Starting server on port {port}")
|
125 |
-
httpd.serve_forever()
|
126 |
|
127 |
if __name__ == '__main__':
|
128 |
-
run()
|
|
|
1 |
+
from flask import Flask, request, jsonify, Response
|
2 |
+
import requests
|
3 |
import json
|
4 |
+
import time
|
5 |
+
import random
|
|
|
|
|
6 |
|
7 |
+
app = Flask(__name__)
|
|
|
|
|
8 |
|
9 |
+
@app.route('/')
|
10 |
+
def index():
|
11 |
+
return "flux2api with siliconflow", 200
|
|
|
|
|
|
|
|
|
|
|
|
|
12 |
|
13 |
+
@app.route('/v1/chat/completions', methods=['POST'])
|
14 |
+
def handle_request():
|
15 |
+
try:
|
16 |
+
body = request.json
|
17 |
model = body.get('model')
|
18 |
messages = body.get('messages')
|
19 |
stream = body.get('stream', False)
|
20 |
|
21 |
if not model or not messages or len(messages) == 0:
|
22 |
+
return jsonify({"error": "Bad Request: Missing required fields"}), 400
|
|
|
23 |
|
24 |
prompt = messages[-1]['content']
|
25 |
+
new_url = f'https://api.siliconflow.cn/v1/{model}/text-to-image'
|
26 |
+
|
27 |
new_request_body = {
|
28 |
"prompt": prompt,
|
29 |
"image_size": "1024x1024",
|
|
|
32 |
"guidance_scale": 1
|
33 |
}
|
34 |
|
35 |
+
# 从传入的 Authorization 头中随机选择一个 token
|
36 |
+
authorization_header = request.headers.get('Authorization')
|
37 |
+
if authorization_header:
|
38 |
+
# 去掉 "Bearer " 前缀并分割 token
|
39 |
+
tokens = authorization_header.replace("Bearer ", "").split(',')
|
40 |
+
if len(tokens) > 1:
|
41 |
+
selected_token = random.choice(tokens).strip()
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
42 |
else:
|
43 |
+
selected_token = tokens[0].strip()
|
44 |
+
# 重新格式化为 "Bearer 随机选择的token"
|
45 |
+
selected_token = f"Bearer {selected_token}"
|
46 |
+
else:
|
47 |
+
return jsonify({"error": "Unauthorized: Missing Authorization header"}), 401
|
48 |
+
|
49 |
+
headers = {
|
50 |
+
'accept': 'application/json',
|
51 |
+
'content-type': 'application/json',
|
52 |
+
'Authorization': selected_token
|
53 |
+
}
|
54 |
+
|
55 |
+
response = requests.post(new_url, headers=headers, json=new_request_body)
|
56 |
+
response_body = response.json()
|
57 |
+
|
58 |
+
image_url = response_body['images'][0]['url']
|
59 |
+
unique_id = int(time.time() * 1000)
|
60 |
+
current_timestamp = unique_id // 1000
|
61 |
+
|
62 |
+
if stream:
|
63 |
+
response_payload = {
|
64 |
+
"id": unique_id,
|
65 |
+
"object": "chat.completion.chunk",
|
66 |
+
"created": current_timestamp,
|
67 |
+
"model": model,
|
68 |
+
"choices": [
|
69 |
+
{
|
70 |
+
"index": 0,
|
71 |
+
"delta": {
|
72 |
+
"content": f""
|
73 |
+
},
|
74 |
+
"finish_reason": "stop"
|
75 |
+
}
|
76 |
+
]
|
77 |
+
}
|
78 |
+
data_string = json.dumps(response_payload)
|
79 |
+
return Response(f"data: {data_string}\n\n", content_type='text/event-stream')
|
80 |
+
else:
|
81 |
+
response_payload = {
|
82 |
+
"id": unique_id,
|
83 |
+
"object": "chat.completion",
|
84 |
+
"created": current_timestamp,
|
85 |
+
"model": model,
|
86 |
+
"choices": [
|
87 |
+
{
|
88 |
+
"index": 0,
|
89 |
+
"message": {
|
90 |
+
"role": "assistant",
|
91 |
+
"content": f""
|
92 |
+
},
|
93 |
+
"logprobs": None,
|
94 |
+
"finish_reason": "length"
|
95 |
}
|
96 |
+
],
|
97 |
+
"usage": {
|
98 |
+
"prompt_tokens": len(prompt),
|
99 |
+
"completion_tokens": len(image_url),
|
100 |
+
"total_tokens": len(prompt) + len(image_url)
|
101 |
}
|
102 |
+
}
|
103 |
+
data_string = json.dumps(response_payload)
|
104 |
+
return Response(f"{data_string}\n\n", content_type='text/event-stream')
|
|
|
|
|
|
|
|
|
|
|
105 |
|
106 |
+
except Exception as e:
|
107 |
+
return jsonify({"error": f"Internal Server Error: {str(e)}"}), 500
|
|
|
|
|
|
|
108 |
|
109 |
if __name__ == '__main__':
|
110 |
+
app.run(host='0.0.0.0', port=8000)
|