model_manager.cpp 63 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695705715725735745755765775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206216226236246256266276286296306316326336346356366376386396406416426436446456466476486496506516526536546556566576586596606616626636646656666676686696706716726736746756766776786796806816826836846856866876886896906916926936946956966976986997007017027037047057067077087097107117127137147157167177187197207217227237247257267277287297307317327337347357367377387397407417427437447457467477487497507517527537547557567577587597607617627637647657667677687697707717727737747757767777787797807817827837847857867877887897907917927937947957967977987998008018028038048058068078088098108118128138148158168178188198208218228238248258268278288298308318328338348358368378388398408418428438448458468478488498508518528538548558568578588598608618628638648658668678688698708718728738748758768778788798808818828838848858868878888898908918928938948958968978988999009019029039049059069079089099109119129139149159169179189199209219229239249259269279289299309319329339349359369379389399409419429439449459469479489499509519529539549559569579589599609619629639649659669679689699709719729739749759769779789799809819829839849859869879889899909919929939949959969979989991000100110021003100410051006100710081009101010111012101310141015101610171018101910201021102210231024102510261027102810291030103110321033103410351036103710381039104010411042104310441045104610471048104910501051105210531054105510561057105810591060106110621063106410651066106710681069107010711072107310741075107610771078107910801081108210831084108510861087108810891090109110921093109410951096109710981099110011011102110311041105110611071108110911101111111211131114111511161117111811191120112111221123112411251126112711281129113011311132113311341135113611371138113911401141114211431144114511461147114811491150115111521153115411551156115711581159116011611162116311641165116611671168116911701171117211731174117511761177117811791180118111821183118411851186118711881189119011911192119311941195119611971198119912001201120212031204120512061207120812091210121112121213121412151216121712181219122012211222122312241225122612271228122912301231123212331234123512361237123812391240124112421243124412451246124712481249125012511252125312541255125612571258125912601261126212631264126512661267126812691270127112721273127412751276127712781279128012811282128312841285128612871288128912901291129212931294129512961297129812991300130113021303130413051306130713081309131013111312131313141315131613171318131913201321132213231324132513261327132813291330133113321333133413351336133713381339134013411342134313441345134613471348134913501351135213531354135513561357135813591360136113621363136413651366136713681369137013711372137313741375137613771378137913801381138213831384138513861387138813891390139113921393139413951396139713981399140014011402140314041405140614071408140914101411141214131414141514161417141814191420142114221423142414251426142714281429143014311432143314341435143614371438143914401441144214431444144514461447144814491450145114521453145414551456145714581459146014611462146314641465146614671468146914701471147214731474147514761477147814791480148114821483148414851486148714881489149014911492149314941495149614971498149915001501150215031504150515061507150815091510151115121513151415151516151715181519152015211522152315241525152615271528
  1. #include "model_manager.h"
  2. #include "model_detector.h"
  3. #include "stable_diffusion_wrapper.h"
  4. #include <iostream>
  5. #include <fstream>
  6. #include <algorithm>
  7. #include <filesystem>
  8. #include <shared_mutex>
  9. #include <chrono>
  10. #include <future>
  11. #include <atomic>
  12. #include <set>
  13. #include <openssl/evp.h>
  14. #include <sstream>
  15. #include <iomanip>
  16. #include <nlohmann/json.hpp>
  17. namespace fs = std::filesystem;
  18. // File extension mappings for each model type
  19. const std::vector<std::string> CHECKPOINT_FILE_EXTENSIONS = {"safetensors", "ckpt", "gguf"};
  20. const std::vector<std::string> EMBEDDING_FILE_EXTENSIONS = {"safetensors", "pt"};
  21. const std::vector<std::string> LORA_FILE_EXTENSIONS = {"safetensors", "ckpt"};
  22. const std::vector<std::string> VAE_FILE_EXTENSIONS = {"safetensors", "pt", "ckpt", "gguf"};
  23. const std::vector<std::string> TAESD_FILE_EXTENSIONS = {"safetensors", "pth", "gguf"};
  24. const std::vector<std::string> ESRGAN_FILE_EXTENSIONS = {"pth", "pt"};
  25. const std::vector<std::string> CONTROLNET_FILE_EXTENSIONS = {"safetensors", "pth"};
  26. class ModelManager::Impl {
  27. public:
  28. std::string modelsDirectory = "./models";
  29. std::map<ModelType, std::string> modelTypeDirectories;
  30. std::map<std::string, ModelInfo> availableModels;
  31. std::map<std::string, std::unique_ptr<StableDiffusionWrapper>> loadedModels;
  32. mutable std::shared_mutex modelsMutex;
  33. std::atomic<bool> scanCancelled{false};
  34. /**
  35. * @brief Validate a directory path
  36. *
  37. * @param path The directory path to validate
  38. * @return true if the directory exists and is valid, false otherwise
  39. */
  40. bool validateDirectory(const std::string& path) const {
  41. if (path.empty()) {
  42. return false;
  43. }
  44. std::filesystem::path dirPath(path);
  45. if (!std::filesystem::exists(dirPath)) {
  46. std::cerr << "Directory does not exist: " << path << std::endl;
  47. return false;
  48. }
  49. if (!std::filesystem::is_directory(dirPath)) {
  50. std::cerr << "Path is not a directory: " << path << std::endl;
  51. return false;
  52. }
  53. return true;
  54. }
  55. /**
  56. * @brief Get default directory name for a model type
  57. *
  58. * @param type The model type
  59. * @return std::string Default directory name
  60. */
  61. std::string getDefaultDirectoryName(ModelType type) const {
  62. switch (type) {
  63. case ModelType::CHECKPOINT:
  64. return "checkpoints";
  65. case ModelType::CONTROLNET:
  66. return "controlnet";
  67. case ModelType::EMBEDDING:
  68. return "embeddings";
  69. case ModelType::ESRGAN:
  70. return "esrgan";
  71. case ModelType::LORA:
  72. return "lora";
  73. case ModelType::TAESD:
  74. return "taesd";
  75. case ModelType::VAE:
  76. return "vae";
  77. case ModelType::DIFFUSION_MODELS:
  78. return "diffusion_models";
  79. default:
  80. return "";
  81. }
  82. }
  83. /**
  84. * @brief Get directory path for a model type
  85. *
  86. * @param type The model type
  87. * @return std::string Directory path, empty if not set
  88. */
  89. std::string getModelTypeDirectory(ModelType type) const {
  90. auto it = modelTypeDirectories.find(type);
  91. if (it != modelTypeDirectories.end()) {
  92. return it->second;
  93. }
  94. // Always use explicit directory configuration
  95. std::string defaultDir = getDefaultDirectoryName(type);
  96. if (!defaultDir.empty()) {
  97. return modelsDirectory + "/" + defaultDir;
  98. }
  99. return "";
  100. }
  101. /**
  102. * @brief Get file extensions for a specific model type
  103. *
  104. * @param type The model type
  105. * @return const std::vector<std::string>& Vector of file extensions
  106. */
  107. const std::vector<std::string>& getFileExtensions(ModelType type) const {
  108. switch (type) {
  109. case ModelType::CHECKPOINT:
  110. case ModelType::DIFFUSION_MODELS:
  111. return CHECKPOINT_FILE_EXTENSIONS;
  112. case ModelType::EMBEDDING:
  113. return EMBEDDING_FILE_EXTENSIONS;
  114. case ModelType::LORA:
  115. return LORA_FILE_EXTENSIONS;
  116. case ModelType::VAE:
  117. return VAE_FILE_EXTENSIONS;
  118. case ModelType::TAESD:
  119. return TAESD_FILE_EXTENSIONS;
  120. case ModelType::ESRGAN:
  121. return ESRGAN_FILE_EXTENSIONS;
  122. case ModelType::CONTROLNET:
  123. return CONTROLNET_FILE_EXTENSIONS;
  124. default:
  125. static const std::vector<std::string> empty;
  126. return empty;
  127. }
  128. }
  129. /**
  130. * @brief Check if a file extension matches a model type
  131. *
  132. * @param extension The file extension
  133. * @param type The model type
  134. * @return true if the extension matches the model type
  135. */
  136. bool isExtensionMatch(const std::string& extension, ModelType type) const {
  137. const auto& extensions = getFileExtensions(type);
  138. return std::find(extensions.begin(), extensions.end(), extension) != extensions.end();
  139. }
  140. /**
  141. * @brief FIXED: Determine model type based on file path and extension
  142. *
  143. * THIS IS THE FIXED VERSION - no extension-based fallback!
  144. * Only returns a model type if the file is actually in the right directory.
  145. *
  146. * @param filePath The file path
  147. * @return ModelType The determined model type
  148. */
  149. ModelType determineModelType(const fs::path& filePath) const {
  150. std::string extension = filePath.extension().string();
  151. if (extension.empty()) {
  152. return ModelType::NONE;
  153. }
  154. // Remove the dot from extension
  155. if (extension[0] == '.') {
  156. extension = extension.substr(1);
  157. }
  158. // Convert to lowercase for comparison
  159. std::transform(extension.begin(), extension.end(), extension.begin(), ::tolower);
  160. // Check if the file resides under a directory registered for a given ModelType
  161. fs::path absoluteFilePath = fs::absolute(filePath);
  162. // First check configured directories (if any)
  163. for (const auto& [type, directory] : modelTypeDirectories) {
  164. if (!directory.empty()) {
  165. fs::path absoluteDirPath = fs::absolute(directory).lexically_normal();
  166. fs::path normalizedFilePath = absoluteFilePath.lexically_normal();
  167. // Check if the file is under this directory (directly or in subdirectories)
  168. // Get the relative path from directory to file
  169. auto relativePath = normalizedFilePath.lexically_relative(absoluteDirPath);
  170. // If relative path doesn't start with "..", then file is under the directory
  171. std::string relPathStr = relativePath.string();
  172. bool isUnderDirectory = !relPathStr.empty() &&
  173. relPathStr.substr(0, 2) != ".." &&
  174. relPathStr[0] != '/';
  175. if (isUnderDirectory && isExtensionMatch(extension, type)) {
  176. return type;
  177. }
  178. }
  179. }
  180. // Check default directory structure when no explicit directories configured
  181. if (modelTypeDirectories.empty()) {
  182. // Check the entire path hierarchy for model type directories
  183. fs::path currentPath = filePath.parent_path();
  184. while (currentPath.has_filename()) {
  185. std::string dirName = currentPath.filename().string();
  186. std::transform(dirName.begin(), dirName.end(), dirName.begin(), ::tolower);
  187. // Check default directory names
  188. if (dirName == "checkpoints" || dirName == "stable-diffusion") {
  189. if (isExtensionMatch(extension, ModelType::CHECKPOINT)) {
  190. return ModelType::CHECKPOINT;
  191. }
  192. } else if (dirName == "controlnet") {
  193. if (isExtensionMatch(extension, ModelType::CONTROLNET)) {
  194. return ModelType::CONTROLNET;
  195. }
  196. } else if (dirName == "lora") {
  197. if (isExtensionMatch(extension, ModelType::LORA)) {
  198. return ModelType::LORA;
  199. }
  200. } else if (dirName == "vae") {
  201. if (isExtensionMatch(extension, ModelType::VAE)) {
  202. return ModelType::VAE;
  203. }
  204. } else if (dirName == "taesd") {
  205. if (isExtensionMatch(extension, ModelType::TAESD)) {
  206. return ModelType::TAESD;
  207. }
  208. } else if (dirName == "esrgan" || dirName == "upscaler") {
  209. if (isExtensionMatch(extension, ModelType::ESRGAN)) {
  210. return ModelType::ESRGAN;
  211. }
  212. } else if (dirName == "embeddings" || dirName == "textual-inversion") {
  213. } else if (dirName == "diffusion_models" || dirName == "diffusion") {
  214. if (isExtensionMatch(extension, ModelType::DIFFUSION_MODELS)) {
  215. return ModelType::DIFFUSION_MODELS;
  216. }
  217. if (isExtensionMatch(extension, ModelType::EMBEDDING)) {
  218. return ModelType::EMBEDDING;
  219. }
  220. }
  221. // Move up to parent directory
  222. currentPath = currentPath.parent_path();
  223. }
  224. }
  225. // NO EXTENSION-BASED FALLBACK - this was the bug!
  226. // Files must be in the correct directory to be recognized
  227. return ModelType::NONE;
  228. }
  229. /**
  230. * @brief Get file information with timeout
  231. *
  232. * @param filePath The file path to get info for
  233. * @param timeoutMs Timeout in milliseconds
  234. * @return std::pair<bool, std::pair<uintmax_t, fs::file_time_type>> Success flag and file info
  235. */
  236. std::pair<bool, std::pair<uintmax_t, fs::file_time_type>> getFileInfoWithTimeout(
  237. const fs::path& filePath, int timeoutMs = 5000) {
  238. auto future = std::async(std::launch::async, [&filePath]() -> std::pair<uintmax_t, fs::file_time_type> {
  239. try {
  240. uintmax_t fileSize = fs::file_size(filePath);
  241. fs::file_time_type modifiedAt = fs::last_write_time(filePath);
  242. return {fileSize, modifiedAt};
  243. } catch (const fs::filesystem_error&) {
  244. return {0, fs::file_time_type{}};
  245. }
  246. });
  247. if (future.wait_for(std::chrono::milliseconds(timeoutMs)) == std::future_status::timeout) {
  248. std::cerr << "Timeout getting file info for " << filePath << std::endl;
  249. return {false, {0, fs::file_time_type{}}};
  250. }
  251. return {true, future.get()};
  252. }
  253. /**
  254. * @brief Scan a directory for models recursively (all types, without holding mutex)
  255. *
  256. * Recursively walks the directory tree to find all model files. For each model
  257. * found, constructs the display name as 'relative_path/model_name' where
  258. * relative_path is the path from the models root directory to the file's
  259. * containing folder (using forward slashes). Models in the root directory
  260. * appear without a prefix.
  261. *
  262. * @param directory The directory to scan
  263. * @param modelsMap Reference to the map to store results
  264. * @return bool True if scanning completed without cancellation
  265. */
  266. bool scanDirectory(const fs::path& directory, std::map<std::string, ModelInfo>& modelsMap) {
  267. if (scanCancelled.load()) {
  268. return false;
  269. }
  270. if (!fs::exists(directory) || !fs::is_directory(directory)) {
  271. return true;
  272. }
  273. try {
  274. for (const auto& entry : fs::recursive_directory_iterator(directory)) {
  275. if (scanCancelled.load()) {
  276. return false;
  277. }
  278. if (entry.is_regular_file()) {
  279. fs::path filePath = entry.path();
  280. ModelType detectedType = determineModelType(filePath);
  281. // Only add files that have a valid model type (not NONE)
  282. if (detectedType != ModelType::NONE) {
  283. ModelInfo info;
  284. // Calculate relative path from the model type directory to exclude model type folder names
  285. fs::path relativePath;
  286. try {
  287. // Get the specific model type directory for this detected type
  288. std::string modelTypeDir = getModelTypeDirectory(detectedType);
  289. if (!modelTypeDir.empty()) {
  290. fs::path typeBaseDir(modelTypeDir);
  291. // Get relative path from the model type directory
  292. relativePath = fs::relative(filePath, typeBaseDir);
  293. } else {
  294. // Fallback: use the base models directory
  295. if (!modelsDirectory.empty()) {
  296. fs::path baseDir(modelsDirectory);
  297. relativePath = fs::relative(filePath, baseDir);
  298. } else {
  299. relativePath = fs::relative(filePath, directory);
  300. }
  301. }
  302. } catch (const fs::filesystem_error&) {
  303. // If relative path calculation fails, use filename only
  304. relativePath = filePath.filename();
  305. }
  306. std::string modelName = relativePath.string();
  307. // Normalize path separators for consistency
  308. std::replace(modelName.begin(), modelName.end(), '\\', '/');
  309. // Check if model already exists to avoid duplicates
  310. if (modelsMap.find(modelName) == modelsMap.end()) {
  311. info.name = modelName;
  312. info.path = filePath.string();
  313. info.fullPath = fs::absolute(filePath).string();
  314. info.type = detectedType;
  315. info.isLoaded = false;
  316. info.description = ""; // Initialize description
  317. info.metadata = {}; // Initialize metadata
  318. // Get file info with timeout
  319. auto [success, fileInfo] = getFileInfoWithTimeout(filePath);
  320. if (success) {
  321. info.fileSize = fileInfo.first;
  322. info.modifiedAt = fileInfo.second;
  323. info.createdAt = fileInfo.second; // Use modified time as creation time for now
  324. } else {
  325. info.fileSize = 0;
  326. info.modifiedAt = fs::file_time_type{};
  327. info.createdAt = fs::file_time_type{};
  328. }
  329. // Try to load cached hash from .json file
  330. std::string hashFile = info.fullPath + ".json";
  331. if (fs::exists(hashFile)) {
  332. try {
  333. std::ifstream file(hashFile);
  334. nlohmann::json hashData = nlohmann::json::parse(file);
  335. if (hashData.contains("sha256") && hashData["sha256"].is_string()) {
  336. info.sha256 = hashData["sha256"];
  337. } else {
  338. info.sha256 = "";
  339. }
  340. } catch (...) {
  341. info.sha256 = ""; // If parsing fails, leave empty
  342. }
  343. } else {
  344. info.sha256 = ""; // No cached hash file
  345. }
  346. // Detect architecture for checkpoint models (including diffusion_models)
  347. if (detectedType == ModelType::CHECKPOINT || detectedType == ModelType::DIFFUSION_MODELS) {
  348. // Try to get cached result first
  349. ModelDetectionCache::CacheEntry cachedEntry =
  350. ModelDetectionCache::getCachedResult(info.fullPath, info.modifiedAt);
  351. if (cachedEntry.isValid) {
  352. // Use cached results
  353. info.architecture = cachedEntry.architecture;
  354. info.recommendedVAE = cachedEntry.recommendedVAE;
  355. info.recommendedWidth = cachedEntry.recommendedWidth;
  356. info.recommendedHeight = cachedEntry.recommendedHeight;
  357. info.recommendedSteps = cachedEntry.recommendedSteps;
  358. info.recommendedSampler = cachedEntry.recommendedSampler;
  359. info.requiredModels = cachedEntry.requiredModels;
  360. info.missingModels = cachedEntry.missingModels;
  361. info.cacheValid = true;
  362. info.cacheModifiedAt = cachedEntry.cachedAt;
  363. info.cachePathType = cachedEntry.pathType;
  364. info.useFolderBasedDetection = (cachedEntry.detectionSource == "folder");
  365. info.detectionSource = cachedEntry.detectionSource;
  366. std::cout << "Using cached detection for " << info.name
  367. << " (source: " << cachedEntry.detectionSource << ")" << std::endl;
  368. } else {
  369. // Perform new detection
  370. try {
  371. // First try folder-based detection
  372. std::string checkpointsDir = getModelTypeDirectory(ModelType::CHECKPOINT);
  373. std::string diffusionModelsDir = getModelTypeDirectory(ModelType::DIFFUSION_MODELS);
  374. std::string pathType = ModelPathSelector::selectPathType(
  375. info.fullPath, checkpointsDir, diffusionModelsDir);
  376. bool useFolderBasedDetection = (pathType == "diffusion_model_path");
  377. ModelDetectionResult detection;
  378. std::string detectionSource;
  379. if (useFolderBasedDetection) {
  380. // For models in diffusion_models directory, we can skip full detection
  381. // and use folder-based logic
  382. detectionSource = "folder";
  383. info.architecture = "Modern Architecture (Flux/SD3)";
  384. info.recommendedVAE = "ae.safetensors";
  385. info.recommendedWidth = 1024;
  386. info.recommendedHeight = 1024;
  387. info.recommendedSteps = 20;
  388. info.recommendedSampler = "euler";
  389. // Create a minimal detection result for caching
  390. detection.architecture = ModelArchitecture::FLUX_DEV; // Default modern
  391. detection.architectureName = info.architecture;
  392. detection.recommendedVAE = info.recommendedVAE;
  393. detection.suggestedParams["width"] = std::to_string(info.recommendedWidth);
  394. detection.suggestedParams["height"] = std::to_string(info.recommendedHeight);
  395. detection.suggestedParams["steps"] = std::to_string(info.recommendedSteps);
  396. detection.suggestedParams["sampler"] = info.recommendedSampler;
  397. std::cout << "Using folder-based detection for " << info.name
  398. << " in " << pathType << std::endl;
  399. } else {
  400. // Perform full architecture detection
  401. detectionSource = "architecture";
  402. detection = ModelDetector::detectModel(info.fullPath);
  403. // For .ckpt files that can't be detected, default to SD1.5
  404. if (detection.architecture == ModelArchitecture::UNKNOWN &&
  405. (filePath.extension() == ".ckpt" || filePath.extension() == ".pt")) {
  406. info.architecture = "Stable Diffusion 1.5 (assumed)";
  407. info.recommendedVAE = "vae-ft-mse-840000-ema-pruned.safetensors";
  408. info.recommendedWidth = 512;
  409. info.recommendedHeight = 512;
  410. info.recommendedSteps = 20;
  411. info.recommendedSampler = "euler_a";
  412. detectionSource = "fallback";
  413. } else {
  414. info.architecture = detection.architectureName;
  415. info.recommendedVAE = detection.recommendedVAE;
  416. // Parse recommended parameters
  417. if (detection.suggestedParams.count("width")) {
  418. info.recommendedWidth = std::stoi(detection.suggestedParams["width"]);
  419. }
  420. if (detection.suggestedParams.count("height")) {
  421. info.recommendedHeight = std::stoi(detection.suggestedParams["height"]);
  422. }
  423. if (detection.suggestedParams.count("steps")) {
  424. info.recommendedSteps = std::stoi(detection.suggestedParams["steps"]);
  425. }
  426. if (detection.suggestedParams.count("sampler")) {
  427. info.recommendedSampler = detection.suggestedParams["sampler"];
  428. }
  429. }
  430. std::cout << "Using architecture-based detection for " << info.name << std::endl;
  431. }
  432. // Build list of required models based on detection
  433. // Note: VAE is now optional for SD1x and SDXL models, so we don't add it to requiredModels
  434. // The VAE will still be recommended but not required
  435. // Add CLIP-L if required
  436. if (detection.suggestedParams.count("clip_l_required")) {
  437. info.requiredModels.push_back("CLIP-L: " + detection.suggestedParams.at("clip_l_required"));
  438. }
  439. // Add CLIP-G if required
  440. if (detection.suggestedParams.count("clip_g_required")) {
  441. info.requiredModels.push_back("CLIP-G: " + detection.suggestedParams.at("clip_g_required"));
  442. }
  443. // Add T5XXL if required
  444. if (detection.suggestedParams.count("t5xxl_required")) {
  445. info.requiredModels.push_back("T5XXL: " + detection.suggestedParams.at("t5xxl_required"));
  446. }
  447. // Add Qwen models if required
  448. if (detection.suggestedParams.count("qwen2vl_required")) {
  449. info.requiredModels.push_back("Qwen2-VL: " + detection.suggestedParams.at("qwen2vl_required"));
  450. }
  451. if (detection.suggestedParams.count("qwen2vl_vision_required")) {
  452. info.requiredModels.push_back("Qwen2-VL-Vision: " + detection.suggestedParams.at("qwen2vl_vision_required"));
  453. }
  454. // Check if required models exist
  455. if (!info.requiredModels.empty()) {
  456. // Create a temporary ModelManager instance to check existence
  457. ModelManager tempManager;
  458. std::vector<ModelDetails> modelDetails = tempManager.checkRequiredModelsExistence(info.requiredModels);
  459. // Clear missing models and repopulate based on existence check
  460. info.missingModels.clear();
  461. for (const auto& detail : modelDetails) {
  462. if (!detail.exists) {
  463. info.missingModels.push_back(detail.type + ": " + detail.name);
  464. }
  465. }
  466. std::cout << "Model " << info.name << " requires " << info.requiredModels.size()
  467. << " models, " << info.missingModels.size() << " are missing" << std::endl;
  468. }
  469. // Cache the detection result
  470. ModelDetectionCache::cacheDetectionResult(
  471. info.fullPath, detection, pathType, detectionSource, info.modifiedAt);
  472. info.cacheValid = true;
  473. info.cacheModifiedAt = std::filesystem::file_time_type::clock::now();
  474. info.cachePathType = pathType;
  475. info.useFolderBasedDetection = useFolderBasedDetection;
  476. info.detectionSource = detectionSource;
  477. } catch (const std::exception& e) {
  478. // If detection fails completely, default to SD1.5
  479. info.architecture = "Stable Diffusion 1.5 (assumed)";
  480. info.recommendedVAE = "vae-ft-mse-840000-ema-pruned.safetensors";
  481. info.recommendedWidth = 512;
  482. info.recommendedHeight = 512;
  483. info.recommendedSteps = 20;
  484. info.recommendedSampler = "euler_a";
  485. info.detectionSource = "fallback";
  486. std::cerr << "Detection failed for " << info.name << ": " << e.what()
  487. << ", using SD1.5 defaults" << std::endl;
  488. }
  489. }
  490. }
  491. modelsMap[info.name] = info;
  492. }
  493. }
  494. }
  495. }
  496. } catch (const fs::filesystem_error& e) {
  497. // Silently handle filesystem errors
  498. }
  499. return !scanCancelled.load();
  500. }
  501. };
  502. ModelManager::ModelManager() : pImpl(std::make_unique<Impl>()) {
  503. }
  504. ModelManager::~ModelManager() = default;
  505. bool ModelManager::scanModelsDirectory() {
  506. // Reset cancellation flag
  507. pImpl->scanCancelled.store(false);
  508. // Create temporary map to store scan results (outside of lock)
  509. std::map<std::string, ModelInfo> tempModels;
  510. // Scan all configured directories for all model types recursively
  511. // We scan each directory once and detect all model types within it
  512. std::set<std::string> scannedDirectories; // Avoid scanning the same directory multiple times
  513. std::vector<std::string> directoriesToScan;
  514. // Collect unique directories to scan
  515. std::vector<ModelType> allTypes = {
  516. ModelType::CHECKPOINT, ModelType::CONTROLNET, ModelType::LORA,
  517. ModelType::VAE, ModelType::TAESD, ModelType::ESRGAN, ModelType::EMBEDDING,
  518. ModelType::DIFFUSION_MODELS
  519. };
  520. for (const auto& type : allTypes) {
  521. std::string dirPath = pImpl->getModelTypeDirectory(type);
  522. if (!dirPath.empty() && scannedDirectories.find(dirPath) == scannedDirectories.end()) {
  523. directoriesToScan.push_back(dirPath);
  524. scannedDirectories.insert(dirPath);
  525. }
  526. }
  527. // Also scan the base models directory if it exists and isn't already covered
  528. if (!pImpl->modelsDirectory.empty() &&
  529. fs::exists(pImpl->modelsDirectory) &&
  530. scannedDirectories.find(pImpl->modelsDirectory) == scannedDirectories.end()) {
  531. directoriesToScan.push_back(pImpl->modelsDirectory);
  532. }
  533. // Scan each unique directory recursively for all model types
  534. for (const auto& dirPath : directoriesToScan) {
  535. if (!pImpl->scanDirectory(dirPath, tempModels)) {
  536. return false;
  537. }
  538. }
  539. // Brief exclusive lock only to swap the data
  540. {
  541. std::unique_lock<std::shared_mutex> lock(pImpl->modelsMutex);
  542. pImpl->availableModels.swap(tempModels);
  543. }
  544. return true;
  545. }
  546. bool ModelManager::loadModel(const std::string& name, const std::string& path, ModelType type) {
  547. std::unique_lock<std::shared_mutex> lock(pImpl->modelsMutex);
  548. // Check if model is already loaded
  549. if (pImpl->loadedModels.find(name) != pImpl->loadedModels.end()) {
  550. return true;
  551. }
  552. // Check if file exists
  553. if (!fs::exists(path)) {
  554. std::cerr << "Model file does not exist: " << path << std::endl;
  555. return false;
  556. }
  557. // Create and initialize the stable-diffusion wrapper
  558. auto wrapper = std::make_unique<StableDiffusionWrapper>();
  559. // Set up generation parameters for model loading
  560. StableDiffusionWrapper::GenerationParams loadParams;
  561. loadParams.modelPath = path;
  562. loadParams.modelType = "f16"; // Default to f16 for better performance
  563. // Try to detect model type automatically for checkpoint and diffusion models
  564. if (type == ModelType::CHECKPOINT || type == ModelType::DIFFUSION_MODELS) {
  565. try {
  566. ModelDetectionResult detection = ModelDetector::detectModel(path);
  567. // Apply detected model type and parameters
  568. if (detection.architecture != ModelArchitecture::UNKNOWN) {
  569. std::cout << "Detected model architecture: " << detection.architectureName << " for " << name << std::endl;
  570. // Set model type from detection if available
  571. if (detection.suggestedParams.count("model_type")) {
  572. loadParams.modelType = detection.suggestedParams.at("model_type");
  573. }
  574. // Set additional model paths based on detection
  575. // VAE is now optional for SD1x and SDXL models, but we still set it if available
  576. if (!detection.recommendedVAE.empty()) {
  577. loadParams.vaePath = detection.recommendedVAE;
  578. }
  579. // Apply other suggested parameters (only for fields that exist in GenerationParams)
  580. for (const auto& [param, value] : detection.suggestedParams) {
  581. if (param == "clip_l_path") {
  582. loadParams.clipLPath = value;
  583. } else if (param == "clip_g_path") {
  584. loadParams.clipGPath = value;
  585. }
  586. // Note: t5xxl_path and qwen2vl_path are not available in GenerationParams structure
  587. // These would need to be passed through the underlying stable-diffusion.cpp library directly
  588. }
  589. } else {
  590. std::cout << "Could not detect model architecture for " << name << ", using defaults" << std::endl;
  591. }
  592. } catch (const std::exception& e) {
  593. std::cerr << "Model detection failed for " << name << ": " << e.what() << " - using defaults" << std::endl;
  594. }
  595. }
  596. // Try to load the model
  597. if (!wrapper->loadModel(path, loadParams)) {
  598. std::cerr << "Failed to load model '" << name << "': " << wrapper->getLastError() << std::endl;
  599. return false;
  600. }
  601. pImpl->loadedModels[name] = std::move(wrapper);
  602. // Update model info
  603. if (pImpl->availableModels.find(name) != pImpl->availableModels.end()) {
  604. pImpl->availableModels[name].isLoaded = true;
  605. } else {
  606. // Create a new model info entry
  607. ModelInfo info;
  608. info.name = name;
  609. info.path = path;
  610. info.fullPath = fs::absolute(path).string();
  611. info.type = type;
  612. info.isLoaded = true;
  613. info.sha256 = "";
  614. info.description = ""; // Initialize description
  615. info.metadata = {}; // Initialize metadata
  616. try {
  617. info.fileSize = fs::file_size(path);
  618. info.modifiedAt = fs::last_write_time(path);
  619. info.createdAt = info.modifiedAt; // Use modified time as creation time for now
  620. } catch (const fs::filesystem_error& e) {
  621. std::cerr << "Error getting file info for " << path << ": " << e.what() << std::endl;
  622. info.fileSize = 0;
  623. info.modifiedAt = fs::file_time_type{};
  624. info.createdAt = fs::file_time_type{};
  625. }
  626. pImpl->availableModels[name] = info;
  627. }
  628. return true;
  629. }
  630. bool ModelManager::loadModel(const std::string& name) {
  631. std::string path;
  632. ModelType type;
  633. {
  634. std::unique_lock<std::shared_mutex> lock(pImpl->modelsMutex);
  635. // Check if model exists in available models
  636. auto it = pImpl->availableModels.find(name);
  637. if (it == pImpl->availableModels.end()) {
  638. std::cerr << "Model '" << name << "' not found in available models" << std::endl;
  639. return false;
  640. }
  641. // Check if already loaded
  642. if (pImpl->loadedModels.find(name) != pImpl->loadedModels.end()) {
  643. return true;
  644. }
  645. // Extract path and type while we have the lock
  646. path = it->second.path;
  647. type = it->second.type;
  648. } // Release lock here
  649. // Load the model without holding the lock
  650. return loadModel(name, path, type);
  651. }
  652. bool ModelManager::unloadModel(const std::string& name) {
  653. std::unique_lock<std::shared_mutex> lock(pImpl->modelsMutex);
  654. // Check if model is loaded
  655. auto loadedIt = pImpl->loadedModels.find(name);
  656. if (loadedIt == pImpl->loadedModels.end()) {
  657. return false;
  658. }
  659. // Unload the model properly
  660. if (loadedIt->second) {
  661. loadedIt->second->unloadModel();
  662. }
  663. pImpl->loadedModels.erase(loadedIt);
  664. // Update model info
  665. auto availableIt = pImpl->availableModels.find(name);
  666. if (availableIt != pImpl->availableModels.end()) {
  667. availableIt->second.isLoaded = false;
  668. }
  669. return true;
  670. }
  671. StableDiffusionWrapper* ModelManager::getModel(const std::string& name) {
  672. std::shared_lock<std::shared_mutex> lock(pImpl->modelsMutex);
  673. auto it = pImpl->loadedModels.find(name);
  674. if (it == pImpl->loadedModels.end()) {
  675. return nullptr;
  676. }
  677. return it->second.get();
  678. }
  679. std::map<std::string, ModelManager::ModelInfo> ModelManager::getAllModels() const {
  680. std::shared_lock<std::shared_mutex> lock(pImpl->modelsMutex);
  681. return pImpl->availableModels;
  682. }
  683. std::vector<ModelManager::ModelInfo> ModelManager::getModelsByType(ModelType type) const {
  684. std::shared_lock<std::shared_mutex> lock(pImpl->modelsMutex);
  685. std::vector<ModelInfo> result;
  686. for (const auto& pair : pImpl->availableModels) {
  687. if (pair.second.type == type) {
  688. result.push_back(pair.second);
  689. }
  690. }
  691. return result;
  692. }
  693. ModelManager::ModelInfo ModelManager::getModelInfo(const std::string& name) const {
  694. std::unique_lock<std::shared_mutex> lock(pImpl->modelsMutex);
  695. auto it = pImpl->availableModels.find(name);
  696. if (it == pImpl->availableModels.end()) {
  697. return ModelInfo{}; // Return empty ModelInfo if not found
  698. }
  699. return it->second;
  700. }
  701. bool ModelManager::isModelLoaded(const std::string& name) const {
  702. std::unique_lock<std::shared_mutex> lock(pImpl->modelsMutex);
  703. auto it = pImpl->loadedModels.find(name);
  704. return it != pImpl->loadedModels.end();
  705. }
  706. size_t ModelManager::getLoadedModelsCount() const {
  707. std::shared_lock<std::shared_mutex> lock(pImpl->modelsMutex);
  708. return pImpl->loadedModels.size();
  709. }
  710. size_t ModelManager::getAvailableModelsCount() const {
  711. std::shared_lock<std::shared_mutex> lock(pImpl->modelsMutex);
  712. return pImpl->availableModels.size();
  713. }
  714. void ModelManager::setModelsDirectory(const std::string& path) {
  715. pImpl->modelsDirectory = path;
  716. }
  717. std::string ModelManager::getModelsDirectory() const {
  718. return pImpl->modelsDirectory;
  719. }
  720. std::string ModelManager::modelTypeToString(ModelType type) {
  721. switch (type) {
  722. case ModelType::LORA:
  723. return "lora";
  724. case ModelType::CHECKPOINT:
  725. return "checkpoint";
  726. case ModelType::VAE:
  727. return "vae";
  728. case ModelType::PRESETS:
  729. return "presets";
  730. case ModelType::PROMPTS:
  731. return "prompts";
  732. case ModelType::NEG_PROMPTS:
  733. return "neg_prompts";
  734. case ModelType::TAESD:
  735. return "taesd";
  736. case ModelType::ESRGAN:
  737. return "esrgan";
  738. case ModelType::CONTROLNET:
  739. return "controlnet";
  740. case ModelType::UPSCALER:
  741. return "upscaler";
  742. case ModelType::EMBEDDING:
  743. return "embedding";
  744. case ModelType::DIFFUSION_MODELS:
  745. return "checkpoint";
  746. default:
  747. return "unknown";
  748. }
  749. }
  750. ModelType ModelManager::stringToModelType(const std::string& typeStr) {
  751. std::string lowerType = typeStr;
  752. std::transform(lowerType.begin(), lowerType.end(), lowerType.begin(), ::tolower);
  753. if (lowerType == "lora") {
  754. return ModelType::LORA;
  755. } else if (lowerType == "checkpoint" || lowerType == "stable-diffusion") {
  756. return ModelType::CHECKPOINT;
  757. } else if (lowerType == "vae") {
  758. return ModelType::VAE;
  759. } else if (lowerType == "presets") {
  760. return ModelType::PRESETS;
  761. } else if (lowerType == "prompts") {
  762. return ModelType::PROMPTS;
  763. } else if (lowerType == "neg_prompts" || lowerType == "negative_prompts") {
  764. return ModelType::NEG_PROMPTS;
  765. } else if (lowerType == "taesd") {
  766. return ModelType::TAESD;
  767. } else if (lowerType == "esrgan") {
  768. return ModelType::ESRGAN;
  769. } else if (lowerType == "controlnet") {
  770. return ModelType::CONTROLNET;
  771. } else if (lowerType == "upscaler") {
  772. return ModelType::UPSCALER;
  773. } else if (lowerType == "embedding" || lowerType == "textual-inversion") {
  774. return ModelType::EMBEDDING;
  775. }
  776. return ModelType::NONE;
  777. }
  778. bool ModelManager::setModelTypeDirectory(ModelType type, const std::string& path) {
  779. std::unique_lock<std::shared_mutex> lock(pImpl->modelsMutex);
  780. if (!pImpl->validateDirectory(path)) {
  781. return false;
  782. }
  783. pImpl->modelTypeDirectories[type] = path;
  784. return true;
  785. }
  786. std::string ModelManager::getModelTypeDirectory(ModelType type) const {
  787. std::shared_lock<std::shared_mutex> lock(pImpl->modelsMutex);
  788. return pImpl->getModelTypeDirectory(type);
  789. }
  790. bool ModelManager::setAllModelTypeDirectories(const std::map<ModelType, std::string>& directories) {
  791. std::unique_lock<std::shared_mutex> lock(pImpl->modelsMutex);
  792. // Validate all directories first
  793. for (const auto& [type, path] : directories) {
  794. if (!path.empty() && !pImpl->validateDirectory(path)) {
  795. return false;
  796. }
  797. }
  798. // Set all directories
  799. pImpl->modelTypeDirectories = directories;
  800. return true;
  801. }
  802. std::map<ModelType, std::string> ModelManager::getAllModelTypeDirectories() const {
  803. std::shared_lock<std::shared_mutex> lock(pImpl->modelsMutex);
  804. return pImpl->modelTypeDirectories;
  805. }
  806. // Legacy resetToLegacyDirectories method removed
  807. // Using explicit directory configuration only
  808. bool ModelManager::configureFromServerConfig(const ServerConfig& config) {
  809. std::unique_lock<std::shared_mutex> lock(pImpl->modelsMutex);
  810. // Set the base models directory
  811. pImpl->modelsDirectory = config.modelsDir;
  812. // Always use explicit directory configuration
  813. std::map<ModelType, std::string> directories;
  814. if (!config.checkpoints.empty()) {
  815. directories[ModelType::CHECKPOINT] = config.checkpoints;
  816. }
  817. if (!config.controlnetDir.empty()) {
  818. directories[ModelType::CONTROLNET] = config.controlnetDir;
  819. }
  820. if (!config.embeddingsDir.empty()) {
  821. directories[ModelType::EMBEDDING] = config.embeddingsDir;
  822. }
  823. if (!config.esrganDir.empty()) {
  824. directories[ModelType::ESRGAN] = config.esrganDir;
  825. }
  826. if (!config.loraDir.empty()) {
  827. directories[ModelType::LORA] = config.loraDir;
  828. }
  829. if (!config.taesdDir.empty()) {
  830. directories[ModelType::TAESD] = config.taesdDir;
  831. }
  832. if (!config.vaeDir.empty()) {
  833. directories[ModelType::VAE] = config.vaeDir;
  834. }
  835. if (!config.diffusionModelsDir.empty()) {
  836. directories[ModelType::DIFFUSION_MODELS] = config.diffusionModelsDir;
  837. }
  838. // Validate all directories first
  839. for (const auto& [type, path] : directories) {
  840. if (!path.empty() && !pImpl->validateDirectory(path)) {
  841. return false;
  842. }
  843. }
  844. // Set all directories (inlined to avoid deadlock from calling setAllModelTypeDirectories)
  845. pImpl->modelTypeDirectories = directories;
  846. return true;
  847. }
  848. void ModelManager::cancelScan() {
  849. pImpl->scanCancelled.store(true);
  850. }
  851. // SHA256 Hashing Implementation
  852. std::string ModelManager::computeModelHash(const std::string& modelName) {
  853. std::shared_lock<std::shared_mutex> lock(pImpl->modelsMutex);
  854. auto it = pImpl->availableModels.find(modelName);
  855. if (it == pImpl->availableModels.end()) {
  856. std::cerr << "Model not found: " << modelName << std::endl;
  857. return "";
  858. }
  859. std::string filePath = it->second.fullPath;
  860. lock.unlock();
  861. std::ifstream file(filePath, std::ios::binary);
  862. if (!file.is_open()) {
  863. std::cerr << "Failed to open file for hashing: " << filePath << std::endl;
  864. return "";
  865. }
  866. // Create and initialize EVP context for SHA256
  867. EVP_MD_CTX* mdctx = EVP_MD_CTX_new();
  868. if (mdctx == nullptr) {
  869. std::cerr << "Failed to create EVP context" << std::endl;
  870. return "";
  871. }
  872. if (EVP_DigestInit_ex(mdctx, EVP_sha256(), nullptr) != 1) {
  873. std::cerr << "Failed to initialize SHA256 digest" << std::endl;
  874. EVP_MD_CTX_free(mdctx);
  875. return "";
  876. }
  877. const size_t bufferSize = 8192;
  878. char buffer[bufferSize];
  879. std::cout << "Computing SHA256 for: " << modelName << std::endl;
  880. size_t totalRead = 0;
  881. size_t lastReportedMB = 0;
  882. while (file.read(buffer, bufferSize) || file.gcount() > 0) {
  883. size_t bytesRead = file.gcount();
  884. if (EVP_DigestUpdate(mdctx, buffer, bytesRead) != 1) {
  885. std::cerr << "Failed to update digest" << std::endl;
  886. EVP_MD_CTX_free(mdctx);
  887. return "";
  888. }
  889. totalRead += bytesRead;
  890. // Progress reporting every 100MB
  891. size_t currentMB = totalRead / (1024 * 1024);
  892. if (currentMB >= lastReportedMB + 100) {
  893. std::cout << " Hashed " << currentMB << " MB..." << std::endl;
  894. lastReportedMB = currentMB;
  895. }
  896. }
  897. file.close();
  898. unsigned char hash[EVP_MAX_MD_SIZE];
  899. unsigned int hashLen = 0;
  900. if (EVP_DigestFinal_ex(mdctx, hash, &hashLen) != 1) {
  901. std::cerr << "Failed to finalize digest" << std::endl;
  902. EVP_MD_CTX_free(mdctx);
  903. return "";
  904. }
  905. EVP_MD_CTX_free(mdctx);
  906. // Convert to hex string
  907. std::ostringstream oss;
  908. for (unsigned int i = 0; i < hashLen; i++) {
  909. oss << std::hex << std::setw(2) << std::setfill('0') << static_cast<int>(hash[i]);
  910. }
  911. std::string hashStr = oss.str();
  912. std::cout << "Hash computed: " << hashStr.substr(0, 16) << "..." << std::endl;
  913. return hashStr;
  914. }
  915. std::string ModelManager::loadModelHashFromFile(const std::string& modelName) {
  916. std::shared_lock<std::shared_mutex> lock(pImpl->modelsMutex);
  917. auto it = pImpl->availableModels.find(modelName);
  918. if (it == pImpl->availableModels.end()) {
  919. return "";
  920. }
  921. std::string jsonPath = it->second.fullPath + ".json";
  922. lock.unlock();
  923. if (!fs::exists(jsonPath)) {
  924. return "";
  925. }
  926. try {
  927. std::ifstream jsonFile(jsonPath);
  928. if (!jsonFile.is_open()) {
  929. return "";
  930. }
  931. nlohmann::json j;
  932. jsonFile >> j;
  933. jsonFile.close();
  934. if (j.contains("sha256") && j["sha256"].is_string()) {
  935. return j["sha256"].get<std::string>();
  936. }
  937. } catch (const std::exception& e) {
  938. std::cerr << "Error loading hash from JSON: " << e.what() << std::endl;
  939. }
  940. return "";
  941. }
  942. bool ModelManager::saveModelHashToFile(const std::string& modelName, const std::string& hash) {
  943. std::shared_lock<std::shared_mutex> lock(pImpl->modelsMutex);
  944. auto it = pImpl->availableModels.find(modelName);
  945. if (it == pImpl->availableModels.end()) {
  946. return false;
  947. }
  948. std::string jsonPath = it->second.fullPath + ".json";
  949. size_t fileSize = it->second.fileSize;
  950. lock.unlock();
  951. try {
  952. nlohmann::json j;
  953. j["sha256"] = hash;
  954. j["file_size"] = fileSize;
  955. j["computed_at"] = std::chrono::system_clock::now().time_since_epoch().count();
  956. std::ofstream jsonFile(jsonPath);
  957. if (!jsonFile.is_open()) {
  958. std::cerr << "Failed to open file for writing: " << jsonPath << std::endl;
  959. return false;
  960. }
  961. jsonFile << j.dump(2);
  962. jsonFile.close();
  963. std::cout << "Saved hash to: " << jsonPath << std::endl;
  964. return true;
  965. } catch (const std::exception& e) {
  966. std::cerr << "Error saving hash to JSON: " << e.what() << std::endl;
  967. return false;
  968. }
  969. }
  970. std::string ModelManager::findModelByHash(const std::string& hash) {
  971. if (hash.length() < 10) {
  972. std::cerr << "Hash must be at least 10 characters" << std::endl;
  973. return "";
  974. }
  975. std::shared_lock<std::shared_mutex> lock(pImpl->modelsMutex);
  976. for (const auto& [name, info] : pImpl->availableModels) {
  977. if (info.sha256.empty()) {
  978. continue;
  979. }
  980. // Support full or partial match (minimum 10 chars)
  981. if (info.sha256 == hash || info.sha256.substr(0, hash.length()) == hash) {
  982. return name;
  983. }
  984. }
  985. return "";
  986. }
  987. std::string ModelManager::ensureModelHash(const std::string& modelName, bool forceCompute) {
  988. // Try to load existing hash if not forcing recompute
  989. if (!forceCompute) {
  990. std::string existingHash = loadModelHashFromFile(modelName);
  991. if (!existingHash.empty()) {
  992. // Update in-memory model info
  993. std::unique_lock<std::shared_mutex> lock(pImpl->modelsMutex);
  994. auto it = pImpl->availableModels.find(modelName);
  995. if (it != pImpl->availableModels.end()) {
  996. it->second.sha256 = existingHash;
  997. }
  998. return existingHash;
  999. }
  1000. }
  1001. // Compute new hash
  1002. std::string hash = computeModelHash(modelName);
  1003. if (hash.empty()) {
  1004. return "";
  1005. }
  1006. // Save to file
  1007. saveModelHashToFile(modelName, hash);
  1008. // Update in-memory model info
  1009. std::unique_lock<std::shared_mutex> lock(pImpl->modelsMutex);
  1010. auto it = pImpl->availableModels.find(modelName);
  1011. if (it != pImpl->availableModels.end()) {
  1012. it->second.sha256 = hash;
  1013. }
  1014. return hash;
  1015. }
  1016. // ModelPathSelector Implementation
  1017. std::string ModelManager::ModelPathSelector::selectPathType(
  1018. const std::string& modelPath,
  1019. const std::string& checkpointsDir,
  1020. const std::string& diffusionModelsDir) {
  1021. std::cout << "Selecting path type for model: " << modelPath << std::endl;
  1022. std::cout << "Checkpoints directory: " << checkpointsDir << std::endl;
  1023. std::cout << "Diffusion models directory: " << diffusionModelsDir << std::endl;
  1024. // Check if model is in diffusion_models directory first (priority)
  1025. if (!diffusionModelsDir.empty() && isModelInDirectory(modelPath, diffusionModelsDir)) {
  1026. std::cout << "Model is in diffusion_models directory, using diffusion_model_path" << std::endl;
  1027. return "diffusion_model_path";
  1028. }
  1029. // Check if model is in checkpoints directory
  1030. if (!checkpointsDir.empty() && isModelInDirectory(modelPath, checkpointsDir)) {
  1031. std::cout << "Model is in checkpoints directory, using model_path" << std::endl;
  1032. return "model_path";
  1033. }
  1034. // Fallback: use directory name detection
  1035. std::filesystem::path modelFilePath(modelPath);
  1036. std::filesystem::path parentDir = modelFilePath.parent_path();
  1037. if (parentDir.filename().string() == "diffusion_models") {
  1038. std::cout << "Model is in diffusion_models directory (detected from path), using diffusion_model_path" << std::endl;
  1039. return "diffusion_model_path";
  1040. } else if (parentDir.filename().string() == "checkpoints") {
  1041. std::cout << "Model is in checkpoints directory (detected from path), using model_path" << std::endl;
  1042. return "model_path";
  1043. }
  1044. // Default fallback for unknown locations
  1045. std::cout << "Model location unknown, defaulting to model_path for backward compatibility" << std::endl;
  1046. return "model_path";
  1047. }
  1048. bool ModelManager::ModelPathSelector::isModelInDirectory(const std::string& modelPath, const std::string& directory) {
  1049. if (modelPath.empty() || directory.empty()) {
  1050. return false;
  1051. }
  1052. try {
  1053. std::filesystem::path absoluteModelPath = std::filesystem::absolute(modelPath).lexically_normal();
  1054. std::filesystem::path absoluteDirPath = std::filesystem::absolute(directory).lexically_normal();
  1055. // Get relative path from directory to model
  1056. auto relativePath = absoluteModelPath.lexically_relative(absoluteDirPath);
  1057. std::string relPathStr = relativePath.string();
  1058. // Check if the relative path doesn't start with ".." and is not empty
  1059. bool isUnderDirectory = !relPathStr.empty() &&
  1060. relPathStr.substr(0, 2) != ".." &&
  1061. relPathStr[0] != '/';
  1062. return isUnderDirectory;
  1063. } catch (const std::filesystem::filesystem_error& e) {
  1064. std::cerr << "Error checking if model is in directory: " << e.what() << std::endl;
  1065. return false;
  1066. }
  1067. }
  1068. // ModelDetectionCache Implementation
  1069. std::map<std::string, ModelManager::ModelDetectionCache::CacheEntry> ModelManager::ModelDetectionCache::cache_;
  1070. std::mutex ModelManager::ModelDetectionCache::cacheMutex_;
  1071. ModelManager::ModelDetectionCache::CacheEntry ModelManager::ModelDetectionCache::getCachedResult(
  1072. const std::string& modelPath,
  1073. const std::filesystem::file_time_type& currentModifiedTime) {
  1074. std::lock_guard<std::mutex> lock(cacheMutex_);
  1075. auto it = cache_.find(modelPath);
  1076. if (it == cache_.end()) {
  1077. return CacheEntry{}; // Return invalid entry if not found
  1078. }
  1079. const CacheEntry& entry = it->second;
  1080. // Check if cache is still valid (file hasn't been modified)
  1081. if (entry.fileModifiedAt == currentModifiedTime && entry.isValid) {
  1082. std::cout << "Using cached detection result for: " << modelPath << std::endl;
  1083. return entry;
  1084. }
  1085. // Cache is stale, remove it
  1086. cache_.erase(it);
  1087. std::cout << "Cache entry expired for: " << modelPath << std::endl;
  1088. return CacheEntry{}; // Return invalid entry
  1089. }
  1090. void ModelManager::ModelDetectionCache::cacheDetectionResult(
  1091. const std::string& modelPath,
  1092. const ModelDetectionResult& detection,
  1093. const std::string& pathType,
  1094. const std::string& detectionSource,
  1095. const std::filesystem::file_time_type& fileModifiedTime) {
  1096. std::lock_guard<std::mutex> lock(cacheMutex_);
  1097. CacheEntry entry;
  1098. entry.architecture = detection.architectureName;
  1099. entry.recommendedVAE = detection.recommendedVAE;
  1100. entry.recommendedWidth = 0;
  1101. entry.recommendedHeight = 0;
  1102. entry.recommendedSteps = 0;
  1103. entry.recommendedSampler = "";
  1104. entry.pathType = pathType;
  1105. entry.detectionSource = detectionSource;
  1106. entry.cachedAt = std::filesystem::file_time_type::clock::now();
  1107. entry.fileModifiedAt = fileModifiedTime;
  1108. entry.isValid = true;
  1109. // Parse recommended parameters
  1110. for (const auto& [param, value] : detection.suggestedParams) {
  1111. if (param == "width") {
  1112. entry.recommendedWidth = std::stoi(value);
  1113. } else if (param == "height") {
  1114. entry.recommendedHeight = std::stoi(value);
  1115. } else if (param == "steps") {
  1116. entry.recommendedSteps = std::stoi(value);
  1117. } else if (param == "sampler") {
  1118. entry.recommendedSampler = value;
  1119. }
  1120. }
  1121. // Build list of required models
  1122. // Note: VAE is now optional for SD1x and SDXL models, so we don't add it to requiredModels
  1123. // The VAE will still be recommended but not required
  1124. if (detection.suggestedParams.count("clip_l_required")) {
  1125. entry.requiredModels.push_back("CLIP-L: " + detection.suggestedParams.at("clip_l_required"));
  1126. }
  1127. if (detection.suggestedParams.count("clip_g_required")) {
  1128. entry.requiredModels.push_back("CLIP-G: " + detection.suggestedParams.at("clip_g_required"));
  1129. }
  1130. if (detection.suggestedParams.count("t5xxl_required")) {
  1131. entry.requiredModels.push_back("T5XXL: " + detection.suggestedParams.at("t5xxl_required"));
  1132. }
  1133. if (detection.suggestedParams.count("qwen2vl_required")) {
  1134. entry.requiredModels.push_back("Qwen2-VL: " + detection.suggestedParams.at("qwen2vl_required"));
  1135. }
  1136. if (detection.suggestedParams.count("qwen2vl_vision_required")) {
  1137. entry.requiredModels.push_back("Qwen2-VL-Vision: " + detection.suggestedParams.at("qwen2vl_vision_required"));
  1138. }
  1139. // Check for missing models and store in cache
  1140. if (!entry.requiredModels.empty()) {
  1141. // Create a temporary ModelManager instance to check existence
  1142. // Note: This is a simplified approach - in a production environment,
  1143. // we might want to pass the models directory or use a different approach
  1144. std::string baseModelsDir = "/data/SD_MODELS";
  1145. for (const auto& requiredModel : entry.requiredModels) {
  1146. size_t colonPos = requiredModel.find(':');
  1147. if (colonPos == std::string::npos) continue;
  1148. std::string modelType = requiredModel.substr(0, colonPos);
  1149. std::string modelName = requiredModel.substr(colonPos + 1);
  1150. // Trim whitespace
  1151. modelType.erase(0, modelType.find_first_not_of(" \t"));
  1152. modelType.erase(modelType.find_last_not_of(" \t") + 1);
  1153. modelName.erase(0, modelName.find_first_not_of(" \t"));
  1154. modelName.erase(modelName.find_last_not_of(" \t") + 1);
  1155. // Determine the appropriate subdirectory
  1156. std::string subdirectory;
  1157. if (modelType == "VAE") {
  1158. subdirectory = "vae";
  1159. } else if (modelType == "CLIP-L" || modelType == "CLIP-G") {
  1160. subdirectory = "clip";
  1161. } else if (modelType == "T5XXL") {
  1162. subdirectory = "t5xxl";
  1163. } else if (modelType == "CLIP-Vision") {
  1164. subdirectory = "clip";
  1165. } else if (modelType == "Qwen2-VL" || modelType == "Qwen2-VL-Vision") {
  1166. subdirectory = "qwen2vl";
  1167. }
  1168. // Check if model exists
  1169. std::string fullPath;
  1170. if (!subdirectory.empty()) {
  1171. fullPath = baseModelsDir + "/" + subdirectory + "/" + modelName;
  1172. } else {
  1173. fullPath = baseModelsDir + "/" + modelName;
  1174. }
  1175. try {
  1176. if (!fs::exists(fullPath) || !fs::is_regular_file(fullPath)) {
  1177. entry.missingModels.push_back(requiredModel);
  1178. }
  1179. } catch (const fs::filesystem_error&) {
  1180. // If we can't check, assume it's missing
  1181. entry.missingModels.push_back(requiredModel);
  1182. }
  1183. }
  1184. }
  1185. cache_[modelPath] = entry;
  1186. std::cout << "Cached detection result for: " << modelPath
  1187. << " (source: " << detectionSource << ", path type: " << pathType << ")" << std::endl;
  1188. }
  1189. void ModelManager::ModelDetectionCache::invalidateCache(const std::string& modelPath) {
  1190. std::lock_guard<std::mutex> lock(cacheMutex_);
  1191. auto it = cache_.find(modelPath);
  1192. if (it != cache_.end()) {
  1193. cache_.erase(it);
  1194. std::cout << "Invalidated cache for: " << modelPath << std::endl;
  1195. }
  1196. }
  1197. void ModelManager::ModelDetectionCache::clearAllCache() {
  1198. std::lock_guard<std::mutex> lock(cacheMutex_);
  1199. size_t count = cache_.size();
  1200. cache_.clear();
  1201. std::cout << "Cleared " << count << " cache entries" << std::endl;
  1202. }
  1203. std::vector<ModelManager::ModelDetails> ModelManager::checkRequiredModelsExistence(const std::vector<std::string>& requiredModels) {
  1204. std::vector<ModelDetails> modelDetails;
  1205. // Base models directory according to project guidelines
  1206. std::string baseModelsDir = "/data/SD_MODELS";
  1207. for (const auto& requiredModel : requiredModels) {
  1208. ModelDetails details;
  1209. // Parse the required model string (format: "TYPE: filename")
  1210. size_t colonPos = requiredModel.find(':');
  1211. if (colonPos == std::string::npos) {
  1212. // Invalid format, skip
  1213. continue;
  1214. }
  1215. std::string modelType = requiredModel.substr(0, colonPos);
  1216. std::string modelName = requiredModel.substr(colonPos + 1);
  1217. // Trim whitespace
  1218. modelType.erase(0, modelType.find_first_not_of(" \t"));
  1219. modelType.erase(modelType.find_last_not_of(" \t") + 1);
  1220. modelName.erase(0, modelName.find_first_not_of(" \t"));
  1221. modelName.erase(modelName.find_last_not_of(" \t") + 1);
  1222. details.name = modelName;
  1223. details.type = modelType;
  1224. details.is_required = true;
  1225. details.is_recommended = false;
  1226. details.exists = false;
  1227. details.file_size = 0;
  1228. details.path = "";
  1229. details.sha256 = "";
  1230. // Determine the appropriate subdirectory based on model type
  1231. std::string subdirectory;
  1232. if (modelType == "VAE") {
  1233. subdirectory = "vae";
  1234. } else if (modelType == "CLIP-L" || modelType == "CLIP-G") {
  1235. subdirectory = "clip";
  1236. } else if (modelType == "T5XXL") {
  1237. subdirectory = "t5xxl";
  1238. } else if (modelType == "CLIP-Vision") {
  1239. subdirectory = "clip";
  1240. } else if (modelType == "Qwen2-VL" || modelType == "Qwen2-VL-Vision") {
  1241. subdirectory = "qwen2vl";
  1242. } else {
  1243. // For unknown types, check in root directory
  1244. subdirectory = "";
  1245. }
  1246. // Construct the full path to check
  1247. std::string fullPath;
  1248. if (!subdirectory.empty()) {
  1249. fullPath = baseModelsDir + "/" + subdirectory + "/" + modelName;
  1250. } else {
  1251. fullPath = baseModelsDir + "/" + modelName;
  1252. }
  1253. // Check if the file exists
  1254. try {
  1255. if (fs::exists(fullPath) && fs::is_regular_file(fullPath)) {
  1256. details.exists = true;
  1257. details.path = fs::absolute(fullPath).string();
  1258. details.file_size = fs::file_size(fullPath);
  1259. // Try to get cached hash
  1260. std::string jsonPath = fullPath + ".json";
  1261. if (fs::exists(jsonPath)) {
  1262. try {
  1263. std::ifstream jsonFile(jsonPath);
  1264. if (jsonFile.is_open()) {
  1265. nlohmann::json j;
  1266. jsonFile >> j;
  1267. jsonFile.close();
  1268. if (j.contains("sha256") && j["sha256"].is_string()) {
  1269. details.sha256 = j["sha256"].get<std::string>();
  1270. }
  1271. }
  1272. } catch (const std::exception& e) {
  1273. std::cerr << "Error loading hash for " << fullPath << ": " << e.what() << std::endl;
  1274. }
  1275. }
  1276. std::cout << "Found required model: " << modelType << " at " << details.path << std::endl;
  1277. } else {
  1278. std::cout << "Missing required model: " << modelType << " - expected at " << fullPath << std::endl;
  1279. }
  1280. } catch (const fs::filesystem_error& e) {
  1281. std::cerr << "Error checking model existence for " << fullPath << ": " << e.what() << std::endl;
  1282. }
  1283. modelDetails.push_back(details);
  1284. }
  1285. return modelDetails;
  1286. }