|
import os |
|
import time |
|
|
|
import requests |
|
from extensions.openai.errors import ServiceUnavailableError |
|
|
|
|
|
def generations(prompt: str, size: str, response_format: str, n: int): |
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
base_model_size = 512 if 'SD_BASE_MODEL_SIZE' not in os.environ else int(os.environ.get('SD_BASE_MODEL_SIZE', 512)) |
|
sd_defaults = { |
|
'sampler_name': 'DPM++ 2M Karras', |
|
'steps': 30, |
|
} |
|
|
|
width, height = [int(x) for x in size.split('x')] |
|
|
|
|
|
payload = { |
|
'prompt': prompt, |
|
'width': width, |
|
'height': height, |
|
'batch_size': n, |
|
} |
|
payload.update(sd_defaults) |
|
|
|
scale = min(width, height) / base_model_size |
|
if scale >= 1.2: |
|
|
|
scaler = { |
|
'width': width // scale, |
|
'height': height // scale, |
|
'hr_scale': scale, |
|
'enable_hr': True, |
|
'hr_upscaler': 'Latent', |
|
'denoising_strength': 0.68, |
|
} |
|
payload.update(scaler) |
|
|
|
resp = { |
|
'created': int(time.time()), |
|
'data': [] |
|
} |
|
from extensions.openai.script import params |
|
|
|
|
|
sd_url = f"{os.environ.get('SD_WEBUI_URL', params.get('sd_webui_url', ''))}/sdapi/v1/txt2img" |
|
|
|
response = requests.post(url=sd_url, json=payload) |
|
r = response.json() |
|
if response.status_code != 200 or 'images' not in r: |
|
print(r) |
|
raise ServiceUnavailableError(r.get('error', 'Unknown error calling Stable Diffusion'), code=response.status_code, internal_message=r.get('errors', None)) |
|
|
|
for b64_json in r['images']: |
|
if response_format == 'b64_json': |
|
resp['data'].extend([{'b64_json': b64_json}]) |
|
else: |
|
resp['data'].extend([{'url': f'data:image/png;base64,{b64_json}'}]) |
|
|
|
return resp |
|
|