File size: 7,613 Bytes
3aed964 |
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 |
import asyncio
import json
import traceback
from .base import Backend
class AIDRAW(Backend):
def __init__(self, count, payload, **kwargs):
super().__init__(count=count, payload=payload, **kwargs)
self.xl = self.config.liblibai_setting['xl'][self.count]
self.flux = self.config.liblibai_setting['flux'][self.count]
site_name = 'LiblibAI_XL' if self.xl else 'LiblibAI'
self.model = f"{site_name} - {self.config.liblibai_setting['model_name'][self.count]}"
self.model_id = self.config.liblibai_setting['model'][self.count]
self.model_hash = "c7352c5d2f"
self.logger = self.setup_logger('[LiblibAI]')
token = self.config.liblibai[self.count]
self.token = token
self.backend_name = self.config.backend_name_list[4]
self.workload_name = f"{self.backend_name}-{token}"
async def heart_beat(self, id_):
self.logger.info(f"{id_}开始请求")
for i in range(60):
response = await self.http_request(
method="POST",
target_url=f"https://liblib-api.vibrou.com/gateway/sd-api/generate/progress/msg/v3/{id_}",
headers=self.headers,
content=json.dumps({"flag": 0}),
verify=False
)
# 检查请求结果并处理
if response.get('error') == "error":
self.logger.warning(f"Failed to request: {response}")
raise RuntimeError('服务器返回错误')
if response['code'] != 0 or response['data']['statusMsg'] == '执行异常':
raise RuntimeError('服务器返回错误')
images = response['data']['images']
if images is None:
self.logger.info(f"第{i+1}次心跳,未返回结果")
await asyncio.sleep(5)
continue
else:
# await self.set_backend_working_status(available=True)
for i in images:
if 'porn' in i['previewPath']:
self.nsfw_detected = True
self.logger.warning("API侧检测到NSFW图片")
else:
self.logger.img(f"图片url: {i['previewPath']}")
self.img_url.append(i['previewPath'])
self.comment = i['imageInfo']
break
async def update_progress(self):
# 覆写函数
pass
async def check_backend_usability(self):
pass
async def err_formating_to_sd_style(self):
if self.nsfw_detected:
await self.return_build_image()
else:
await self.download_img()
self.format_api_respond()
self.result = self.build_respond
async def posting(self):
if self.xl or self.flux:
if self.xl:
pre_tag, pre_ntag = tuple(self.config.liblibai_setting.get('preference')[self.count]['pretags']['xl'])
elif self.flux:
pre_tag, pre_ntag = tuple(self.config.liblibai_setting.get('preference')[self.count]['pretags']['flux'])
self.tags = pre_tag + self.tags
self.ntags = pre_ntag + self.ntags
if self.enable_hr:
self.width = int(self.width * self.hr_scale)
self.height = int(self.height * self.hr_scale)
self.enable_hr = False
elif self.width * self.height < 1048576:
self.width = int(self.width * 1.5)
self.height = int(self.height * 1.5)
self.steps = self.config.liblibai_setting.get('preference')[self.count].get('steps', 12)
if self.flux:
input_ = {
"checkpointId": 2295774,
"generateType": 17,
"frontCustomerReq": {
"windowId": "",
"tabType": "txt2img",
"conAndSegAndGen": "gen"
},
"adetailerEnable": 0,
"text2imgV3": {
"clipSkip": 2,
"checkPointName": 2295774,
"prompt": self.tags,
"negPrompt": self.ntags,
"seed": self.seed,
"randnSource": 0,
"samplingMethod": 31,
"imgCount": self.batch_size,
"samplingStep": self.steps,
"cfgScale": self.scale,
"width": self.width,
"height": self.height
},
"taskQueuePriority": 1
}
else:
input_ = {
"checkpointId": self.model_id,
"generateType": 1,
"frontCustomerReq": {
# "frontId": "f46f8e35-5728-4ded-b163-832c3b85009d",
"windowId": "",
"tabType": "txt2img",
"conAndSegAndGen": "gen"
}
,
"adetailerEnable": 0,
"text2img": {
"prompt": self.tags,
"negativePrompt": self.ntags,
"extraNetwork": "",
"samplingMethod": 0,
"samplingStep": self.steps,
"width": self.width,
"height": self.height,
"imgCount": self.batch_size,
"cfgScale": self.scale,
"seed": self.seed,
"seedExtra": 0,
"hiResFix": 0,
"restoreFaces": 0,
"tiling": 0,
"clipSkip": 2,
"randnSource": 0,
"tileDiffusion": None
}
,
"taskQueuePriority": 1
}
if self.enable_hr and self.flux is False and self.xl is False:
hr_payload = {
"hiresSteps": self.hr_second_pass_steps,
"denoisingStrength": self.denoising_strength,
"hiResFix": 1 if self.enable_hr else 0,
"hiResFixInfo": {
"upscaler": 6,
"upscaleBy": self.hr_scale,
"resizeWidth": int(self.width * self.hr_scale),
"resizeHeight": int(self.height * self.hr_scale)
}
}
input_['text2img'].update(hr_payload)
new_headers = {
"Accept": "application/json, text/plain, */*",
"Token": self.token
}
self.headers.update(new_headers)
response = await self.http_request(
method="POST",
target_url="https://liblib-api.vibrou.com/gateway/sd-api/generate/image",
headers=self.headers,
content=json.dumps(input_),
verify=False
)
# 检查请求结果
if response.get('error') == "error":
self.logger.warning(f"Failed to request: {response}")
else:
task = response
if task.get('msg') == 'Insufficient power':
self.logger.warning('费用不足!')
self.logger.info(f"API返回{task}")
task_id = task['data']
await self.heart_beat(task_id)
await self.err_formating_to_sd_style()
|