Update app.py
Browse files
app.py
CHANGED
@@ -5,6 +5,7 @@ import time
|
|
5 |
import random
|
6 |
import logging
|
7 |
import sys
|
|
|
8 |
|
9 |
app = Flask(__name__)
|
10 |
|
@@ -133,60 +134,115 @@ def handle_request():
|
|
133 |
|
134 |
response.raise_for_status()
|
135 |
response_body = response.json()
|
136 |
-
|
|
|
|
|
|
|
|
|
|
|
|
|
137 |
except requests.exceptions.RequestException as e:
|
138 |
logger.error(f"Error in image generation request: {str(e)}")
|
139 |
return jsonify({"error": "Failed to generate image"}), 500
|
|
|
|
|
|
|
140 |
|
141 |
unique_id = int(time.time() * 1000)
|
142 |
current_timestamp = unique_id // 1000
|
|
|
|
|
|
|
143 |
|
144 |
if stream:
|
145 |
-
|
146 |
-
"id": unique_id,
|
147 |
-
"object": "chat.completion.chunk",
|
148 |
-
"created": current_timestamp,
|
149 |
-
"model": model,
|
150 |
-
"choices": [
|
151 |
-
{
|
152 |
-
"index": 0,
|
153 |
-
"delta": {
|
154 |
-
"content": f"原始提示词:{prompt}\n增强后的提示词:{enhanced_prompt}\n生成的图像:\n"
|
155 |
-
},
|
156 |
-
"finish_reason": "stop"
|
157 |
-
}
|
158 |
-
]
|
159 |
-
}
|
160 |
-
data_string = json.dumps(response_payload)
|
161 |
-
return Response(f"data: {data_string}\n\n", content_type='text/event-stream')
|
162 |
else:
|
163 |
-
|
164 |
-
"id": unique_id,
|
165 |
-
"object": "chat.completion",
|
166 |
-
"created": current_timestamp,
|
167 |
-
"model": model,
|
168 |
-
"choices": [
|
169 |
-
{
|
170 |
-
"index": 0,
|
171 |
-
"message": {
|
172 |
-
"role": "assistant",
|
173 |
-
"content": f"原始提示词:{prompt}\n增强后的提示词:{enhanced_prompt}\n生成的图像:\n"
|
174 |
-
},
|
175 |
-
"logprobs": None,
|
176 |
-
"finish_reason": "length"
|
177 |
-
}
|
178 |
-
],
|
179 |
-
"usage": {
|
180 |
-
"prompt_tokens": len(prompt),
|
181 |
-
"completion_tokens": len(enhanced_prompt) + len(image_url),
|
182 |
-
"total_tokens": len(prompt) + len(enhanced_prompt) + len(image_url)
|
183 |
-
}
|
184 |
-
}
|
185 |
-
data_string = json.dumps(response_payload)
|
186 |
-
return Response(f"{data_string}\n\n", content_type='text/event-stream')
|
187 |
except Exception as e:
|
188 |
logger.error(f"Unexpected error in handle_request: {str(e)}")
|
189 |
return jsonify({"error": f"Internal Server Error: {str(e)}"}), 500
|
190 |
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
191 |
if __name__ == '__main__':
|
192 |
app.run(host='0.0.0.0', port=8000)
|
|
|
5 |
import random
|
6 |
import logging
|
7 |
import sys
|
8 |
+
import asyncio
|
9 |
|
10 |
app = Flask(__name__)
|
11 |
|
|
|
134 |
|
135 |
response.raise_for_status()
|
136 |
response_body = response.json()
|
137 |
+
|
138 |
+
if 'images' in response_body and response_body['images'] and 'url' in response_body['images'][0]:
|
139 |
+
image_url = response_body['images'][0]['url']
|
140 |
+
logger.info(f"Successfully retrieved image URL: {image_url}")
|
141 |
+
else:
|
142 |
+
logger.error(f"Unexpected response structure: {response_body}")
|
143 |
+
return jsonify({"error": "Unexpected response structure from image generation API"}), 500
|
144 |
except requests.exceptions.RequestException as e:
|
145 |
logger.error(f"Error in image generation request: {str(e)}")
|
146 |
return jsonify({"error": "Failed to generate image"}), 500
|
147 |
+
except (KeyError, IndexError, ValueError) as e:
|
148 |
+
logger.error(f"Error parsing image generation response: {str(e)}")
|
149 |
+
return jsonify({"error": "Failed to parse image generation response"}), 500
|
150 |
|
151 |
unique_id = int(time.time() * 1000)
|
152 |
current_timestamp = unique_id // 1000
|
153 |
+
system_fingerprint = "fp_" + ''.join(random.choices('abcdefghijklmnopqrstuvwxyz0123456789', k=9))
|
154 |
+
|
155 |
+
image_data = {'data': [{'url': image_url}]}
|
156 |
|
157 |
if stream:
|
158 |
+
return stream_response(request, unique_id, image_data, prompt, enhanced_prompt, "1024x1024", current_timestamp, model, system_fingerprint)
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
159 |
else:
|
160 |
+
return non_stream_response(unique_id, image_data, prompt, enhanced_prompt, "1024x1024", current_timestamp, model, system_fingerprint)
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
161 |
except Exception as e:
|
162 |
logger.error(f"Unexpected error in handle_request: {str(e)}")
|
163 |
return jsonify({"error": f"Internal Server Error: {str(e)}"}), 500
|
164 |
|
165 |
+
def stream_response(request, unique_id, image_data, original_prompt, translated_prompt, size, created, model, system_fingerprint):
|
166 |
+
logger.debug("Starting stream response")
|
167 |
+
response = Response(stream_with_context(generate_stream(unique_id, image_data, original_prompt, translated_prompt, size, created, model, system_fingerprint)), content_type='text/event-stream')
|
168 |
+
logger.debug("Stream response completed")
|
169 |
+
return response
|
170 |
+
|
171 |
+
def generate_stream(unique_id, image_data, original_prompt, translated_prompt, size, created, model, system_fingerprint):
|
172 |
+
chunks = [
|
173 |
+
f"原始提示词:\n{original_prompt}\n",
|
174 |
+
f"翻译后的提示词:\n{translated_prompt}\n",
|
175 |
+
f"图像规格:{size}\n",
|
176 |
+
"正在根据提示词生成图像...\n",
|
177 |
+
"图像正在处理中...\n",
|
178 |
+
"即将完成...\n",
|
179 |
+
f"生成成功!\n图像生成完毕,以下是结果:\n\n"
|
180 |
+
]
|
181 |
+
|
182 |
+
for i, chunk in enumerate(chunks):
|
183 |
+
json_chunk = json.dumps({
|
184 |
+
"id": unique_id,
|
185 |
+
"object": "chat.completion.chunk",
|
186 |
+
"created": created,
|
187 |
+
"model": model,
|
188 |
+
"system_fingerprint": system_fingerprint,
|
189 |
+
"choices": [{
|
190 |
+
"index": 0,
|
191 |
+
"delta": {"content": chunk},
|
192 |
+
"logprobs": None,
|
193 |
+
"finish_reason": None
|
194 |
+
}]
|
195 |
+
})
|
196 |
+
yield f"data: {json_chunk}\n\n"
|
197 |
+
time.sleep(0.5) # 模拟生成时间
|
198 |
+
|
199 |
+
final_chunk = json.dumps({
|
200 |
+
"id": unique_id,
|
201 |
+
"object": "chat.completion.chunk",
|
202 |
+
"created": created,
|
203 |
+
"model": model,
|
204 |
+
"system_fingerprint": system_fingerprint,
|
205 |
+
"choices": [{
|
206 |
+
"index": 0,
|
207 |
+
"delta": {},
|
208 |
+
"logprobs": None,
|
209 |
+
"finish_reason": "stop"
|
210 |
+
}]
|
211 |
+
})
|
212 |
+
yield f"data: {final_chunk}\n\n"
|
213 |
+
|
214 |
+
def non_stream_response(unique_id, image_data, original_prompt, translated_prompt, size, created, model, system_fingerprint):
|
215 |
+
content = (
|
216 |
+
f"原始提示词:{original_prompt}\n"
|
217 |
+
f"翻译后的提示词:{translated_prompt}\n"
|
218 |
+
f"图像规格:{size}\n"
|
219 |
+
f"图像生成成功!\n"
|
220 |
+
f"以下是结果:\n\n"
|
221 |
+
f""
|
222 |
+
)
|
223 |
+
|
224 |
+
response = {
|
225 |
+
'id': unique_id,
|
226 |
+
'object': "chat.completion",
|
227 |
+
'created': created,
|
228 |
+
'model': model,
|
229 |
+
'system_fingerprint': system_fingerprint,
|
230 |
+
'choices': [{
|
231 |
+
'index': 0,
|
232 |
+
'message': {
|
233 |
+
'role': "assistant",
|
234 |
+
'content': content
|
235 |
+
},
|
236 |
+
'finish_reason': "stop"
|
237 |
+
}],
|
238 |
+
'usage': {
|
239 |
+
'prompt_tokens': len(original_prompt),
|
240 |
+
'completion_tokens': len(content),
|
241 |
+
'total_tokens': len(original_prompt) + len(content)
|
242 |
+
}
|
243 |
+
}
|
244 |
+
|
245 |
+
return jsonify(response)
|
246 |
+
|
247 |
if __name__ == '__main__':
|
248 |
app.run(host='0.0.0.0', port=8000)
|