smgc commited on
Commit
83608e4
1 Parent(s): 4edac9e

Update app.py

Browse files
Files changed (1) hide show
  1. app.py +73 -36
app.py CHANGED
@@ -3,13 +3,60 @@ import requests
3
  import json
4
  import time
5
  import random
6
- import logging
7
 
8
  app = Flask(__name__)
9
 
10
- # 配置日志格式
11
- logging.basicConfig(level=logging.INFO, format='%(asctime)s - %(message)s')
12
- logger = logging.getLogger(__name__)
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
13
 
14
  @app.route('/')
15
  def index():
@@ -22,45 +69,40 @@ def handle_request():
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
  return jsonify({"error": "Bad Request: Missing required fields"}), 400
28
-
29
- authorization_header = request.headers.get('Authorization')
30
- if not authorization_header:
31
- return jsonify({"error": "Unauthorized: Missing Authorization header"}), 401
32
-
33
- # Extract tokens from Authorization header
34
- tokens = authorization_header.split(' ')[1].split(',')
35
- if len(tokens) == 1:
36
- selected_token = tokens[0]
37
- else:
38
- selected_token = random.choice(tokens)
39
-
40
  prompt = messages[-1]['content']
 
 
 
 
 
 
 
 
 
41
  new_url = f'https://api.siliconflow.cn/v1/{model}/text-to-image'
42
-
43
  new_request_body = {
44
- "prompt": prompt,
45
  "image_size": "1024x1024",
46
  "batch_size": 1,
47
  "num_inference_steps": 4,
48
  "guidance_scale": 1
49
  }
50
-
51
  headers = {
52
  'accept': 'application/json',
53
  'content-type': 'application/json',
54
- 'Authorization': f'Bearer {selected_token}'
55
  }
56
-
57
  response = requests.post(new_url, headers=headers, json=new_request_body)
58
  response_body = response.json()
59
-
60
  image_url = response_body['images'][0]['url']
61
- unique_id = str(int(time.time() * 1000)) # Convert id to string
62
- current_timestamp = int(unique_id) // 1000
63
-
64
  if stream:
65
  response_payload = {
66
  "id": unique_id,
@@ -71,7 +113,7 @@ def handle_request():
71
  {
72
  "index": 0,
73
  "delta": {
74
- "content": f"![]({image_url})"
75
  },
76
  "finish_reason": "stop"
77
  }
@@ -90,7 +132,7 @@ def handle_request():
90
  "index": 0,
91
  "message": {
92
  "role": "assistant",
93
- "content": f"![]({image_url})"
94
  },
95
  "logprobs": None,
96
  "finish_reason": "length"
@@ -98,19 +140,14 @@ def handle_request():
98
  ],
99
  "usage": {
100
  "prompt_tokens": len(prompt),
101
- "completion_tokens": len(image_url),
102
- "total_tokens": len(prompt) + len(image_url)
103
  }
104
  }
105
  data_string = json.dumps(response_payload)
106
  return Response(f"{data_string}\n\n", content_type='text/event-stream')
107
-
108
  except Exception as e:
109
  return jsonify({"error": f"Internal Server Error: {str(e)}"}), 500
110
 
111
- finally:
112
- # 记录请求的 model 和 被命中的 token
113
- logger.info(f'"POST /ai/v1/chat/completions HTTP/1.1" "model: {model}" "token: {selected_token}" "status: {response.status_code}" -')
114
-
115
  if __name__ == '__main__':
116
- app.run(host='0.0.0.0', port=8000)
 
3
  import json
4
  import time
5
  import random
 
6
 
7
  app = Flask(__name__)
8
 
