Spaces:
Paused
Paused
Update app.py
Browse files
app.py
CHANGED
@@ -1,16 +1,48 @@
|
|
|
|
|
|
1 |
from flask import Flask, request, Response
|
2 |
-
import os
|
3 |
import requests
|
4 |
-
import json
|
5 |
import time
|
6 |
from openai import OpenAI
|
7 |
|
8 |
app = Flask(__name__)
|
9 |
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
10 |
def get_token():
|
11 |
url = "https://fluxaiweb.com/flux/getToken"
|
12 |
-
response =
|
13 |
-
if response.status_code == 200:
|
14 |
response_json = response.json()
|
15 |
return response_json.get("data", {}).get("token")
|
16 |
return None
|
@@ -28,14 +60,11 @@ def req_flux(token, prompt_value, aspect_ratio="1:1", output_format="webp", num_
|
|
28 |
'Content-Type': 'application/json',
|
29 |
'token': token
|
30 |
}
|
31 |
-
|
32 |
-
|
33 |
-
response.raise_for_status()
|
34 |
data = response.json()
|
35 |
return data.get("data", {}).get("image")
|
36 |
-
|
37 |
-
print(f"Error making request: {e}")
|
38 |
-
return None
|
39 |
|
40 |
def generate_optimized_prompt(api_key, api_base, system_prompt, user_input):
|
41 |
client = OpenAI(api_key=api_key, base_url=api_base)
|
@@ -71,27 +100,35 @@ def chat_completions():
|
|
71 |
messages = data.get('messages', [])
|
72 |
stream = data.get('stream', False)
|
73 |
|
74 |
-
# Extract the prompt from the last user message
|
75 |
user_input = next((msg['content'] for msg in reversed(messages) if msg['role'] == 'user'), None)
|
76 |
|
77 |
if not user_input:
|
78 |
return Response(json.dumps({'error': 'No valid user input provided'}), status=400, mimetype='application/json')
|
79 |
|
80 |
-
# Generate optimized prompt using GPT-4-mini
|
81 |
-
#api_key变量从环境变量获取
|
82 |
api_key = os.getenv('api_key')
|
83 |
api_base = os.getenv('api_base')
|
84 |
system_prompt = """作为 Stable Diffusion Prompt 提示词专家,您将从关键词中创建提示,通常来自 Danbooru 等数据库。提示通常描述图像,使用常见词汇,按重要性排列,并用逗号分隔。避免使用"-"或".",但可以接受空格和自然语言。避免词汇重复。为了强调关键词,请将其放在括号中以增加其权重。例如,"(flowers)"将'flowers'的权重增加1.1倍,而"(((flowers)))"将其增加1.331倍。使用"(flowers:1.5)"将'flowers'的权重增加1.5倍。只为重要的标签增加权重。提示包括三个部分:前缀(质量标签+风格词+效果器)+ 主题(图像的主要焦点)+ 场景(背景、环境)。前缀影响图像质量。像"masterpiece"、"best quality"、"ultra-detailed"、"high resolution"、"photorealistic" 这样的标签可以显著提高图像的细节和整体质量。像"illustration"、"lensflare"、"cinematic lighting" 这样的风格词定义图像的风格和光影效果。像"best lighting"、"volumetric lighting"、"depth of field" 这样的效果器会影响光照和深度。主题是图像的主要焦点,如角色或场景。对主题进行详细描述可以确保图像丰富而详细。增加主题的权重以增强其清晰度。对于角色,描述面部、头发、身体、服装、姿势等特征,同时加入细致的纹理和高光处理。场景描述环境。没有场景,图像的背景是平淡的,主题显得过大。某些主题本身包含场景(例如建筑物、风景)。像"lush greenery"、"golden sunlight"、"crystal clear river" 这样的环境词可以丰富场景,并增强其视觉吸引力。考虑添加天气效果,如"soft morning mist"、"sunset glow" 来进一步增强场景的氛围。你的任务是设计图像生成的提示。请按照以下步骤进行操作:我会发送给您一个图像场景。需要你生成详细的图像描述。图像描述必须是英文,输出为Positive Prompt。确保提示词仅用于描述图像内容,不包含会显示在图像中的文本。示例:我发送:二战时期的护士。您回复只回复: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, ultra-detailed, high resolution, photorealistic, illustration style, best lighting, volumetric lighting, depth of field, sharp focus, detailed character, richly textured environment."""
|
85 |
optimized_prompt = generate_optimized_prompt(api_key, api_base, system_prompt, user_input)
|
86 |
|
87 |
-
|
88 |
-
|
|
|
|
|
|
|
|
|
|
|
89 |
if not token:
|
90 |
-
return Response(json.dumps({'error': 'Failed to get token'}), status=500, mimetype='application/json')
|
91 |
|
92 |
-
image_url =
|
|
|
|
|
|
|
|
|
|
|
|
|
93 |
if not image_url:
|
94 |
-
return Response(json.dumps({'error': 'Failed to generate image'}), status=500, mimetype='application/json')
|
95 |
|
96 |
if stream:
|
97 |
return Response(generate_fake_stream(image_url, optimized_prompt), mimetype='text/event-stream')
|
|
|
1 |
+
import json
|
2 |
+
import random
|
3 |
from flask import Flask, request, Response
|
|
|
4 |
import requests
|
|
|
5 |
import time
|
6 |
from openai import OpenAI
|
7 |
|
8 |
app = Flask(__name__)
|
9 |
|
10 |
+
# 解析JSON数据并创建代理池
|
11 |
+
with open('proxy_list.json', 'r') as f:
|
12 |
+
proxy_data = json.load(f)
|
13 |
+
|
14 |
+
proxy_pool = {}
|
15 |
+
for country, proxies in proxy_data['proxy_list'].items():
|
16 |
+
proxy_pool[country] = [
|
17 |
+
{
|
18 |
+
'url': f"{p['type'].lower()}://{p['host']}:{p['port']}",
|
19 |
+
'type': p['type'].lower()
|
20 |
+
} for p in proxies
|
21 |
+
]
|
22 |
+
|
23 |
+
def get_random_proxy(country=None):
|
24 |
+
if country and country in proxy_pool:
|
25 |
+
return random.choice(proxy_pool[country])
|
26 |
+
else:
|
27 |
+
all_proxies = [proxy for proxies in proxy_pool.values() for proxy in proxies]
|
28 |
+
return random.choice(all_proxies)
|
29 |
+
|
30 |
+
def make_request_with_proxy(method, url, **kwargs):
|
31 |
+
proxy = get_random_proxy()
|
32 |
+
proxies = {proxy['type']: proxy['url']}
|
33 |
+
|
34 |
+
try:
|
35 |
+
response = requests.request(method, url, proxies=proxies, timeout=30, **kwargs)
|
36 |
+
response.raise_for_status()
|
37 |
+
return response
|
38 |
+
except requests.exceptions.RequestException as e:
|
39 |
+
print(f"Error with proxy {proxy['url']}: {e}")
|
40 |
+
return None
|
41 |
+
|
42 |
def get_token():
|
43 |
url = "https://fluxaiweb.com/flux/getToken"
|
44 |
+
response = make_request_with_proxy('GET', url)
|
45 |
+
if response and response.status_code == 200:
|
46 |
response_json = response.json()
|
47 |
return response_json.get("data", {}).get("token")
|
48 |
return None
|
|
|
60 |
'Content-Type': 'application/json',
|
61 |
'token': token
|
62 |
}
|
63 |
+
response = make_request_with_proxy('POST', url, headers=headers, json=payload)
|
64 |
+
if response:
|
|
|
65 |
data = response.json()
|
66 |
return data.get("data", {}).get("image")
|
67 |
+
return None
|
|
|
|
|
68 |
|
69 |
def generate_optimized_prompt(api_key, api_base, system_prompt, user_input):
|
70 |
client = OpenAI(api_key=api_key, base_url=api_base)
|
|
|
100 |
messages = data.get('messages', [])
|
101 |
stream = data.get('stream', False)
|
102 |
|
|
|
103 |
user_input = next((msg['content'] for msg in reversed(messages) if msg['role'] == 'user'), None)
|
104 |
|
105 |
if not user_input:
|
106 |
return Response(json.dumps({'error': 'No valid user input provided'}), status=400, mimetype='application/json')
|
107 |
|
|
|
|
|
108 |
api_key = os.getenv('api_key')
|
109 |
api_base = os.getenv('api_base')
|
110 |
system_prompt = """作为 Stable Diffusion Prompt 提示词专家,您将从关键词中创建提示,通常来自 Danbooru 等数据库。提示通常描述图像,使用常见词汇,按重要性排列,并用逗号分隔。避免使用"-"或".",但可以接受空格和自然语言。避免词汇重复。为了强调关键词,请将其放在括号中以增加其权重。例如,"(flowers)"将'flowers'的权重增加1.1倍,而"(((flowers)))"将其增加1.331倍。使用"(flowers:1.5)"将'flowers'的权重增加1.5倍。只为重要的标签增加权重。提示包括三个部分:前缀(质量标签+风格词+效果器)+ 主题(图像的主要焦点)+ 场景(背景、环境)。前缀影响图像质量。像"masterpiece"、"best quality"、"ultra-detailed"、"high resolution"、"photorealistic" 这样的标签可以显著提高图像的细节和整体质量。像"illustration"、"lensflare"、"cinematic lighting" 这样的风格词定义图像的风格和光影效果。像"best lighting"、"volumetric lighting"、"depth of field" 这样的效果器会影响光照和深度。主题是图像的主要焦点,如角色或场景。对主题进行详细描述可以确保图像丰富而详细。增加主题的权重以增强其清晰度。对于角色,描述面部、头发、身体、服装、姿势等特征,同时加入细致的纹理和高光处理。场景描述环境。没有场景,图像的背景是平淡的,主题显得过大。某些主题本身包含场景(例如建筑物、风景)。像"lush greenery"、"golden sunlight"、"crystal clear river" 这样的环境词可以丰富场景,并增强其视觉吸引力。考虑添加天气效果,如"soft morning mist"、"sunset glow" 来进一步增强场景的氛围。你的任务是设计图像生成的提示。请按照以下步骤进行操作:我会发送给您一个图像场景。需要你生成详细的图像描述。图像描述必须是英文,输出为Positive Prompt。确保提示词仅用于描述图像内容,不包含会显示在图像中的文本。示例:我发送:二战时期的护士。您回复只回复: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, ultra-detailed, high resolution, photorealistic, illustration style, best lighting, volumetric lighting, depth of field, sharp focus, detailed character, richly textured environment."""
|
111 |
optimized_prompt = generate_optimized_prompt(api_key, api_base, system_prompt, user_input)
|
112 |
|
113 |
+
token = None
|
114 |
+
for _ in range(3): # 尝试最多3次
|
115 |
+
token = get_token()
|
116 |
+
if token:
|
117 |
+
break
|
118 |
+
time.sleep(1) # 在重试之前等待1秒
|
119 |
+
|
120 |
if not token:
|
121 |
+
return Response(json.dumps({'error': 'Failed to get token after multiple attempts'}), status=500, mimetype='application/json')
|
122 |
|
123 |
+
image_url = None
|
124 |
+
for _ in range(3): # 尝试最多3次
|
125 |
+
image_url = req_flux(token, optimized_prompt)
|
126 |
+
if image_url:
|
127 |
+
break
|
128 |
+
time.sleep(1) # 在重试之前等待1秒
|
129 |
+
|
130 |
if not image_url:
|
131 |
+
return Response(json.dumps({'error': 'Failed to generate image after multiple attempts'}), status=500, mimetype='application/json')
|
132 |
|
133 |
if stream:
|
134 |
return Response(generate_fake_stream(image_url, optimized_prompt), mimetype='text/event-stream')
|