tianlong12 commited on
Commit
7f3f885
·
verified ·
1 Parent(s): e3f15a1

Update app.py

Browse files
Files changed (1) hide show
  1. app.py +18 -56
app.py CHANGED
@@ -1,49 +1,16 @@
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
- import os
8
 
9
  app = Flask(__name__)
10
 
11
- # 解析JSON数据并创建代理池
12
- with open('proxy_list.json', 'r') as f:
13
- proxy_data = json.load(f)
14
-
15
- proxy_pool = {}
16
- for country, proxies in proxy_data['proxy_list'].items():
17
- proxy_pool[country] = [
18
- {
19
- 'url': f"{p['type'].lower()}://{p['host']}:{p['port']}",
20
- 'type': p['type'].lower()
21
- } for p in proxies
22
- ]
23
-
24
- def get_random_proxy(country=None):
25
- if country and country in proxy_pool:
26
- return random.choice(proxy_pool[country])
27
- else:
28
- all_proxies = [proxy for proxies in proxy_pool.values() for proxy in proxies]
29
- return random.choice(all_proxies)
30
-
31
- def make_request_with_proxy(method, url, **kwargs):
32
- proxy = get_random_proxy()
33
- proxies = {proxy['type']: proxy['url']}
34
-
35
- try:
36
- response = requests.request(method, url, proxies=proxies, timeout=30, **kwargs)
37
- response.raise_for_status()
38
- return response
39
- except requests.exceptions.RequestException as e:
40
- print(f"Error with proxy {proxy['url']}: {e}")
41
- return None
42
-
43
  def get_token():
44
  url = "https://fluxaiweb.com/flux/getToken"
45
- response = make_request_with_proxy('GET', url)
46
- if response and response.status_code == 200:
47
  response_json = response.json()
48
  return response_json.get("data", {}).get("token")
49
  return None
@@ -61,11 +28,14 @@ def req_flux(token, prompt_value, aspect_ratio="1:1", output_format="webp", num_
61
  'Content-Type': 'application/json',
62
  'token': token
63
  }
64
- response = make_request_with_proxy('POST', url, headers=headers, json=payload)
65
- if response:
 
66
  data = response.json()
67
  return data.get("data", {}).get("image")
68
- return None
 
 
69
 
70
  def generate_optimized_prompt(api_key, api_base, system_prompt, user_input):
71
  client = OpenAI(api_key=api_key, base_url=api_base)
@@ -101,35 +71,27 @@ def chat_completions():
101
  messages = data.get('messages', [])
102
  stream = data.get('stream', False)
103
 
 
104
  user_input = next((msg['content'] for msg in reversed(messages) if msg['role'] == 'user'), None)
105
 
106
  if not user_input:
107
  return Response(json.dumps({'error': 'No valid user input provided'}), status=400, mimetype='application/json')
108
 
 
 
109
  api_key = os.getenv('api_key')
110
  api_base = os.getenv('api_base')
111
  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."""
112
  optimized_prompt = generate_optimized_prompt(api_key, api_base, system_prompt, user_input)
113
 
114
- token = None
115
- for _ in range(3): # 尝试最多3次
116
- token = get_token()
117
- if token:
118
- break
119
- time.sleep(1) # 在重试之前等待1秒
120
-
121
  if not token:
122
- return Response(json.dumps({'error': 'Failed to get token after multiple attempts'}), status=500, mimetype='application/json')
123
 
124
- image_url = None
125
- for _ in range(3): # 尝试最多3次
126
- image_url = req_flux(token, optimized_prompt)
127
- if image_url:
128
- break
129
- time.sleep(1) # 在重试之前等待1秒
130
-
131
  if not image_url:
132
- return Response(json.dumps({'error': 'Failed to generate image after multiple attempts'}), status=500, mimetype='application/json')
133
 
134
  if stream:
135
  return Response(generate_fake_stream(image_url, optimized_prompt), mimetype='text/event-stream')
 
 
 
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 = requests.get(url)
13
+ if response.status_code == 200:
14
  response_json = response.json()
15
  return response_json.get("data", {}).get("token")
16
  return None
 
28
  'Content-Type': 'application/json',
29
  'token': token
30
  }
31
+ try:
32
+ response = requests.post(url, headers=headers, json=payload)
33
+ response.raise_for_status()
34
  data = response.json()
35
  return data.get("data", {}).get("image")
36
+ except requests.exceptions.RequestException as e:
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
  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
+ # Generate image using the optimized prompt
88
+ token = get_token()
 
 
 
 
 
89
  if not token:
90
+ return Response(json.dumps({'error': 'Failed to get token'}), status=500, mimetype='application/json')
91
 
92
+ image_url = req_flux(token, optimized_prompt)
 
 
 
 
 
 
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')