9
+ SYSTEM_ASSISTANT = """作为 Stable Diffusion Prompt 提示词专家,您将从关键词中创建提示,通常来自 Danbooru 等数据库。
10
+ 提示通常描述图像,使用常见词汇,按重要性排列,并用逗号分隔。避免使用"-"或".",但可以接受空格和自然语言。避免词汇重复。
11
+
12
+ 为了强调关键词,请将其放在括号中以增加其权重。例如,"(flowers)"将'flowers'的权重增加1.1倍,而"(((flowers)))"将其增加1.331倍。使用"(flowers:1.5)"将'flowers'的权重增加1.5倍。只为重要的标签增加权重。
13
+
14
+ 提示包括三个部分:**前缀** (质量标签+风格词+效果器)+ **主题** (图像的主要焦点)+ **场景** (背景、环境)。
15
+
16
+ * 前缀影响图像质量。像"masterpiece"、"best quality"、"4k"这样的标签可以提高图像的细节。像"illustration"、"lensflare"这样的风格词定义图像的风格。像"bestlighting"、"lensflare"、"depthoffield"这样的效果器会影响光照和深度。
17
+
18
+ * 主题是图像的主要焦点,如角色或场景。对主题进行详细描述可以确保图像丰富而详细。增加主题的权重以增强其清晰度。对于角色,描述面部、头发、身体、服装、姿势等特征。
19
+
20
+ * 场景描述环境。没有场景,图像的背景是平淡的,主题显得过大。某些主题本身包含场景(例如建筑物、风景)。像"花草草地"、"阳光"、"河流"这样的环境词可以丰富场景。你的任务是设计图像生成的提示。请按照以下步骤进行操作:
21
+
22
+ 1. 我会发送给您一个图像场景。需要你生成详细的图像描述
23
+ 2. 图像描述必须是英文,输出为Positive Prompt。
24
+
25
+ 示例:
26
+
27
+ 我发送:二战时期的护士。
28
+ 您回复只回复:
29
+ A WWII-era nurse in a German uniform, holding a wine bottle and stethoscope, sitting at a table in white attire, with a table in the background, masterpiece, best quality, 4k, illustration style, best lighting, depth of field, detailed character, detailed environment.
30
+ """
31
+
32
+ def get_random_token(auth_header):
33
+ if not auth_header:
34
+ return None
35
+ if auth_header.startswith('Bearer '):
36
+ auth_header = auth_header[7:]
37
+ tokens = [token.strip() for token in auth_header.split(',') if token.strip()]
38
+ if not tokens:
39
+ return None
40
+ return f"Bearer {random.choice(tokens)}"
41
+
42
+ def translate_and_enhance_prompt(prompt, auth_token):
43
+ translate_url = 'https://api.siliconflow.cn/v1/chat/completions'
44
+ translate_body = {
45
+ 'model': 'Qwen/Qwen2-72B-Instruct',
46
+ 'messages': [
47
+ {'role': 'system', 'content': SYSTEM_ASSISTANT},
48
+ {'role': 'user', 'content': prompt}
49
+ ]
50
+ }
51
+ headers = {
52
+ 'Content-Type': 'application/json',
53
+ 'Authorization': auth_token
54
+ }
55
+ response = requests.post(translate_url, headers=headers, json=translate_body)
56
+ if response.status_code != 200:
57
+ raise Exception(f'Translation error: {response.status_code}')
58
+ result = response.json()
59
+ return result['choices'][0]['message']['content']
60
 
61
  @app.route('/')
62
  def index():
 
69
  model = body.get('model')
70
  messages = body.get('messages')
71
  stream = body.get('stream', False)
 
72
  if not model or not messages or len(messages) == 0:
73
  return jsonify({"error": "Bad Request: Missing required fields"}), 400
74
+
 
 
 
 
 
 
 
 
 
 
 
75
  prompt = messages[-1]['content']
76
+
77
+ # 获取随机token
78
+ random_token = get_random_token(request.headers.get('Authorization'))
79
+ if not random_token:
80
+ return jsonify({"error": "Unauthorized: Invalid or missing Authorization header"}), 401
81
+
82
+ # 翻译并增强prompt
83
+ enhanced_prompt = translate_and_enhance_prompt(prompt, random_token)
84
+
85
  new_url = f'https://api.siliconflow.cn/v1/{model}/text-to-image'
 
86
  new_request_body = {
87
+ "prompt": enhanced_prompt,
88
  "image_size": "1024x1024",
89
  "batch_size": 1,
90
  "num_inference_steps": 4,
91
  "guidance_scale": 1
92
  }
93
+
94
  headers = {
95
  'accept': 'application/json',
96
  'content-type': 'application/json',
97
+ 'Authorization': random_token
98
  }
99
+
100
  response = requests.post(new_url, headers=headers, json=new_request_body)
101
  response_body = response.json()
 
102
  image_url = response_body['images'][0]['url']
103
+ unique_id = int(time.time() * 1000)
104
+ current_timestamp = unique_id // 1000
105
+
106
  if stream:
107
  response_payload = {
108
  "id": unique_id,
 
113
  {
114
  "index": 0,
115
  "delta": {
116
+ "content": f"原始提示词:{prompt}\n增强后的提示词:{enhanced_prompt}\n生成的图像:\n![]({image_url})"
117
  },
118
  "finish_reason": "stop"
119
  }
 
132
  "index": 0,
133
  "message": {
134
  "role": "assistant",
135
+ "content": f"原始提示词:{prompt}\n增强后的提示词:{enhanced_prompt}\n生成的图像:\n![]({image_url})"
136
  },
137
  "logprobs": None,
138
  "finish_reason": "length"
 
140
  ],
141
  "usage": {
142
  "prompt_tokens": len(prompt),
143
+ "completion_tokens": len(enhanced_prompt) + len(image_url),
144
+ "total_tokens": len(prompt) + len(enhanced_prompt) + len(image_url)
145
  }
146
  }
147
  data_string = json.dumps(response_payload)
148
  return Response(f"{data_string}\n\n", content_type='text/event-stream')
 
149
  except Exception as e:
150
  return jsonify({"error": f"Internal Server Error: {str(e)}"}), 500
151
 
 
 
 
 
152
  if __name__ == '__main__':
153
+ app.run(host='0.0.0.0', port=8000)