mirror of
https://github.com/leejet/stable-diffusion.cpp.git
synced 2026-11-27 07:40:36 +00:00
The engine keeps, for the whole process, a record of how each device,
the RAM and the disk are doing (src/core/device_health.*). A component
under strain offers less of its capacity, one step per level (85%, 70%,
55%); an excluded one offers nothing and is never computed on. A level
rises by one for a compute that fails, a backend that does not start,
the memory guard that cannot reach its threshold or a read of the
weights that fails (events less than 10 s apart count once), and comes
down one step after each quiet period of 300 s. Outside watchers report
signals with a source and a duration; a signal reaches the other
listings of the same card, a failure of one backend does not.
- C API, additions only: sd_device_health_t, sd_get_device_health(),
sd_report_device_pressure() and sd_resume_device_health().
- The layer split gives each device its share of capacity, the run plan
and the multi-GPU planner their share of memory, and an excluded
device is never the default one. When the record changes, the next
generation releases the cached models and places them again.
- The engine refuses to compute on an excluded device (a backend error
at the start of the segment), computes on the CPU with 25% fewer
threads per level and does not fall back to an excluded CPU. The RAM
is never cut below the share of level 3; with the disk excluded,
weights that would be read from it during the run are refused as out
of memory.
- sd-server: the context keeper skips excluded devices and does not
climb back to them. A guardian (examples/server/guardian.*) stops all
work when a component is reported critical or every compute device is
excluded: the generation in progress ends with the code halted, new
work is refused with 503 halted and Retry-After, queued jobs wait, and
/sdcpp/v1/health reports the guardian and every component. It resumes
when the cause ends, or with POST /sdcpp/v1/guardian/resume; while it
is halted the keeper neither loads the model again nor steps down.
--guardian on|off, on by default.
- POST /sdcpp/v1/devices/{device}/pressure takes the reports of outside
watchers, and termico.py osserva --segnala sends the temperature band
of an NVIDIA GPU as the level of its device.
The values are provisional. This is a layer of the software, not a
safety system, and the docs say so: examples/server/api.md (Device
health and the guardian), the server README, the README of
scripts/diagnostica_termica, docs/agenti_indipendenti.md (section 9)
and the fork history.
test: device_health_test and server_guardian_test are new, and the
recovery, layer split, planner and termico tests cover the new rules.
server_guardian_e2e.py runs the guardian against a real sd-server: 59
checks, three runs in a row, with a synthetic SD 1.5 model. Every
program of test/ passes, the server tests under ThreadSanitizer too,
and broken versions of the registry, guardian, keeper and termico code
make them fail. Not tried: real GPUs, a layer split between two
devices, Windows.
Claude-Session: https://claude.ai/code/session_01EhZzDBkuuMp1jBf4WtEySC
603 lines
23 KiB
C++
603 lines
23 KiB
C++
#include "runtime.h"
|
|
|
|
#include <algorithm>
|
|
#include <cctype>
|
|
#include <charconv>
|
|
#include <chrono>
|
|
#include <cmath>
|
|
#include <cstdlib>
|
|
#include <filesystem>
|
|
#include <mutex>
|
|
#include <regex>
|
|
#include <sstream>
|
|
#include <string_view>
|
|
|
|
#include "common/common.h"
|
|
#include "common/log.h"
|
|
#include "model_catalog.h"
|
|
#include "recovery.h"
|
|
|
|
#include <map>
|
|
#include <set>
|
|
|
|
namespace fs = std::filesystem;
|
|
|
|
bool PromptImageCallbackGuard::load_image(const char* source, void* data, const sd_tensor_t** image_out) {
|
|
auto& guard = *static_cast<PromptImageCallbackGuard*>(data);
|
|
const auto& params = guard.params_;
|
|
const auto it = params.prompt_images.find(source);
|
|
if (it == params.prompt_images.end()) {
|
|
LOG_ERROR("Unknown prompt image ID: %s", source);
|
|
return false;
|
|
}
|
|
guard.image_tensor_ = image_tensor(it->second.get());
|
|
*image_out = guard.image_tensor_.get();
|
|
return *image_out != nullptr;
|
|
}
|
|
|
|
PromptImageCallbackGuard::PromptImageCallbackGuard(sd_ctx_t* ctx, const SDGenerationParams& params)
|
|
: ctx_(ctx), params_(params) {
|
|
sd_set_prompt_image_callback(ctx_, load_image, this);
|
|
}
|
|
|
|
PromptImageCallbackGuard::~PromptImageCallbackGuard() {
|
|
sd_set_prompt_image_callback(ctx_, nullptr, nullptr);
|
|
}
|
|
|
|
bool validate_server_img_gen_request(const ServerRuntime& runtime,
|
|
const ImgGenJobRequest& request,
|
|
std::string& error_message) {
|
|
auto within_dimension_limit = [&](double value) {
|
|
if (!std::isfinite(value) || value > k_max_generation_dimension) {
|
|
error_message = "generation dimensions must not exceed " + std::to_string(k_max_generation_dimension);
|
|
return false;
|
|
}
|
|
return true;
|
|
};
|
|
const auto& params = request.gen_params;
|
|
if ((params.width && !within_dimension_limit(*params.width)) ||
|
|
(params.height && !within_dimension_limit(*params.height)))
|
|
return false;
|
|
if (params.hires_enabled.value_or(false)) {
|
|
const double width = params.width.value_or(runtime.default_gen_params->width.value_or(512));
|
|
const double height = params.height.value_or(runtime.default_gen_params->height.value_or(512));
|
|
const double scale = params.hires_scale.value_or(2.f);
|
|
const auto target_width = params.hires_width.value_or(0), target_height = params.hires_height.value_or(0);
|
|
if (!within_dimension_limit(target_width > 0 ? target_width : target_height > 0 ? target_height
|
|
: width * scale) ||
|
|
!within_dimension_limit(target_height > 0 ? target_height : target_width > 0 ? target_width
|
|
: height * scale))
|
|
return false;
|
|
}
|
|
if ((!runtime.default_gen_params->ad_model_path.empty() && request.adetailer_enabled) || !request.adetailer_passes.empty()) {
|
|
error_message = "ADetailer requires a DGL script";
|
|
return false;
|
|
}
|
|
return true;
|
|
}
|
|
|
|
static std::string lower_ascii(std::string value) {
|
|
std::transform(value.begin(), value.end(), value.begin(), [](unsigned char c) {
|
|
return static_cast<char>(std::tolower(c));
|
|
});
|
|
return value;
|
|
}
|
|
|
|
static bool is_supported_model_ext(const fs::path& p) {
|
|
auto ext = lower_ascii(p.extension().u8string());
|
|
return ext == ".gguf" || ext == ".pt" || ext == ".pth" || ext == ".safetensors";
|
|
}
|
|
|
|
static const std::string k_base64_chars =
|
|
"ABCDEFGHIJKLMNOPQRSTUVWXYZ"
|
|
"abcdefghijklmnopqrstuvwxyz"
|
|
"0123456789+/";
|
|
|
|
std::string base64_encode(const std::vector<uint8_t>& bytes) {
|
|
return base64_encode(bytes.data(), bytes.size());
|
|
}
|
|
|
|
std::string base64_encode(const void* data, size_t size) {
|
|
std::string ret;
|
|
ret.reserve((size + 2) / 3 * 4);
|
|
uint32_t val = 0;
|
|
int valb = -6;
|
|
const auto* bytes = static_cast<const uint8_t*>(data);
|
|
for (size_t i = 0; i < size; ++i) {
|
|
const auto c = bytes[i];
|
|
val = (val << 8) + c;
|
|
valb += 8;
|
|
while (valb >= 0) {
|
|
ret.push_back(k_base64_chars[(val >> valb) & 0x3F]);
|
|
valb -= 6;
|
|
}
|
|
}
|
|
if (valb > -6) {
|
|
ret.push_back(k_base64_chars[((val << 8) >> (valb + 8)) & 0x3F]);
|
|
}
|
|
while (ret.size() % 4) {
|
|
ret.push_back('=');
|
|
}
|
|
return ret;
|
|
}
|
|
|
|
std::string normalize_output_format(std::string output_format) {
|
|
std::transform(output_format.begin(), output_format.end(), output_format.begin(),
|
|
[](unsigned char c) { return static_cast<char>(std::tolower(c)); });
|
|
return output_format;
|
|
}
|
|
|
|
std::vector<std::string> supported_img_output_formats(bool allow_webp) {
|
|
std::vector<std::string> formats = {"png", "jpeg"};
|
|
#ifdef SD_USE_WEBP
|
|
if (allow_webp) {
|
|
formats.push_back("webp");
|
|
}
|
|
#else
|
|
(void)allow_webp;
|
|
#endif
|
|
return formats;
|
|
}
|
|
|
|
std::vector<std::string> supported_vid_output_formats() {
|
|
std::vector<std::string> formats;
|
|
#ifdef SD_USE_WEBM
|
|
formats.push_back("webm");
|
|
#endif
|
|
#ifdef SD_USE_WEBP
|
|
formats.push_back("webp");
|
|
#endif
|
|
formats.push_back("avi");
|
|
return formats;
|
|
}
|
|
|
|
static std::string valid_vid_output_formats_message() {
|
|
const std::vector<std::string> formats = supported_vid_output_formats();
|
|
|
|
std::string message = "invalid output_format, must be one of [";
|
|
for (size_t i = 0; i < formats.size(); ++i) {
|
|
if (i > 0) {
|
|
message += ", ";
|
|
}
|
|
message += formats[i];
|
|
}
|
|
message += "]";
|
|
return message;
|
|
}
|
|
|
|
bool assign_output_options(ImgGenJobRequest& request,
|
|
std::string output_format,
|
|
int output_compression,
|
|
bool allow_webp,
|
|
std::string& error_message) {
|
|
request.output_format = normalize_output_format(std::move(output_format));
|
|
request.output_compression = std::clamp(output_compression, 0, 100);
|
|
|
|
const std::vector<std::string> valid_formats = supported_img_output_formats(allow_webp);
|
|
const bool valid_format = std::find(valid_formats.begin(),
|
|
valid_formats.end(),
|
|
request.output_format) != valid_formats.end();
|
|
if (!valid_format) {
|
|
error_message = "invalid output_format, must be one of [";
|
|
for (size_t i = 0; i < valid_formats.size(); ++i) {
|
|
if (i > 0) {
|
|
error_message += ", ";
|
|
}
|
|
error_message += valid_formats[i];
|
|
}
|
|
error_message += "]";
|
|
return false;
|
|
}
|
|
|
|
return true;
|
|
}
|
|
|
|
bool assign_output_options(VidGenJobRequest& request,
|
|
std::string output_format,
|
|
int output_compression,
|
|
std::string& error_message) {
|
|
request.output_format = normalize_output_format(std::move(output_format));
|
|
request.output_compression = std::clamp(output_compression, 0, 100);
|
|
|
|
if (request.output_format == "avi") {
|
|
return true;
|
|
}
|
|
|
|
if (request.output_format == "webm") {
|
|
#ifdef SD_USE_WEBM
|
|
return true;
|
|
#else
|
|
error_message = valid_vid_output_formats_message();
|
|
return false;
|
|
#endif
|
|
}
|
|
|
|
if (request.output_format == "webp") {
|
|
#ifdef SD_USE_WEBP
|
|
return true;
|
|
#else
|
|
error_message = valid_vid_output_formats_message();
|
|
return false;
|
|
#endif
|
|
}
|
|
|
|
error_message = valid_vid_output_formats_message();
|
|
return false;
|
|
}
|
|
|
|
std::string video_mime_type(const std::string& output_format) {
|
|
if (output_format == "webm") {
|
|
return "video/webm";
|
|
}
|
|
if (output_format == "webp") {
|
|
return "image/webp";
|
|
}
|
|
return "video/x-msvideo";
|
|
}
|
|
|
|
bool runtime_supports_generation_mode(const ServerRuntime& runtime, SDMode mode) {
|
|
if (!runtime.keeper->has_model()) {
|
|
return false;
|
|
}
|
|
if (mode == VID_GEN) {
|
|
return runtime.keeper->supports_video_generation();
|
|
}
|
|
if (mode == IMG_GEN) {
|
|
return runtime.keeper->supports_image_generation();
|
|
}
|
|
return true;
|
|
}
|
|
|
|
bool has_current_model(const ServerRuntime& runtime) {
|
|
return !runtime.ctx_params->model_path.empty() || !runtime.ctx_params->diffusion_model_path.empty();
|
|
}
|
|
|
|
bool generate_server_images(sd_ctx_t* ctx,
|
|
ImgGenJobRequest& request,
|
|
SDImageVec& results,
|
|
std::string& error_message,
|
|
bool force_vae_tiling) {
|
|
auto params = request.to_image_opt();
|
|
if (force_vae_tiling) {
|
|
sd_opt_set_bool(params.get(), "vae_tiling.enabled", true);
|
|
}
|
|
PromptImageCallbackGuard prompt_images(ctx, request.gen_params);
|
|
sd_result_t* generated = nullptr;
|
|
if (!generate_sd_image(ctx, params, &generated)) {
|
|
error_message = sd_get_last_error();
|
|
if (error_message.empty())
|
|
error_message = "generate_image returned no results";
|
|
return false;
|
|
}
|
|
results.adopt(generated);
|
|
if (results.empty()) {
|
|
error_message = "generate_image returned no results";
|
|
return false;
|
|
}
|
|
return true;
|
|
}
|
|
|
|
std::string unsupported_generation_mode_error(const ServerRuntime& runtime, SDMode mode) {
|
|
if (!runtime.keeper->has_model()) {
|
|
return "no model loaded; pick one from the model catalog or restart the server with -m/--diffusion-model";
|
|
}
|
|
if (mode == VID_GEN) {
|
|
return "current model does not support vid_gen";
|
|
}
|
|
if (mode == IMG_GEN) {
|
|
return "current model does not support img_gen";
|
|
}
|
|
return "current model does not support requested mode";
|
|
}
|
|
|
|
static int parse_weight_ttl(int argc, const char** argv, int index, int& ttl) {
|
|
if (index + 1 < argc) {
|
|
const std::string_view value = argv[index + 1];
|
|
const auto* end = value.data() + value.size();
|
|
int seconds = 0;
|
|
const auto parsed = std::from_chars(value.data(), end, seconds);
|
|
if (parsed.ec == std::errc{} && parsed.ptr == end && seconds >= -1) {
|
|
ttl = seconds;
|
|
return 1;
|
|
}
|
|
}
|
|
LOG_ERROR("%s expects an integer greater than or equal to -1", argv[index]);
|
|
return -1;
|
|
}
|
|
|
|
ArgOptions SDSvrParams::get_options() {
|
|
ArgOptions options;
|
|
|
|
options.string_options = {
|
|
{"-l", "--listen-ip", "server listen ip (default: 127.0.0.1)", 0, &listen_ip},
|
|
{"", "--serve-html-path", "path to HTML file to serve at root (optional)", 0, &serve_html_path},
|
|
{"", "--api-key", "require this API key on every request, via 'Authorization: Bearer <key>' or 'X-API-Key: <key>' (default: empty, no authentication)", 0, &api_key},
|
|
{"", "--cors-origins", "comma-separated list of allowed CORS origins, e.g. http://localhost:3000 (default: empty, any origin is reflected)", 0, &cors_origins},
|
|
{"", "--dgl-dir", "Web UI script directory (default: dgl)", 0, &dgl_dir},
|
|
};
|
|
|
|
options.int_options = {
|
|
{"", "--listen-port", "server listen port (default: 1234)", &listen_port},
|
|
{"", "--degradation-cooldown", "seconds the server waits, after stepping down to a lighter profile, before it tries the next heavier one again; a failed attempt doubles the wait up to one hour (default: 300, 0 = never go back up)", °radation_cooldown},
|
|
{"", "--max-pending-jobs",
|
|
"maximum number of pending async jobs (default: 64)",
|
|
&max_pending_jobs},
|
|
{"", "--completed-ttl-seconds",
|
|
"retention time for completed async jobs in seconds (default: 600)",
|
|
&completed_ttl_seconds},
|
|
};
|
|
|
|
options.bool_options = {
|
|
{"", "--color", "colors the logging tags according to level", true, &color},
|
|
{"", "--disable-degradation", "answer a request that runs out of memory with an error (503) instead of loading the model again with a lighter profile and repeating the request", true, &disable_degradation},
|
|
};
|
|
|
|
auto on_help_arg = [&](int, const char**, int, bool& valid) {
|
|
normal_exit = true;
|
|
valid = true;
|
|
return -1;
|
|
};
|
|
|
|
options.manual_options = {
|
|
{"-h", "--help", "show this help message and exit", on_help_arg},
|
|
{"", "--weight-staging-ttl",
|
|
"idle seconds before releasing GPU staging copies of RAM weights (-1 disabled, 0 immediate; default: -1)",
|
|
[this](int argc, const char** argv, int index) {
|
|
return parse_weight_ttl(argc, argv, index, weight_staging_ttl);
|
|
}},
|
|
{"", "--weight-residency-ttl",
|
|
"idle seconds before unloading model components from RAM and VRAM (-1 disabled, 0 immediate; default: -1)",
|
|
[this](int argc, const char** argv, int index) {
|
|
return parse_weight_ttl(argc, argv, index, weight_residency_ttl);
|
|
}},
|
|
{"", "--model-dir", "model root; repeat to search multiple directories (default: models)",
|
|
[this](int argc, const char** argv, int index) {
|
|
if (++index >= argc || argv[index][0] == '\0')
|
|
return -1;
|
|
model_dirs.push_back(argv_to_utf8(index, argv));
|
|
return 1;
|
|
}},
|
|
{"", "--guardian",
|
|
"on|off: stop all work, answering 503 until the cause ends, when a component is reported critical or device health excludes every GPU and the CPU (default: on)",
|
|
[this](int argc, const char** argv, int index) {
|
|
if (++index < argc) {
|
|
const std::string value = argv[index];
|
|
if (value == "on" || value == "off") {
|
|
guardian = value == "on";
|
|
return 1;
|
|
}
|
|
}
|
|
LOG_ERROR("--guardian expects on or off");
|
|
return -1;
|
|
}},
|
|
};
|
|
add_log_options(options, log_level);
|
|
return options;
|
|
}
|
|
|
|
bool SDSvrParams::validate() {
|
|
if (listen_ip.empty()) {
|
|
LOG_ERROR("error: the following arguments are required: listen_ip");
|
|
return false;
|
|
}
|
|
|
|
if (listen_port < 0 || listen_port > 65535) {
|
|
LOG_ERROR("error: listen_port should be in the range [0, 65535]");
|
|
return false;
|
|
}
|
|
|
|
if (degradation_cooldown < 0) {
|
|
LOG_ERROR("error: --degradation-cooldown must be 0 or more seconds");
|
|
return false;
|
|
}
|
|
|
|
if (max_pending_jobs <= 0) {
|
|
LOG_ERROR("error: max_pending_jobs must be greater than 0");
|
|
return false;
|
|
}
|
|
|
|
if (completed_ttl_seconds < 0) {
|
|
LOG_ERROR("error: completed_ttl_seconds must be non-negative");
|
|
return false;
|
|
}
|
|
|
|
if (!serve_html_path.empty() && !fs::exists(fs::u8path(serve_html_path))) {
|
|
LOG_ERROR("error: serve_html_path file does not exist: %s", serve_html_path.c_str());
|
|
return false;
|
|
}
|
|
if (dgl_dir.empty()) {
|
|
LOG_ERROR("--dgl-dir requires a directory path");
|
|
return false;
|
|
}
|
|
return true;
|
|
}
|
|
|
|
bool SDSvrParams::resolve_and_validate() {
|
|
if (!validate()) {
|
|
return false;
|
|
}
|
|
return true;
|
|
}
|
|
|
|
std::string SDSvrParams::to_string() const {
|
|
std::ostringstream oss;
|
|
oss << "SDSvrParams {\n"
|
|
<< " log_level: " << log_level_name(log_level) << ",\n"
|
|
<< " listen_ip: " << listen_ip << ",\n"
|
|
<< " listen_port: \"" << listen_port << "\",\n"
|
|
<< " max_pending_jobs: " << max_pending_jobs << ",\n"
|
|
<< " completed_ttl_seconds: " << completed_ttl_seconds << ",\n"
|
|
<< " weight_staging_ttl: " << weight_staging_ttl << ",\n"
|
|
<< " weight_residency_ttl: " << weight_residency_ttl << ",\n"
|
|
<< " serve_html_path: \"" << serve_html_path << "\",\n"
|
|
<< " api_key: " << (api_key.empty() ? "(not set)" : "(set)") << ",\n"
|
|
<< " cors_origins: \"" << cors_origins << "\",\n"
|
|
<< " disable_degradation: " << (disable_degradation ? "true" : "false") << ",\n"
|
|
<< " degradation_cooldown: " << degradation_cooldown << ",\n"
|
|
<< " guardian: " << (guardian ? "on" : "off") << ",\n"
|
|
<< " dgl_dir: \"" << dgl_dir << "\",\n"
|
|
<< "}";
|
|
return oss.str();
|
|
}
|
|
|
|
void refresh_lora_cache(ServerRuntime& rt) {
|
|
std::vector<LoraEntry> new_cache;
|
|
std::vector<ModelRoot> directories;
|
|
if (!rt.ctx_params->lora_model_dir.empty()) {
|
|
directories.push_back(make_model_root(fs::u8path(rt.ctx_params->lora_model_dir), true));
|
|
} else {
|
|
for (const auto& root : get_model_roots(*rt.svr_params)) {
|
|
try {
|
|
const auto paths = model_category_directories(root, "loras");
|
|
for (size_t i = 0; i < paths.size(); ++i) {
|
|
if (!model_path_inside(root.path, fs::canonical(paths[i]))) {
|
|
LOG_WARN("LoRA directory escapes model directory: %s", paths[i].u8string().c_str());
|
|
continue;
|
|
}
|
|
directories.push_back(make_model_root(paths[i], root.primary && lower_ascii(paths[i].filename().u8string()) == "loras"));
|
|
}
|
|
} catch (const std::exception& e) {
|
|
LOG_WARN("error while finding LoRA directories in %s: %s", root.label.c_str(), e.what());
|
|
}
|
|
}
|
|
}
|
|
std::set<std::string> seen;
|
|
std::map<std::string, size_t> names;
|
|
for (const auto& directory : directories) {
|
|
try {
|
|
if (!fs::exists(directory.path))
|
|
continue;
|
|
for (fs::recursive_directory_iterator it(directory.path), end; it != end; ++it) {
|
|
std::error_code ec;
|
|
const auto canonical = fs::canonical(it->path(), ec);
|
|
if (ec || !model_path_inside(directory.path, canonical)) {
|
|
it.disable_recursion_pending();
|
|
LOG_WARN("skipping inaccessible LoRA or path outside LoRA directory: %s", it->path().u8string().c_str());
|
|
continue;
|
|
}
|
|
const auto ext = lower_ascii(it->path().extension().u8string());
|
|
if (!it->is_regular_file() || (!is_supported_model_ext(it->path()) && ext != ".ckpt" && ext != ".sft") ||
|
|
!seen.insert(model_path_key(canonical)).second)
|
|
continue;
|
|
const auto relative = it->path().lexically_relative(directory.path).generic_u8string();
|
|
LoraEntry entry;
|
|
entry.name = it->path().stem().u8string();
|
|
entry.path = directory.primary ? relative : directory.id + "/" + relative;
|
|
entry.fullpath = it->path().u8string();
|
|
entry.display_path = relative;
|
|
entry.root = directory.path;
|
|
++names[relative];
|
|
new_cache.push_back(std::move(entry));
|
|
}
|
|
} catch (const std::exception& e) {
|
|
LOG_WARN("error while scanning LoRA directory '%s': %s", directory.path.u8string().c_str(), e.what());
|
|
}
|
|
}
|
|
for (auto& entry : new_cache) {
|
|
if (names[entry.display_path] > 1)
|
|
entry.display_path = fs::u8path(entry.fullpath).generic_u8string();
|
|
}
|
|
std::sort(new_cache.begin(), new_cache.end(), [](const LoraEntry& a, const LoraEntry& b) {
|
|
return a.path < b.path;
|
|
});
|
|
std::lock_guard<std::mutex> lock(*rt.lora_mutex);
|
|
*rt.lora_cache = std::move(new_cache);
|
|
}
|
|
|
|
std::string get_lora_full_path(ServerRuntime& rt, const std::string& path) {
|
|
std::lock_guard<std::mutex> lock(*rt.lora_mutex);
|
|
auto it = std::find_if(rt.lora_cache->begin(), rt.lora_cache->end(),
|
|
[&](const LoraEntry& entry) { return entry.path == path; });
|
|
if (it == rt.lora_cache->end())
|
|
return "";
|
|
std::error_code ec;
|
|
const auto canonical = fs::canonical(fs::u8path(it->fullpath), ec);
|
|
if (ec || !model_path_inside(it->root, canonical) || !fs::is_regular_file(canonical, ec) || ec)
|
|
return "";
|
|
return canonical.u8string();
|
|
}
|
|
|
|
void refresh_upscaler_cache(ServerRuntime& rt) {
|
|
std::vector<UpscalerEntry> new_cache;
|
|
std::vector<UpscalerEntry> previous_cache;
|
|
{
|
|
std::lock_guard<std::mutex> lock(*rt.upscaler_mutex);
|
|
previous_cache = *rt.upscaler_cache;
|
|
}
|
|
|
|
fs::path upscaler_dir = fs::u8path(rt.ctx_params->hires_upscalers_dir);
|
|
std::error_code ec;
|
|
if (fs::exists(upscaler_dir, ec) && !ec && fs::is_directory(upscaler_dir, ec) && !ec) {
|
|
try {
|
|
auto it = fs::directory_iterator(
|
|
upscaler_dir,
|
|
fs::directory_options::skip_permission_denied,
|
|
ec);
|
|
auto end = fs::directory_iterator();
|
|
while (!ec && it != end) {
|
|
std::error_code entry_ec;
|
|
bool is_reg = it->is_regular_file(entry_ec);
|
|
if (entry_ec || !is_reg) {
|
|
it.increment(ec);
|
|
continue;
|
|
}
|
|
const fs::path& p = it->path();
|
|
if (!is_supported_model_ext(p)) {
|
|
it.increment(ec);
|
|
continue;
|
|
}
|
|
|
|
UpscalerEntry upscaler_entry;
|
|
upscaler_entry.name = p.stem().u8string();
|
|
std::error_code abs_ec;
|
|
fs::path abs_path = fs::absolute(p, abs_ec);
|
|
upscaler_entry.fullpath = (abs_ec ? p : abs_path.lexically_normal()).u8string();
|
|
upscaler_entry.path = p.filename().u8string();
|
|
|
|
std::error_code size_ec;
|
|
upscaler_entry.file_size = it->file_size(size_ec);
|
|
if (size_ec) {
|
|
it.increment(ec);
|
|
continue;
|
|
}
|
|
|
|
std::error_code time_ec;
|
|
upscaler_entry.last_modified = it->last_write_time(time_ec);
|
|
auto previous = std::find_if(previous_cache.begin(), previous_cache.end(), [&](const UpscalerEntry& cached) {
|
|
return cached.fullpath == upscaler_entry.fullpath &&
|
|
cached.file_size == upscaler_entry.file_size &&
|
|
(!time_ec && cached.last_modified == upscaler_entry.last_modified);
|
|
});
|
|
const int scale = previous != previous_cache.end() ? previous->scale : sd_upscaler_probe_scale(upscaler_entry.fullpath.c_str());
|
|
upscaler_entry.scale = scale > 0 ? scale : 4;
|
|
upscaler_entry.model_name = "ESRGAN_" + std::to_string(upscaler_entry.scale) + "x";
|
|
|
|
new_cache.push_back(std::move(upscaler_entry));
|
|
it.increment(ec);
|
|
}
|
|
} catch (const std::exception& e) {
|
|
LOG_WARN("error while scanning upscalers directory '%s': %s", upscaler_dir.u8string().c_str(), e.what());
|
|
return;
|
|
}
|
|
}
|
|
|
|
if (ec) {
|
|
LOG_WARN("error while scanning upscalers directory '%s': %s", upscaler_dir.u8string().c_str(), ec.message().c_str());
|
|
return;
|
|
}
|
|
|
|
std::sort(new_cache.begin(), new_cache.end(), [](const UpscalerEntry& a, const UpscalerEntry& b) {
|
|
return a.name < b.name;
|
|
});
|
|
|
|
{
|
|
std::lock_guard<std::mutex> lock(*rt.upscaler_mutex);
|
|
*rt.upscaler_cache = std::move(new_cache);
|
|
}
|
|
}
|
|
|
|
int64_t unix_timestamp_now_ms() {
|
|
return std::chrono::duration_cast<std::chrono::milliseconds>(
|
|
std::chrono::system_clock::now().time_since_epoch())
|
|
.count();
|
|
}
|