mirror of
https://github.com/leejet/stable-diffusion.cpp.git
synced 2026-11-29 03:26:12 +00:00
A request that ran the machine out of memory ended in a 500 and left the
server on the configuration that had just failed, so every later request
of that size failed the same way. The context now belongs to a
ContextKeeper (examples/server/recovery.*) and every generation of the
OpenAI, sdapi and sdcpp endpoints goes through ContextKeeper::run().
On out_of_memory or backend (the codes of sd_get_last_error()) it frees
the model, loads it again with the next lighter profile of
max > balanced > lite > lite-disk > lite-cpu and runs the same request
again. Steps that would load the same configuration are skipped, a
device failure jumps to lite-cpu, and from lite on the VAE is decoded in
tiles whatever the request asked. --profile sets the top of the ladder.
After --degradation-cooldown seconds (300; 0 = never) the server climbs
back one profile at the start of the next request. A climb that fails
on its first use is undone and doubles the wait, up to an hour. If the
model cannot be loaded again, requests get 503 "unavailable" and the
load is retried no more than every 15 seconds. --disable-degradation
keeps the old behavior of answering with the error.
Failures are answered with 503 and Retry-After (out of memory, no
context), 400 (invalid_argument) or 500, with a body of
{"error", "code", "retry_after_seconds"}. Async jobs report the same
code in error.code, 429 carries Retry-After, and std::bad_alloc in a
handler becomes a 503. New endpoints: GET /sdcpp/v1/health (status,
profile, counters, last error, queue; it never waits for a running
generation) and GET /sdcpp/v1/resources (system memory and devices).
sd-server now exits with code 1 and a message when it cannot listen or
create its HTTP threads; the second used to end in std::terminate and
the first in a silent exit 0. The lite-disk profile clears --eager-load,
which read every weight into memory and so saved nothing.
test/server_recovery_test.cpp checks the ladder, the step downs, the
climb back, the reload after a failure, the HTTP answers and use from
several threads with a scripted library and clock (114 checks, also
under ASan/UBSan and TSan). Checked with a synthetic SD 1.5 model on
the CPU under address-space limits: a 384x384 request at 2400 MiB steps
down to lite-disk and succeeds, below 2200 MiB it answers 503 and the
server stays up, the climb back and a failed climb behave as described,
and nine parallel requests of the three kinds are all served. The server
and the whole engine built with ASan/UBSan went through the ladder, the
CPU memory-guard scenarios and injected read errors without a report.
Not checked: Windows, GPUs, real models.
Claude-Session: https://claude.ai/code/session_01EhZzDBkuuMp1jBf4WtEySC
883 lines
36 KiB
C++
883 lines
36 KiB
C++
#include "routes.h"
|
|
|
|
#include <algorithm>
|
|
#include <cmath>
|
|
#include <filesystem>
|
|
#include <limits>
|
|
#include <new>
|
|
|
|
#include "async_jobs.h"
|
|
#include "common/common.h"
|
|
#include "common/media_io.h"
|
|
#include "common/resource_owners.hpp"
|
|
|
|
namespace fs = std::filesystem;
|
|
|
|
static constexpr uint32_t k_max_upscale_dimension = 8192;
|
|
|
|
static bool valid_upscale_dimensions(const sd_image_t& image, int factor, int repeats) {
|
|
if (image.width == 0 || image.height == 0 || factor < 1 || repeats < 1 || repeats > 4) {
|
|
return false;
|
|
}
|
|
uint32_t width = image.width;
|
|
uint32_t height = image.height;
|
|
for (int i = 0; i < repeats; ++i) {
|
|
if (width > k_max_upscale_dimension / factor || height > k_max_upscale_dimension / factor) {
|
|
return false;
|
|
}
|
|
width *= factor;
|
|
height *= factor;
|
|
}
|
|
return true;
|
|
}
|
|
|
|
static bool parse_cache_mode(const std::string& mode_str, sd_cache_mode_t& mode_out) {
|
|
if (mode_str == "disabled") {
|
|
mode_out = SD_CACHE_DISABLED;
|
|
return true;
|
|
}
|
|
if (mode_str == "easycache") {
|
|
mode_out = SD_CACHE_EASYCACHE;
|
|
return true;
|
|
}
|
|
if (mode_str == "ucache") {
|
|
mode_out = SD_CACHE_UCACHE;
|
|
return true;
|
|
}
|
|
if (mode_str == "dbcache") {
|
|
mode_out = SD_CACHE_DBCACHE;
|
|
return true;
|
|
}
|
|
if (mode_str == "taylorseer") {
|
|
mode_out = SD_CACHE_TAYLORSEER;
|
|
return true;
|
|
}
|
|
if (mode_str == "cache-dit") {
|
|
mode_out = SD_CACHE_CACHE_DIT;
|
|
return true;
|
|
}
|
|
if (mode_str == "spectrum") {
|
|
mode_out = SD_CACHE_SPECTRUM;
|
|
return true;
|
|
}
|
|
return false;
|
|
}
|
|
|
|
static json finite_number_or_null(float value) {
|
|
return std::isfinite(value) ? json(value) : json(nullptr);
|
|
}
|
|
|
|
static const char* capability_scheduler_name(enum scheduler_t scheduler) {
|
|
return scheduler < SCHEDULER_COUNT ? sd_scheduler_name(scheduler) : "default";
|
|
}
|
|
|
|
static const char* capability_sample_method_name(enum sample_method_t sample_method) {
|
|
return sample_method < SAMPLE_METHOD_COUNT ? sd_sample_method_name(sample_method) : "default";
|
|
}
|
|
|
|
static json make_vae_tiling_json(const sd_tiling_params_t& params) {
|
|
return {
|
|
{"enabled", params.enabled},
|
|
{"temporal_tiling", params.temporal_tiling},
|
|
{"tile_size_w", params.tile_size_w},
|
|
{"tile_size_h", params.tile_size_h},
|
|
{"target_overlap", params.target_overlap},
|
|
{"rel_size_w", params.rel_size_w},
|
|
{"rel_size_h", params.rel_size_h},
|
|
{"extra_tiling_args", params.extra_tiling_args ? params.extra_tiling_args : ""},
|
|
};
|
|
}
|
|
|
|
static fs::path resolve_display_model_path(const ServerRuntime& runtime) {
|
|
const auto& ctx = *runtime.ctx_params;
|
|
if (!ctx.model_path.empty()) {
|
|
return fs::path(ctx.model_path);
|
|
}
|
|
if (!ctx.diffusion_model_path.empty()) {
|
|
return fs::path(ctx.diffusion_model_path);
|
|
}
|
|
return {};
|
|
}
|
|
|
|
static json make_sample_params_json(const sd_sample_params_t& sample_params, const std::vector<int>& skip_layers) {
|
|
const auto& guidance = sample_params.guidance;
|
|
return {
|
|
{"scheduler", capability_scheduler_name(sample_params.scheduler)},
|
|
{"sample_method", capability_sample_method_name(sample_params.sample_method)},
|
|
{"sample_steps", sample_params.sample_steps},
|
|
{"eta", finite_number_or_null(sample_params.eta)},
|
|
{"shifted_timestep", sample_params.shifted_timestep},
|
|
{"flow_shift", finite_number_or_null(sample_params.flow_shift)},
|
|
{"guidance",
|
|
{
|
|
{"txt_cfg", guidance.txt_cfg},
|
|
{"img_cfg", finite_number_or_null(guidance.img_cfg)},
|
|
{"distilled_guidance", guidance.distilled_guidance},
|
|
{"slg",
|
|
{
|
|
{"layers", skip_layers},
|
|
{"layer_start", guidance.slg.layer_start},
|
|
{"layer_end", guidance.slg.layer_end},
|
|
{"scale", guidance.slg.scale},
|
|
}},
|
|
}},
|
|
};
|
|
}
|
|
|
|
static json make_hires_json(const SDGenerationParams& defaults) {
|
|
return {
|
|
{"enabled", defaults.hires_enabled},
|
|
{"upscaler", defaults.hires_upscaler},
|
|
{"scale", defaults.hires_scale},
|
|
{"target_width", defaults.hires_width},
|
|
{"target_height", defaults.hires_height},
|
|
{"steps", defaults.hires_steps},
|
|
{"denoising_strength", defaults.hires_denoising_strength},
|
|
{"custom_sigmas", defaults.hires_custom_sigmas},
|
|
{"upscale_tile_size", defaults.hires_upscale_tile_size},
|
|
};
|
|
}
|
|
|
|
static json make_img_gen_defaults_json(const SDGenerationParams& defaults, const std::string& output_format) {
|
|
return {
|
|
{"prompt", defaults.prompt},
|
|
{"negative_prompt", defaults.negative_prompt},
|
|
{"clip_skip", defaults.clip_skip},
|
|
{"width", defaults.width > 0 ? defaults.width : 512},
|
|
{"height", defaults.height > 0 ? defaults.height : 512},
|
|
{"strength", defaults.strength},
|
|
{"seed", defaults.seed},
|
|
{"batch_count", defaults.batch_count},
|
|
{"qwen_image_layers", defaults.qwen_image_layers},
|
|
{"ref_image_args", defaults.ref_image_args},
|
|
{"image_preprocess", defaults.image_preprocess},
|
|
{"increase_ref_index", defaults.increase_ref_index},
|
|
{"control_strength", defaults.control_strength},
|
|
{"ip_adapter_strength", defaults.ip_adapter_strength},
|
|
{"sample_params", make_sample_params_json(defaults.sample_params, defaults.skip_layers)},
|
|
{"hires", make_hires_json(defaults)},
|
|
{"vae_tiling_params", make_vae_tiling_json(defaults.vae_tiling_params)},
|
|
{"cache_mode", defaults.cache_mode},
|
|
{"cache_option", defaults.cache_option},
|
|
{"scm_mask", defaults.scm_mask},
|
|
{"scm_policy_dynamic", defaults.scm_policy_dynamic},
|
|
{"output_format", output_format},
|
|
{"output_compression", 100},
|
|
};
|
|
}
|
|
|
|
static json make_vid_gen_defaults_json(const SDGenerationParams& defaults, const std::string& output_format) {
|
|
return {
|
|
{"prompt", defaults.prompt},
|
|
{"negative_prompt", defaults.negative_prompt},
|
|
{"clip_skip", defaults.clip_skip},
|
|
{"width", defaults.width > 0 ? defaults.width : 512},
|
|
{"height", defaults.height > 0 ? defaults.height : 512},
|
|
{"strength", defaults.strength},
|
|
{"seed", defaults.seed},
|
|
{"video_frames", defaults.video_frames},
|
|
{"image_preprocess", defaults.image_preprocess},
|
|
{"fps", defaults.fps},
|
|
{"moe_boundary", defaults.moe_boundary},
|
|
{"vace_strength", defaults.vace_strength},
|
|
{"sample_params", make_sample_params_json(defaults.sample_params, defaults.skip_layers)},
|
|
{"high_noise_sample_params", make_sample_params_json(defaults.high_noise_sample_params, defaults.high_noise_skip_layers)},
|
|
{"hires", make_hires_json(defaults)},
|
|
{"vae_tiling_params", make_vae_tiling_json(defaults.vae_tiling_params)},
|
|
{"cache_mode", defaults.cache_mode},
|
|
{"cache_option", defaults.cache_option},
|
|
{"scm_mask", defaults.scm_mask},
|
|
{"scm_policy_dynamic", defaults.scm_policy_dynamic},
|
|
{"output_format", output_format},
|
|
{"output_compression", 100},
|
|
};
|
|
}
|
|
|
|
static json make_img_gen_features_json() {
|
|
return {
|
|
{"init_image", true},
|
|
{"mask_image", true},
|
|
{"control_image", true},
|
|
{"ip_adapter_image", true},
|
|
{"ref_images", true},
|
|
{"lora", true},
|
|
{"vae_tiling", true},
|
|
{"hires", true},
|
|
{"cache", true},
|
|
{"cancel_queued", true},
|
|
{"cancel_generating", false},
|
|
{"preview", true},
|
|
};
|
|
}
|
|
|
|
static json make_vid_gen_features_json() {
|
|
return {
|
|
{"init_image", true},
|
|
{"end_image", true},
|
|
{"control_frames", true},
|
|
{"high_noise_sample_params", true},
|
|
{"lora", true},
|
|
{"vae_tiling", true},
|
|
{"cache", true},
|
|
{"cancel_queued", true},
|
|
{"cancel_generating", false},
|
|
{"preview", true},
|
|
};
|
|
}
|
|
|
|
static json make_preview_modes_json() {
|
|
json modes = json::array();
|
|
for (int i = 0; i < PREVIEW_COUNT; ++i) {
|
|
modes.push_back(sd_preview_name((preview_t)i));
|
|
}
|
|
return modes;
|
|
}
|
|
|
|
static json make_capabilities_json(ServerRuntime& runtime) {
|
|
refresh_lora_cache(runtime);
|
|
refresh_upscaler_cache(runtime);
|
|
|
|
AsyncJobManager& manager = *runtime.async_job_manager;
|
|
const auto& defaults = *runtime.default_gen_params;
|
|
const fs::path model_path = resolve_display_model_path(runtime);
|
|
const bool supports_img = runtime_supports_generation_mode(runtime, IMG_GEN);
|
|
const bool supports_vid = runtime_supports_generation_mode(runtime, VID_GEN);
|
|
json samplers = json::array();
|
|
json schedulers = json::array();
|
|
json image_output_formats = supported_img_output_formats();
|
|
json video_output_formats = supported_vid_output_formats();
|
|
json available_loras = json::array();
|
|
json available_upscalers = json::array();
|
|
json supported_modes = json::array();
|
|
|
|
for (int i = 0; i < SAMPLE_METHOD_COUNT; ++i) {
|
|
samplers.push_back(sd_sample_method_name((sample_method_t)i));
|
|
}
|
|
|
|
for (int i = 0; i < SCHEDULER_COUNT; ++i) {
|
|
schedulers.push_back(sd_scheduler_name((scheduler_t)i));
|
|
if (i == DISCRETE_SCHEDULER) {
|
|
schedulers.push_back("normal");
|
|
}
|
|
}
|
|
|
|
{
|
|
std::lock_guard<std::mutex> lock(*runtime.lora_mutex);
|
|
for (const auto& entry : *runtime.lora_cache) {
|
|
available_loras.push_back({
|
|
{"name", entry.name},
|
|
{"path", entry.path},
|
|
});
|
|
}
|
|
}
|
|
|
|
available_upscalers.push_back({
|
|
{"name", "None"},
|
|
{"model", false},
|
|
{"image_upscale", false},
|
|
});
|
|
available_upscalers.push_back({
|
|
{"name", "Lanczos"},
|
|
{"model", false},
|
|
{"image_upscale", false},
|
|
});
|
|
available_upscalers.push_back({
|
|
{"name", "Nearest"},
|
|
{"model", false},
|
|
{"image_upscale", false},
|
|
});
|
|
available_upscalers.push_back({
|
|
{"name", "Latent"},
|
|
{"model", false},
|
|
{"image_upscale", false},
|
|
});
|
|
available_upscalers.push_back({
|
|
{"name", "Latent (nearest)"},
|
|
{"model", false},
|
|
{"image_upscale", false},
|
|
});
|
|
available_upscalers.push_back({
|
|
{"name", "Latent (nearest-exact)"},
|
|
{"model", false},
|
|
{"image_upscale", false},
|
|
});
|
|
available_upscalers.push_back({
|
|
{"name", "Latent (antialiased)"},
|
|
{"model", false},
|
|
{"image_upscale", false},
|
|
});
|
|
available_upscalers.push_back({
|
|
{"name", "Latent (bicubic)"},
|
|
{"model", false},
|
|
{"image_upscale", false},
|
|
});
|
|
available_upscalers.push_back({
|
|
{"name", "Latent (bicubic antialiased)"},
|
|
{"model", false},
|
|
{"image_upscale", false},
|
|
});
|
|
bool have_upscaler_models = false;
|
|
{
|
|
std::lock_guard<std::mutex> lock(*runtime.upscaler_mutex);
|
|
for (const auto& entry : *runtime.upscaler_cache) {
|
|
available_upscalers.push_back({
|
|
{"name", entry.name},
|
|
{"model", true},
|
|
{"image_upscale", entry.image_upscale_factor > 0},
|
|
});
|
|
have_upscaler_models = have_upscaler_models || entry.image_upscale_factor > 0;
|
|
}
|
|
}
|
|
|
|
if (supports_img) {
|
|
supported_modes.push_back("img_gen");
|
|
}
|
|
if (supports_vid) {
|
|
supported_modes.push_back("vid_gen");
|
|
}
|
|
|
|
std::string default_img_output_format = "png";
|
|
std::string default_vid_output_format = "avi";
|
|
if (!image_output_formats.empty()) {
|
|
default_img_output_format = image_output_formats[0].get<std::string>();
|
|
}
|
|
if (!video_output_formats.empty()) {
|
|
default_vid_output_format = video_output_formats[0].get<std::string>();
|
|
}
|
|
|
|
json defaults_by_mode = json::object();
|
|
json output_formats_by_mode = json::object();
|
|
json features_by_mode = json::object();
|
|
if (supports_img) {
|
|
defaults_by_mode["img_gen"] = make_img_gen_defaults_json(defaults, default_img_output_format);
|
|
output_formats_by_mode["img_gen"] = image_output_formats;
|
|
features_by_mode["img_gen"] = make_img_gen_features_json();
|
|
}
|
|
if (supports_vid) {
|
|
defaults_by_mode["vid_gen"] = make_vid_gen_defaults_json(defaults, default_vid_output_format);
|
|
output_formats_by_mode["vid_gen"] = video_output_formats;
|
|
features_by_mode["vid_gen"] = make_vid_gen_features_json();
|
|
}
|
|
|
|
json top_level_defaults = json::object();
|
|
json top_level_output_formats = json::array();
|
|
json top_level_features = {
|
|
{"cancel_queued", true},
|
|
{"cancel_generating", false},
|
|
};
|
|
std::string current_mode = "";
|
|
if (supports_img) {
|
|
current_mode = "img_gen";
|
|
top_level_defaults = defaults_by_mode["img_gen"];
|
|
top_level_output_formats = output_formats_by_mode["img_gen"];
|
|
top_level_features = features_by_mode["img_gen"];
|
|
} else if (supports_vid) {
|
|
current_mode = "vid_gen";
|
|
top_level_defaults = defaults_by_mode["vid_gen"];
|
|
top_level_output_formats = output_formats_by_mode["vid_gen"];
|
|
top_level_features = features_by_mode["vid_gen"];
|
|
}
|
|
|
|
json result;
|
|
result["model"] = {
|
|
{"name", model_path.filename().u8string()},
|
|
{"stem", model_path.stem().u8string()},
|
|
{"path", model_path.u8string()},
|
|
};
|
|
result["current_mode"] = current_mode;
|
|
result["supported_modes"] = supported_modes;
|
|
result["defaults"] = top_level_defaults;
|
|
result["defaults_by_mode"] = defaults_by_mode;
|
|
result["limits"] = {
|
|
{"min_width", 64},
|
|
{"max_width", 4096},
|
|
{"min_height", 64},
|
|
{"max_height", 4096},
|
|
{"max_batch_count", 8},
|
|
{"max_queue_size", manager.max_pending_jobs},
|
|
{"max_upscale_width", k_max_upscale_dimension},
|
|
{"max_upscale_height", k_max_upscale_dimension},
|
|
};
|
|
result["samplers"] = samplers;
|
|
result["schedulers"] = schedulers;
|
|
result["output_formats"] = top_level_output_formats;
|
|
result["output_formats_by_mode"] = output_formats_by_mode;
|
|
result["features"] = top_level_features;
|
|
result["features_by_mode"] = features_by_mode;
|
|
result["loras"] = available_loras;
|
|
result["upscalers"] = available_upscalers;
|
|
result["upscale"] = have_upscaler_models;
|
|
result["preview_modes"] = make_preview_modes_json();
|
|
return result;
|
|
}
|
|
|
|
static bool parse_img_gen_request(const json& body,
|
|
ServerRuntime& runtime,
|
|
ImgGenJobRequest& request,
|
|
std::string& error_message) {
|
|
request.gen_params = *runtime.default_gen_params;
|
|
|
|
refresh_lora_cache(runtime);
|
|
if (!request.gen_params.from_json_str(body.dump(), [&](const std::string& path) {
|
|
return get_lora_full_path(runtime, path);
|
|
})) {
|
|
error_message = "invalid generation parameters";
|
|
return false;
|
|
}
|
|
|
|
std::string output_format = body.value("output_format", "png");
|
|
int output_compression = body.value("output_compression", 100);
|
|
if (!assign_output_options(request, output_format, output_compression, true, error_message)) {
|
|
return false;
|
|
}
|
|
request.preview_mode = body.value("preview", std::string("none"));
|
|
request.preview_interval = body.value("preview_interval", 1);
|
|
// Intentionally disable prompt-embedded LoRA tag parsing for server APIs.
|
|
if (!request.gen_params.resolve_and_validate(IMG_GEN, "", runtime.ctx_params->hires_upscalers_dir, true)) {
|
|
error_message = "invalid generation parameters";
|
|
return false;
|
|
}
|
|
return true;
|
|
}
|
|
|
|
static bool parse_vid_gen_request(const json& body,
|
|
ServerRuntime& runtime,
|
|
VidGenJobRequest& request,
|
|
std::string& error_message) {
|
|
request.gen_params = *runtime.default_gen_params;
|
|
|
|
refresh_lora_cache(runtime);
|
|
if (!request.gen_params.from_json_str(body.dump(), [&](const std::string& path) {
|
|
return get_lora_full_path(runtime, path);
|
|
})) {
|
|
error_message = "invalid generation parameters";
|
|
return false;
|
|
}
|
|
|
|
std::string output_format = body.value("output_format", "webm");
|
|
int output_compression = body.value("output_compression", 100);
|
|
if (!assign_output_options(request, output_format, output_compression, error_message)) {
|
|
return false;
|
|
}
|
|
request.preview_mode = body.value("preview", std::string("none"));
|
|
request.preview_interval = body.value("preview_interval", 1);
|
|
// Intentionally disable prompt-embedded LoRA tag parsing for server APIs.
|
|
if (!request.gen_params.resolve_and_validate(VID_GEN, "", runtime.ctx_params->hires_upscalers_dir, true)) {
|
|
error_message = "invalid generation parameters";
|
|
return false;
|
|
}
|
|
return true;
|
|
}
|
|
|
|
void register_sdcpp_api_endpoints(httplib::Server& svr, ServerRuntime& rt) {
|
|
ServerRuntime* runtime = &rt;
|
|
|
|
svr.Get("/sdcpp/v1/capabilities", [runtime](const httplib::Request&, httplib::Response& res) {
|
|
res.status = 200;
|
|
res.set_content(make_capabilities_json(*runtime).dump(), "application/json");
|
|
});
|
|
|
|
svr.Get("/sdcpp/v1/health", [runtime](const httplib::Request&, httplib::Response& res) {
|
|
json body = runtime->keeper->health_json();
|
|
{
|
|
AsyncJobManager& manager = *runtime->async_job_manager;
|
|
std::lock_guard<std::mutex> lock(manager.mutex);
|
|
body["queue"] = {
|
|
{"pending", count_pending_jobs(manager)},
|
|
{"waiting", manager.queue.size()},
|
|
{"max", manager.max_pending_jobs},
|
|
};
|
|
}
|
|
res.status = body.value("status", std::string()) == "unavailable" ? 503 : 200;
|
|
res.set_content(safe_json_dump(body), "application/json");
|
|
});
|
|
|
|
svr.Get("/sdcpp/v1/resources", [runtime](const httplib::Request&, httplib::Response& res) {
|
|
json body;
|
|
sd_system_memory_t memory;
|
|
if (sd_get_system_memory(&memory)) {
|
|
body["system_memory"] = {
|
|
{"total_bytes", memory.total_bytes},
|
|
{"available_bytes", memory.available_bytes},
|
|
{"process_bytes", memory.process_bytes},
|
|
};
|
|
} else {
|
|
body["system_memory"] = nullptr;
|
|
}
|
|
|
|
json devices = json::array();
|
|
for (size_t i = 0; i < sd_get_device_count(); ++i) {
|
|
sd_device_info_t info;
|
|
if (!sd_get_device_info(i, &info)) {
|
|
continue;
|
|
}
|
|
devices.push_back({
|
|
{"name", info.name},
|
|
{"description", info.description},
|
|
{"type", sd_device_type_name(info.type)},
|
|
{"free_memory_bytes", info.free_memory_bytes},
|
|
{"total_memory_bytes", info.total_memory_bytes},
|
|
});
|
|
}
|
|
body["devices"] = std::move(devices);
|
|
res.status = 200;
|
|
res.set_content(safe_json_dump(body), "application/json");
|
|
});
|
|
|
|
svr.Post("/sdcpp/v1/upscale", [runtime](const httplib::Request& req, httplib::Response& res) {
|
|
try {
|
|
if (req.body.empty()) {
|
|
res.status = 400;
|
|
res.set_content(R"({"error":"empty body"})", "application/json");
|
|
return;
|
|
}
|
|
json body = json::parse(req.body);
|
|
if (!body.is_object()) {
|
|
res.status = 400;
|
|
res.set_content(R"({"error":"body must be an object"})", "application/json");
|
|
return;
|
|
}
|
|
for (const char* key : {"repeats", "tile_size", "output_compression"}) {
|
|
if (!body.contains(key)) {
|
|
continue;
|
|
}
|
|
const auto& value = body[key];
|
|
const bool valid = value.is_number_unsigned()
|
|
? value.get<uint64_t>() <= static_cast<uint64_t>(std::numeric_limits<int>::max())
|
|
: value.is_number_integer() && value.get<int64_t>() >= std::numeric_limits<int>::min() &&
|
|
value.get<int64_t>() <= std::numeric_limits<int>::max();
|
|
if (!valid) {
|
|
res.status = 400;
|
|
res.set_content(json({{"error", std::string(key) + " must be a 32-bit integer"}}).dump(), "application/json");
|
|
return;
|
|
}
|
|
}
|
|
ImgGenJobRequest output_options;
|
|
std::string error_message;
|
|
if (!assign_output_options(output_options,
|
|
body.value("output_format", std::string("png")),
|
|
body.value("output_compression", 100),
|
|
true,
|
|
error_message)) {
|
|
res.status = 400;
|
|
res.set_content(json({{"error", error_message}}).dump(), "application/json");
|
|
return;
|
|
}
|
|
const int tile_size = std::max(32, body.value("tile_size", runtime->default_gen_params->upscale_tile_size));
|
|
const int repeats = std::clamp(body.value("repeats", 1), 1, 4);
|
|
const std::string wanted = body.value("upscaler", std::string());
|
|
|
|
const std::string encoded = body.value("image", std::string());
|
|
if (encoded.empty()) {
|
|
res.status = 400;
|
|
res.set_content(R"({"error":"image is required"})", "application/json");
|
|
return;
|
|
}
|
|
SDImageOwner input;
|
|
if (!decode_base64_image(encoded, 3, 0, 0, input) || input.get().data == nullptr) {
|
|
res.status = 400;
|
|
res.set_content(R"({"error":"image could not be read"})", "application/json");
|
|
return;
|
|
}
|
|
|
|
refresh_upscaler_cache(*runtime);
|
|
int model_scale = 0;
|
|
std::string model_path;
|
|
std::string used_name;
|
|
{
|
|
std::lock_guard<std::mutex> lock(*runtime->upscaler_mutex);
|
|
for (const auto& entry : *runtime->upscaler_cache) {
|
|
if (entry.image_upscale_factor > 0 && (wanted.empty() || entry.name == wanted)) {
|
|
model_path = entry.fullpath;
|
|
used_name = entry.name;
|
|
model_scale = entry.image_upscale_factor;
|
|
break;
|
|
}
|
|
}
|
|
}
|
|
if (model_path.empty()) {
|
|
res.status = 400;
|
|
res.set_content(json({{"error", wanted.empty()
|
|
? std::string("no RGB ESRGAN upscaler models are available; "
|
|
"start the server with --hires-upscalers-dir")
|
|
: "no compatible image upscaler called " + wanted}})
|
|
.dump(),
|
|
"application/json");
|
|
return;
|
|
}
|
|
|
|
if (!valid_upscale_dimensions(input.get(), model_scale, repeats)) {
|
|
res.status = 400;
|
|
res.set_content(R"({"error":"upscaled dimensions must not exceed 8192 x 8192"})", "application/json");
|
|
return;
|
|
}
|
|
|
|
// One GPU: an upscale must not run while a generation is using it. The upscaler follows the
|
|
// settings the server is running with, which are lighter after it stepped down.
|
|
std::lock_guard<std::mutex> ctx_lock(runtime->keeper->mutex());
|
|
const ContextKeeper::BackendChoice choice = runtime->keeper->backend_choice();
|
|
UpscalerCtxPtr upscaler_ctx(new_upscaler_ctx(model_path.c_str(),
|
|
choice.diffusion_conv_direct,
|
|
choice.n_threads,
|
|
tile_size,
|
|
choice.backend.c_str(),
|
|
choice.params_backend.c_str()));
|
|
if (upscaler_ctx == nullptr) {
|
|
res.status = 500;
|
|
res.set_content(R"({"error":"the upscaler model could not be loaded"})", "application/json");
|
|
return;
|
|
}
|
|
const int factor = get_upscale_factor(upscaler_ctx.get());
|
|
// The model file may have changed since its metadata was cached.
|
|
if (!valid_upscale_dimensions(input.get(), factor, repeats)) {
|
|
res.status = 400;
|
|
res.set_content(R"({"error":"upscaled dimensions must not exceed 8192 x 8192"})", "application/json");
|
|
return;
|
|
}
|
|
|
|
SDImageOwner current(input.release());
|
|
for (int i = 0; i < repeats; ++i) {
|
|
sd_image_t* out_images = nullptr;
|
|
int out_count = 0;
|
|
if (!upscale(upscaler_ctx.get(), current.get(), (uint32_t)factor, &out_images, &out_count) ||
|
|
out_count <= 0 || out_images[0].data == nullptr) {
|
|
free_sd_images(out_images, out_count);
|
|
res.status = 500;
|
|
res.set_content(R"({"error":"upscale failed"})", "application/json");
|
|
return;
|
|
}
|
|
sd_image_t produced = out_images[0];
|
|
out_images[0] = {0, 0, 0, nullptr};
|
|
free_sd_images(out_images, out_count);
|
|
current.reset(produced);
|
|
}
|
|
|
|
const std::string& format = output_options.output_format;
|
|
const int compression = output_options.output_compression;
|
|
const sd_image_t result = current.get();
|
|
auto image_bytes = encode_image_to_vector(format == "jpeg" ? EncodedImageFormat::JPEG
|
|
: format == "webp" ? EncodedImageFormat::WEBP
|
|
: EncodedImageFormat::PNG,
|
|
result.data,
|
|
result.width,
|
|
result.height,
|
|
result.channel,
|
|
"",
|
|
compression);
|
|
if (image_bytes.empty()) {
|
|
res.status = 500;
|
|
res.set_content(R"({"error":"the result could not be encoded"})", "application/json");
|
|
return;
|
|
}
|
|
|
|
json out;
|
|
out["upscaler"] = used_name;
|
|
out["scale"] = factor;
|
|
out["repeats"] = repeats;
|
|
out["width"] = result.width;
|
|
out["height"] = result.height;
|
|
out["output_format"] = format;
|
|
json images = json::array();
|
|
images.push_back({{"index", 0}, {"b64_json", base64_encode(image_bytes)}});
|
|
out["images"] = std::move(images);
|
|
res.set_content(out.dump(), "application/json");
|
|
res.status = 200;
|
|
} catch (const json::exception& e) {
|
|
res.status = 400;
|
|
res.set_content(json({{"error", "invalid request"}, {"message", e.what()}}).dump(), "application/json");
|
|
} catch (const std::bad_alloc&) {
|
|
send_generation_failure(res, out_of_memory_failure());
|
|
} catch (const std::exception& e) {
|
|
res.status = 500;
|
|
res.set_content(safe_json_dump(json({{"error", std::string("server_error: ") + e.what()}})), "application/json");
|
|
}
|
|
});
|
|
|
|
svr.Post("/sdcpp/v1/img_gen", [runtime](const httplib::Request& req, httplib::Response& res) {
|
|
try {
|
|
if (req.body.empty()) {
|
|
res.status = 400;
|
|
res.set_content(R"({"error":"empty body"})", "application/json");
|
|
return;
|
|
}
|
|
if (!runtime_supports_generation_mode(*runtime, IMG_GEN)) {
|
|
res.status = 400;
|
|
res.set_content(json({{"error", unsupported_generation_mode_error(*runtime, IMG_GEN)}}).dump(), "application/json");
|
|
return;
|
|
}
|
|
|
|
json body = json::parse(req.body);
|
|
ImgGenJobRequest request;
|
|
std::string error_message;
|
|
if (!parse_img_gen_request(body, *runtime, request, error_message)) {
|
|
res.status = 400;
|
|
res.set_content(json({{"error", error_message}}).dump(), "application/json");
|
|
return;
|
|
}
|
|
|
|
AsyncJobManager& manager = *runtime->async_job_manager;
|
|
std::shared_ptr<AsyncGenerationJob> job = std::make_shared<AsyncGenerationJob>();
|
|
job->kind = AsyncJobKind::ImgGen;
|
|
job->status = AsyncJobStatus::Queued;
|
|
job->created_at = unix_timestamp_now();
|
|
job->img_gen = std::move(request);
|
|
|
|
{
|
|
std::lock_guard<std::mutex> lock(manager.mutex);
|
|
purge_expired_jobs(manager);
|
|
if (count_pending_jobs(manager) >= manager.max_pending_jobs) {
|
|
res.status = 429;
|
|
res.set_header("Retry-After", "10");
|
|
res.set_content(R"({"error":"job queue is full"})", "application/json");
|
|
return;
|
|
}
|
|
job->id = make_async_job_id(manager);
|
|
manager.jobs[job->id] = job;
|
|
manager.queue.push_back(job->id);
|
|
}
|
|
|
|
manager.cv.notify_one();
|
|
|
|
json out;
|
|
out["id"] = job->id;
|
|
out["kind"] = async_job_kind_name(job->kind);
|
|
out["status"] = async_job_status_name(job->status);
|
|
out["created"] = job->created_at;
|
|
out["poll_url"] = "/sdcpp/v1/jobs/" + job->id;
|
|
|
|
res.status = 202;
|
|
res.set_content(out.dump(), "application/json");
|
|
} catch (const json::parse_error& e) {
|
|
res.status = 400;
|
|
res.set_content(json({{"error", "invalid json"}, {"message", e.what()}}).dump(), "application/json");
|
|
} catch (const std::exception& e) {
|
|
res.status = 500;
|
|
res.set_content(json({{"error", "server_error"}, {"message", e.what()}}).dump(), "application/json");
|
|
}
|
|
});
|
|
|
|
svr.Post("/sdcpp/v1/vid_gen", [runtime](const httplib::Request& req, httplib::Response& res) {
|
|
try {
|
|
if (req.body.empty()) {
|
|
res.status = 400;
|
|
res.set_content(R"({"error":"empty body"})", "application/json");
|
|
return;
|
|
}
|
|
if (!runtime_supports_generation_mode(*runtime, VID_GEN)) {
|
|
res.status = 400;
|
|
res.set_content(json({{"error", unsupported_generation_mode_error(*runtime, VID_GEN)}}).dump(), "application/json");
|
|
return;
|
|
}
|
|
|
|
json body = json::parse(req.body);
|
|
VidGenJobRequest request;
|
|
std::string error_message;
|
|
if (!parse_vid_gen_request(body, *runtime, request, error_message)) {
|
|
res.status = 400;
|
|
res.set_content(json({{"error", error_message}}).dump(), "application/json");
|
|
return;
|
|
}
|
|
|
|
AsyncJobManager& manager = *runtime->async_job_manager;
|
|
std::shared_ptr<AsyncGenerationJob> job = std::make_shared<AsyncGenerationJob>();
|
|
job->kind = AsyncJobKind::VidGen;
|
|
job->status = AsyncJobStatus::Queued;
|
|
job->created_at = unix_timestamp_now();
|
|
job->vid_gen = std::move(request);
|
|
|
|
{
|
|
std::lock_guard<std::mutex> lock(manager.mutex);
|
|
purge_expired_jobs(manager);
|
|
if (count_pending_jobs(manager) >= manager.max_pending_jobs) {
|
|
res.status = 429;
|
|
res.set_header("Retry-After", "10");
|
|
res.set_content(R"({"error":"job queue is full"})", "application/json");
|
|
return;
|
|
}
|
|
job->id = make_async_job_id(manager);
|
|
manager.jobs[job->id] = job;
|
|
manager.queue.push_back(job->id);
|
|
}
|
|
|
|
manager.cv.notify_one();
|
|
|
|
json out;
|
|
out["id"] = job->id;
|
|
out["kind"] = async_job_kind_name(job->kind);
|
|
out["status"] = async_job_status_name(job->status);
|
|
out["created"] = job->created_at;
|
|
out["poll_url"] = "/sdcpp/v1/jobs/" + job->id;
|
|
|
|
res.status = 202;
|
|
res.set_content(out.dump(), "application/json");
|
|
} catch (const json::parse_error& e) {
|
|
res.status = 400;
|
|
res.set_content(json({{"error", "invalid json"}, {"message", e.what()}}).dump(), "application/json");
|
|
} catch (const std::exception& e) {
|
|
res.status = 500;
|
|
res.set_content(json({{"error", "server_error"}, {"message", e.what()}}).dump(), "application/json");
|
|
}
|
|
});
|
|
|
|
svr.Get(R"(/sdcpp/v1/jobs/([A-Za-z0-9_\-]+))", [runtime](const httplib::Request& req, httplib::Response& res) {
|
|
AsyncJobManager& manager = *runtime->async_job_manager;
|
|
std::lock_guard<std::mutex> lock(manager.mutex);
|
|
purge_expired_jobs(manager);
|
|
|
|
std::string job_id = req.matches[1];
|
|
auto it = manager.jobs.find(job_id);
|
|
if (it == manager.jobs.end()) {
|
|
if (manager.expired_jobs.find(job_id) != manager.expired_jobs.end()) {
|
|
res.status = 410;
|
|
res.set_content(R"({"error":"job expired"})", "application/json");
|
|
} else {
|
|
res.status = 404;
|
|
res.set_content(R"({"error":"job not found"})", "application/json");
|
|
}
|
|
return;
|
|
}
|
|
|
|
res.status = 200;
|
|
res.set_content(make_async_job_json(manager, *it->second).dump(), "application/json");
|
|
});
|
|
|
|
svr.Post(R"(/sdcpp/v1/jobs/([A-Za-z0-9_\-]+)/cancel)", [runtime](const httplib::Request& req, httplib::Response& res) {
|
|
AsyncJobManager& manager = *runtime->async_job_manager;
|
|
std::lock_guard<std::mutex> lock(manager.mutex);
|
|
purge_expired_jobs(manager);
|
|
|
|
std::string job_id = req.matches[1];
|
|
auto it = manager.jobs.find(job_id);
|
|
if (it == manager.jobs.end()) {
|
|
if (manager.expired_jobs.find(job_id) != manager.expired_jobs.end()) {
|
|
res.status = 410;
|
|
res.set_content(R"({"error":"job expired"})", "application/json");
|
|
} else {
|
|
res.status = 404;
|
|
res.set_content(R"({"error":"job not found"})", "application/json");
|
|
}
|
|
return;
|
|
}
|
|
|
|
auto& job = *it->second;
|
|
if (job.status == AsyncJobStatus::Queued) {
|
|
if (!cancel_queued_job(manager, job)) {
|
|
res.status = 409;
|
|
res.set_content(R"({"error":"job queue state changed before cancellation"})", "application/json");
|
|
return;
|
|
}
|
|
res.status = 200;
|
|
res.set_content(make_async_job_json(manager, job).dump(), "application/json");
|
|
return;
|
|
}
|
|
|
|
if (job.status == AsyncJobStatus::Generating) {
|
|
res.status = 409;
|
|
res.set_content(R"({"error":"job is currently generating and cannot be interrupted yet"})", "application/json");
|
|
return;
|
|
}
|
|
|
|
res.status = 200;
|
|
res.set_content(make_async_job_json(manager, job).dump(), "application/json");
|
|
});
|
|
}
|