smgc commited on
Commit
e45ad65
·
verified ·
1 Parent(s): 99e8375

Update app.py

Browse files
Files changed (1) hide show
  1. app.py +31 -29
app.py CHANGED
@@ -1,28 +1,24 @@
1
- from flask import Flask, request, jsonify, Response
2
- import requests
3
  import json
4
- import time
5
-
6
- app = Flask(__name__)
7
 
8
  @app.route('/')
9
  def index():
10
- return "text-to-image with siliconflow", 200
11
-
12
- @app.route('/ai/v1/chat/completions', methods=['POST'])
13
- def handle_request():
14
  try:
15
- body = request.json
16
  model = body.get('model')
17
  messages = body.get('messages')
18
  stream = body.get('stream', False)
19
 
20
  if not model or not messages or len(messages) == 0:
21
- return jsonify({"error": "Bad Request: Missing required fields"}), 400
22
 
23
  prompt = messages[-1]['content']
24
- new_url = f'https://api.siliconflow.cn/v1/{model}/text-to-image'
25
-
26
  new_request_body = {
27
  "prompt": prompt,
28
  "image_size": "1024x1024",
@@ -31,20 +27,20 @@ def handle_request():
31
  "guidance_scale": 1
32
  }
33
 
34
- headers = {
35
- 'accept': 'application/json',
36
- 'content-type': 'application/json',
37
- 'Authorization': request.headers.get('Authorization')
38
- }
39
-
40
- response = requests.post(new_url, headers=headers, json=new_request_body)
41
- response_body = response.json()
42
 
43
  image_url = response_body['images'][0]['url']
44
- unique_id = int(time.time() * 1000)
45
- current_timestamp = unique_id // 1000
46
 
47
  if stream:
 
48
  response_payload = {
49
  "id": unique_id,
50
  "object": "chat.completion.chunk",
@@ -61,8 +57,11 @@ def handle_request():
61
  ]
62
  }
63
  data_string = json.dumps(response_payload)
64
- return Response(f"data: {data_string}\n\n", content_type='text/event-stream')
 
 
65
  else:
 
66
  response_payload = {
67
  "id": unique_id,
68
  "object": "chat.completion",
@@ -85,11 +84,14 @@ def handle_request():
85
  "total_tokens": len(prompt) + len(image_url)
86
  }
87
  }
88
- data_string = json.dumps(response_payload)
89
- return Response(f"{data_string}\n\n", content_type='text/event-stream')
 
 
 
 
 
90
 
91
- except Exception as e:
92
- return jsonify({"error": f"Internal Server Error: {str(e)}"}), 500
93
 
94
  if __name__ == '__main__':
95
- app.run(host='0.0.0.0', port=8000, debug=True)
 
 
 
1
  import json
2
+ from datetime import datetime
3
+ import aiohttp
4
+ from aiohttp import web
5
 
6
  @app.route('/')
7
  def index():
8
+ return "flux2api with siliconflow", 200
9
+
10
+ async def handle_chat_completions(request):
 
11
  try:
12
+ body = await request.json()
13
  model = body.get('model')
14
  messages = body.get('messages')
15
  stream = body.get('stream', False)
16
 
17
  if not model or not messages or len(messages) == 0:
18
+ return web.json_response({'error': 'Bad Request: Missing required fields'}, status=400)
19
 
20
  prompt = messages[-1]['content']
21
+ new_url = f"https://api.siliconflow.cn/v1/{model}/text-to-image"
 
22
  new_request_body = {
23
  "prompt": prompt,
24
  "image_size": "1024x1024",
 
27
  "guidance_scale": 1
28
  }
29
 
30
+ async with aiohttp.ClientSession() as session:
31
+ async with session.post(new_url, json=new_request_body, headers={
32
+ 'accept': 'application/json',
33
+ 'content-type': 'application/json',
34
+ 'Authorization': request.headers.get('Authorization')
35
+ }) as response:
36
+ response_body = await response.json()
 
37
 
38
  image_url = response_body['images'][0]['url']
39
+ unique_id = int(datetime.now().timestamp() * 1000)
40
+ current_timestamp = int(unique_id / 1000)
41
 
42
  if stream:
43
+ # 构造流式响应
44
  response_payload = {
45
  "id": unique_id,
46
  "object": "chat.completion.chunk",
 
57
  ]
58
  }
59
  data_string = json.dumps(response_payload)
60
+ return web.Response(text=f"data: {data_string}\n\n",
61
+ status=200,
62
+ content_type='text/event-stream')
63
  else:
64
+ # 构造非流响应
65
  response_payload = {
66
  "id": unique_id,
67
  "object": "chat.completion",
 
84
  "total_tokens": len(prompt) + len(image_url)
85
  }
86
  }
87
+ return web.json_response(response_payload)
88
+
89
+ except Exception as error:
90
+ return web.json_response({'error': f"Internal Server Error: {str(error)}"}, status=500)
91
+
92
+ app = web.Application()
93
+ app.router.add_post('/ai/v1/chat/completions', handle_chat_completions)
94
 
 
 
95
 
96
  if __name__ == '__main__':
97
+ web.run_app(app, port=8000)