server.cpp 224 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697989910010110210310410510610710810911011111211311411511611711811912012112212312412512612712812913013113213313413513613713813914014114214314414514614714814915015115215315415515615715815916016116216316416516616716816917017117217317417517617717817918018118218318418518618718818919019119219319419519619719819920020120220320420520620720820921021121221321421521621721821922022122222322422522622722822923023123223323423523623723823924024124224324424524624724824925025125225325425525625725825926026126226326426526626726826927027127227327427527627727827928028128228328428528628728828929029129229329429529629729829930030130230330430530630730830931031131231331431531631731831932032132232332432532632732832933033133233333433533633733833934034134234334434534634734834935035135235335435535635735835936036136236336436536636736836937037137237337437537637737837938038138238338438538638738838939039139239339439539639739839940040140240340440540640740840941041141241341441541641741841942042142242342442542642742842943043143243343443543643743843944044144244344444544644744844945045145245345445545645745845946046146246346446546646746846947047147247347447547647747847948048148248348448548648748848949049149249349449549649749849950050150250350450550650750850951051151251351451551651751851952052152252352452552652752852953053153253353453553653753853954054154254354454554654754854955055155255355455555655755855956056156256356456556656756856957057157257357457557657757857958058158258358458558658758858959059159259359459559659759859960060160260360460560660760860961061161261361461561661761861962062162262362462562662762862963063163263363463563663763863964064164264364464564664764864965065165265365465565665765865966066166266366466566666766866967067167267367467567667767867968068168268368468568668768868969069169269369469569669769869970070170270370470570670770870971071171271371471571671771871972072172272372472572672772872973073173273373473573673773873974074174274374474574674774874975075175275375475575675775875976076176276376476576676776876977077177277377477577677777877978078178278378478578678778878979079179279379479579679779879980080180280380480580680780880981081181281381481581681781881982082182282382482582682782882983083183283383483583683783883984084184284384484584684784884985085185285385485585685785885986086186286386486586686786886987087187287387487587687787887988088188288388488588688788888989089189289389489589689789889990090190290390490590690790890991091191291391491591691791891992092192292392492592692792892993093193293393493593693793893994094194294394494594694794894995095195295395495595695795895996096196296396496596696796896997097197297397497597697797897998098198298398498598698798898999099199299399499599699799899910001001100210031004100510061007100810091010101110121013101410151016101710181019102010211022102310241025102610271028102910301031103210331034103510361037103810391040104110421043104410451046104710481049105010511052105310541055105610571058105910601061106210631064106510661067106810691070107110721073107410751076107710781079108010811082108310841085108610871088108910901091109210931094109510961097109810991100110111021103110411051106110711081109111011111112111311141115111611171118111911201121112211231124112511261127112811291130113111321133113411351136113711381139114011411142114311441145114611471148114911501151115211531154115511561157115811591160116111621163116411651166116711681169117011711172117311741175117611771178117911801181118211831184118511861187118811891190119111921193119411951196119711981199120012011202120312041205120612071208120912101211121212131214121512161217121812191220122112221223122412251226122712281229123012311232123312341235123612371238123912401241124212431244124512461247124812491250125112521253125412551256125712581259126012611262126312641265126612671268126912701271127212731274127512761277127812791280128112821283128412851286128712881289129012911292129312941295129612971298129913001301130213031304130513061307130813091310131113121313131413151316131713181319132013211322132313241325132613271328132913301331133213331334133513361337133813391340134113421343134413451346134713481349135013511352135313541355135613571358135913601361136213631364136513661367136813691370137113721373137413751376137713781379138013811382138313841385138613871388138913901391139213931394139513961397139813991400140114021403140414051406140714081409141014111412141314141415141614171418141914201421142214231424142514261427142814291430143114321433143414351436143714381439144014411442144314441445144614471448144914501451145214531454145514561457145814591460146114621463146414651466146714681469147014711472147314741475147614771478147914801481148214831484148514861487148814891490149114921493149414951496149714981499150015011502150315041505150615071508150915101511151215131514151515161517151815191520152115221523152415251526152715281529153015311532153315341535153615371538153915401541154215431544154515461547154815491550155115521553155415551556155715581559156015611562156315641565156615671568156915701571157215731574157515761577157815791580158115821583158415851586158715881589159015911592159315941595159615971598159916001601160216031604160516061607160816091610161116121613161416151616161716181619162016211622162316241625162616271628162916301631163216331634163516361637163816391640164116421643164416451646164716481649165016511652165316541655165616571658165916601661166216631664166516661667166816691670167116721673167416751676167716781679168016811682168316841685168616871688168916901691169216931694169516961697169816991700170117021703170417051706170717081709171017111712171317141715171617171718171917201721172217231724172517261727172817291730173117321733173417351736173717381739174017411742174317441745174617471748174917501751175217531754175517561757175817591760176117621763176417651766176717681769177017711772177317741775177617771778177917801781178217831784178517861787178817891790179117921793179417951796179717981799180018011802180318041805180618071808180918101811181218131814181518161817181818191820182118221823182418251826182718281829183018311832183318341835183618371838183918401841184218431844184518461847184818491850185118521853185418551856185718581859186018611862186318641865186618671868186918701871187218731874187518761877187818791880188118821883188418851886188718881889189018911892189318941895189618971898189919001901190219031904190519061907190819091910191119121913191419151916191719181919192019211922192319241925192619271928192919301931193219331934193519361937193819391940194119421943194419451946194719481949195019511952195319541955195619571958195919601961196219631964196519661967196819691970197119721973197419751976197719781979198019811982198319841985198619871988198919901991199219931994199519961997199819992000200120022003200420052006200720082009201020112012201320142015201620172018201920202021202220232024202520262027202820292030203120322033203420352036203720382039204020412042204320442045204620472048204920502051205220532054205520562057205820592060206120622063206420652066206720682069207020712072207320742075207620772078207920802081208220832084208520862087208820892090209120922093209420952096209720982099210021012102210321042105210621072108210921102111211221132114211521162117211821192120212121222123212421252126212721282129213021312132213321342135213621372138213921402141214221432144214521462147214821492150215121522153215421552156215721582159216021612162216321642165216621672168216921702171217221732174217521762177217821792180218121822183218421852186218721882189219021912192219321942195219621972198219922002201220222032204220522062207220822092210221122122213221422152216221722182219222022212222222322242225222622272228222922302231223222332234223522362237223822392240224122422243224422452246224722482249225022512252225322542255225622572258225922602261226222632264226522662267226822692270227122722273227422752276227722782279228022812282228322842285228622872288228922902291229222932294229522962297229822992300230123022303230423052306230723082309231023112312231323142315231623172318231923202321232223232324232523262327232823292330233123322333233423352336233723382339234023412342234323442345234623472348234923502351235223532354235523562357235823592360236123622363236423652366236723682369237023712372237323742375237623772378237923802381238223832384238523862387238823892390239123922393239423952396239723982399240024012402240324042405240624072408240924102411241224132414241524162417241824192420242124222423242424252426242724282429243024312432243324342435243624372438243924402441244224432444244524462447244824492450245124522453245424552456245724582459246024612462246324642465246624672468246924702471247224732474247524762477247824792480248124822483248424852486248724882489249024912492249324942495249624972498249925002501250225032504250525062507250825092510251125122513251425152516251725182519252025212522252325242525252625272528252925302531253225332534253525362537253825392540254125422543254425452546254725482549255025512552255325542555255625572558255925602561256225632564256525662567256825692570257125722573257425752576257725782579258025812582258325842585258625872588258925902591259225932594259525962597259825992600260126022603260426052606260726082609261026112612261326142615261626172618261926202621262226232624262526262627262826292630263126322633263426352636263726382639264026412642264326442645264626472648264926502651265226532654265526562657265826592660266126622663266426652666266726682669267026712672267326742675267626772678267926802681268226832684268526862687268826892690269126922693269426952696269726982699270027012702270327042705270627072708270927102711271227132714271527162717271827192720272127222723272427252726272727282729273027312732273327342735273627372738273927402741274227432744274527462747274827492750275127522753275427552756275727582759276027612762276327642765276627672768276927702771277227732774277527762777277827792780278127822783278427852786278727882789279027912792279327942795279627972798279928002801280228032804280528062807280828092810281128122813281428152816281728182819282028212822282328242825282628272828282928302831283228332834283528362837283828392840284128422843284428452846284728482849285028512852285328542855285628572858285928602861286228632864286528662867286828692870287128722873287428752876287728782879288028812882288328842885288628872888288928902891289228932894289528962897289828992900290129022903290429052906290729082909291029112912291329142915291629172918291929202921292229232924292529262927292829292930293129322933293429352936293729382939294029412942294329442945294629472948294929502951295229532954295529562957295829592960296129622963296429652966296729682969297029712972297329742975297629772978297929802981298229832984298529862987298829892990299129922993299429952996299729982999300030013002300330043005300630073008300930103011301230133014301530163017301830193020302130223023302430253026302730283029303030313032303330343035303630373038303930403041304230433044304530463047304830493050305130523053305430553056305730583059306030613062306330643065306630673068306930703071307230733074307530763077307830793080308130823083308430853086308730883089309030913092309330943095309630973098309931003101310231033104310531063107310831093110311131123113311431153116311731183119312031213122312331243125312631273128312931303131313231333134313531363137313831393140314131423143314431453146314731483149315031513152315331543155315631573158315931603161316231633164316531663167316831693170317131723173317431753176317731783179318031813182318331843185318631873188318931903191319231933194319531963197319831993200320132023203320432053206320732083209321032113212321332143215321632173218321932203221322232233224322532263227322832293230323132323233323432353236323732383239324032413242324332443245324632473248324932503251325232533254325532563257325832593260326132623263326432653266326732683269327032713272327332743275327632773278327932803281328232833284328532863287328832893290329132923293329432953296329732983299330033013302330333043305330633073308330933103311331233133314331533163317331833193320332133223323332433253326332733283329333033313332333333343335333633373338333933403341334233433344334533463347334833493350335133523353335433553356335733583359336033613362336333643365336633673368336933703371337233733374337533763377337833793380338133823383338433853386338733883389339033913392339333943395339633973398339934003401340234033404340534063407340834093410341134123413341434153416341734183419342034213422342334243425342634273428342934303431343234333434343534363437343834393440344134423443344434453446344734483449345034513452345334543455345634573458345934603461346234633464346534663467346834693470347134723473347434753476347734783479348034813482348334843485348634873488348934903491349234933494349534963497349834993500350135023503350435053506350735083509351035113512351335143515351635173518351935203521352235233524352535263527352835293530353135323533353435353536353735383539354035413542354335443545354635473548354935503551355235533554355535563557355835593560356135623563356435653566356735683569357035713572357335743575357635773578357935803581358235833584358535863587358835893590359135923593359435953596359735983599360036013602360336043605360636073608360936103611361236133614361536163617361836193620362136223623362436253626362736283629363036313632363336343635363636373638363936403641364236433644364536463647364836493650365136523653365436553656365736583659366036613662366336643665366636673668366936703671367236733674367536763677367836793680368136823683368436853686368736883689369036913692369336943695369636973698369937003701370237033704370537063707370837093710371137123713371437153716371737183719372037213722372337243725372637273728372937303731373237333734373537363737373837393740374137423743374437453746374737483749375037513752375337543755375637573758375937603761376237633764376537663767376837693770377137723773377437753776377737783779378037813782378337843785378637873788378937903791379237933794379537963797379837993800380138023803380438053806380738083809381038113812381338143815381638173818381938203821382238233824382538263827382838293830383138323833383438353836383738383839384038413842384338443845384638473848384938503851385238533854385538563857385838593860386138623863386438653866386738683869387038713872387338743875387638773878387938803881388238833884388538863887388838893890389138923893389438953896389738983899390039013902390339043905390639073908390939103911391239133914391539163917391839193920392139223923392439253926392739283929393039313932393339343935393639373938393939403941394239433944394539463947394839493950395139523953395439553956395739583959396039613962396339643965396639673968396939703971397239733974397539763977397839793980398139823983398439853986398739883989399039913992399339943995399639973998399940004001400240034004400540064007400840094010401140124013401440154016401740184019402040214022402340244025402640274028402940304031403240334034403540364037403840394040404140424043404440454046404740484049405040514052405340544055405640574058405940604061406240634064406540664067406840694070407140724073407440754076407740784079408040814082408340844085408640874088408940904091409240934094409540964097409840994100410141024103410441054106410741084109411041114112411341144115411641174118411941204121412241234124412541264127412841294130413141324133413441354136413741384139414041414142414341444145414641474148414941504151415241534154415541564157415841594160416141624163416441654166416741684169417041714172417341744175417641774178417941804181418241834184418541864187418841894190419141924193419441954196419741984199420042014202420342044205420642074208420942104211421242134214421542164217421842194220422142224223422442254226422742284229423042314232423342344235423642374238423942404241424242434244424542464247424842494250425142524253425442554256425742584259426042614262426342644265426642674268426942704271427242734274427542764277427842794280428142824283428442854286428742884289429042914292429342944295429642974298429943004301430243034304430543064307430843094310431143124313431443154316431743184319432043214322432343244325432643274328432943304331433243334334433543364337433843394340434143424343434443454346434743484349435043514352435343544355435643574358435943604361436243634364436543664367436843694370437143724373437443754376437743784379438043814382438343844385438643874388438943904391439243934394439543964397439843994400440144024403440444054406440744084409441044114412441344144415441644174418441944204421442244234424442544264427442844294430443144324433443444354436443744384439444044414442444344444445444644474448444944504451445244534454445544564457445844594460446144624463446444654466446744684469447044714472447344744475447644774478447944804481448244834484448544864487448844894490449144924493449444954496449744984499450045014502450345044505450645074508450945104511451245134514451545164517451845194520452145224523452445254526452745284529453045314532453345344535453645374538453945404541454245434544454545464547454845494550455145524553455445554556455745584559456045614562456345644565456645674568456945704571457245734574457545764577457845794580458145824583458445854586458745884589459045914592459345944595459645974598459946004601460246034604460546064607460846094610461146124613461446154616461746184619462046214622462346244625462646274628462946304631463246334634463546364637463846394640464146424643464446454646464746484649465046514652465346544655465646574658465946604661466246634664466546664667466846694670467146724673467446754676467746784679468046814682468346844685468646874688468946904691469246934694469546964697469846994700470147024703470447054706470747084709471047114712471347144715471647174718471947204721472247234724472547264727472847294730473147324733473447354736473747384739474047414742474347444745474647474748474947504751475247534754475547564757475847594760476147624763476447654766476747684769477047714772477347744775477647774778477947804781478247834784478547864787478847894790479147924793479447954796479747984799480048014802480348044805480648074808480948104811481248134814481548164817481848194820482148224823482448254826482748284829483048314832483348344835483648374838483948404841484248434844484548464847484848494850485148524853485448554856485748584859486048614862486348644865486648674868486948704871487248734874487548764877487848794880488148824883488448854886488748884889489048914892489348944895489648974898489949004901490249034904490549064907490849094910491149124913491449154916491749184919492049214922492349244925492649274928492949304931493249334934493549364937493849394940494149424943494449454946494749484949495049514952495349544955495649574958495949604961496249634964496549664967496849694970497149724973497449754976497749784979498049814982498349844985498649874988498949904991499249934994499549964997499849995000500150025003500450055006500750085009501050115012501350145015501650175018501950205021502250235024502550265027502850295030503150325033503450355036503750385039504050415042504350445045504650475048504950505051505250535054505550565057505850595060506150625063506450655066506750685069507050715072507350745075507650775078507950805081508250835084508550865087508850895090509150925093509450955096509750985099510051015102510351045105510651075108510951105111511251135114511551165117511851195120512151225123512451255126512751285129513051315132513351345135513651375138513951405141514251435144514551465147514851495150515151525153515451555156515751585159516051615162516351645165516651675168516951705171517251735174517551765177517851795180518151825183518451855186518751885189519051915192519351945195519651975198519952005201
  1. #include "server.h"
  2. #include <httplib.h>
  3. #include <algorithm>
  4. #include <chrono>
  5. #include <filesystem>
  6. #include <fstream>
  7. #include <iostream>
  8. #include <nlohmann/json.hpp>
  9. #include <random>
  10. #include <sstream>
  11. #include <thread>
  12. #include "auth_middleware.h"
  13. #include "generation_queue.h"
  14. #include "logger.h"
  15. #include "model_manager.h"
  16. #include "user_manager.h"
  17. #include "utils.h"
  18. #include "version.h"
  19. // Include stb_image for loading images (implementation is in generation_queue.cpp)
  20. #include <arpa/inet.h>
  21. #include <netinet/in.h>
  22. #include <sys/socket.h>
  23. #include <unistd.h>
  24. #include "../stable-diffusion.cpp-src/thirdparty/stb_image.h"
  25. Server::Server(ModelManager* modelManager, GenerationQueue* generationQueue, const std::string& outputDir, const std::string& uiDir, const ServerConfig& config)
  26. : m_modelManager(modelManager), m_generationQueue(generationQueue), m_isRunning(false), m_startupFailed(false), m_port(config.port), m_outputDir(outputDir), m_uiDir(uiDir), m_userManager(nullptr), m_authMiddleware(nullptr), m_config(config) {
  27. m_httpServer = std::make_unique<httplib::Server>();
  28. }
  29. Server::~Server() {
  30. stop();
  31. }
  32. bool Server::start(const std::string& host, int port) {
  33. if (m_isRunning.load()) {
  34. return false;
  35. }
  36. m_host = host;
  37. m_port = port;
  38. // Validate host and port
  39. if (host.empty() || (port < 1 || port > 65535)) {
  40. return false;
  41. }
  42. // Set up CORS headers
  43. setupCORS();
  44. // Register API endpoints
  45. registerEndpoints();
  46. // Reset startup flags
  47. m_startupFailed.store(false);
  48. // Start server in a separate thread
  49. m_serverThread = std::thread(&Server::serverThreadFunction, this, host, port);
  50. // Wait for server to actually start and bind to the port
  51. // Give more time for server to actually start and bind
  52. for (int i = 0; i < 100; i++) { // Wait up to 10 seconds
  53. std::this_thread::sleep_for(std::chrono::milliseconds(100));
  54. // Check if startup failed early
  55. if (m_startupFailed.load()) {
  56. if (m_serverThread.joinable()) {
  57. m_serverThread.join();
  58. }
  59. return false;
  60. }
  61. if (m_isRunning.load()) {
  62. // Give it a moment more to ensure server is fully started
  63. std::this_thread::sleep_for(std::chrono::milliseconds(500));
  64. if (m_isRunning.load()) {
  65. return true;
  66. }
  67. }
  68. }
  69. if (m_isRunning.load()) {
  70. return true;
  71. } else {
  72. if (m_serverThread.joinable()) {
  73. m_serverThread.join();
  74. }
  75. return false;
  76. }
  77. }
  78. void Server::stop() {
  79. // Use atomic check to ensure thread safety
  80. bool wasRunning = m_isRunning.exchange(false);
  81. if (!wasRunning) {
  82. return; // Already stopped
  83. }
  84. if (m_httpServer) {
  85. m_httpServer->stop();
  86. // Give the server a moment to stop the blocking listen call
  87. std::this_thread::sleep_for(std::chrono::milliseconds(100));
  88. // If server thread is still running, try to force unblock the listen call
  89. // by making a quick connection to the server port
  90. if (m_serverThread.joinable()) {
  91. try {
  92. // Create a quick connection to interrupt the blocking listen
  93. httplib::Client client("127.0.0.1", m_port);
  94. client.set_connection_timeout(0, m_config.connectionTimeoutMs * 1000); // Convert ms to microseconds
  95. client.set_read_timeout(0, m_config.readTimeoutMs * 1000); // Convert ms to microseconds
  96. client.set_write_timeout(0, m_config.writeTimeoutMs * 1000); // Convert ms to microseconds
  97. auto res = client.Get("/api/health");
  98. // We don't care about the response, just trying to unblock
  99. } catch (...) {
  100. // Ignore any connection errors - we're just trying to unblock
  101. }
  102. }
  103. }
  104. if (m_serverThread.joinable()) {
  105. m_serverThread.join();
  106. }
  107. }
  108. bool Server::isRunning() const {
  109. return m_isRunning.load();
  110. }
  111. void Server::waitForStop() {
  112. if (m_serverThread.joinable()) {
  113. m_serverThread.join();
  114. }
  115. }
  116. void Server::registerEndpoints() {
  117. // Register authentication endpoints first (before applying middleware)
  118. registerAuthEndpoints();
  119. m_httpServer->set_logger([&](const httplib::Request& req, const httplib::Response& res) {
  120. // LOG_INFO(req.method + " " + req.path + " " + std::to_string(res.status));
  121. logHttpAccess(req, res, req.path);
  122. });
  123. // Health check endpoint (public)
  124. m_httpServer->Get("/api/health", [this](const httplib::Request& req, httplib::Response& res) {
  125. LOG_DEBUG("Health endpoint lambda called");
  126. handleHealthCheck(req, res);
  127. });
  128. // API status endpoint (public)
  129. m_httpServer->Get("/api/status", [this](const httplib::Request& req, httplib::Response& res) {
  130. handleApiStatus(req, res);
  131. });
  132. // Version information endpoint (public)
  133. m_httpServer->Get("/api/version", [this](const httplib::Request& req, httplib::Response& res) {
  134. handleVersion(req, res);
  135. });
  136. // Apply authentication middleware to protected endpoints
  137. auto withAuth = [this](std::function<void(const httplib::Request&, httplib::Response&)> handler) {
  138. return [this, handler](const httplib::Request& req, httplib::Response& res) {
  139. if (m_authMiddleware) {
  140. AuthContext authContext = m_authMiddleware->authenticate(req, res);
  141. if (!authContext.authenticated) {
  142. m_authMiddleware->sendAuthError(res, authContext.errorMessage, authContext.errorCode);
  143. return;
  144. }
  145. }
  146. handler(req, res);
  147. };
  148. };
  149. // Specialized generation endpoints (protected)
  150. m_httpServer->Post("/api/generate/text2img", withAuth([this](const httplib::Request& req, httplib::Response& res) {
  151. handleText2Img(req, res);
  152. }));
  153. m_httpServer->Post("/api/generate/img2img", withAuth([this](const httplib::Request& req, httplib::Response& res) {
  154. handleImg2Img(req, res);
  155. }));
  156. m_httpServer->Post("/api/generate/controlnet", withAuth([this](const httplib::Request& req, httplib::Response& res) {
  157. handleControlNet(req, res);
  158. }));
  159. m_httpServer->Post("/api/generate/upscale", withAuth([this](const httplib::Request& req, httplib::Response& res) {
  160. handleUpscale(req, res);
  161. }));
  162. m_httpServer->Post("/api/generate/inpainting", withAuth([this](const httplib::Request& req, httplib::Response& res) {
  163. handleInpainting(req, res);
  164. }));
  165. // Utility endpoints (now protected - require authentication)
  166. m_httpServer->Get("/api/samplers", withAuth([this](const httplib::Request& req, httplib::Response& res) {
  167. handleSamplers(req, res);
  168. }));
  169. m_httpServer->Get("/api/schedulers", withAuth([this](const httplib::Request& req, httplib::Response& res) {
  170. handleSchedulers(req, res);
  171. }));
  172. m_httpServer->Get("/api/parameters", withAuth([this](const httplib::Request& req, httplib::Response& res) {
  173. handleParameters(req, res);
  174. }));
  175. m_httpServer->Post("/api/validate", [this](const httplib::Request& req, httplib::Response& res) {
  176. handleValidate(req, res);
  177. });
  178. m_httpServer->Post("/api/estimate", withAuth([this](const httplib::Request& req, httplib::Response& res) {
  179. handleEstimate(req, res);
  180. }));
  181. m_httpServer->Get("/api/config", withAuth([this](const httplib::Request& req, httplib::Response& res) {
  182. handleConfig(req, res);
  183. }));
  184. m_httpServer->Get("/api/system", withAuth([this](const httplib::Request& req, httplib::Response& res) {
  185. handleSystem(req, res);
  186. }));
  187. m_httpServer->Post("/api/system/restart", withAuth([this](const httplib::Request& req, httplib::Response& res) {
  188. handleSystemRestart(req, res);
  189. }));
  190. // Models list endpoint (now protected - require authentication)
  191. m_httpServer->Get("/api/models", withAuth([this](const httplib::Request& req, httplib::Response& res) {
  192. handleModelsList(req, res);
  193. }));
  194. // Model management endpoints (now protected - require authentication) - MUST be before catch-all routes
  195. m_httpServer->Get("/api/models/types", withAuth([this](const httplib::Request& req, httplib::Response& res) {
  196. handleModelTypes(req, res);
  197. }));
  198. m_httpServer->Get("/api/models/directories", withAuth([this](const httplib::Request& req, httplib::Response& res) {
  199. handleModelDirectories(req, res);
  200. }));
  201. m_httpServer->Post("/api/models/refresh", withAuth([this](const httplib::Request& req, httplib::Response& res) {
  202. handleRefreshModels(req, res);
  203. }));
  204. m_httpServer->Post("/api/models/hash", withAuth([this](const httplib::Request& req, httplib::Response& res) {
  205. handleHashModels(req, res);
  206. }));
  207. m_httpServer->Post("/api/models/convert", withAuth([this](const httplib::Request& req, httplib::Response& res) {
  208. handleConvertModel(req, res);
  209. }));
  210. m_httpServer->Get("/api/models/stats", withAuth([this](const httplib::Request& req, httplib::Response& res) {
  211. handleModelStats(req, res);
  212. }));
  213. m_httpServer->Post("/api/models/batch", withAuth([this](const httplib::Request& req, httplib::Response& res) {
  214. handleBatchModels(req, res);
  215. }));
  216. // Model validation endpoints (already protected with withAuth) - MUST be before catch-all routes
  217. m_httpServer->Post("/api/models/validate", withAuth([this](const httplib::Request& req, httplib::Response& res) {
  218. handleValidateModel(req, res);
  219. }));
  220. m_httpServer->Post("/api/models/compatible", withAuth([this](const httplib::Request& req, httplib::Response& res) {
  221. handleCheckCompatibility(req, res);
  222. }));
  223. m_httpServer->Post("/api/models/requirements", withAuth([this](const httplib::Request& req, httplib::Response& res) {
  224. handleModelRequirements(req, res);
  225. }));
  226. // Model-specific endpoints (catch-all routes) - MUST be after specific routes
  227. m_httpServer->Get("/api/models/(.*)", [this](const httplib::Request& req, httplib::Response& res) {
  228. handleModelInfo(req, res);
  229. });
  230. m_httpServer->Post("/api/models/(.*)/load", withAuth([this](const httplib::Request& req, httplib::Response& res) {
  231. handleLoadModelById(req, res);
  232. }));
  233. m_httpServer->Post("/api/models/(.*)/unload", withAuth([this](const httplib::Request& req, httplib::Response& res) {
  234. handleUnloadModelById(req, res);
  235. }));
  236. // Queue status endpoint (now protected - require authentication)
  237. m_httpServer->Get("/api/queue/status", withAuth([this](const httplib::Request& req, httplib::Response& res) {
  238. handleQueueStatus(req, res);
  239. }));
  240. // Download job output file endpoint (must be before job status endpoint to match more specific pattern first)
  241. // Note: This endpoint is public to allow frontend to display generated images without authentication
  242. m_httpServer->Get("/api/queue/job/(.*)/output/(.*)", [this](const httplib::Request& req, httplib::Response& res) {
  243. handleDownloadOutput(req, res);
  244. });
  245. // Get job output by job ID endpoint (public to allow frontend to display generated images without authentication)
  246. // m_httpServer->Get("/api/v1/jobs/(.*)/output", [this](const httplib::Request& req, httplib::Response& res) {
  247. // handleJobOutput(req, res);
  248. // });
  249. // Get specific job output file by filename (public)
  250. m_httpServer->Get("/api/v1/jobs/(.*)/output/(.*)", [this](const httplib::Request& req, httplib::Response& res) {
  251. handleJobOutputFile(req, res);
  252. });
  253. // Download image from URL endpoint (public for CORS-free image handling)
  254. m_httpServer->Get("/api/image/download", [this](const httplib::Request& req, httplib::Response& res) {
  255. handleDownloadImageFromUrl(req, res);
  256. });
  257. // Image resize endpoint (protected)
  258. m_httpServer->Post("/api/image/resize", withAuth([this](const httplib::Request& req, httplib::Response& res) {
  259. handleImageResize(req, res);
  260. }));
  261. // Image crop endpoint (protected)
  262. m_httpServer->Post("/api/image/crop", withAuth([this](const httplib::Request& req, httplib::Response& res) {
  263. handleImageCrop(req, res);
  264. }));
  265. // Job status endpoint (now protected - require authentication)
  266. m_httpServer->Get("/api/queue/job/(.*)", withAuth([this](const httplib::Request& req, httplib::Response& res) {
  267. handleJobStatus(req, res);
  268. }));
  269. // Cancel job endpoint (protected)
  270. m_httpServer->Post("/api/queue/cancel", withAuth([this](const httplib::Request& req, httplib::Response& res) {
  271. handleCancelJob(req, res);
  272. }));
  273. // Clear queue endpoint (protected)
  274. m_httpServer->Post("/api/queue/clear", withAuth([this](const httplib::Request& req, httplib::Response& res) {
  275. handleClearQueue(req, res);
  276. }));
  277. // Serve static web UI files if uiDir is configured
  278. if (!m_uiDir.empty() && std::filesystem::exists(m_uiDir)) {
  279. LOG_INFO("Serving static UI files from: " + m_uiDir + " at /ui");
  280. // Read UI version from version.nlohmann::json if available
  281. std::string uiVersion = "unknown";
  282. std::string versionFilePath = m_uiDir + "/version.nlohmann::json";
  283. if (std::filesystem::exists(versionFilePath)) {
  284. try {
  285. std::ifstream versionFile(versionFilePath);
  286. if (versionFile.is_open()) {
  287. nlohmann::json versionData = nlohmann::json::parse(versionFile);
  288. if (versionData.contains("version")) {
  289. uiVersion = versionData["version"].get<std::string>();
  290. }
  291. versionFile.close();
  292. }
  293. } catch (const std::exception& e) {
  294. LOG_ERROR("Failed to read UI version: " + std::string(e.what()));
  295. }
  296. }
  297. LOG_INFO("UI version: " + uiVersion);
  298. // Serve dynamic config.js that provides runtime configuration to the web UI
  299. m_httpServer->Get("/ui/config.js", [this, uiVersion](const httplib::Request& /*req*/, httplib::Response& res) {
  300. // Generate JavaScript configuration with current server settings
  301. std::ostringstream configJs;
  302. configJs << "// Auto-generated configuration\n"
  303. << "window.__SERVER_CONFIG__ = {\n"
  304. << " apiUrl: 'http://" << m_host << ":" << m_port << "',\n"
  305. << " apiBasePath: '/api',\n"
  306. << " host: '" << m_host << "',\n"
  307. << " port: " << m_port << ",\n"
  308. << " uiVersion: '" << uiVersion << "',\n";
  309. // Add authentication method information
  310. if (m_authMiddleware) {
  311. auto authConfig = m_authMiddleware->getConfig();
  312. std::string authMethod = "none";
  313. switch (authConfig.authMethod) {
  314. case AuthMethod::UNIX:
  315. authMethod = "unix";
  316. break;
  317. case AuthMethod::JWT:
  318. authMethod = "jwt";
  319. break;
  320. default:
  321. authMethod = "none";
  322. break;
  323. }
  324. configJs << " authMethod: '" << authMethod << "',\n"
  325. << " authEnabled: " << (authConfig.authMethod != AuthMethod::NONE ? "true" : "false") << "\n";
  326. } else {
  327. configJs << " authMethod: 'none',\n"
  328. << " authEnabled: false\n";
  329. }
  330. configJs << "};\n";
  331. // No cache for config.js - always fetch fresh
  332. res.set_header("Cache-Control", "no-cache, no-store, must-revalidate");
  333. res.set_header("Pragma", "no-cache");
  334. res.set_header("Expires", "0");
  335. res.set_content(configJs.str(), "application/javascript");
  336. });
  337. // Set up file request handler for caching static assets
  338. m_httpServer->set_file_request_handler([uiVersion](const httplib::Request& req, httplib::Response& res) {
  339. // Add cache headers based on file type and version
  340. std::string path = req.path;
  341. // For versioned static assets (.js, .css, images), use long cache
  342. if (path.find("/_next/") != std::string::npos ||
  343. path.find(".js") != std::string::npos ||
  344. path.find(".css") != std::string::npos ||
  345. path.find(".png") != std::string::npos ||
  346. path.find(".jpg") != std::string::npos ||
  347. path.find(".svg") != std::string::npos ||
  348. path.find(".ico") != std::string::npos ||
  349. path.find(".woff") != std::string::npos ||
  350. path.find(".woff2") != std::string::npos ||
  351. path.find(".ttf") != std::string::npos) {
  352. // Long cache (1 year) for static assets
  353. res.set_header("Cache-Control", "public, max-age=31536000, immutable");
  354. // Add ETag based on UI version for cache validation
  355. res.set_header("ETag", "\"" + uiVersion + "\"");
  356. // Check If-None-Match for conditional requests
  357. if (req.has_header("If-None-Match")) {
  358. std::string clientETag = req.get_header_value("If-None-Match");
  359. if (clientETag == "\"" + uiVersion + "\"") {
  360. res.status = 304; // Not Modified
  361. return;
  362. }
  363. }
  364. } else if (path.find(".html") != std::string::npos || path == "/ui/" || path == "/ui") {
  365. // HTML files should revalidate but can be cached briefly
  366. res.set_header("Cache-Control", "public, max-age=0, must-revalidate");
  367. res.set_header("ETag", "\"" + uiVersion + "\"");
  368. }
  369. });
  370. // Create a handler for UI routes with authentication check
  371. auto uiHandler = [this](const httplib::Request& req, httplib::Response& res) {
  372. // Check if authentication is enabled
  373. if (m_authMiddleware) {
  374. auto authConfig = m_authMiddleware->getConfig();
  375. if (authConfig.authMethod != AuthMethod::NONE) {
  376. // Authentication is enabled, check if user is authenticated
  377. AuthContext authContext = m_authMiddleware->authenticate(req, res);
  378. // For Unix auth, we need to check if the user is authenticated
  379. // The authenticateUnix function will return a guest context for UI requests
  380. // when no Authorization header is present, but we still need to show the login page
  381. if (!authContext.authenticated) {
  382. // Check if this is a request for a static asset (JS, CSS, images)
  383. // These should be served even without authentication to allow the login page to work
  384. bool isStaticAsset = false;
  385. std::string path = req.path;
  386. if (path.find(".js") != std::string::npos ||
  387. path.find(".css") != std::string::npos ||
  388. path.find(".png") != std::string::npos ||
  389. path.find(".jpg") != std::string::npos ||
  390. path.find(".jpeg") != std::string::npos ||
  391. path.find(".svg") != std::string::npos ||
  392. path.find(".ico") != std::string::npos ||
  393. path.find("/_next/") != std::string::npos) {
  394. isStaticAsset = true;
  395. }
  396. // For static assets, allow them to be served without authentication
  397. if (isStaticAsset) {
  398. // Continue to serve the file
  399. } else {
  400. // For HTML requests, redirect to login page
  401. if (req.path.find(".html") != std::string::npos ||
  402. req.path == "/ui/" || req.path == "/ui") {
  403. // Serve the login page instead of the requested page
  404. std::string loginPagePath = m_uiDir + "/login.html";
  405. if (std::filesystem::exists(loginPagePath)) {
  406. std::ifstream loginFile(loginPagePath);
  407. if (loginFile.is_open()) {
  408. std::string content((std::istreambuf_iterator<char>(loginFile)),
  409. std::istreambuf_iterator<char>());
  410. res.set_content(content, "text/html; charset=utf-8");
  411. return;
  412. }
  413. }
  414. // If login.html doesn't exist, serve a simple login page
  415. std::string simpleLoginPage = R"(
  416. <!DOCTYPE html>
  417. <html>
  418. <head>
  419. <title>Login Required</title>
  420. <style>
  421. body { font-family: Arial, sans-serif; max-width: 500px; margin: 100px auto; padding: 20px; }
  422. .form-group { margin-bottom: 15px; }
  423. label { display: block; margin-bottom: 5px; }
  424. input { width: 100%; padding: 8px; box-sizing: border-box; }
  425. button { background-color: #007bff; color: white; padding: 10px 15px; border: none; cursor: pointer; }
  426. .error { color: red; margin-top: 10px; }
  427. </style>
  428. </head>
  429. <body>
  430. <h1>Login Required</h1>
  431. <p>Please enter your username to continue.</p>
  432. <form id="loginForm">
  433. <div class="form-group">
  434. <label for="username">Username:</label>
  435. <input type="text" id="username" name="username" required>
  436. </div>
  437. <button type="submit">Login</button>
  438. </form>
  439. <div id="error" class="error"></div>
  440. <script>
  441. document.getElementById('loginForm').addEventListener('submit', async (e) => {
  442. e.preventDefault();
  443. const username = document.getElementById('username').value;
  444. const errorDiv = document.getElementById('error');
  445. try {
  446. const response = await fetch('/api/auth/login', {
  447. method: 'POST',
  448. headers: { 'Content-Type': 'application/nlohmann::json' },
  449. body: JSON.stringify({ username })
  450. });
  451. if (response.ok) {
  452. const data = await response.nlohmann::json();
  453. localStorage.setItem('auth_token', data.token);
  454. localStorage.setItem('unix_user', username);
  455. window.location.reload();
  456. } else {
  457. const error = await response.nlohmann::json();
  458. errorDiv.textContent = error.message || 'Login failed';
  459. }
  460. } catch (err) {
  461. errorDiv.textContent = 'Login failed: ' + err.message;
  462. }
  463. });
  464. </script>
  465. </body>
  466. </html>
  467. )";
  468. res.set_content(simpleLoginPage, "text/html; charset=utf-8");
  469. return;
  470. } else {
  471. // For non-HTML files, return unauthorized
  472. m_authMiddleware->sendAuthError(res, "Authentication required", "AUTH_REQUIRED");
  473. return;
  474. }
  475. }
  476. }
  477. }
  478. }
  479. // If we get here, either auth is disabled or user is authenticated
  480. // Serve the requested file
  481. std::string filePath = req.path.substr(3); // Remove "/ui" prefix
  482. if (filePath.empty() || filePath == "/") {
  483. filePath = "/index.html";
  484. } else if (!filePath.empty() && filePath[0] != '/') {
  485. filePath = "/" + filePath;
  486. }
  487. // For Next.js static export, try .html extension first
  488. if (filePath != "/index.html" && !filePath.empty()) {
  489. std::string htmlPath = filePath;
  490. if (!htmlPath.empty() && htmlPath.back() != '/') {
  491. htmlPath += ".html";
  492. } else if (!htmlPath.empty()) {
  493. htmlPath = htmlPath.substr(0, htmlPath.size() - 1) + ".html";
  494. }
  495. std::string testPath = m_uiDir + htmlPath;
  496. if (std::filesystem::exists(testPath) && std::filesystem::is_regular_file(testPath)) {
  497. filePath = htmlPath;
  498. }
  499. }
  500. std::string fullPath = m_uiDir + filePath;
  501. // Check if path corresponds to a directory, if so append index.html
  502. if (std::filesystem::exists(fullPath) && std::filesystem::is_directory(fullPath)) {
  503. fullPath += "/index.html";
  504. }
  505. if (std::filesystem::exists(fullPath) && std::filesystem::is_regular_file(fullPath)) {
  506. std::ifstream file(fullPath, std::ios::binary);
  507. if (file.is_open()) {
  508. std::string content((std::istreambuf_iterator<char>(file)),
  509. std::istreambuf_iterator<char>());
  510. // Determine content type based on file extension
  511. std::string contentType = "text/plain";
  512. if (fullPath.find(".html") != std::string::npos) {
  513. contentType = "text/html; charset=utf-8";
  514. } else if (fullPath.find(".js") != std::string::npos) {
  515. contentType = "application/javascript; charset=utf-8";
  516. } else if (fullPath.find(".css") != std::string::npos) {
  517. contentType = "text/css; charset=utf-8";
  518. } else if (fullPath.find(".png") != std::string::npos) {
  519. contentType = "image/png";
  520. } else if (fullPath.find(".jpg") != std::string::npos || fullPath.find(".jpeg") != std::string::npos) {
  521. contentType = "image/jpeg";
  522. } else if (fullPath.find(".svg") != std::string::npos) {
  523. contentType = "image/svg+xml";
  524. } else if (fullPath.find(".json") != std::string::npos) {
  525. contentType = "application/json; charset=utf-8";
  526. }
  527. res.set_content(content, contentType);
  528. } else {
  529. res.status = 404;
  530. res.set_content("File not found", "text/plain");
  531. }
  532. } else {
  533. // For SPA routing, if the file doesn't exist, serve index.html
  534. // This allows Next.js to handle client-side routing
  535. std::string indexPath = m_uiDir + "/index.html";
  536. if (std::filesystem::exists(indexPath)) {
  537. std::ifstream indexFile(indexPath, std::ios::binary);
  538. if (indexFile.is_open()) {
  539. std::string content((std::istreambuf_iterator<char>(indexFile)),
  540. std::istreambuf_iterator<char>());
  541. res.set_content(content, "text/html; charset=utf-8");
  542. } else {
  543. res.status = 404;
  544. res.set_content("File not found", "text/plain");
  545. }
  546. } else {
  547. res.status = 404;
  548. res.set_content("File not found", "text/plain");
  549. }
  550. }
  551. };
  552. // Set up UI routes with authentication
  553. m_httpServer->Get("/ui/.*", uiHandler);
  554. // Redirect /ui to /ui/ to ensure proper routing
  555. m_httpServer->Get("/ui", [](const httplib::Request& /*req*/, httplib::Response& res) {
  556. res.set_redirect("/ui/");
  557. });
  558. }
  559. }
  560. void Server::setAuthComponents(std::shared_ptr<UserManager> userManager, std::shared_ptr<AuthMiddleware> authMiddleware) {
  561. m_userManager = userManager;
  562. m_authMiddleware = authMiddleware;
  563. }
  564. void Server::registerAuthEndpoints() {
  565. // Login endpoint
  566. m_httpServer->Post("/api/auth/login", [this](const httplib::Request& req, httplib::Response& res) {
  567. handleLogin(req, res);
  568. });
  569. // Logout endpoint
  570. m_httpServer->Post("/api/auth/logout", [this](const httplib::Request& req, httplib::Response& res) {
  571. handleLogout(req, res);
  572. });
  573. // Token validation endpoint
  574. m_httpServer->Get("/api/auth/validate", [this](const httplib::Request& req, httplib::Response& res) {
  575. handleValidateToken(req, res);
  576. });
  577. // Refresh token endpoint
  578. m_httpServer->Post("/api/auth/refresh", [this](const httplib::Request& req, httplib::Response& res) {
  579. handleRefreshToken(req, res);
  580. });
  581. // Get current user endpoint
  582. m_httpServer->Get("/api/auth/me", [this](const httplib::Request& req, httplib::Response& res) {
  583. handleGetCurrentUser(req, res);
  584. });
  585. }
  586. void Server::handleLogin(const httplib::Request& req, httplib::Response& res) {
  587. std::string requestId = generateRequestId();
  588. try {
  589. if (!m_userManager || !m_authMiddleware) {
  590. sendErrorResponse(res, "Authentication system not available", 500, "AUTH_UNAVAILABLE", requestId);
  591. return;
  592. }
  593. // Parse request body
  594. nlohmann::json requestJson;
  595. try {
  596. requestJson = nlohmann::json::parse(req.body);
  597. } catch (const nlohmann::json::parse_error& e) {
  598. sendErrorResponse(res, std::string("Invalid JSON: ") + e.what(), 400, "JSON_PARSE_ERROR", requestId);
  599. return;
  600. }
  601. // Check if using Unix authentication
  602. if (m_authMiddleware->getConfig().authMethod == AuthMethod::UNIX) {
  603. // For Unix auth, get username and password from request body
  604. std::string username = requestJson.value("username", "");
  605. std::string password = requestJson.value("password", "");
  606. if (username.empty()) {
  607. sendErrorResponse(res, "Missing username", 400, "MISSING_USERNAME", requestId);
  608. return;
  609. }
  610. // Check if PAM is enabled - if so, password is required
  611. if (m_userManager->isPamAuthEnabled() && password.empty()) {
  612. sendErrorResponse(res, "Password is required for Unix authentication", 400, "MISSING_PASSWORD", requestId);
  613. return;
  614. }
  615. // Authenticate Unix user (with or without password depending on PAM)
  616. auto result = m_userManager->authenticateUnix(username, password);
  617. if (!result.success) {
  618. sendErrorResponse(res, result.errorMessage, 401, "UNIX_AUTH_FAILED", requestId);
  619. return;
  620. }
  621. // Generate simple token for Unix auth
  622. std::string token = "unix_token_" + std::to_string(std::chrono::duration_cast<std::chrono::seconds>(std::chrono::system_clock::now().time_since_epoch()).count()) + "_" + username;
  623. nlohmann::json response = {
  624. {"token", token},
  625. {"user", {{"id", result.userId}, {"username", result.username}, {"role", result.role}, {"permissions", result.permissions}}},
  626. {"message", "Unix authentication successful"}};
  627. sendJsonResponse(res, response);
  628. return;
  629. }
  630. // For non-Unix auth, validate required fields
  631. if (!requestJson.contains("username") || !requestJson.contains("password")) {
  632. sendErrorResponse(res, "Missing username or password", 400, "MISSING_CREDENTIALS", requestId);
  633. return;
  634. }
  635. std::string username = requestJson["username"];
  636. std::string password = requestJson["password"];
  637. // Authenticate user
  638. auto result = m_userManager->authenticateUser(username, password);
  639. if (!result.success) {
  640. sendErrorResponse(res, result.errorMessage, 401, "INVALID_CREDENTIALS", requestId);
  641. return;
  642. }
  643. // Generate JWT token if using JWT auth
  644. std::string token;
  645. if (m_authMiddleware->getConfig().authMethod == AuthMethod::JWT) {
  646. // For now, create a simple token (in a real implementation, use JWT)
  647. token = "token_" + std::to_string(std::chrono::duration_cast<std::chrono::seconds>(std::chrono::system_clock::now().time_since_epoch()).count()) + "_" + username;
  648. }
  649. nlohmann::json response = {
  650. {"token", token},
  651. {"user", {{"id", result.userId}, {"username", result.username}, {"role", result.role}, {"permissions", result.permissions}}},
  652. {"message", "Login successful"}};
  653. sendJsonResponse(res, response);
  654. } catch (const std::exception& e) {
  655. sendErrorResponse(res, std::string("Login failed: ") + e.what(), 500, "LOGIN_ERROR", requestId);
  656. }
  657. }
  658. void Server::handleLogout(const httplib::Request& /*req*/, httplib::Response& res) {
  659. std::string requestId = generateRequestId();
  660. try {
  661. // For now, just return success (in a real implementation, invalidate the token)
  662. nlohmann::json response = {
  663. {"message", "Logout successful"}};
  664. sendJsonResponse(res, response);
  665. } catch (const std::exception& e) {
  666. sendErrorResponse(res, std::string("Logout failed: ") + e.what(), 500, "LOGOUT_ERROR", requestId);
  667. }
  668. }
  669. void Server::handleValidateToken(const httplib::Request& req, httplib::Response& res) {
  670. std::string requestId = generateRequestId();
  671. try {
  672. if (!m_userManager || !m_authMiddleware) {
  673. sendErrorResponse(res, "Authentication system not available", 500, "AUTH_UNAVAILABLE", requestId);
  674. return;
  675. }
  676. // Extract token from header
  677. std::string authHeader = req.get_header_value("Authorization");
  678. if (authHeader.empty()) {
  679. sendErrorResponse(res, "Missing authorization token", 401, "MISSING_TOKEN", requestId);
  680. return;
  681. }
  682. // Simple token validation (in a real implementation, validate JWT)
  683. // For now, just check if it starts with "token_"
  684. if (authHeader.find("Bearer ") != 0) {
  685. sendErrorResponse(res, "Invalid authorization header format", 401, "INVALID_HEADER", requestId);
  686. return;
  687. }
  688. std::string token = authHeader.substr(7); // Remove "Bearer "
  689. if (token.find("token_") != 0) {
  690. sendErrorResponse(res, "Invalid token", 401, "INVALID_TOKEN", requestId);
  691. return;
  692. }
  693. // Extract username from token (simple format: token_timestamp_username)
  694. size_t last_underscore = token.find_last_of('_');
  695. if (last_underscore == std::string::npos) {
  696. sendErrorResponse(res, "Invalid token format", 401, "INVALID_TOKEN", requestId);
  697. return;
  698. }
  699. std::string username = token.substr(last_underscore + 1);
  700. // Get user info
  701. auto userInfo = m_userManager->getUserInfoByUsername(username);
  702. if (userInfo.id.empty()) {
  703. sendErrorResponse(res, "User not found", 401, "USER_NOT_FOUND", requestId);
  704. return;
  705. }
  706. nlohmann::json response = {
  707. {"user", {{"id", userInfo.id}, {"username", userInfo.username}, {"role", userInfo.role}, {"permissions", userInfo.permissions}}},
  708. {"valid", true}};
  709. sendJsonResponse(res, response);
  710. } catch (const std::exception& e) {
  711. sendErrorResponse(res, std::string("Token validation failed: ") + e.what(), 500, "VALIDATION_ERROR", requestId);
  712. }
  713. }
  714. void Server::handleRefreshToken(const httplib::Request& /*req*/, httplib::Response& res) {
  715. std::string requestId = generateRequestId();
  716. try {
  717. // For now, just return a new token (in a real implementation, refresh JWT)
  718. nlohmann::json response = {
  719. {"token", "new_token_" + std::to_string(std::chrono::duration_cast<std::chrono::seconds>(
  720. std::chrono::system_clock::now().time_since_epoch())
  721. .count())},
  722. {"message", "Token refreshed successfully"}};
  723. sendJsonResponse(res, response);
  724. } catch (const std::exception& e) {
  725. sendErrorResponse(res, std::string("Token refresh failed: ") + e.what(), 500, "REFRESH_ERROR", requestId);
  726. }
  727. }
  728. void Server::handleGetCurrentUser(const httplib::Request& req, httplib::Response& res) {
  729. std::string requestId = generateRequestId();
  730. try {
  731. if (!m_userManager || !m_authMiddleware) {
  732. sendErrorResponse(res, "Authentication system not available", 500, "AUTH_UNAVAILABLE", requestId);
  733. return;
  734. }
  735. // Authenticate the request
  736. AuthContext authContext = m_authMiddleware->authenticate(req, res);
  737. if (!authContext.authenticated) {
  738. sendErrorResponse(res, "Authentication required", 401, "AUTH_REQUIRED", requestId);
  739. return;
  740. }
  741. nlohmann::json response = {
  742. {"user", {{"id", authContext.userId}, {"username", authContext.username}, {"role", authContext.role}, {"permissions", authContext.permissions}}}};
  743. sendJsonResponse(res, response);
  744. } catch (const std::exception& e) {
  745. sendErrorResponse(res, std::string("Get current user failed: ") + e.what(), 500, "USER_ERROR", requestId);
  746. }
  747. }
  748. void Server::setupCORS() {
  749. // Use post-routing handler to set CORS headers after the response is generated
  750. // This ensures we don't duplicate headers that may be set by other handlers
  751. m_httpServer->set_post_routing_handler([](const httplib::Request& /*req*/, httplib::Response& res) {
  752. // Only add CORS headers if they haven't been set already
  753. if (!res.has_header("Access-Control-Allow-Origin")) {
  754. res.set_header("Access-Control-Allow-Origin", "*");
  755. }
  756. if (!res.has_header("Access-Control-Allow-Methods")) {
  757. res.set_header("Access-Control-Allow-Methods", "GET, POST, PUT, DELETE, OPTIONS");
  758. }
  759. if (!res.has_header("Access-Control-Allow-Headers")) {
  760. res.set_header("Access-Control-Allow-Headers", "Content-Type, Authorization");
  761. }
  762. });
  763. // Handle OPTIONS requests for CORS preflight (API endpoints only)
  764. m_httpServer->Options("/api/.*", [](const httplib::Request&, httplib::Response& res) {
  765. res.set_header("Access-Control-Allow-Origin", "*");
  766. res.set_header("Access-Control-Allow-Methods", "GET, POST, PUT, DELETE, OPTIONS");
  767. res.set_header("Access-Control-Allow-Headers", "Content-Type, Authorization");
  768. res.status = 200;
  769. });
  770. }
  771. void Server::handleHealthCheck(const httplib::Request& /*req*/, httplib::Response& res) {
  772. LOG_DEBUG("handleHealthCheck called");
  773. try {
  774. nlohmann::json response = {
  775. {"status", "healthy"},
  776. {"timestamp", std::chrono::duration_cast<std::chrono::seconds>(
  777. std::chrono::system_clock::now().time_since_epoch())
  778. .count()},
  779. {"version", sd_rest::VERSION_INFO.version_full}};
  780. sendJsonResponse(res, response);
  781. } catch (const std::exception& e) {
  782. sendErrorResponse(res, std::string("Health check failed: ") + e.what(), 500);
  783. }
  784. }
  785. void Server::handleApiStatus(const httplib::Request& /*req*/, httplib::Response& res) {
  786. try {
  787. nlohmann::json response = {
  788. {"server", {{"running", m_isRunning.load()}, {"host", m_host}, {"port", m_port}}},
  789. {"generation_queue", {{"running", m_generationQueue ? m_generationQueue->isRunning() : false}, {"queue_size", m_generationQueue ? m_generationQueue->getQueueSize() : 0}, {"active_generations", m_generationQueue ? m_generationQueue->getActiveGenerations() : 0}}},
  790. {"models", {{"loaded_count", m_modelManager ? m_modelManager->getLoadedModelsCount() : 0}, {"available_count", m_modelManager ? m_modelManager->getAvailableModelsCount() : 0}, {"loaded_models", {{"checkpoint", m_loadedModels.checkpoint.empty() ? "" : m_loadedModels.checkpoint}, {"esrgan", m_loadedModels.esrgan.empty() ? "" : m_loadedModels.esrgan}}}}}};
  791. sendJsonResponse(res, response);
  792. } catch (const std::exception& e) {
  793. sendErrorResponse(res, std::string("Status check failed: ") + e.what(), 500);
  794. }
  795. }
  796. void Server::handleVersion(const httplib::Request& /*req*/, httplib::Response& res) {
  797. try {
  798. nlohmann::json response = {
  799. {"version", sd_rest::VERSION_INFO.version_full},
  800. {"type", sd_rest::VERSION_INFO.version_type},
  801. {"commit", {{"short", sd_rest::VERSION_INFO.commit_short}, {"full", sd_rest::VERSION_INFO.commit_full}}},
  802. {"branch", sd_rest::VERSION_INFO.branch},
  803. {"clean", sd_rest::VERSION_INFO.is_clean},
  804. {"build_time", sd_rest::VERSION_INFO.build_time}};
  805. sendJsonResponse(res, response);
  806. } catch (const std::exception& e) {
  807. sendErrorResponse(res, std::string("Version check failed: ") + e.what(), 500);
  808. }
  809. }
  810. // Helper function to convert ModelDetails vector to JSON array
  811. nlohmann::json Server::modelDetailsToJson(const std::vector<ModelManager::ModelDetails>& modelDetails) {
  812. nlohmann::json jsonArray = nlohmann::json::array();
  813. for (const auto& detail : modelDetails) {
  814. nlohmann::json modelJson = {
  815. {"name", detail.name},
  816. {"exists", detail.exists},
  817. {"type", detail.type},
  818. {"file_size", detail.file_size}};
  819. // Handle path and sha256 separately to avoid type mismatch
  820. if (detail.exists) {
  821. modelJson["path"] = detail.path;
  822. modelJson["sha256"] = detail.sha256;
  823. } else {
  824. modelJson["path"] = nullptr;
  825. modelJson["sha256"] = "";
  826. }
  827. // Add conditional fields for required/recommended models
  828. if (detail.is_required) {
  829. modelJson["is_required"] = true;
  830. }
  831. if (detail.is_recommended) {
  832. modelJson["is_recommended"] = true;
  833. }
  834. jsonArray.push_back(modelJson);
  835. }
  836. return jsonArray;
  837. }
  838. // Helper function to determine which recommended fields to include based on architecture
  839. std::map<std::string, bool> Server::getRecommendedModelFields(const std::string& architecture) {
  840. std::map<std::string, bool> recommendedFields;
  841. // Initialize all fields as false (will be set to null if not applicable)
  842. recommendedFields["recommended_vae"] = false;
  843. recommendedFields["recommended_clip_l"] = false;
  844. recommendedFields["recommended_clip_g"] = false;
  845. recommendedFields["recommended_t5xxl"] = false;
  846. recommendedFields["recommended_clip_vision"] = false;
  847. recommendedFields["recommended_qwen2vl"] = false;
  848. // Architecture-specific field inclusion based on actual architecture strings
  849. if (architecture.find("Stable Diffusion 1.5") != std::string::npos) {
  850. // SD 1.x: recommended_vae only
  851. recommendedFields["recommended_vae"] = true;
  852. } else if (architecture.find("Stable Diffusion XL") != std::string::npos) {
  853. // SDXL: recommended_vae only
  854. recommendedFields["recommended_vae"] = true;
  855. } else if (architecture.find("Modern Architecture") != std::string::npos ||
  856. architecture.find("Flux Dev") != std::string::npos ||
  857. architecture.find("Flux Chroma") != std::string::npos) {
  858. // FLUX/SD3/Modern Architecture: recommended_vae, recommended_clip_l, recommended_t5xxl
  859. recommendedFields["recommended_vae"] = true;
  860. recommendedFields["recommended_clip_l"] = true;
  861. recommendedFields["recommended_t5xxl"] = true;
  862. } else if (architecture.find("SD 3") != std::string::npos) {
  863. // SD3: recommended_vae, recommended_clip_l, recommended_clip_g, recommended_t5xxl
  864. recommendedFields["recommended_vae"] = true;
  865. recommendedFields["recommended_clip_l"] = true;
  866. recommendedFields["recommended_clip_g"] = true;
  867. recommendedFields["recommended_t5xxl"] = true;
  868. } else if (architecture.find("Wan") != std::string::npos) {
  869. // Wan models: recommended_vae, recommended_t5xxl, recommended_clip_vision
  870. recommendedFields["recommended_vae"] = true;
  871. recommendedFields["recommended_t5xxl"] = true;
  872. recommendedFields["recommended_clip_vision"] = true;
  873. } else if (architecture.find("Qwen") != std::string::npos) {
  874. // Qwen models: recommended_vae, recommended_qwen2vl
  875. recommendedFields["recommended_vae"] = true;
  876. recommendedFields["recommended_qwen2vl"] = true;
  877. }
  878. // For UNKNOWN architecture, keep all fields false
  879. return recommendedFields;
  880. }
  881. // Helper function to populate recommended models with existence information
  882. void Server::populateRecommendedModels(nlohmann::json& response, const ModelManager::ModelInfo& modelInfo) {
  883. if (modelInfo.requiredModels.empty()) {
  884. return;
  885. }
  886. // Check existence of required models
  887. auto requiredModelsDetails = m_modelManager->checkRequiredModelsExistence(modelInfo.requiredModels);
  888. // Get the recommended fields for this architecture
  889. auto recommendedFields = getRecommendedModelFields(modelInfo.architecture);
  890. // Group models by type
  891. std::map<std::string, std::vector<ModelManager::ModelDetails>> modelsByType;
  892. for (const auto& detail : requiredModelsDetails) {
  893. modelsByType[detail.type].push_back(detail);
  894. }
  895. // Populate recommended fields based on model types and architecture requirements
  896. for (const auto& [type, models] : modelsByType) {
  897. if (type == "VAE" && recommendedFields["recommended_vae"]) {
  898. response["recommended_vae"] = modelDetailsToJson(models);
  899. } else if (type == "CLIP-L" && recommendedFields["recommended_clip_l"]) {
  900. response["recommended_clip_l"] = modelDetailsToJson(models);
  901. } else if (type == "CLIP-G" && recommendedFields["recommended_clip_g"]) {
  902. response["recommended_clip_g"] = modelDetailsToJson(models);
  903. } else if (type == "T5XXL" && recommendedFields["recommended_t5xxl"]) {
  904. response["recommended_t5xxl"] = modelDetailsToJson(models);
  905. } else if (type == "CLIP-Vision" && recommendedFields["recommended_clip_vision"]) {
  906. response["recommended_clip_vision"] = modelDetailsToJson(models);
  907. } else if (type == "Qwen2VL" && recommendedFields["recommended_qwen2vl"]) {
  908. response["recommended_qwen2vl"] = modelDetailsToJson(models);
  909. }
  910. }
  911. // Set non-applicable fields to null
  912. for (const auto& [fieldName, shouldInclude] : recommendedFields) {
  913. if (!shouldInclude || !response.contains(fieldName)) {
  914. response[fieldName] = nlohmann::json(nullptr);
  915. }
  916. }
  917. }
  918. void Server::handleModelsList(const httplib::Request& req, httplib::Response& res) {
  919. std::string requestId = generateRequestId();
  920. try {
  921. if (!m_modelManager) {
  922. sendErrorResponse(res, "Model manager not available", 500, "MODEL_MANAGER_UNAVAILABLE", requestId);
  923. return;
  924. }
  925. // Parse query parameters for enhanced filtering
  926. std::string typeFilter = req.get_param_value("type");
  927. std::string searchQuery = req.get_param_value("search");
  928. std::string sortBy = req.get_param_value("sort_by");
  929. std::string sortOrder = req.get_param_value("sort_order");
  930. std::string dateFilter = req.get_param_value("date");
  931. std::string sizeFilter = req.get_param_value("size");
  932. // Pagination parameters - only apply if limit is explicitly provided
  933. int page = 1;
  934. int limit = 50;
  935. bool usePagination = false;
  936. try {
  937. if (!req.get_param_value("limit").empty()) {
  938. limit = std::stoi(req.get_param_value("limit"));
  939. // Special case: limit<=0 means return all models (no pagination)
  940. if (limit <= 0) {
  941. usePagination = false;
  942. limit = INT_MAX; // Set to very large number to effectively disable pagination
  943. } else {
  944. usePagination = true;
  945. if (!req.get_param_value("page").empty()) {
  946. page = std::stoi(req.get_param_value("page"));
  947. if (page < 1)
  948. page = 1;
  949. }
  950. }
  951. }
  952. } catch (const std::exception& e) {
  953. sendErrorResponse(res, "Invalid pagination parameters", 400, "INVALID_PAGINATION", requestId);
  954. return;
  955. }
  956. // Filter parameters
  957. bool includeLoaded = req.get_param_value("loaded") == "true";
  958. bool includeUnloaded = req.get_param_value("unloaded") == "true";
  959. (void)req.get_param_value("include_metadata"); // unused but kept for API compatibility
  960. (void)req.get_param_value("include_thumbnails"); // unused but kept for API compatibility
  961. // Get all models
  962. auto allModels = m_modelManager->getAllModels();
  963. nlohmann::json models = nlohmann::json::array();
  964. // Apply filters and build response
  965. for (const auto& pair : allModels) {
  966. const auto& modelInfo = pair.second;
  967. // Apply type filter
  968. if (!typeFilter.empty()) {
  969. ModelType filterType = ModelManager::stringToModelType(typeFilter);
  970. if (modelInfo.type != filterType)
  971. continue;
  972. }
  973. // Apply loaded/unloaded filters
  974. if (includeLoaded && !modelInfo.isLoaded)
  975. continue;
  976. if (includeUnloaded && modelInfo.isLoaded)
  977. continue;
  978. // Apply search filter (case-insensitive search in name and description)
  979. if (!searchQuery.empty()) {
  980. std::string searchLower = searchQuery;
  981. std::transform(searchLower.begin(), searchLower.end(), searchLower.begin(), ::tolower);
  982. std::string nameLower = modelInfo.name;
  983. std::transform(nameLower.begin(), nameLower.end(), nameLower.begin(), ::tolower);
  984. std::string descLower = modelInfo.description;
  985. std::transform(descLower.begin(), descLower.end(), descLower.begin(), ::tolower);
  986. if (nameLower.find(searchLower) == std::string::npos &&
  987. descLower.find(searchLower) == std::string::npos) {
  988. continue;
  989. }
  990. }
  991. // Apply date filter (simplified - expects "recent", "old", or YYYY-MM-DD)
  992. if (!dateFilter.empty()) {
  993. auto now = std::filesystem::file_time_type::clock::now();
  994. auto modelTime = modelInfo.modifiedAt;
  995. auto duration = std::chrono::duration_cast<std::chrono::hours>(now - modelTime).count();
  996. if (dateFilter == "recent" && duration > 24 * 7)
  997. continue; // Older than 1 week
  998. if (dateFilter == "old" && duration < 24 * 30)
  999. continue; // Newer than 1 month
  1000. }
  1001. // Apply size filter (expects "small", "medium", "large", or size in MB)
  1002. if (!sizeFilter.empty()) {
  1003. double sizeMB = modelInfo.fileSize / (1024.0 * 1024.0);
  1004. if (sizeFilter == "small" && sizeMB > 1024)
  1005. continue; // > 1GB
  1006. if (sizeFilter == "medium" && (sizeMB < 1024 || sizeMB > 4096))
  1007. continue; // < 1GB or > 4GB
  1008. if (sizeFilter == "large" && sizeMB < 4096)
  1009. continue; // < 4GB
  1010. // Try to parse as specific size in MB
  1011. try {
  1012. double maxSizeMB = std::stod(sizeFilter);
  1013. if (sizeMB > maxSizeMB)
  1014. continue;
  1015. } catch (...) {
  1016. // Ignore if parsing fails
  1017. }
  1018. }
  1019. // Build model JSON with enhanced structure
  1020. nlohmann::json modelJson = {
  1021. {"name", modelInfo.name},
  1022. {"type", ModelManager::modelTypeToString(modelInfo.type)},
  1023. {"file_size", modelInfo.fileSize},
  1024. {"file_size_mb", modelInfo.fileSize / (1024.0 * 1024.0)},
  1025. {"sha256", modelInfo.sha256.empty() ? nullptr : nlohmann::json(modelInfo.sha256)},
  1026. {"sha256_short", (modelInfo.sha256.empty() || modelInfo.sha256.length() < 10) ? nullptr : nlohmann::json(modelInfo.sha256.substr(0, 10))}};
  1027. // Add architecture information if available (checkpoints only)
  1028. if (!modelInfo.architecture.empty()) {
  1029. modelJson["architecture"] = modelInfo.architecture;
  1030. modelJson["recommended_vae"] = modelInfo.recommendedVAE.empty() ? nullptr : nlohmann::json(modelInfo.recommendedVAE);
  1031. if (modelInfo.recommendedWidth > 0) {
  1032. modelJson["recommended_width"] = modelInfo.recommendedWidth;
  1033. }
  1034. if (modelInfo.recommendedHeight > 0) {
  1035. modelJson["recommended_height"] = modelInfo.recommendedHeight;
  1036. }
  1037. if (modelInfo.recommendedSteps > 0) {
  1038. modelJson["recommended_steps"] = modelInfo.recommendedSteps;
  1039. }
  1040. if (!modelInfo.recommendedSampler.empty()) {
  1041. modelJson["recommended_sampler"] = modelInfo.recommendedSampler;
  1042. }
  1043. // Enhanced model information with existence checking
  1044. if (!modelInfo.requiredModels.empty()) {
  1045. auto requiredModelsDetails = m_modelManager->checkRequiredModelsExistence(modelInfo.requiredModels);
  1046. modelJson["required_models"] = modelDetailsToJson(requiredModelsDetails);
  1047. // Populate recommended models based on architecture
  1048. populateRecommendedModels(modelJson, modelInfo);
  1049. }
  1050. // Backward compatibility - keep existing fields
  1051. if (!modelInfo.missingModels.empty()) {
  1052. modelJson["missing_models"] = modelInfo.missingModels;
  1053. modelJson["has_missing_dependencies"] = true;
  1054. } else {
  1055. modelJson["has_missing_dependencies"] = false;
  1056. }
  1057. }
  1058. models.push_back(modelJson);
  1059. }
  1060. // Apply sorting
  1061. if (!sortBy.empty()) {
  1062. std::sort(models.begin(), models.end(), [&sortBy, &sortOrder](const nlohmann::json& a, const nlohmann::json& b) {
  1063. bool ascending = sortOrder != "desc";
  1064. if (sortBy == "name") {
  1065. return ascending ? a["name"] < b["name"] : a["name"] > b["name"];
  1066. } else if (sortBy == "size") {
  1067. return ascending ? a["file_size"] < b["file_size"] : a["file_size"] > b["file_size"];
  1068. } else if (sortBy == "date") {
  1069. return ascending ? a["last_modified"] < b["last_modified"] : a["last_modified"] > b["last_modified"];
  1070. } else if (sortBy == "type") {
  1071. return ascending ? a["type"] < b["type"] : a["type"] > b["type"];
  1072. } else if (sortBy == "loaded") {
  1073. return ascending ? a["is_loaded"] < b["is_loaded"] : a["is_loaded"] > b["is_loaded"];
  1074. }
  1075. return false;
  1076. });
  1077. }
  1078. // Apply pagination only if limit parameter was provided
  1079. int totalCount = models.size();
  1080. nlohmann::json paginatedModels = nlohmann::json::array();
  1081. nlohmann::json paginationInfo = nlohmann::json::object();
  1082. if (usePagination) {
  1083. // Apply pagination
  1084. int totalPages = (totalCount + limit - 1) / limit;
  1085. int startIndex = (page - 1) * limit;
  1086. int endIndex = std::min(startIndex + limit, totalCount);
  1087. for (int i = startIndex; i < endIndex; ++i) {
  1088. paginatedModels.push_back(models[i]);
  1089. }
  1090. paginationInfo = {
  1091. {"page", page},
  1092. {"limit", limit},
  1093. {"total_count", totalCount},
  1094. {"total_pages", totalPages},
  1095. {"has_next", page < totalPages},
  1096. {"has_prev", page > 1}};
  1097. } else {
  1098. // Return all models without pagination
  1099. paginatedModels = models;
  1100. paginationInfo = {
  1101. {"page", 1},
  1102. {"limit", totalCount},
  1103. {"total_count", totalCount},
  1104. {"total_pages", 1},
  1105. {"has_next", false},
  1106. {"has_prev", false}};
  1107. }
  1108. // Build comprehensive response
  1109. nlohmann::json response = {
  1110. {"models", paginatedModels},
  1111. {"pagination", paginationInfo},
  1112. {"filters_applied", {{"type", typeFilter.empty() ? nlohmann::json(nullptr) : nlohmann::json(typeFilter)}, {"search", searchQuery.empty() ? nlohmann::json(nullptr) : nlohmann::json(searchQuery)}, {"date", dateFilter.empty() ? nlohmann::json(nullptr) : nlohmann::json(dateFilter)}, {"size", sizeFilter.empty() ? nlohmann::json(nullptr) : nlohmann::json(sizeFilter)}, {"loaded", includeLoaded ? nlohmann::json(true) : nlohmann::json(nullptr)}, {"unloaded", includeUnloaded ? nlohmann::json(true) : nlohmann::json(nullptr)}}},
  1113. {"sorting", {{"sort_by", sortBy.empty() ? "name" : nlohmann::json(sortBy)}, {"sort_order", sortOrder.empty() ? "asc" : nlohmann::json(sortOrder)}}},
  1114. {"statistics", {{"loaded_count", m_modelManager->getLoadedModelsCount()}, {"available_count", m_modelManager->getAvailableModelsCount()}}},
  1115. {"request_id", requestId}};
  1116. sendJsonResponse(res, response);
  1117. } catch (const std::exception& e) {
  1118. sendErrorResponse(res, std::string("Failed to list models: ") + e.what(), 500, "MODEL_LIST_ERROR", requestId);
  1119. }
  1120. }
  1121. void Server::handleQueueStatus(const httplib::Request& /*req*/, httplib::Response& res) {
  1122. try {
  1123. if (!m_generationQueue) {
  1124. sendErrorResponse(res, "Generation queue not available", 500);
  1125. return;
  1126. }
  1127. // Get detailed queue status
  1128. auto jobs = m_generationQueue->getQueueStatus();
  1129. // Convert jobs to JSON
  1130. nlohmann::json jobsJson = nlohmann::json::array();
  1131. for (const auto& job : jobs) {
  1132. std::string statusStr;
  1133. switch (job.status) {
  1134. case GenerationStatus::QUEUED:
  1135. statusStr = "queued";
  1136. break;
  1137. case GenerationStatus::PROCESSING:
  1138. statusStr = "processing";
  1139. break;
  1140. case GenerationStatus::COMPLETED:
  1141. statusStr = "completed";
  1142. break;
  1143. case GenerationStatus::FAILED:
  1144. statusStr = "failed";
  1145. break;
  1146. case GenerationStatus::MODEL_LOADING:
  1147. statusStr = "model_loading";
  1148. break;
  1149. }
  1150. // Convert time points to timestamps
  1151. auto queuedTime = std::chrono::duration_cast<std::chrono::milliseconds>(
  1152. job.queuedTime.time_since_epoch())
  1153. .count();
  1154. auto startTime = std::chrono::duration_cast<std::chrono::milliseconds>(
  1155. job.startTime.time_since_epoch())
  1156. .count();
  1157. auto endTime = std::chrono::duration_cast<std::chrono::milliseconds>(
  1158. job.endTime.time_since_epoch())
  1159. .count();
  1160. jobsJson.push_back({{"id", job.id},
  1161. {"status", statusStr},
  1162. {"prompt", job.prompt},
  1163. {"queued_time", queuedTime},
  1164. {"start_time", startTime > 0 ? nlohmann::json(startTime) : nlohmann::json(nullptr)},
  1165. {"end_time", endTime > 0 ? nlohmann::json(endTime) : nlohmann::json(nullptr)},
  1166. {"position", job.position},
  1167. {"progress", job.progress}});
  1168. }
  1169. nlohmann::json response = {
  1170. {"queue", {{"size", m_generationQueue->getQueueSize()}, {"active_generations", m_generationQueue->getActiveGenerations()}, {"running", m_generationQueue->isRunning()}, {"jobs", jobsJson}}}};
  1171. sendJsonResponse(res, response);
  1172. } catch (const std::exception& e) {
  1173. sendErrorResponse(res, std::string("Queue status check failed: ") + e.what(), 500);
  1174. }
  1175. }
  1176. void Server::handleJobStatus(const httplib::Request& req, httplib::Response& res) {
  1177. try {
  1178. if (!m_generationQueue) {
  1179. sendErrorResponse(res, "Generation queue not available", 500);
  1180. return;
  1181. }
  1182. // Extract job ID from URL path
  1183. std::string jobId = req.matches[1].str();
  1184. if (jobId.empty()) {
  1185. sendErrorResponse(res, "Missing job ID", 400);
  1186. return;
  1187. }
  1188. // Get job information
  1189. auto jobInfo = m_generationQueue->getJobInfo(jobId);
  1190. if (jobInfo.id.empty()) {
  1191. sendErrorResponse(res, "Job not found", 404);
  1192. return;
  1193. }
  1194. // Convert status to string
  1195. std::string statusStr;
  1196. switch (jobInfo.status) {
  1197. case GenerationStatus::QUEUED:
  1198. statusStr = "queued";
  1199. break;
  1200. case GenerationStatus::PROCESSING:
  1201. statusStr = "processing";
  1202. break;
  1203. case GenerationStatus::COMPLETED:
  1204. statusStr = "completed";
  1205. break;
  1206. case GenerationStatus::FAILED:
  1207. statusStr = "failed";
  1208. break;
  1209. case GenerationStatus::MODEL_LOADING:
  1210. statusStr = "model_loading";
  1211. break;
  1212. }
  1213. // Convert time points to timestamps
  1214. auto queuedTime = std::chrono::duration_cast<std::chrono::milliseconds>(
  1215. jobInfo.queuedTime.time_since_epoch())
  1216. .count();
  1217. auto startTime = std::chrono::duration_cast<std::chrono::milliseconds>(
  1218. jobInfo.startTime.time_since_epoch())
  1219. .count();
  1220. auto endTime = std::chrono::duration_cast<std::chrono::milliseconds>(
  1221. jobInfo.endTime.time_since_epoch())
  1222. .count();
  1223. // Create download URLs for output files
  1224. nlohmann::json outputUrls = nlohmann::json::array();
  1225. LOG_DEBUG("Job " + jobInfo.id + " has " + std::to_string(jobInfo.outputFiles.size()) + " output files");
  1226. for (const auto& filePath : jobInfo.outputFiles) {
  1227. // Extract filename from full path
  1228. std::filesystem::path p(filePath);
  1229. std::string filename = p.filename().string();
  1230. // Create download URL
  1231. std::string url = "/api/queue/job/" + jobInfo.id + "/output/" + filename;
  1232. nlohmann::json fileInfo = {
  1233. {"filename", filename},
  1234. {"url", url},
  1235. {"path", filePath}};
  1236. outputUrls.push_back(fileInfo);
  1237. {
  1238. std::ostringstream oss;
  1239. oss << "Added output file: " << filename << " -> " << url;
  1240. LOG_DEBUG(oss.str());
  1241. }
  1242. }
  1243. nlohmann::json response = {
  1244. {"job", {{"id", jobInfo.id}, {"status", statusStr}, {"prompt", jobInfo.prompt}, {"queued_time", queuedTime}, {"start_time", startTime > 0 ? nlohmann::json(startTime) : nlohmann::json(nullptr)}, {"end_time", endTime > 0 ? nlohmann::json(endTime) : nlohmann::json(nullptr)}, {"position", jobInfo.position}, {"outputs", outputUrls}, {"error_message", jobInfo.errorMessage}, {"progress", jobInfo.progress}}}};
  1245. sendJsonResponse(res, response);
  1246. } catch (const std::exception& e) {
  1247. sendErrorResponse(res, std::string("Job status check failed: ") + e.what(), 500);
  1248. }
  1249. }
  1250. void Server::handleCancelJob(const httplib::Request& req, httplib::Response& res) {
  1251. try {
  1252. if (!m_generationQueue) {
  1253. sendErrorResponse(res, "Generation queue not available", 500);
  1254. return;
  1255. }
  1256. // Parse JSON request body
  1257. nlohmann::json requestJson = nlohmann::json::parse(req.body);
  1258. // Validate required fields
  1259. if (!requestJson.contains("job_id") || !requestJson["job_id"].is_string()) {
  1260. sendErrorResponse(res, "Missing or invalid 'job_id' field", 400);
  1261. return;
  1262. }
  1263. std::string jobId = requestJson["job_id"];
  1264. // Try to cancel the job
  1265. bool cancelled = m_generationQueue->cancelJob(jobId);
  1266. if (cancelled) {
  1267. nlohmann::json response = {
  1268. {"status", "success"},
  1269. {"message", "Job cancelled successfully"},
  1270. {"job_id", jobId}};
  1271. sendJsonResponse(res, response);
  1272. } else {
  1273. nlohmann::json response = {
  1274. {"status", "error"},
  1275. {"message", "Job not found or already processing"},
  1276. {"job_id", jobId}};
  1277. sendJsonResponse(res, response, 404);
  1278. }
  1279. } catch (const nlohmann::json::parse_error& e) {
  1280. sendErrorResponse(res, std::string("Invalid JSON: ") + e.what(), 400);
  1281. } catch (const std::exception& e) {
  1282. sendErrorResponse(res, std::string("Job cancellation failed: ") + e.what(), 500);
  1283. }
  1284. }
  1285. void Server::handleClearQueue(const httplib::Request& /*req*/, httplib::Response& res) {
  1286. try {
  1287. if (!m_generationQueue) {
  1288. sendErrorResponse(res, "Generation queue not available", 500);
  1289. return;
  1290. }
  1291. // Clear the queue
  1292. m_generationQueue->clearQueue();
  1293. nlohmann::json response = {
  1294. {"status", "success"},
  1295. {"message", "Queue cleared successfully"}};
  1296. sendJsonResponse(res, response);
  1297. } catch (const std::exception& e) {
  1298. sendErrorResponse(res, std::string("Queue clear failed: ") + e.what(), 500);
  1299. }
  1300. }
  1301. void Server::handleDownloadOutput(const httplib::Request& req, httplib::Response& res) {
  1302. try {
  1303. // Extract job ID and filename from URL path
  1304. if (req.matches.size() < 3) {
  1305. sendErrorResponse(res, "Invalid request: job ID and filename required", 400, "INVALID_REQUEST", "");
  1306. return;
  1307. }
  1308. std::string jobId = req.matches[1];
  1309. std::string filename = req.matches[2];
  1310. // Validate inputs
  1311. if (jobId.empty() || filename.empty()) {
  1312. sendErrorResponse(res, "Job ID and filename cannot be empty", 400, "INVALID_PARAMETERS", "");
  1313. return;
  1314. }
  1315. // Construct absolute file path using the same logic as when saving:
  1316. // {outputDir}/{jobId}/{filename}
  1317. std::string fullPath = std::filesystem::absolute(m_outputDir + "/" + jobId + "/" + filename).string();
  1318. LOG_INFO("Image download requested: " + jobId + " filename: " + filename);
  1319. // Check if file exists
  1320. if (!std::filesystem::exists(fullPath)) {
  1321. LOG_ERROR("Output file not found: " + fullPath);
  1322. sendErrorResponse(res, "Output file not found: " + filename, 404, "FILE_NOT_FOUND", "");
  1323. return;
  1324. }
  1325. // Check file size to detect zero-byte files
  1326. auto fileSize = std::filesystem::file_size(fullPath);
  1327. if (fileSize == 0) {
  1328. LOG_ERROR("Output file is zero bytes: " + fullPath);
  1329. sendErrorResponse(res, "Output file is empty (corrupted generation)", 500, "EMPTY_FILE", "");
  1330. return;
  1331. }
  1332. // Check if file is accessible
  1333. std::ifstream file(fullPath, std::ios::binary);
  1334. if (!file.is_open()) {
  1335. LOG_ERROR("Failed to open output file: " + fullPath);
  1336. sendErrorResponse(res, "Output file not accessible", 500, "FILE_ACCESS_ERROR", "");
  1337. return;
  1338. }
  1339. // Read file contents
  1340. std::string fileContent;
  1341. try {
  1342. fileContent = std::string(
  1343. std::istreambuf_iterator<char>(file),
  1344. std::istreambuf_iterator<char>());
  1345. file.close();
  1346. } catch (const std::exception& e) {
  1347. LOG_ERROR("Failed to read file content: " + std::string(e.what()));
  1348. sendErrorResponse(res, "Failed to read file content", 500, "FILE_READ_ERROR", "");
  1349. return;
  1350. }
  1351. // Verify we actually read data
  1352. if (fileContent.empty()) {
  1353. LOG_ERROR("File content is empty after read: " + fullPath);
  1354. sendErrorResponse(res, "File content is empty after read", 500, "EMPTY_CONTENT", "");
  1355. return;
  1356. }
  1357. // Determine content type based on file extension
  1358. std::string contentType = "application/octet-stream";
  1359. if (Utils::endsWith(filename, ".png")) {
  1360. contentType = "image/png";
  1361. } else if (Utils::endsWith(filename, ".jpg") || Utils::endsWith(filename, ".jpeg")) {
  1362. contentType = "image/jpeg";
  1363. } else if (Utils::endsWith(filename, ".mp4")) {
  1364. contentType = "video/mp4";
  1365. } else if (Utils::endsWith(filename, ".gif")) {
  1366. contentType = "image/gif";
  1367. } else if (Utils::endsWith(filename, ".webp")) {
  1368. contentType = "image/webp";
  1369. }
  1370. // Set response headers for proper browser handling
  1371. res.set_header("Content-Type", contentType);
  1372. res.set_header("Content-Length", std::to_string(fileContent.length()));
  1373. res.set_header("Cache-Control", "public, max-age=3600"); // Cache for 1 hour
  1374. res.set_header("Access-Control-Allow-Origin", "*"); // CORS for image access
  1375. // Uncomment if you want to force download instead of inline display:
  1376. // res.set_header("Content-Disposition", "attachment; filename=\"" + filename + "\"");
  1377. // Set the content
  1378. res.set_content(fileContent, contentType);
  1379. res.status = 200;
  1380. LOG_DEBUG("Successfully server image: " + filename + " (" + std::to_string(fileContent.length()) + " bytes)");
  1381. } catch (const std::exception& e) {
  1382. LOG_ERROR("Exception in handleDownloadOutput: " + std::string(e.what()));
  1383. sendErrorResponse(res, std::string("Failed to download file: ") + e.what(), 500, "DOWNLOAD_ERROR", "");
  1384. }
  1385. }
  1386. void Server::handleJobOutput(const httplib::Request& req, httplib::Response& res) {
  1387. std::string requestId = generateRequestId();
  1388. try {
  1389. // Extract job ID from URL path
  1390. if (req.matches.size() < 2) {
  1391. sendErrorResponse(res, "Invalid request: job ID required", 400, "INVALID_REQUEST", requestId);
  1392. return;
  1393. }
  1394. std::string jobId = req.matches[1].str();
  1395. // Validate job ID
  1396. if (jobId.empty()) {
  1397. sendErrorResponse(res, "Job ID cannot be empty", 400, "INVALID_PARAMETERS", requestId);
  1398. return;
  1399. }
  1400. // Log the request for debugging
  1401. LOG_DEBUG("Job output request: " + jobId);
  1402. // Get job information to check if it exists and is completed
  1403. if (!m_generationQueue) {
  1404. sendErrorResponse(res, "Generation queue not available", 500, "QUEUE_UNAVAILABLE", requestId);
  1405. return;
  1406. }
  1407. auto jobInfo = m_generationQueue->getJobInfo(jobId);
  1408. if (jobInfo.id.empty()) {
  1409. sendErrorResponse(res, "Job not found", 404, "JOB_NOT_FOUND", requestId);
  1410. return;
  1411. }
  1412. // Check if job is completed
  1413. if (jobInfo.status != GenerationStatus::COMPLETED) {
  1414. std::string statusStr;
  1415. switch (jobInfo.status) {
  1416. case GenerationStatus::QUEUED:
  1417. statusStr = "queued";
  1418. break;
  1419. case GenerationStatus::PROCESSING:
  1420. statusStr = "processing";
  1421. break;
  1422. case GenerationStatus::FAILED:
  1423. statusStr = "failed";
  1424. break;
  1425. default:
  1426. statusStr = "unknown";
  1427. break;
  1428. }
  1429. nlohmann::json response = {
  1430. {"error", {{"message", "Job not completed yet"}, {"status_code", 400}, {"error_code", "JOB_NOT_COMPLETED"}, {"request_id", requestId}, {"timestamp", std::chrono::duration_cast<std::chrono::seconds>(std::chrono::system_clock::now().time_since_epoch()).count()}, {"job_status", statusStr}}}};
  1431. sendJsonResponse(res, response, 400);
  1432. return;
  1433. }
  1434. // Check if job has output files
  1435. if (jobInfo.outputFiles.empty()) {
  1436. sendErrorResponse(res, "No output files found for completed job", 404, "NO_OUTPUT_FILES", requestId);
  1437. return;
  1438. }
  1439. // For simplicity, return the first output file
  1440. // In a more complex implementation, we could return all files or allow file selection
  1441. std::string firstOutputFile = jobInfo.outputFiles[0];
  1442. // Extract filename from full path
  1443. std::filesystem::path filePath(firstOutputFile);
  1444. std::string filename = filePath.filename().string();
  1445. // Construct absolute file path
  1446. std::string fullPath = std::filesystem::absolute(firstOutputFile).string();
  1447. // Check if file exists
  1448. if (!std::filesystem::exists(fullPath)) {
  1449. LOG_ERROR("Output file not found: " + fullPath);
  1450. sendErrorResponse(res, "Output file not found: " + filename, 404, "FILE_NOT_FOUND", requestId);
  1451. return;
  1452. }
  1453. // Check file size to detect zero-byte files
  1454. auto fileSize = std::filesystem::file_size(fullPath);
  1455. if (fileSize == 0) {
  1456. LOG_ERROR("Output file is zero bytes: " + fullPath);
  1457. sendErrorResponse(res, "Output file is empty (corrupted generation)", 500, "EMPTY_FILE", requestId);
  1458. return;
  1459. }
  1460. // Check if file is accessible
  1461. std::ifstream file(fullPath, std::ios::binary);
  1462. if (!file.is_open()) {
  1463. LOG_ERROR("Failed to open output file: " + fullPath);
  1464. sendErrorResponse(res, "Output file not accessible", 500, "FILE_ACCESS_ERROR", requestId);
  1465. return;
  1466. }
  1467. // Read file contents
  1468. std::string fileContent;
  1469. try {
  1470. fileContent = std::string(
  1471. std::istreambuf_iterator<char>(file),
  1472. std::istreambuf_iterator<char>());
  1473. file.close();
  1474. } catch (const std::exception& e) {
  1475. LOG_ERROR("Failed to read file content: " + std::string(e.what()));
  1476. sendErrorResponse(res, "Failed to read file content", 500, "FILE_READ_ERROR", requestId);
  1477. return;
  1478. }
  1479. // Verify we actually read data
  1480. if (fileContent.empty()) {
  1481. LOG_ERROR("File content is empty after read: " + fullPath);
  1482. sendErrorResponse(res, "File content is empty after read", 500, "EMPTY_CONTENT", requestId);
  1483. return;
  1484. }
  1485. // Determine content type based on file extension
  1486. std::string contentType = "application/octet-stream";
  1487. if (Utils::endsWith(filename, ".png")) {
  1488. contentType = "image/png";
  1489. } else if (Utils::endsWith(filename, ".jpg") || Utils::endsWith(filename, ".jpeg")) {
  1490. contentType = "image/jpeg";
  1491. } else if (Utils::endsWith(filename, ".mp4")) {
  1492. contentType = "video/mp4";
  1493. } else if (Utils::endsWith(filename, ".gif")) {
  1494. contentType = "image/gif";
  1495. } else if (Utils::endsWith(filename, ".webp")) {
  1496. contentType = "image/webp";
  1497. }
  1498. // Set response headers for proper browser handling
  1499. res.set_header("Content-Type", contentType);
  1500. res.set_header("Content-Length", std::to_string(fileContent.length()));
  1501. res.set_header("Cache-Control", "public, max-age=3600"); // Cache for 1 hour
  1502. res.set_header("Access-Control-Allow-Origin", "*"); // CORS for image access
  1503. // Set additional metadata headers
  1504. res.set_header("X-Job-ID", jobId);
  1505. res.set_header("X-Filename", filename);
  1506. res.set_header("X-File-Size", std::to_string(fileSize));
  1507. // If there are multiple files, indicate this
  1508. if (jobInfo.outputFiles.size() > 1) {
  1509. res.set_header("X-Total-Files", std::to_string(jobInfo.outputFiles.size()));
  1510. res.set_header("X-File-Index", "1");
  1511. }
  1512. // Set the content
  1513. res.set_content(fileContent, contentType);
  1514. res.status = 200;
  1515. LOG_DEBUG("Successfully served job output: jobId=" + jobId +
  1516. ", filename=" + filename +
  1517. " (" + std::to_string(fileContent.length()) + " bytes)");
  1518. } catch (const std::exception& e) {
  1519. LOG_ERROR("Exception in handleJobOutput: " + std::string(e.what()));
  1520. sendErrorResponse(res, std::string("Failed to get job output: ") + e.what(), 500, "OUTPUT_ERROR", requestId);
  1521. }
  1522. }
  1523. void Server::handleJobOutputFile(const httplib::Request& req, httplib::Response& res) {
  1524. std::string requestId = generateRequestId();
  1525. // DEBUG: Print immediately at function start
  1526. LOG_DEBUG("handleJobOutputFile called!");
  1527. try {
  1528. // Extract job ID and filename from URL path
  1529. if (req.matches.size() < 3) {
  1530. sendErrorResponse(res, "Invalid request: job ID and filename required", 400, "INVALID_REQUEST", requestId);
  1531. return;
  1532. }
  1533. std::string jobId = req.matches[1];
  1534. std::string filename = req.matches[2];
  1535. // Validate inputs
  1536. if (jobId.empty()) {
  1537. sendErrorResponse(res, "Job ID cannot be empty", 400, "INVALID_PARAMETERS", requestId);
  1538. return;
  1539. }
  1540. if (filename.empty()) {
  1541. sendErrorResponse(res, "Filename cannot be empty", 400, "INVALID_PARAMETERS", requestId);
  1542. return;
  1543. }
  1544. // URL decode filename
  1545. std::string decodedFilename = filename; // Utils::urlDecode(filename);
  1546. // Check if this is a thumbnail request
  1547. bool isThumbnail = false;
  1548. int thumbnailSize = 200; // Default thumbnail size
  1549. // Check for thumbnail query parameters
  1550. auto thumbIt = req.params.find("thumb");
  1551. if (thumbIt != req.params.end() && (thumbIt->second == "1" || thumbIt->second == "true")) {
  1552. isThumbnail = true;
  1553. }
  1554. auto sizeIt = req.params.find("size");
  1555. if (sizeIt != req.params.end()) {
  1556. try {
  1557. thumbnailSize = std::stoi(sizeIt->second);
  1558. thumbnailSize = std::max(50, std::min(500, thumbnailSize)); // Clamp between 50-500
  1559. } catch (...) {
  1560. // Use default if invalid
  1561. }
  1562. }
  1563. // Log request for debugging
  1564. LOG_DEBUG("Job output file request: jobId=" + jobId + ", filename=" + decodedFilename +
  1565. (isThumbnail ? " (thumbnail " + std::to_string(thumbnailSize) + "px)" : " (full size)"));
  1566. // NEW DEBUG: Add this debug line to verify function execution
  1567. LOG_DEBUG("NEW DEBUG: Function execution reached!");
  1568. // Get job information to check if it exists and is completed
  1569. if (!m_generationQueue) {
  1570. LOG_DEBUG("m_generationQueue is null!");
  1571. sendErrorResponse(res, "Generation queue not available", 500, "QUEUE_UNAVAILABLE", requestId);
  1572. return;
  1573. }
  1574. auto jobInfo = m_generationQueue->getJobInfo(jobId);
  1575. if (jobInfo.id.empty()) {
  1576. sendErrorResponse(res, "Job not found", 404, "JOB_NOT_FOUND", requestId);
  1577. return;
  1578. }
  1579. // Check if job is completed (allow access to completed jobs)
  1580. if (jobInfo.status != GenerationStatus::COMPLETED) {
  1581. std::string statusStr;
  1582. switch (jobInfo.status) {
  1583. case GenerationStatus::QUEUED:
  1584. statusStr = "queued";
  1585. break;
  1586. case GenerationStatus::PROCESSING:
  1587. statusStr = "processing";
  1588. break;
  1589. case GenerationStatus::FAILED:
  1590. statusStr = "failed";
  1591. break;
  1592. default:
  1593. statusStr = "unknown";
  1594. break;
  1595. }
  1596. nlohmann::json response = {
  1597. {"error", {{"message", "Job not completed yet"}, {"status_code", 400}, {"error_code", "JOB_NOT_COMPLETED"}, {"request_id", requestId}, {"timestamp", std::chrono::duration_cast<std::chrono::seconds>(std::chrono::system_clock::now().time_since_epoch()).count()}, {"job_status", statusStr}}}};
  1598. sendJsonResponse(res, response, 400);
  1599. return;
  1600. }
  1601. // Find the specific file in job outputs
  1602. std::string targetFilePath;
  1603. bool found = false;
  1604. for (const auto& outputFile : jobInfo.outputFiles) {
  1605. std::filesystem::path filePath(outputFile);
  1606. std::string currentFilename = filePath.filename().string();
  1607. if (currentFilename == decodedFilename) {
  1608. targetFilePath = outputFile;
  1609. found = true;
  1610. break;
  1611. }
  1612. }
  1613. if (!found) {
  1614. sendErrorResponse(res, "File not found in job outputs: " + decodedFilename, 404, "FILE_NOT_FOUND", requestId);
  1615. return;
  1616. }
  1617. // Construct absolute file path
  1618. std::string fullPath = std::filesystem::absolute(targetFilePath).string();
  1619. // Check if file exists
  1620. if (!std::filesystem::exists(fullPath)) {
  1621. LOG_ERROR("Output file not found: " + fullPath);
  1622. sendErrorResponse(res, "Output file not found: " + decodedFilename, 404, "FILE_NOT_FOUND", requestId);
  1623. return;
  1624. }
  1625. // Check file size to detect zero-byte files
  1626. auto fileSize = std::filesystem::file_size(fullPath);
  1627. if (fileSize == 0) {
  1628. LOG_ERROR("Output file is zero bytes: " + fullPath);
  1629. sendErrorResponse(res, "Output file is empty (corrupted generation)", 500, "EMPTY_FILE", requestId);
  1630. return;
  1631. }
  1632. // If thumbnail is requested and it's an image, generate thumbnail
  1633. if (isThumbnail && Utils::isImageFile(decodedFilename)) {
  1634. std::string thumbnailData = generateThumbnail(fullPath, thumbnailSize);
  1635. if (!thumbnailData.empty()) {
  1636. // Set response headers for thumbnail
  1637. res.set_header("Content-Type", "image/jpeg"); // Always use JPEG for thumbnails
  1638. res.set_header("Content-Length", std::to_string(thumbnailData.length()));
  1639. res.set_header("Cache-Control", "public, max-age=86400"); // Cache thumbnails longer
  1640. res.set_header("Access-Control-Allow-Origin", "*");
  1641. res.set_header("X-Job-ID", jobId);
  1642. res.set_header("X-Filename", decodedFilename);
  1643. res.set_header("X-Thumbnail", "true");
  1644. res.set_header("X-Thumbnail-Size", std::to_string(thumbnailSize));
  1645. res.set_content(thumbnailData, "image/jpeg");
  1646. res.status = 200;
  1647. LOG_DEBUG("Successfully served thumbnail: jobId=" + jobId +
  1648. ", filename=" + decodedFilename +
  1649. " (" + std::to_string(thumbnailData.length()) + " bytes)");
  1650. return;
  1651. } else {
  1652. // Thumbnail generation failed, fall back to full image
  1653. LOG_ERROR("Failed to generate thumbnail for: " + fullPath);
  1654. }
  1655. }
  1656. // Read full file content (original behavior)
  1657. std::ifstream file(fullPath, std::ios::binary);
  1658. if (!file.is_open()) {
  1659. LOG_ERROR("Failed to open output file: " + fullPath);
  1660. sendErrorResponse(res, "Output file not accessible", 500, "FILE_ACCESS_ERROR", requestId);
  1661. return;
  1662. }
  1663. std::string fileContent;
  1664. try {
  1665. fileContent = std::string(
  1666. std::istreambuf_iterator<char>(file),
  1667. std::istreambuf_iterator<char>());
  1668. file.close();
  1669. } catch (const std::exception& e) {
  1670. LOG_ERROR("Failed to read file content: " + std::string(e.what()));
  1671. sendErrorResponse(res, "Failed to read file content", 500, "FILE_READ_ERROR", requestId);
  1672. return;
  1673. }
  1674. // Verify we actually read data
  1675. if (fileContent.empty()) {
  1676. LOG_ERROR("File content is empty after read: " + fullPath);
  1677. sendErrorResponse(res, "File content is empty after read", 500, "EMPTY_CONTENT", requestId);
  1678. return;
  1679. }
  1680. // Determine content type based on file extension
  1681. std::string contentType = "application/octet-stream";
  1682. if (Utils::endsWith(decodedFilename, ".png")) {
  1683. contentType = "image/png";
  1684. } else if (Utils::endsWith(decodedFilename, ".jpg") || Utils::endsWith(decodedFilename, ".jpeg")) {
  1685. contentType = "image/jpeg";
  1686. } else if (Utils::endsWith(decodedFilename, ".mp4")) {
  1687. contentType = "video/mp4";
  1688. } else if (Utils::endsWith(decodedFilename, ".gif")) {
  1689. contentType = "image/gif";
  1690. } else if (Utils::endsWith(decodedFilename, ".webp")) {
  1691. contentType = "image/webp";
  1692. } else if (Utils::endsWith(decodedFilename, ".webm")) {
  1693. contentType = "video/webm";
  1694. } else if (Utils::endsWith(decodedFilename, ".avi")) {
  1695. contentType = "video/avi";
  1696. } else if (Utils::endsWith(decodedFilename, ".mov")) {
  1697. contentType = "video/quicktime";
  1698. }
  1699. // Set response headers for proper browser handling
  1700. res.set_header("Content-Type", contentType);
  1701. res.set_header("Content-Length", std::to_string(fileContent.length()));
  1702. res.set_header("Cache-Control", "public, max-age=3600"); // Cache for 1 hour
  1703. res.set_header("Access-Control-Allow-Origin", "*"); // CORS for image access
  1704. res.set_header("X-Job-ID", jobId);
  1705. res.set_header("X-Filename", decodedFilename);
  1706. res.set_header("X-File-Size", std::to_string(fileSize));
  1707. // Set content
  1708. res.set_content(fileContent, contentType);
  1709. res.status = 200;
  1710. LOG_DEBUG("Successfully served job output file: jobId=" + jobId +
  1711. ", filename=" + decodedFilename +
  1712. " (" + std::to_string(fileContent.length()) + " bytes)");
  1713. } catch (const std::exception& e) {
  1714. LOG_ERROR("Exception in handleJobOutputFile: " + std::string(e.what()));
  1715. sendErrorResponse(res, std::string("Failed to get job output file: ") + e.what(), 500, "OUTPUT_ERROR", requestId);
  1716. }
  1717. }
  1718. void Server::handleImageResize(const httplib::Request& req, httplib::Response& res) {
  1719. std::string requestId = generateRequestId();
  1720. try {
  1721. // Parse JSON request body
  1722. nlohmann::json requestJson = nlohmann::json::parse(req.body);
  1723. // Validate required fields
  1724. if (!requestJson.contains("image") || !requestJson["image"].is_string()) {
  1725. sendErrorResponse(res, "Missing or invalid 'image' field", 400, "INVALID_PARAMETERS", requestId);
  1726. return;
  1727. }
  1728. if (!requestJson.contains("width") || !requestJson["width"].is_number_integer()) {
  1729. sendErrorResponse(res, "Missing or invalid 'width' field", 400, "INVALID_PARAMETERS", requestId);
  1730. return;
  1731. }
  1732. if (!requestJson.contains("height") || !requestJson["height"].is_number_integer()) {
  1733. sendErrorResponse(res, "Missing or invalid 'height' field", 400, "INVALID_PARAMETERS", requestId);
  1734. return;
  1735. }
  1736. std::string imageInput = requestJson["image"];
  1737. int targetWidth = requestJson["width"];
  1738. int targetHeight = requestJson["height"];
  1739. // Validate dimensions
  1740. if (targetWidth < 1 || targetWidth > 4096) {
  1741. sendErrorResponse(res, "Width must be between 1 and 4096", 400, "INVALID_DIMENSIONS", requestId);
  1742. return;
  1743. }
  1744. if (targetHeight < 1 || targetHeight > 4096) {
  1745. sendErrorResponse(res, "Height must be between 1 and 4096", 400, "INVALID_DIMENSIONS", requestId);
  1746. return;
  1747. }
  1748. // Load the source image
  1749. auto [imageData, sourceWidth, sourceHeight, sourceChannels, success, loadError] = loadImageFromInput(imageInput);
  1750. if (!success) {
  1751. sendErrorResponse(res, "Failed to load image: " + loadError, 400, "IMAGE_LOAD_ERROR", requestId);
  1752. return;
  1753. }
  1754. // Convert image data to stb_image format for processing
  1755. int channels = 3; // Force RGB
  1756. size_t sourceSize = sourceWidth * sourceHeight * channels;
  1757. std::vector<uint8_t> sourcePixels(sourceSize);
  1758. std::memcpy(sourcePixels.data(), imageData.data(), std::min(imageData.size(), sourceSize));
  1759. // Resize the image using stb_image_resize if available, otherwise use simple scaling
  1760. std::vector<uint8_t> resizedPixels(targetWidth * targetHeight * channels);
  1761. // Simple nearest-neighbor scaling for now (can be improved with better algorithms)
  1762. float xScale = static_cast<float>(sourceWidth) / targetWidth;
  1763. float yScale = static_cast<float>(sourceHeight) / targetHeight;
  1764. for (int y = 0; y < targetHeight; y++) {
  1765. for (int x = 0; x < targetWidth; x++) {
  1766. int sourceX = static_cast<int>(x * xScale);
  1767. int sourceY = static_cast<int>(y * yScale);
  1768. // Clamp to source bounds
  1769. sourceX = std::min(sourceX, sourceWidth - 1);
  1770. sourceY = std::min(sourceY, sourceHeight - 1);
  1771. for (int c = 0; c < channels; c++) {
  1772. resizedPixels[(y * targetWidth + x) * channels + c] =
  1773. sourcePixels[(sourceY * sourceWidth + sourceX) * channels + c];
  1774. }
  1775. }
  1776. }
  1777. // Convert resized image to base64
  1778. std::string base64Data = Utils::base64Encode(resizedPixels);
  1779. // Determine MIME type based on input
  1780. std::string mimeType = "image/jpeg"; // default
  1781. if (Utils::startsWith(imageInput, "data:image/png")) {
  1782. mimeType = "image/png";
  1783. } else if (Utils::startsWith(imageInput, "data:image/gif")) {
  1784. mimeType = "image/gif";
  1785. } else if (Utils::startsWith(imageInput, "data:image/webp")) {
  1786. mimeType = "image/webp";
  1787. } else if (Utils::startsWith(imageInput, "data:image/bmp")) {
  1788. mimeType = "image/bmp";
  1789. }
  1790. // Create data URL format
  1791. std::string dataUrl = "data:" + mimeType + ";base64," + base64Data;
  1792. // Build response
  1793. nlohmann::json response = {
  1794. {"success", true},
  1795. {"original_width", sourceWidth},
  1796. {"original_height", sourceHeight},
  1797. {"resized_width", targetWidth},
  1798. {"resized_height", targetHeight},
  1799. {"mime_type", mimeType},
  1800. {"base64_data", dataUrl},
  1801. {"file_size_bytes", resizedPixels.size()},
  1802. {"request_id", requestId}};
  1803. sendJsonResponse(res, response, 200);
  1804. LOG_DEBUG("Successfully resized image from " + std::to_string(sourceWidth) + "x" + std::to_string(sourceHeight) +
  1805. " to " + std::to_string(targetWidth) + "x" + std::to_string(targetHeight) +
  1806. " (" + std::to_string(resizedPixels.size()) + " bytes)");
  1807. } catch (const nlohmann::json::parse_error& e) {
  1808. sendErrorResponse(res, std::string("Invalid JSON: ") + e.what(), 400, "JSON_PARSE_ERROR", requestId);
  1809. } catch (const std::exception& e) {
  1810. LOG_ERROR("Exception in handleImageResize: " + std::string(e.what()));
  1811. sendErrorResponse(res, std::string("Failed to resize image: ") + e.what(), 500, "INTERNAL_ERROR", requestId);
  1812. }
  1813. }
  1814. void Server::handleImageCrop(const httplib::Request& req, httplib::Response& res) {
  1815. std::string requestId = generateRequestId();
  1816. try {
  1817. // Parse JSON request body
  1818. nlohmann::json requestJson = nlohmann::json::parse(req.body);
  1819. // Validate required fields
  1820. if (!requestJson.contains("image") || !requestJson["image"].is_string()) {
  1821. sendErrorResponse(res, "Missing or invalid 'image' field", 400, "INVALID_PARAMETERS", requestId);
  1822. return;
  1823. }
  1824. if (!requestJson.contains("x") || !requestJson["x"].is_number_integer()) {
  1825. sendErrorResponse(res, "Missing or invalid 'x' field", 400, "INVALID_PARAMETERS", requestId);
  1826. return;
  1827. }
  1828. if (!requestJson.contains("y") || !requestJson["y"].is_number_integer()) {
  1829. sendErrorResponse(res, "Missing or invalid 'y' field", 400, "INVALID_PARAMETERS", requestId);
  1830. return;
  1831. }
  1832. if (!requestJson.contains("width") || !requestJson["width"].is_number_integer()) {
  1833. sendErrorResponse(res, "Missing or invalid 'width' field", 400, "INVALID_PARAMETERS", requestId);
  1834. return;
  1835. }
  1836. if (!requestJson.contains("height") || !requestJson["height"].is_number_integer()) {
  1837. sendErrorResponse(res, "Missing or invalid 'height' field", 400, "INVALID_PARAMETERS", requestId);
  1838. return;
  1839. }
  1840. std::string imageInput = requestJson["image"];
  1841. int cropX = requestJson["x"];
  1842. int cropY = requestJson["y"];
  1843. int cropWidth = requestJson["width"];
  1844. int cropHeight = requestJson["height"];
  1845. // Load the source image
  1846. auto [imageData, sourceWidth, sourceHeight, sourceChannels, success, loadError] = loadImageFromInput(imageInput);
  1847. if (!success) {
  1848. sendErrorResponse(res, "Failed to load image: " + loadError, 400, "IMAGE_LOAD_ERROR", requestId);
  1849. return;
  1850. }
  1851. // Validate crop dimensions
  1852. if (cropX < 0 || cropY < 0) {
  1853. sendErrorResponse(res, "Crop coordinates must be non-negative", 400, "INVALID_CROP_AREA", requestId);
  1854. return;
  1855. }
  1856. if (cropX + cropWidth > sourceWidth || cropY + cropHeight > sourceHeight) {
  1857. sendErrorResponse(res, "Crop area exceeds image dimensions", 400, "INVALID_CROP_AREA", requestId);
  1858. return;
  1859. }
  1860. if (cropWidth < 1 || cropHeight < 1) {
  1861. sendErrorResponse(res, "Crop width and height must be at least 1", 400, "INVALID_CROP_AREA", requestId);
  1862. return;
  1863. }
  1864. // Convert image data to stb_image format for processing
  1865. int channels = 3; // Force RGB
  1866. size_t sourceSize = sourceWidth * sourceHeight * channels;
  1867. std::vector<uint8_t> sourcePixels(sourceSize);
  1868. std::memcpy(sourcePixels.data(), imageData.data(), std::min(imageData.size(), sourceSize));
  1869. // Crop the image
  1870. std::vector<uint8_t> croppedPixels(cropWidth * cropHeight * channels);
  1871. for (int y = 0; y < cropHeight; y++) {
  1872. for (int x = 0; x < cropWidth; x++) {
  1873. int sourceX = cropX + x;
  1874. int sourceY = cropY + y;
  1875. for (int c = 0; c < channels; c++) {
  1876. croppedPixels[(y * cropWidth + x) * channels + c] =
  1877. sourcePixels[(sourceY * sourceWidth + sourceX) * channels + c];
  1878. }
  1879. }
  1880. }
  1881. // Convert cropped image to base64
  1882. std::string base64Data = Utils::base64Encode(croppedPixels);
  1883. // Determine MIME type based on input
  1884. std::string mimeType = "image/jpeg"; // default
  1885. if (Utils::startsWith(imageInput, "data:image/png")) {
  1886. mimeType = "image/png";
  1887. } else if (Utils::startsWith(imageInput, "data:image/gif")) {
  1888. mimeType = "image/gif";
  1889. } else if (Utils::startsWith(imageInput, "data:image/webp")) {
  1890. mimeType = "image/webp";
  1891. } else if (Utils::startsWith(imageInput, "data:image/bmp")) {
  1892. mimeType = "image/bmp";
  1893. }
  1894. // Create data URL format
  1895. std::string dataUrl = "data:" + mimeType + ";base64," + base64Data;
  1896. // Build response
  1897. nlohmann::json response = {
  1898. {"success", true},
  1899. {"original_width", sourceWidth},
  1900. {"original_height", sourceHeight},
  1901. {"crop_x", cropX},
  1902. {"crop_y", cropY},
  1903. {"cropped_width", cropWidth},
  1904. {"cropped_height", cropHeight},
  1905. {"mime_type", mimeType},
  1906. {"base64_data", dataUrl},
  1907. {"file_size_bytes", croppedPixels.size()},
  1908. {"request_id", requestId}};
  1909. sendJsonResponse(res, response, 200);
  1910. LOG_DEBUG("Successfully cropped image from " + std::to_string(sourceWidth) + "x" + std::to_string(sourceHeight) +
  1911. " to " + std::to_string(cropWidth) + "x" + std::to_string(cropHeight) +
  1912. " at (" + std::to_string(cropX) + "," + std::to_string(cropY) + ")" +
  1913. " (" + std::to_string(croppedPixels.size()) + " bytes)");
  1914. } catch (const nlohmann::json::parse_error& e) {
  1915. sendErrorResponse(res, std::string("Invalid JSON: ") + e.what(), 400, "JSON_PARSE_ERROR", requestId);
  1916. } catch (const std::exception& e) {
  1917. LOG_ERROR("Exception in handleImageCrop: " + std::string(e.what()));
  1918. sendErrorResponse(res, std::string("Failed to crop image: ") + e.what(), 500, "INTERNAL_ERROR", requestId);
  1919. }
  1920. }
  1921. void Server::handleDownloadImageFromUrl(const httplib::Request& req, httplib::Response& res) {
  1922. std::string requestId = generateRequestId();
  1923. try {
  1924. // Parse query parameters
  1925. std::string imageUrl = req.get_param_value("url");
  1926. if (imageUrl.empty()) {
  1927. sendErrorResponse(res, "Missing 'url' parameter", 400, "MISSING_URL", requestId);
  1928. return;
  1929. }
  1930. // Basic URL format validation
  1931. if (!Utils::startsWith(imageUrl, "http://") && !Utils::startsWith(imageUrl, "https://")) {
  1932. sendErrorResponse(res, "Invalid URL format. URL must start with http:// or https://", 400, "INVALID_URL_FORMAT", requestId);
  1933. return;
  1934. }
  1935. // Extract filename from URL for content type detection
  1936. std::string filename = imageUrl;
  1937. size_t lastSlash = imageUrl.find_last_of('/');
  1938. if (lastSlash != std::string::npos) {
  1939. filename = imageUrl.substr(lastSlash + 1);
  1940. }
  1941. // Remove query parameters and fragments
  1942. size_t questionMark = filename.find('?');
  1943. if (questionMark != std::string::npos) {
  1944. filename = filename.substr(0, questionMark);
  1945. }
  1946. size_t hashMark = filename.find('#');
  1947. if (hashMark != std::string::npos) {
  1948. filename = filename.substr(0, hashMark);
  1949. }
  1950. // Check if URL has image extension
  1951. std::string extension;
  1952. size_t lastDot = filename.find_last_of('.');
  1953. if (lastDot != std::string::npos) {
  1954. extension = filename.substr(lastDot + 1);
  1955. std::transform(extension.begin(), extension.end(), extension.begin(), ::tolower);
  1956. }
  1957. // Validate image extension
  1958. const std::vector<std::string> validExtensions = {"jpg", "jpeg", "png", "gif", "webp", "bmp"};
  1959. if (extension.empty() || std::find(validExtensions.begin(), validExtensions.end(), extension) == validExtensions.end()) {
  1960. sendErrorResponse(res, "URL must point to an image file with a valid extension: " + std::accumulate(validExtensions.begin(), validExtensions.end(), std::string(), [](const std::string& a, const std::string& b) {
  1961. return a.empty() ? b : a + ", " + b;
  1962. }),
  1963. 400, "INVALID_IMAGE_EXTENSION", requestId);
  1964. return;
  1965. }
  1966. // Load image using existing loadImageFromInput function
  1967. auto [imageData, width, height, channels, success, error] = loadImageFromInput(imageUrl);
  1968. if (!success) {
  1969. sendErrorResponse(res, "Failed to download image from URL: " + error, 400, "IMAGE_DOWNLOAD_FAILED", requestId);
  1970. return;
  1971. }
  1972. // Convert image data to base64
  1973. std::string base64Data = Utils::base64Encode(imageData);
  1974. // Determine MIME type based on extension
  1975. std::string mimeType = "image/jpeg"; // default
  1976. if (extension == "png") {
  1977. mimeType = "image/png";
  1978. } else if (extension == "gif") {
  1979. mimeType = "image/gif";
  1980. } else if (extension == "webp") {
  1981. mimeType = "image/webp";
  1982. } else if (extension == "bmp") {
  1983. mimeType = "image/bmp";
  1984. } else if (extension == "jpg" || extension == "jpeg") {
  1985. mimeType = "image/jpeg";
  1986. }
  1987. // Create data URL format
  1988. std::string dataUrl = "data:" + mimeType + ";base64," + base64Data;
  1989. // Build response
  1990. nlohmann::json response = {
  1991. {"success", true},
  1992. {"url", imageUrl},
  1993. {"filename", filename},
  1994. {"width", width},
  1995. {"height", height},
  1996. {"channels", channels},
  1997. {"mime_type", mimeType},
  1998. {"base64_data", dataUrl},
  1999. {"file_size_bytes", imageData.size()},
  2000. {"request_id", requestId}};
  2001. sendJsonResponse(res, response, 200);
  2002. LOG_DEBUG("Successfully downloaded and encoded image from URL: " + imageUrl +
  2003. " (" + std::to_string(width) + "x" + std::to_string(height) + ", " + std::to_string(imageData.size()) + " bytes)");
  2004. } catch (const nlohmann::json::parse_error& e) {
  2005. sendErrorResponse(res, std::string("Invalid JSON: ") + e.what(), 400, "JSON_PARSE_ERROR", requestId);
  2006. } catch (const std::exception& e) {
  2007. LOG_ERROR("Exception in handleDownloadImageFromUrl: " + std::string(e.what()));
  2008. sendErrorResponse(res, std::string("Failed to download image from URL: ") + e.what(), 500, "INTERNAL_ERROR", requestId);
  2009. }
  2010. }
  2011. void Server::sendJsonResponse(httplib::Response& res, const nlohmann::json& json, int status_code) {
  2012. res.set_header("Content-Type", "application/json");
  2013. res.status = status_code;
  2014. res.body = json.dump();
  2015. }
  2016. void Server::sendErrorResponse(httplib::Response& res, const std::string& message, int status_code, const std::string& error_code, const std::string& request_id) {
  2017. nlohmann::json errorResponse = {
  2018. {"error", {{"message", message}, {"status_code", status_code}, {"error_code", error_code}, {"request_id", request_id}, {"timestamp", std::chrono::duration_cast<std::chrono::seconds>(std::chrono::system_clock::now().time_since_epoch()).count()}}}};
  2019. sendJsonResponse(res, errorResponse, status_code);
  2020. }
  2021. std::pair<bool, std::string> Server::validateGenerationParameters(const nlohmann::json& params) {
  2022. // Validate required fields
  2023. if (!params.contains("prompt") || !params["prompt"].is_string()) {
  2024. return {false, "Missing or invalid 'prompt' field"};
  2025. }
  2026. const std::string& prompt = params["prompt"];
  2027. if (prompt.empty()) {
  2028. return {false, "Prompt cannot be empty"};
  2029. }
  2030. if (static_cast<int>(prompt.length()) > m_config.maxPromptLength) {
  2031. return {false, "Prompt too long (max " + std::to_string(m_config.maxPromptLength) + " characters)"};
  2032. }
  2033. // Validate negative prompt if present
  2034. if (params.contains("negative_prompt")) {
  2035. if (!params["negative_prompt"].is_string()) {
  2036. return {false, "Invalid 'negative_prompt' field, must be string"};
  2037. }
  2038. if (static_cast<int>(params["negative_prompt"].get<std::string>().length()) > m_config.maxNegativePromptLength) {
  2039. return {false, "Negative prompt too long (max " + std::to_string(m_config.maxNegativePromptLength) + " characters)"};
  2040. }
  2041. }
  2042. // Validate width
  2043. if (params.contains("width")) {
  2044. if (!params["width"].is_number_integer()) {
  2045. return {false, "Invalid 'width' field, must be integer"};
  2046. }
  2047. int width = params["width"];
  2048. if (width < 64 || width > 2048 || width % 64 != 0) {
  2049. return {false, "Width must be between 64 and 2048 and divisible by 64"};
  2050. }
  2051. }
  2052. // Validate height
  2053. if (params.contains("height")) {
  2054. if (!params["height"].is_number_integer()) {
  2055. return {false, "Invalid 'height' field, must be integer"};
  2056. }
  2057. int height = params["height"];
  2058. if (height < 64 || height > 2048 || height % 64 != 0) {
  2059. return {false, "Height must be between 64 and 2048 and divisible by 64"};
  2060. }
  2061. }
  2062. // Validate batch count
  2063. if (params.contains("batch_count")) {
  2064. if (!params["batch_count"].is_number_integer()) {
  2065. return {false, "Invalid 'batch_count' field, must be integer"};
  2066. }
  2067. int batchCount = params["batch_count"];
  2068. if (batchCount < 1 || batchCount > 100) {
  2069. return {false, "Batch count must be between 1 and 100"};
  2070. }
  2071. }
  2072. // Validate steps
  2073. if (params.contains("steps")) {
  2074. if (!params["steps"].is_number_integer()) {
  2075. return {false, "Invalid 'steps' field, must be integer"};
  2076. }
  2077. int steps = params["steps"];
  2078. if (steps < 1 || steps > 150) {
  2079. return {false, "Steps must be between 1 and 150"};
  2080. }
  2081. }
  2082. // Validate CFG scale
  2083. if (params.contains("cfg_scale")) {
  2084. if (!params["cfg_scale"].is_number()) {
  2085. return {false, "Invalid 'cfg_scale' field, must be number"};
  2086. }
  2087. float cfgScale = params["cfg_scale"];
  2088. if (cfgScale < 1.0f || cfgScale > 30.0f) {
  2089. return {false, "CFG scale must be between 1.0 and 30.0"};
  2090. }
  2091. }
  2092. // Validate seed
  2093. if (params.contains("seed")) {
  2094. if (!params["seed"].is_string() && !params["seed"].is_number_integer()) {
  2095. return {false, "Invalid 'seed' field, must be string or integer"};
  2096. }
  2097. }
  2098. // Validate sampling method
  2099. if (params.contains("sampling_method")) {
  2100. if (!params["sampling_method"].is_string()) {
  2101. return {false, "Invalid 'sampling_method' field, must be string"};
  2102. }
  2103. std::string method = params["sampling_method"];
  2104. std::vector<std::string> validMethods = {
  2105. "euler", "euler_a", "heun", "dpm2", "dpm++2s_a", "dpm++2m",
  2106. "dpm++2mv2", "ipndm", "ipndm_v", "lcm", "ddim_trailing", "tcd", "default"};
  2107. if (std::find(validMethods.begin(), validMethods.end(), method) == validMethods.end()) {
  2108. return {false, "Invalid sampling method"};
  2109. }
  2110. }
  2111. // Validate scheduler
  2112. if (params.contains("scheduler")) {
  2113. if (!params["scheduler"].is_string()) {
  2114. return {false, "Invalid 'scheduler' field, must be string"};
  2115. }
  2116. std::string scheduler = params["scheduler"];
  2117. std::vector<std::string> validSchedulers = {
  2118. "discrete", "karras", "exponential", "ays", "gits",
  2119. "smoothstep", "sgm_uniform", "simple", "default"};
  2120. if (std::find(validSchedulers.begin(), validSchedulers.end(), scheduler) == validSchedulers.end()) {
  2121. return {false, "Invalid scheduler"};
  2122. }
  2123. }
  2124. // Validate strength
  2125. if (params.contains("strength")) {
  2126. if (!params["strength"].is_number()) {
  2127. return {false, "Invalid 'strength' field, must be number"};
  2128. }
  2129. float strength = params["strength"];
  2130. if (strength < 0.0f || strength > 1.0f) {
  2131. return {false, "Strength must be between 0.0 and 1.0"};
  2132. }
  2133. }
  2134. // Validate control strength
  2135. if (params.contains("control_strength")) {
  2136. if (!params["control_strength"].is_number()) {
  2137. return {false, "Invalid 'control_strength' field, must be number"};
  2138. }
  2139. float controlStrength = params["control_strength"];
  2140. if (controlStrength < 0.0f || controlStrength > 1.0f) {
  2141. return {false, "Control strength must be between 0.0 and 1.0"};
  2142. }
  2143. }
  2144. // Validate clip skip
  2145. if (params.contains("clip_skip")) {
  2146. if (!params["clip_skip"].is_number_integer()) {
  2147. return {false, "Invalid 'clip_skip' field, must be integer"};
  2148. }
  2149. int clipSkip = params["clip_skip"];
  2150. if (clipSkip < -1 || clipSkip > 12) {
  2151. return {false, "Clip skip must be between -1 and 12"};
  2152. }
  2153. }
  2154. // Validate threads
  2155. if (params.contains("threads")) {
  2156. if (!params["threads"].is_number_integer()) {
  2157. return {false, "Invalid 'threads' field, must be integer"};
  2158. }
  2159. int threads = params["threads"];
  2160. if (threads < -1 || threads > 32) {
  2161. return {false, "Threads must be between -1 (auto) and 32"};
  2162. }
  2163. }
  2164. return {true, ""};
  2165. }
  2166. SamplingMethod Server::parseSamplingMethod(const std::string& method) {
  2167. if (method == "euler")
  2168. return SamplingMethod::EULER;
  2169. else if (method == "euler_a")
  2170. return SamplingMethod::EULER_A;
  2171. else if (method == "heun")
  2172. return SamplingMethod::HEUN;
  2173. else if (method == "dpm2")
  2174. return SamplingMethod::DPM2;
  2175. else if (method == "dpm++2s_a")
  2176. return SamplingMethod::DPMPP2S_A;
  2177. else if (method == "dpm++2m")
  2178. return SamplingMethod::DPMPP2M;
  2179. else if (method == "dpm++2mv2")
  2180. return SamplingMethod::DPMPP2MV2;
  2181. else if (method == "ipndm")
  2182. return SamplingMethod::IPNDM;
  2183. else if (method == "ipndm_v")
  2184. return SamplingMethod::IPNDM_V;
  2185. else if (method == "lcm")
  2186. return SamplingMethod::LCM;
  2187. else if (method == "ddim_trailing")
  2188. return SamplingMethod::DDIM_TRAILING;
  2189. else if (method == "tcd")
  2190. return SamplingMethod::TCD;
  2191. else
  2192. return SamplingMethod::DEFAULT;
  2193. }
  2194. Scheduler Server::parseScheduler(const std::string& scheduler) {
  2195. if (scheduler == "discrete")
  2196. return Scheduler::DISCRETE;
  2197. else if (scheduler == "karras")
  2198. return Scheduler::KARRAS;
  2199. else if (scheduler == "exponential")
  2200. return Scheduler::EXPONENTIAL;
  2201. else if (scheduler == "ays")
  2202. return Scheduler::AYS;
  2203. else if (scheduler == "gits")
  2204. return Scheduler::GITS;
  2205. else if (scheduler == "smoothstep")
  2206. return Scheduler::SMOOTHSTEP;
  2207. else if (scheduler == "sgm_uniform")
  2208. return Scheduler::SGM_UNIFORM;
  2209. else if (scheduler == "simple")
  2210. return Scheduler::SIMPLE;
  2211. else
  2212. return Scheduler::DEFAULT;
  2213. }
  2214. std::string Server::generateRequestId() {
  2215. std::random_device rd;
  2216. std::mt19937 gen(rd());
  2217. std::uniform_int_distribution<> dis(100000, 999999);
  2218. return "req_" + std::to_string(dis(gen));
  2219. }
  2220. std::tuple<std::vector<uint8_t>, int, int, int, bool, std::string>
  2221. Server::loadImageFromInput(const std::string& input) {
  2222. std::vector<uint8_t> imageData;
  2223. int width = 0, height = 0, channels = 0;
  2224. // Auto-detect input source type
  2225. // 1. Check if input is a URL (starts with http:// or https://)
  2226. if (Utils::startsWith(input, "http://") || Utils::startsWith(input, "https://")) {
  2227. // Parse URL to extract host and path
  2228. std::string url = input;
  2229. std::string scheme, host, path;
  2230. int port = 80;
  2231. // Determine scheme and port
  2232. if (Utils::startsWith(url, "https://")) {
  2233. scheme = "https";
  2234. port = 443;
  2235. url = url.substr(8); // Remove "https://"
  2236. } else {
  2237. scheme = "http";
  2238. port = 80;
  2239. url = url.substr(7); // Remove "http://"
  2240. }
  2241. // Extract host and path
  2242. size_t slashPos = url.find('/');
  2243. if (slashPos != std::string::npos) {
  2244. host = url.substr(0, slashPos);
  2245. path = url.substr(slashPos);
  2246. } else {
  2247. host = url;
  2248. path = "/";
  2249. }
  2250. // Check for custom port
  2251. size_t colonPos = host.find(':');
  2252. if (colonPos != std::string::npos) {
  2253. try {
  2254. port = std::stoi(host.substr(colonPos + 1));
  2255. host = host.substr(0, colonPos);
  2256. } catch (...) {
  2257. return {imageData, 0, 0, 0, false, "Invalid port in URL"};
  2258. }
  2259. }
  2260. // Download image using httplib
  2261. try {
  2262. httplib::Result res;
  2263. if (scheme == "https") {
  2264. #ifdef CPPHTTPLIB_OPENSSL_SUPPORT
  2265. httplib::SSLClient client(host, port);
  2266. client.set_follow_location(true);
  2267. client.set_connection_timeout(30, 0); // 30 seconds
  2268. client.set_read_timeout(60, 0); // 60 seconds
  2269. res = client.Get(path.c_str());
  2270. #else
  2271. return {imageData, 0, 0, 0, false, "HTTPS not supported (OpenSSL not available)"};
  2272. #endif
  2273. } else {
  2274. httplib::Client client(host, port);
  2275. client.set_follow_location(true);
  2276. client.set_connection_timeout(30, 0); // 30 seconds
  2277. client.set_read_timeout(60, 0); // 60 seconds
  2278. res = client.Get(path.c_str());
  2279. }
  2280. if (!res) {
  2281. return {imageData, 0, 0, 0, false, "Failed to download image from URL: Connection error"};
  2282. }
  2283. if (res->status != 200) {
  2284. return {imageData, 0, 0, 0, false, "Failed to download image from URL: HTTP " + std::to_string(res->status)};
  2285. }
  2286. // Convert response body to vector
  2287. std::vector<uint8_t> downloadedData(res->body.begin(), res->body.end());
  2288. // Load image from memory
  2289. int w, h, c;
  2290. unsigned char* pixels = stbi_load_from_memory(
  2291. downloadedData.data(),
  2292. downloadedData.size(),
  2293. &w, &h, &c,
  2294. 3 // Force RGB
  2295. );
  2296. if (!pixels) {
  2297. return {imageData, 0, 0, 0, false, "Failed to decode image from URL"};
  2298. }
  2299. width = w;
  2300. height = h;
  2301. channels = 3;
  2302. size_t dataSize = width * height * channels;
  2303. imageData.resize(dataSize);
  2304. std::memcpy(imageData.data(), pixels, dataSize);
  2305. stbi_image_free(pixels);
  2306. } catch (const std::exception& e) {
  2307. return {imageData, 0, 0, 0, false, "Failed to download image from URL: " + std::string(e.what())};
  2308. }
  2309. }
  2310. // 2. Check if input is base64 encoded data URI (starts with "data:image")
  2311. else if (Utils::startsWith(input, "data:image")) {
  2312. // Extract base64 data after the comma
  2313. size_t commaPos = input.find(',');
  2314. if (commaPos == std::string::npos) {
  2315. return {imageData, 0, 0, 0, false, "Invalid data URI format"};
  2316. }
  2317. std::string base64Data = input.substr(commaPos + 1);
  2318. // Validate base64 data is not empty
  2319. if (base64Data.empty()) {
  2320. return {imageData, 0, 0, 0, false, "Empty base64 data in data URI"};
  2321. }
  2322. std::vector<uint8_t> decodedData = Utils::base64Decode(base64Data);
  2323. // Check if base64 decoding failed
  2324. if (decodedData.empty()) {
  2325. return {imageData, 0, 0, 0, false, "Failed to decode base64 data: invalid base64 format or contains invalid characters"};
  2326. }
  2327. // Load image from memory using stb_image
  2328. int w, h, c;
  2329. unsigned char* pixels = stbi_load_from_memory(
  2330. decodedData.data(),
  2331. decodedData.size(),
  2332. &w, &h, &c,
  2333. 3 // Force RGB
  2334. );
  2335. if (!pixels) {
  2336. // Get more detailed error information from stb_image if available
  2337. const char* stbError = stbi_failure_reason();
  2338. std::string errorMsg = "Failed to decode image from base64 data URI";
  2339. if (stbError && strlen(stbError) > 0) {
  2340. errorMsg += std::string(": ") + stbError;
  2341. }
  2342. return {imageData, 0, 0, 0, false, errorMsg};
  2343. }
  2344. width = w;
  2345. height = h;
  2346. channels = 3; // We forced RGB
  2347. // Copy pixel data
  2348. size_t dataSize = width * height * channels;
  2349. imageData.resize(dataSize);
  2350. std::memcpy(imageData.data(), pixels, dataSize);
  2351. stbi_image_free(pixels);
  2352. }
  2353. // 3. Check if input is raw base64 (long string without slashes, likely base64)
  2354. else if (input.length() > 100 && input.find('/') == std::string::npos && input.find('.') == std::string::npos) {
  2355. // Likely raw base64 without data URI prefix
  2356. std::vector<uint8_t> decodedData = Utils::base64Decode(input);
  2357. // Check if base64 decoding failed
  2358. if (decodedData.empty()) {
  2359. return {imageData, 0, 0, 0, false, "Failed to decode raw base64 data: invalid base64 format or contains invalid characters"};
  2360. }
  2361. int w, h, c;
  2362. unsigned char* pixels = stbi_load_from_memory(
  2363. decodedData.data(),
  2364. decodedData.size(),
  2365. &w, &h, &c,
  2366. 3 // Force RGB
  2367. );
  2368. if (!pixels) {
  2369. // Get more detailed error information from stb_image if available
  2370. const char* stbError = stbi_failure_reason();
  2371. std::string errorMsg = "Failed to decode image from raw base64 data";
  2372. if (stbError && strlen(stbError) > 0) {
  2373. errorMsg += std::string(": ") + stbError;
  2374. }
  2375. return {imageData, 0, 0, 0, false, errorMsg};
  2376. }
  2377. width = w;
  2378. height = h;
  2379. channels = 3;
  2380. size_t dataSize = width * height * channels;
  2381. imageData.resize(dataSize);
  2382. std::memcpy(imageData.data(), pixels, dataSize);
  2383. stbi_image_free(pixels);
  2384. }
  2385. // 4. Treat as local file path
  2386. else {
  2387. int w, h, c;
  2388. unsigned char* pixels = stbi_load(input.c_str(), &w, &h, &c, 3);
  2389. if (!pixels) {
  2390. return {imageData, 0, 0, 0, false, "Failed to load image from file: " + input};
  2391. }
  2392. width = w;
  2393. height = h;
  2394. channels = 3;
  2395. size_t dataSize = width * height * channels;
  2396. imageData.resize(dataSize);
  2397. std::memcpy(imageData.data(), pixels, dataSize);
  2398. stbi_image_free(pixels);
  2399. }
  2400. return {imageData, width, height, channels, true, ""};
  2401. }
  2402. std::string Server::samplingMethodToString(SamplingMethod method) {
  2403. switch (method) {
  2404. case SamplingMethod::EULER:
  2405. return "euler";
  2406. case SamplingMethod::EULER_A:
  2407. return "euler_a";
  2408. case SamplingMethod::HEUN:
  2409. return "heun";
  2410. case SamplingMethod::DPM2:
  2411. return "dpm2";
  2412. case SamplingMethod::DPMPP2S_A:
  2413. return "dpm++2s_a";
  2414. case SamplingMethod::DPMPP2M:
  2415. return "dpm++2m";
  2416. case SamplingMethod::DPMPP2MV2:
  2417. return "dpm++2mv2";
  2418. case SamplingMethod::IPNDM:
  2419. return "ipndm";
  2420. case SamplingMethod::IPNDM_V:
  2421. return "ipndm_v";
  2422. case SamplingMethod::LCM:
  2423. return "lcm";
  2424. case SamplingMethod::DDIM_TRAILING:
  2425. return "ddim_trailing";
  2426. case SamplingMethod::TCD:
  2427. return "tcd";
  2428. default:
  2429. return "default";
  2430. }
  2431. }
  2432. std::string Server::schedulerToString(Scheduler scheduler) {
  2433. switch (scheduler) {
  2434. case Scheduler::DISCRETE:
  2435. return "discrete";
  2436. case Scheduler::KARRAS:
  2437. return "karras";
  2438. case Scheduler::EXPONENTIAL:
  2439. return "exponential";
  2440. case Scheduler::AYS:
  2441. return "ays";
  2442. case Scheduler::GITS:
  2443. return "gits";
  2444. case Scheduler::SMOOTHSTEP:
  2445. return "smoothstep";
  2446. case Scheduler::SGM_UNIFORM:
  2447. return "sgm_uniform";
  2448. case Scheduler::SIMPLE:
  2449. return "simple";
  2450. default:
  2451. return "default";
  2452. }
  2453. }
  2454. uint64_t Server::estimateGenerationTime(const GenerationRequest& request) {
  2455. // Basic estimation based on parameters
  2456. uint64_t baseTime = 1000; // 1 second base time
  2457. // Factor in steps
  2458. baseTime *= request.steps;
  2459. // Factor in resolution
  2460. double resolutionFactor = (request.width * request.height) / (512.0 * 512.0);
  2461. baseTime = static_cast<uint64_t>(baseTime * resolutionFactor);
  2462. // Factor in batch count
  2463. baseTime *= request.batchCount;
  2464. // Adjust for sampling method (some are faster than others)
  2465. switch (request.samplingMethod) {
  2466. case SamplingMethod::LCM:
  2467. baseTime /= 4; // LCM is much faster
  2468. break;
  2469. case SamplingMethod::EULER:
  2470. case SamplingMethod::EULER_A:
  2471. baseTime *= 0.8; // Euler methods are faster
  2472. break;
  2473. case SamplingMethod::DPM2:
  2474. case SamplingMethod::DPMPP2S_A:
  2475. baseTime *= 1.2; // DPM methods are slower
  2476. break;
  2477. default:
  2478. break;
  2479. }
  2480. return baseTime;
  2481. }
  2482. size_t Server::estimateMemoryUsage(const GenerationRequest& request) {
  2483. // Basic memory estimation in bytes
  2484. size_t baseMemory = 1024 * 1024 * 1024; // 1GB base
  2485. // Factor in resolution
  2486. double resolutionFactor = (request.width * request.height) / (512.0 * 512.0);
  2487. baseMemory = static_cast<size_t>(baseMemory * resolutionFactor);
  2488. // Factor in batch count
  2489. baseMemory *= request.batchCount;
  2490. // Additional memory for certain features
  2491. if (request.diffusionFlashAttn) {
  2492. baseMemory += 512 * 1024 * 1024; // Extra 512MB for flash attention
  2493. }
  2494. if (!request.controlNetPath.empty()) {
  2495. baseMemory += 1024 * 1024 * 1024; // Extra 1GB for ControlNet
  2496. }
  2497. return baseMemory;
  2498. }
  2499. // Specialized generation endpoints
  2500. void Server::handleText2Img(const httplib::Request& req, httplib::Response& res) {
  2501. std::string requestId = generateRequestId();
  2502. try {
  2503. if (!m_generationQueue) {
  2504. sendErrorResponse(res, "Generation queue not available", 500, "QUEUE_UNAVAILABLE", requestId);
  2505. return;
  2506. }
  2507. nlohmann::json requestJson = nlohmann::json::parse(req.body);
  2508. // Validate required fields for text2img
  2509. if (!requestJson.contains("prompt") || !requestJson["prompt"].is_string()) {
  2510. sendErrorResponse(res, "Missing or invalid 'prompt' field", 400, "INVALID_PARAMETERS", requestId);
  2511. return;
  2512. }
  2513. // Validate all parameters
  2514. auto [isValid, errorMessage] = validateGenerationParameters(requestJson);
  2515. if (!isValid) {
  2516. sendErrorResponse(res, errorMessage, 400, "INVALID_PARAMETERS", requestId);
  2517. return;
  2518. }
  2519. // Check if any model is loaded
  2520. if (!m_modelManager) {
  2521. sendErrorResponse(res, "Model manager not available", 500, "MODEL_MANAGER_UNAVAILABLE", requestId);
  2522. return;
  2523. }
  2524. // Get currently loaded checkpoint model
  2525. std::string loadedModelName;
  2526. {
  2527. std::lock_guard<std::mutex> lock(m_loadedModelsMutex);
  2528. loadedModelName = m_loadedModels.checkpoint;
  2529. }
  2530. if (loadedModelName.empty()) {
  2531. sendErrorResponse(res, "No checkpoint model loaded. Please load a checkpoint model first using POST /api/models/{hash}/load", 400, "NO_CHECKPOINT_LOADED", requestId);
  2532. return;
  2533. }
  2534. // Create generation request specifically for text2img
  2535. GenerationRequest genRequest;
  2536. genRequest.id = requestId;
  2537. genRequest.modelName = loadedModelName; // Use the currently loaded model
  2538. genRequest.prompt = requestJson["prompt"];
  2539. genRequest.negativePrompt = requestJson.value("negative_prompt", "");
  2540. genRequest.width = requestJson.value("width", 512);
  2541. genRequest.height = requestJson.value("height", 512);
  2542. genRequest.batchCount = requestJson.value("batch_count", 1);
  2543. genRequest.steps = requestJson.value("steps", 20);
  2544. genRequest.cfgScale = requestJson.value("cfg_scale", 7.5f);
  2545. genRequest.seed = requestJson.value("seed", "random");
  2546. // Parse optional parameters
  2547. if (requestJson.contains("sampling_method")) {
  2548. genRequest.samplingMethod = parseSamplingMethod(requestJson["sampling_method"]);
  2549. }
  2550. if (requestJson.contains("scheduler")) {
  2551. genRequest.scheduler = parseScheduler(requestJson["scheduler"]);
  2552. }
  2553. // Set text2img specific defaults
  2554. genRequest.strength = 1.0f; // Full strength for text2img
  2555. // Optional VAE model
  2556. if (requestJson.contains("vae_model") && requestJson["vae_model"].is_string()) {
  2557. std::string vaeModelId = requestJson["vae_model"];
  2558. if (!vaeModelId.empty()) {
  2559. auto vaeInfo = m_modelManager->getModelInfo(vaeModelId);
  2560. if (!vaeInfo.name.empty() && vaeInfo.type == ModelType::VAE) {
  2561. genRequest.vaePath = vaeInfo.path;
  2562. } else {
  2563. sendErrorResponse(res, "VAE model not found or invalid: " + vaeModelId, 400, "INVALID_VAE_MODEL", requestId);
  2564. return;
  2565. }
  2566. }
  2567. }
  2568. // Optional TAESD model
  2569. if (requestJson.contains("taesd_model") && requestJson["taesd_model"].is_string()) {
  2570. std::string taesdModelId = requestJson["taesd_model"];
  2571. if (!taesdModelId.empty()) {
  2572. auto taesdInfo = m_modelManager->getModelInfo(taesdModelId);
  2573. if (!taesdInfo.name.empty() && taesdInfo.type == ModelType::TAESD) {
  2574. genRequest.taesdPath = taesdInfo.path;
  2575. } else {
  2576. sendErrorResponse(res, "TAESD model not found or invalid: " + taesdModelId, 400, "INVALID_TAESD_MODEL", requestId);
  2577. return;
  2578. }
  2579. }
  2580. }
  2581. // Enqueue request
  2582. auto future = m_generationQueue->enqueueRequest(genRequest);
  2583. nlohmann::json params = {
  2584. {"prompt", genRequest.prompt},
  2585. {"negative_prompt", genRequest.negativePrompt},
  2586. {"model", genRequest.modelName},
  2587. {"width", genRequest.width},
  2588. {"height", genRequest.height},
  2589. {"batch_count", genRequest.batchCount},
  2590. {"steps", genRequest.steps},
  2591. {"cfg_scale", genRequest.cfgScale},
  2592. {"seed", genRequest.seed},
  2593. {"sampling_method", samplingMethodToString(genRequest.samplingMethod)},
  2594. {"scheduler", schedulerToString(genRequest.scheduler)}};
  2595. // Add VAE/TAESD if specified
  2596. if (!genRequest.vaePath.empty()) {
  2597. params["vae_model"] = requestJson.value("vae_model", "");
  2598. }
  2599. if (!genRequest.taesdPath.empty()) {
  2600. params["taesd_model"] = requestJson.value("taesd_model", "");
  2601. }
  2602. nlohmann::json response = {
  2603. {"request_id", requestId},
  2604. {"status", "queued"},
  2605. {"message", "Text-to-image generation request queued successfully"},
  2606. {"queue_position", m_generationQueue->getQueueSize()},
  2607. {"estimated_time_seconds", estimateGenerationTime(genRequest) / 1000},
  2608. {"estimated_memory_mb", estimateMemoryUsage(genRequest) / (1024 * 1024)},
  2609. {"type", "text2img"},
  2610. {"parameters", params}};
  2611. sendJsonResponse(res, response, 202);
  2612. } catch (const nlohmann::json::parse_error& e) {
  2613. sendErrorResponse(res, std::string("Invalid JSON: ") + e.what(), 400, "JSON_PARSE_ERROR", requestId);
  2614. } catch (const std::exception& e) {
  2615. sendErrorResponse(res, std::string("Text-to-image request failed: ") + e.what(), 500, "INTERNAL_ERROR", requestId);
  2616. }
  2617. }
  2618. void Server::handleImg2Img(const httplib::Request& req, httplib::Response& res) {
  2619. std::string requestId = generateRequestId();
  2620. try {
  2621. if (!m_generationQueue) {
  2622. sendErrorResponse(res, "Generation queue not available", 500, "QUEUE_UNAVAILABLE", requestId);
  2623. return;
  2624. }
  2625. nlohmann::json requestJson = nlohmann::json::parse(req.body);
  2626. // Validate required fields for img2img
  2627. if (!requestJson.contains("prompt") || !requestJson["prompt"].is_string()) {
  2628. sendErrorResponse(res, "Missing or invalid 'prompt' field", 400, "INVALID_PARAMETERS", requestId);
  2629. return;
  2630. }
  2631. if (!requestJson.contains("init_image") || !requestJson["init_image"].is_string()) {
  2632. sendErrorResponse(res, "Missing or invalid 'init_image' field", 400, "INVALID_PARAMETERS", requestId);
  2633. return;
  2634. }
  2635. // Validate all parameters
  2636. auto [isValid, errorMessage] = validateGenerationParameters(requestJson);
  2637. if (!isValid) {
  2638. sendErrorResponse(res, errorMessage, 400, "INVALID_PARAMETERS", requestId);
  2639. return;
  2640. }
  2641. // Check if any model is loaded
  2642. if (!m_modelManager) {
  2643. sendErrorResponse(res, "Model manager not available", 500, "MODEL_MANAGER_UNAVAILABLE", requestId);
  2644. return;
  2645. }
  2646. // Get currently loaded checkpoint model
  2647. std::string loadedModelName;
  2648. {
  2649. std::lock_guard<std::mutex> lock(m_loadedModelsMutex);
  2650. loadedModelName = m_loadedModels.checkpoint;
  2651. }
  2652. if (loadedModelName.empty()) {
  2653. sendErrorResponse(res, "No checkpoint model loaded. Please load a checkpoint model first using POST /api/models/{hash}/load", 400, "NO_CHECKPOINT_LOADED", requestId);
  2654. return;
  2655. }
  2656. // Load the init image
  2657. std::string initImageInput = requestJson["init_image"];
  2658. auto [imageData, imgWidth, imgHeight, imgChannels, success, loadError] = loadImageFromInput(initImageInput);
  2659. if (!success) {
  2660. sendErrorResponse(res, "Failed to load init image: " + loadError, 400, "IMAGE_LOAD_ERROR", requestId);
  2661. return;
  2662. }
  2663. // Create generation request specifically for img2img
  2664. GenerationRequest genRequest;
  2665. genRequest.id = requestId;
  2666. genRequest.requestType = GenerationRequest::RequestType::IMG2IMG;
  2667. genRequest.modelName = loadedModelName; // Use the currently loaded model
  2668. genRequest.prompt = requestJson["prompt"];
  2669. genRequest.negativePrompt = requestJson.value("negative_prompt", "");
  2670. genRequest.width = requestJson.value("width", imgWidth); // Default to input image dimensions
  2671. genRequest.height = requestJson.value("height", imgHeight);
  2672. genRequest.batchCount = requestJson.value("batch_count", 1);
  2673. genRequest.steps = requestJson.value("steps", 20);
  2674. genRequest.cfgScale = requestJson.value("cfg_scale", 7.5f);
  2675. genRequest.seed = requestJson.value("seed", "random");
  2676. genRequest.strength = requestJson.value("strength", 0.75f);
  2677. // Set init image data
  2678. genRequest.initImageData = imageData;
  2679. genRequest.initImageWidth = imgWidth;
  2680. genRequest.initImageHeight = imgHeight;
  2681. genRequest.initImageChannels = imgChannels;
  2682. // Parse optional parameters
  2683. if (requestJson.contains("sampling_method")) {
  2684. genRequest.samplingMethod = parseSamplingMethod(requestJson["sampling_method"]);
  2685. }
  2686. if (requestJson.contains("scheduler")) {
  2687. genRequest.scheduler = parseScheduler(requestJson["scheduler"]);
  2688. }
  2689. // Optional VAE model
  2690. if (requestJson.contains("vae_model") && requestJson["vae_model"].is_string()) {
  2691. std::string vaeModelId = requestJson["vae_model"];
  2692. if (!vaeModelId.empty()) {
  2693. auto vaeInfo = m_modelManager->getModelInfo(vaeModelId);
  2694. if (!vaeInfo.name.empty() && vaeInfo.type == ModelType::VAE) {
  2695. genRequest.vaePath = vaeInfo.path;
  2696. } else {
  2697. sendErrorResponse(res, "VAE model not found or invalid: " + vaeModelId, 400, "INVALID_VAE_MODEL", requestId);
  2698. return;
  2699. }
  2700. }
  2701. }
  2702. // Optional TAESD model
  2703. if (requestJson.contains("taesd_model") && requestJson["taesd_model"].is_string()) {
  2704. std::string taesdModelId = requestJson["taesd_model"];
  2705. if (!taesdModelId.empty()) {
  2706. auto taesdInfo = m_modelManager->getModelInfo(taesdModelId);
  2707. if (!taesdInfo.name.empty() && taesdInfo.type == ModelType::TAESD) {
  2708. genRequest.taesdPath = taesdInfo.path;
  2709. } else {
  2710. sendErrorResponse(res, "TAESD model not found or invalid: " + taesdModelId, 400, "INVALID_TAESD_MODEL", requestId);
  2711. return;
  2712. }
  2713. }
  2714. }
  2715. // Enqueue request
  2716. auto future = m_generationQueue->enqueueRequest(genRequest);
  2717. nlohmann::json params = {
  2718. {"prompt", genRequest.prompt},
  2719. {"negative_prompt", genRequest.negativePrompt},
  2720. {"init_image", requestJson["init_image"]},
  2721. {"model", genRequest.modelName},
  2722. {"width", genRequest.width},
  2723. {"height", genRequest.height},
  2724. {"batch_count", genRequest.batchCount},
  2725. {"steps", genRequest.steps},
  2726. {"cfg_scale", genRequest.cfgScale},
  2727. {"seed", genRequest.seed},
  2728. {"strength", genRequest.strength},
  2729. {"sampling_method", samplingMethodToString(genRequest.samplingMethod)},
  2730. {"scheduler", schedulerToString(genRequest.scheduler)}};
  2731. // Add VAE/TAESD if specified
  2732. if (!genRequest.vaePath.empty()) {
  2733. params["vae_model"] = requestJson.value("vae_model", "");
  2734. }
  2735. if (!genRequest.taesdPath.empty()) {
  2736. params["taesd_model"] = requestJson.value("taesd_model", "");
  2737. }
  2738. nlohmann::json response = {
  2739. {"request_id", requestId},
  2740. {"status", "queued"},
  2741. {"message", "Image-to-image generation request queued successfully"},
  2742. {"queue_position", m_generationQueue->getQueueSize()},
  2743. {"estimated_time_seconds", estimateGenerationTime(genRequest) / 1000},
  2744. {"estimated_memory_mb", estimateMemoryUsage(genRequest) / (1024 * 1024)},
  2745. {"type", "img2img"},
  2746. {"parameters", params}};
  2747. sendJsonResponse(res, response, 202);
  2748. } catch (const nlohmann::json::parse_error& e) {
  2749. sendErrorResponse(res, std::string("Invalid JSON: ") + e.what(), 400, "JSON_PARSE_ERROR", requestId);
  2750. } catch (const std::exception& e) {
  2751. sendErrorResponse(res, std::string("Image-to-image request failed: ") + e.what(), 500, "INTERNAL_ERROR", requestId);
  2752. }
  2753. }
  2754. void Server::handleControlNet(const httplib::Request& req, httplib::Response& res) {
  2755. std::string requestId = generateRequestId();
  2756. try {
  2757. if (!m_generationQueue) {
  2758. sendErrorResponse(res, "Generation queue not available", 500, "QUEUE_UNAVAILABLE", requestId);
  2759. return;
  2760. }
  2761. nlohmann::json requestJson = nlohmann::json::parse(req.body);
  2762. // Validate required fields for ControlNet
  2763. if (!requestJson.contains("prompt") || !requestJson["prompt"].is_string()) {
  2764. sendErrorResponse(res, "Missing or invalid 'prompt' field", 400, "INVALID_PARAMETERS", requestId);
  2765. return;
  2766. }
  2767. if (!requestJson.contains("control_image") || !requestJson["control_image"].is_string()) {
  2768. sendErrorResponse(res, "Missing or invalid 'control_image' field", 400, "INVALID_PARAMETERS", requestId);
  2769. return;
  2770. }
  2771. // Validate all parameters
  2772. auto [isValid, errorMessage] = validateGenerationParameters(requestJson);
  2773. if (!isValid) {
  2774. sendErrorResponse(res, errorMessage, 400, "INVALID_PARAMETERS", requestId);
  2775. return;
  2776. }
  2777. // Check if any model is loaded
  2778. if (!m_modelManager) {
  2779. sendErrorResponse(res, "Model manager not available", 500, "MODEL_MANAGER_UNAVAILABLE", requestId);
  2780. return;
  2781. }
  2782. // Get currently loaded checkpoint model
  2783. std::string loadedModelName;
  2784. {
  2785. std::lock_guard<std::mutex> lock(m_loadedModelsMutex);
  2786. loadedModelName = m_loadedModels.checkpoint;
  2787. }
  2788. if (loadedModelName.empty()) {
  2789. sendErrorResponse(res, "No checkpoint model loaded. Please load a checkpoint model first using POST /api/models/{hash}/load", 400, "NO_CHECKPOINT_LOADED", requestId);
  2790. return;
  2791. }
  2792. // Create generation request specifically for ControlNet
  2793. GenerationRequest genRequest;
  2794. genRequest.id = requestId;
  2795. genRequest.modelName = loadedModelName; // Use the currently loaded model
  2796. genRequest.prompt = requestJson["prompt"];
  2797. genRequest.negativePrompt = requestJson.value("negative_prompt", "");
  2798. genRequest.width = requestJson.value("width", 512);
  2799. genRequest.height = requestJson.value("height", 512);
  2800. genRequest.batchCount = requestJson.value("batch_count", 1);
  2801. genRequest.steps = requestJson.value("steps", 20);
  2802. genRequest.cfgScale = requestJson.value("cfg_scale", 7.5f);
  2803. genRequest.seed = requestJson.value("seed", "random");
  2804. genRequest.controlStrength = requestJson.value("control_strength", 0.9f);
  2805. genRequest.controlNetPath = requestJson.value("control_net_model", "");
  2806. // Parse optional parameters
  2807. if (requestJson.contains("sampling_method")) {
  2808. genRequest.samplingMethod = parseSamplingMethod(requestJson["sampling_method"]);
  2809. }
  2810. if (requestJson.contains("scheduler")) {
  2811. genRequest.scheduler = parseScheduler(requestJson["scheduler"]);
  2812. }
  2813. // Optional VAE model
  2814. if (requestJson.contains("vae_model") && requestJson["vae_model"].is_string()) {
  2815. std::string vaeModelId = requestJson["vae_model"];
  2816. if (!vaeModelId.empty()) {
  2817. auto vaeInfo = m_modelManager->getModelInfo(vaeModelId);
  2818. if (!vaeInfo.name.empty() && vaeInfo.type == ModelType::VAE) {
  2819. genRequest.vaePath = vaeInfo.path;
  2820. } else {
  2821. sendErrorResponse(res, "VAE model not found or invalid: " + vaeModelId, 400, "INVALID_VAE_MODEL", requestId);
  2822. return;
  2823. }
  2824. }
  2825. }
  2826. // Optional TAESD model
  2827. if (requestJson.contains("taesd_model") && requestJson["taesd_model"].is_string()) {
  2828. std::string taesdModelId = requestJson["taesd_model"];
  2829. if (!taesdModelId.empty()) {
  2830. auto taesdInfo = m_modelManager->getModelInfo(taesdModelId);
  2831. if (!taesdInfo.name.empty() && taesdInfo.type == ModelType::TAESD) {
  2832. genRequest.taesdPath = taesdInfo.path;
  2833. } else {
  2834. sendErrorResponse(res, "TAESD model not found or invalid: " + taesdModelId, 400, "INVALID_TAESD_MODEL", requestId);
  2835. return;
  2836. }
  2837. }
  2838. }
  2839. // Store control image path (would be handled in actual implementation)
  2840. genRequest.outputPath = requestJson.value("control_image", "");
  2841. // Enqueue request
  2842. auto future = m_generationQueue->enqueueRequest(genRequest);
  2843. nlohmann::json params = {
  2844. {"prompt", genRequest.prompt},
  2845. {"negative_prompt", genRequest.negativePrompt},
  2846. {"control_image", requestJson["control_image"]},
  2847. {"control_net_model", genRequest.controlNetPath},
  2848. {"model", genRequest.modelName},
  2849. {"width", genRequest.width},
  2850. {"height", genRequest.height},
  2851. {"batch_count", genRequest.batchCount},
  2852. {"steps", genRequest.steps},
  2853. {"cfg_scale", genRequest.cfgScale},
  2854. {"seed", genRequest.seed},
  2855. {"control_strength", genRequest.controlStrength},
  2856. {"sampling_method", samplingMethodToString(genRequest.samplingMethod)},
  2857. {"scheduler", schedulerToString(genRequest.scheduler)}};
  2858. // Add VAE/TAESD if specified
  2859. if (!genRequest.vaePath.empty()) {
  2860. params["vae_model"] = requestJson.value("vae_model", "");
  2861. }
  2862. if (!genRequest.taesdPath.empty()) {
  2863. params["taesd_model"] = requestJson.value("taesd_model", "");
  2864. }
  2865. nlohmann::json response = {
  2866. {"request_id", requestId},
  2867. {"status", "queued"},
  2868. {"message", "ControlNet generation request queued successfully"},
  2869. {"queue_position", m_generationQueue->getQueueSize()},
  2870. {"estimated_time_seconds", estimateGenerationTime(genRequest) / 1000},
  2871. {"estimated_memory_mb", estimateMemoryUsage(genRequest) / (1024 * 1024)},
  2872. {"type", "controlnet"},
  2873. {"parameters", params}};
  2874. sendJsonResponse(res, response, 202);
  2875. } catch (const nlohmann::json::parse_error& e) {
  2876. sendErrorResponse(res, std::string("Invalid JSON: ") + e.what(), 400, "JSON_PARSE_ERROR", requestId);
  2877. } catch (const std::exception& e) {
  2878. sendErrorResponse(res, std::string("ControlNet request failed: ") + e.what(), 500, "INTERNAL_ERROR", requestId);
  2879. }
  2880. }
  2881. void Server::handleUpscale(const httplib::Request& req, httplib::Response& res) {
  2882. std::string requestId = generateRequestId();
  2883. try {
  2884. if (!m_generationQueue) {
  2885. sendErrorResponse(res, "Generation queue not available", 500, "QUEUE_UNAVAILABLE", requestId);
  2886. return;
  2887. }
  2888. nlohmann::json requestJson = nlohmann::json::parse(req.body);
  2889. // Validate required fields for upscaler
  2890. if (!requestJson.contains("image") || !requestJson["image"].is_string()) {
  2891. sendErrorResponse(res, "Missing or invalid 'image' field", 400, "INVALID_PARAMETERS", requestId);
  2892. return;
  2893. }
  2894. if (!requestJson.contains("esrgan_model") || !requestJson["esrgan_model"].is_string()) {
  2895. sendErrorResponse(res, "Missing or invalid 'esrgan_model' field (model hash or name)", 400, "INVALID_PARAMETERS", requestId);
  2896. return;
  2897. }
  2898. // Check if model manager is available
  2899. if (!m_modelManager) {
  2900. sendErrorResponse(res, "Model manager not available", 500, "MODEL_MANAGER_UNAVAILABLE", requestId);
  2901. return;
  2902. }
  2903. // Get the ESRGAN/upscaler model
  2904. std::string esrganModelId = requestJson["esrgan_model"];
  2905. auto modelInfo = m_modelManager->getModelInfo(esrganModelId);
  2906. if (modelInfo.name.empty()) {
  2907. sendErrorResponse(res, "ESRGAN model not found: " + esrganModelId, 404, "MODEL_NOT_FOUND", requestId);
  2908. return;
  2909. }
  2910. if (modelInfo.type != ModelType::ESRGAN && modelInfo.type != ModelType::UPSCALER) {
  2911. sendErrorResponse(res, "Model is not an ESRGAN/upscaler model", 400, "INVALID_MODEL_TYPE", requestId);
  2912. return;
  2913. }
  2914. // Load the input image
  2915. std::string imageInput = requestJson["image"];
  2916. auto [imageData, imgWidth, imgHeight, imgChannels, success, loadError] = loadImageFromInput(imageInput);
  2917. if (!success) {
  2918. sendErrorResponse(res, "Failed to load image: " + loadError, 400, "IMAGE_LOAD_ERROR", requestId);
  2919. return;
  2920. }
  2921. // Create upscaler request
  2922. GenerationRequest genRequest;
  2923. genRequest.id = requestId;
  2924. genRequest.requestType = GenerationRequest::RequestType::UPSCALER;
  2925. genRequest.esrganPath = modelInfo.path;
  2926. genRequest.upscaleFactor = requestJson.value("upscale_factor", 4);
  2927. genRequest.nThreads = requestJson.value("threads", -1);
  2928. genRequest.offloadParamsToCpu = requestJson.value("offload_to_cpu", false);
  2929. genRequest.diffusionConvDirect = requestJson.value("direct", false);
  2930. // Set input image data
  2931. genRequest.initImageData = imageData;
  2932. genRequest.initImageWidth = imgWidth;
  2933. genRequest.initImageHeight = imgHeight;
  2934. genRequest.initImageChannels = imgChannels;
  2935. // Enqueue request
  2936. auto future = m_generationQueue->enqueueRequest(genRequest);
  2937. nlohmann::json response = {
  2938. {"request_id", requestId},
  2939. {"status", "queued"},
  2940. {"message", "Upscale request queued successfully"},
  2941. {"queue_position", m_generationQueue->getQueueSize()},
  2942. {"type", "upscale"},
  2943. {"parameters", {{"esrgan_model", esrganModelId}, {"upscale_factor", genRequest.upscaleFactor}, {"input_width", imgWidth}, {"input_height", imgHeight}, {"output_width", imgWidth * genRequest.upscaleFactor}, {"output_height", imgHeight * genRequest.upscaleFactor}}}};
  2944. sendJsonResponse(res, response, 202);
  2945. } catch (const nlohmann::json::parse_error& e) {
  2946. sendErrorResponse(res, std::string("Invalid JSON: ") + e.what(), 400, "JSON_PARSE_ERROR", requestId);
  2947. } catch (const std::exception& e) {
  2948. sendErrorResponse(res, std::string("Upscale request failed: ") + e.what(), 500, "INTERNAL_ERROR", requestId);
  2949. }
  2950. }
  2951. void Server::handleInpainting(const httplib::Request& req, httplib::Response& res) {
  2952. std::string requestId = generateRequestId();
  2953. try {
  2954. if (!m_generationQueue) {
  2955. sendErrorResponse(res, "Generation queue not available", 500, "QUEUE_UNAVAILABLE", requestId);
  2956. return;
  2957. }
  2958. nlohmann::json requestJson = nlohmann::json::parse(req.body);
  2959. // Validate required fields for inpainting
  2960. if (!requestJson.contains("prompt") || !requestJson["prompt"].is_string()) {
  2961. sendErrorResponse(res, "Missing or invalid 'prompt' field", 400, "INVALID_PARAMETERS", requestId);
  2962. return;
  2963. }
  2964. if (!requestJson.contains("source_image") || !requestJson["source_image"].is_string()) {
  2965. sendErrorResponse(res, "Missing or invalid 'source_image' field", 400, "INVALID_PARAMETERS", requestId);
  2966. return;
  2967. }
  2968. if (!requestJson.contains("mask_image") || !requestJson["mask_image"].is_string()) {
  2969. sendErrorResponse(res, "Missing or invalid 'mask_image' field", 400, "INVALID_PARAMETERS", requestId);
  2970. return;
  2971. }
  2972. // Validate all parameters
  2973. auto [isValid, errorMessage] = validateGenerationParameters(requestJson);
  2974. if (!isValid) {
  2975. sendErrorResponse(res, errorMessage, 400, "INVALID_PARAMETERS", requestId);
  2976. return;
  2977. }
  2978. // Check if any model is loaded
  2979. if (!m_modelManager) {
  2980. sendErrorResponse(res, "Model manager not available", 500, "MODEL_MANAGER_UNAVAILABLE", requestId);
  2981. return;
  2982. }
  2983. // Get currently loaded checkpoint model
  2984. std::string loadedModelName;
  2985. {
  2986. std::lock_guard<std::mutex> lock(m_loadedModelsMutex);
  2987. loadedModelName = m_loadedModels.checkpoint;
  2988. }
  2989. if (loadedModelName.empty()) {
  2990. sendErrorResponse(res, "No checkpoint model loaded. Please load a checkpoint model first using POST /api/models/{hash}/load", 400, "NO_CHECKPOINT_LOADED", requestId);
  2991. return;
  2992. }
  2993. // Load the source image
  2994. std::string sourceImageInput = requestJson["source_image"];
  2995. auto [sourceImageData, sourceImgWidth, sourceImgHeight, sourceImgChannels, sourceSuccess, sourceLoadError] = loadImageFromInput(sourceImageInput);
  2996. if (!sourceSuccess) {
  2997. sendErrorResponse(res, "Failed to load source image: " + sourceLoadError, 400, "IMAGE_LOAD_ERROR", requestId);
  2998. return;
  2999. }
  3000. // Load the mask image
  3001. std::string maskImageInput = requestJson["mask_image"];
  3002. auto [maskImageData, maskImgWidth, maskImgHeight, maskImgChannels, maskSuccess, maskLoadError] = loadImageFromInput(maskImageInput);
  3003. if (!maskSuccess) {
  3004. sendErrorResponse(res, "Failed to load mask image: " + maskLoadError, 400, "MASK_LOAD_ERROR", requestId);
  3005. return;
  3006. }
  3007. // Validate that source and mask images have compatible dimensions
  3008. if (sourceImgWidth != maskImgWidth || sourceImgHeight != maskImgHeight) {
  3009. sendErrorResponse(res, "Source and mask images must have the same dimensions", 400, "DIMENSION_MISMATCH", requestId);
  3010. return;
  3011. }
  3012. // Create generation request specifically for inpainting
  3013. GenerationRequest genRequest;
  3014. genRequest.id = requestId;
  3015. genRequest.requestType = GenerationRequest::RequestType::INPAINTING;
  3016. genRequest.modelName = loadedModelName; // Use the currently loaded model
  3017. genRequest.prompt = requestJson["prompt"];
  3018. genRequest.negativePrompt = requestJson.value("negative_prompt", "");
  3019. genRequest.width = requestJson.value("width", sourceImgWidth); // Default to input image dimensions
  3020. genRequest.height = requestJson.value("height", sourceImgHeight);
  3021. genRequest.batchCount = requestJson.value("batch_count", 1);
  3022. genRequest.steps = requestJson.value("steps", 20);
  3023. genRequest.cfgScale = requestJson.value("cfg_scale", 7.5f);
  3024. genRequest.seed = requestJson.value("seed", "random");
  3025. genRequest.strength = requestJson.value("strength", 0.75f);
  3026. // Set source image data
  3027. genRequest.initImageData = sourceImageData;
  3028. genRequest.initImageWidth = sourceImgWidth;
  3029. genRequest.initImageHeight = sourceImgHeight;
  3030. genRequest.initImageChannels = sourceImgChannels;
  3031. // Set mask image data
  3032. genRequest.maskImageData = maskImageData;
  3033. genRequest.maskImageWidth = maskImgWidth;
  3034. genRequest.maskImageHeight = maskImgHeight;
  3035. genRequest.maskImageChannels = maskImgChannels;
  3036. // Parse optional parameters
  3037. if (requestJson.contains("sampling_method")) {
  3038. genRequest.samplingMethod = parseSamplingMethod(requestJson["sampling_method"]);
  3039. }
  3040. if (requestJson.contains("scheduler")) {
  3041. genRequest.scheduler = parseScheduler(requestJson["scheduler"]);
  3042. }
  3043. // Optional VAE model
  3044. if (requestJson.contains("vae_model") && requestJson["vae_model"].is_string()) {
  3045. std::string vaeModelId = requestJson["vae_model"];
  3046. if (!vaeModelId.empty()) {
  3047. auto vaeInfo = m_modelManager->getModelInfo(vaeModelId);
  3048. if (!vaeInfo.name.empty() && vaeInfo.type == ModelType::VAE) {
  3049. genRequest.vaePath = vaeInfo.path;
  3050. } else {
  3051. sendErrorResponse(res, "VAE model not found or invalid: " + vaeModelId, 400, "INVALID_VAE_MODEL", requestId);
  3052. return;
  3053. }
  3054. }
  3055. }
  3056. // Optional TAESD model
  3057. if (requestJson.contains("taesd_model") && requestJson["taesd_model"].is_string()) {
  3058. std::string taesdModelId = requestJson["taesd_model"];
  3059. if (!taesdModelId.empty()) {
  3060. auto taesdInfo = m_modelManager->getModelInfo(taesdModelId);
  3061. if (!taesdInfo.name.empty() && taesdInfo.type == ModelType::TAESD) {
  3062. genRequest.taesdPath = taesdInfo.path;
  3063. } else {
  3064. sendErrorResponse(res, "TAESD model not found or invalid: " + taesdModelId, 400, "INVALID_TAESD_MODEL", requestId);
  3065. return;
  3066. }
  3067. }
  3068. }
  3069. // Enqueue request
  3070. auto future = m_generationQueue->enqueueRequest(genRequest);
  3071. nlohmann::json params = {
  3072. {"prompt", genRequest.prompt},
  3073. {"negative_prompt", genRequest.negativePrompt},
  3074. {"source_image", requestJson["source_image"]},
  3075. {"mask_image", requestJson["mask_image"]},
  3076. {"model", genRequest.modelName},
  3077. {"width", genRequest.width},
  3078. {"height", genRequest.height},
  3079. {"batch_count", genRequest.batchCount},
  3080. {"steps", genRequest.steps},
  3081. {"cfg_scale", genRequest.cfgScale},
  3082. {"seed", genRequest.seed},
  3083. {"strength", genRequest.strength},
  3084. {"sampling_method", samplingMethodToString(genRequest.samplingMethod)},
  3085. {"scheduler", schedulerToString(genRequest.scheduler)}};
  3086. // Add VAE/TAESD if specified
  3087. if (!genRequest.vaePath.empty()) {
  3088. params["vae_model"] = requestJson.value("vae_model", "");
  3089. }
  3090. if (!genRequest.taesdPath.empty()) {
  3091. params["taesd_model"] = requestJson.value("taesd_model", "");
  3092. }
  3093. nlohmann::json response = {
  3094. {"request_id", requestId},
  3095. {"status", "queued"},
  3096. {"message", "Inpainting generation request queued successfully"},
  3097. {"queue_position", m_generationQueue->getQueueSize()},
  3098. {"estimated_time_seconds", estimateGenerationTime(genRequest) / 1000},
  3099. {"estimated_memory_mb", estimateMemoryUsage(genRequest) / (1024 * 1024)},
  3100. {"type", "inpainting"},
  3101. {"parameters", params}};
  3102. sendJsonResponse(res, response, 202);
  3103. } catch (const nlohmann::json::parse_error& e) {
  3104. sendErrorResponse(res, std::string("Invalid JSON: ") + e.what(), 400, "JSON_PARSE_ERROR", requestId);
  3105. } catch (const std::exception& e) {
  3106. sendErrorResponse(res, std::string("Inpainting request failed: ") + e.what(), 500, "INTERNAL_ERROR", requestId);
  3107. }
  3108. }
  3109. // Utility endpoints
  3110. void Server::handleSamplers(const httplib::Request& /*req*/, httplib::Response& res) {
  3111. try {
  3112. nlohmann::json samplers = {
  3113. {"samplers", {{{"name", "euler"}, {"description", "Euler sampler - fast and simple"}, {"recommended_steps", 20}}, {{"name", "euler_a"}, {"description", "Euler ancestral sampler - adds randomness"}, {"recommended_steps", 20}}, {{"name", "heun"}, {"description", "Heun sampler - more accurate but slower"}, {"recommended_steps", 20}}, {{"name", "dpm2"}, {"description", "DPM2 sampler - second-order DPM"}, {"recommended_steps", 20}}, {{"name", "dpm++2s_a"}, {"description", "DPM++ 2s ancestral sampler"}, {"recommended_steps", 20}}, {{"name", "dpm++2m"}, {"description", "DPM++ 2m sampler - multistep"}, {"recommended_steps", 20}}, {{"name", "dpm++2mv2"}, {"description", "DPM++ 2m v2 sampler - improved multistep"}, {"recommended_steps", 20}}, {{"name", "ipndm"}, {"description", "IPNDM sampler - improved noise prediction"}, {"recommended_steps", 20}}, {{"name", "ipndm_v"}, {"description", "IPNDM v sampler - variant of IPNDM"}, {"recommended_steps", 20}}, {{"name", "lcm"}, {"description", "LCM sampler - Latent Consistency Model, very fast"}, {"recommended_steps", 4}}, {{"name", "ddim_trailing"}, {"description", "DDIM trailing sampler - deterministic"}, {"recommended_steps", 20}}, {{"name", "tcd"}, {"description", "TCD sampler - Trajectory Consistency Distillation"}, {"recommended_steps", 8}}, {{"name", "default"}, {"description", "Use model's default sampler"}, {"recommended_steps", 20}}}}};
  3114. sendJsonResponse(res, samplers);
  3115. } catch (const std::exception& e) {
  3116. sendErrorResponse(res, std::string("Failed to get samplers: ") + e.what(), 500);
  3117. }
  3118. }
  3119. void Server::handleSchedulers(const httplib::Request& /*req*/, httplib::Response& res) {
  3120. try {
  3121. nlohmann::json schedulers = {
  3122. {"schedulers", {{{"name", "discrete"}, {"description", "Discrete scheduler - standard noise schedule"}}, {{"name", "karras"}, {"description", "Karras scheduler - improved noise schedule"}}, {{"name", "exponential"}, {"description", "Exponential scheduler - exponential noise decay"}}, {{"name", "ays"}, {"description", "AYS scheduler - Adaptive Your Scheduler"}}, {{"name", "gits"}, {"description", "GITS scheduler - Generalized Iterative Time Steps"}}, {{"name", "smoothstep"}, {"description", "Smoothstep scheduler - smooth transition function"}}, {{"name", "sgm_uniform"}, {"description", "SGM uniform scheduler - uniform noise schedule"}}, {{"name", "simple"}, {"description", "Simple scheduler - basic linear schedule"}}, {{"name", "default"}, {"description", "Use model's default scheduler"}}}}};
  3123. sendJsonResponse(res, schedulers);
  3124. } catch (const std::exception& e) {
  3125. sendErrorResponse(res, std::string("Failed to get schedulers: ") + e.what(), 500);
  3126. }
  3127. }
  3128. void Server::handleParameters(const httplib::Request& /*req*/, httplib::Response& res) {
  3129. try {
  3130. nlohmann::json parameters = {
  3131. {"parameters", {{{"name", "prompt"}, {"type", "string"}, {"required", true}, {"description", "Text prompt for image generation"}, {"min_length", 1}, {"max_length", 10000}, {"example", "a beautiful landscape with mountains"}}, {{"name", "negative_prompt"}, {"type", "string"}, {"required", false}, {"description", "Negative prompt to guide generation away from"}, {"min_length", 0}, {"max_length", 10000}, {"example", "blurry, low quality, distorted"}}, {{"name", "width"}, {"type", "integer"}, {"required", false}, {"description", "Image width in pixels"}, {"min", 64}, {"max", 2048}, {"multiple_of", 64}, {"default", 512}}, {{"name", "height"}, {"type", "integer"}, {"required", false}, {"description", "Image height in pixels"}, {"min", 64}, {"max", 2048}, {"multiple_of", 64}, {"default", 512}}, {{"name", "steps"}, {"type", "integer"}, {"required", false}, {"description", "Number of diffusion steps"}, {"min", 1}, {"max", 150}, {"default", 20}}, {{"name", "cfg_scale"}, {"type", "number"}, {"required", false}, {"description", "Classifier-Free Guidance scale"}, {"min", 1.0}, {"max", 30.0}, {"default", 7.5}}, {{"name", "seed"}, {"type", "string|integer"}, {"required", false}, {"description", "Seed for generation (use 'random' for random seed)"}, {"example", "42"}}, {{"name", "sampling_method"}, {"type", "string"}, {"required", false}, {"description", "Sampling method to use"}, {"enum", {"euler", "euler_a", "heun", "dpm2", "dpm++2s_a", "dpm++2m", "dpm++2mv2", "ipndm", "ipndm_v", "lcm", "ddim_trailing", "tcd", "default"}}, {"default", "default"}}, {{"name", "scheduler"}, {"type", "string"}, {"required", false}, {"description", "Scheduler to use"}, {"enum", {"discrete", "karras", "exponential", "ays", "gits", "smoothstep", "sgm_uniform", "simple", "default"}}, {"default", "default"}}, {{"name", "batch_count"}, {"type", "integer"}, {"required", false}, {"description", "Number of images to generate"}, {"min", 1}, {"max", 100}, {"default", 1}}, {{"name", "strength"}, {"type", "number"}, {"required", false}, {"description", "Strength for img2img (0.0-1.0)"}, {"min", 0.0}, {"max", 1.0}, {"default", 0.75}}, {{"name", "control_strength"}, {"type", "number"}, {"required", false}, {"description", "ControlNet strength (0.0-1.0)"}, {"min", 0.0}, {"max", 1.0}, {"default", 0.9}}}},
  3132. {"openapi", {{"version", "3.0.0"}, {"info", {{"title", "Stable Diffusion REST API"}, {"version", "1.0.0"}, {"description", "Comprehensive REST API for stable-diffusion.cpp functionality"}}}, {"components", {{"schemas", {{"GenerationRequest", {{"type", "object"}, {"required", {"prompt"}}, {"properties", {{"prompt", {{"type", "string"}, {"description", "Text prompt for generation"}}}, {"negative_prompt", {{"type", "string"}, {"description", "Negative prompt"}}}, {"width", {{"type", "integer"}, {"minimum", 64}, {"maximum", 2048}, {"default", 512}}}, {"height", {{"type", "integer"}, {"minimum", 64}, {"maximum", 2048}, {"default", 512}}}, {"steps", {{"type", "integer"}, {"minimum", 1}, {"maximum", 150}, {"default", 20}}}, {"cfg_scale", {{"type", "number"}, {"minimum", 1.0}, {"maximum", 30.0}, {"default", 7.5}}}}}}}}}}}}}};
  3133. sendJsonResponse(res, parameters);
  3134. } catch (const std::exception& e) {
  3135. sendErrorResponse(res, std::string("Failed to get parameters: ") + e.what(), 500);
  3136. }
  3137. }
  3138. void Server::handleValidate(const httplib::Request& req, httplib::Response& res) {
  3139. std::string requestId = generateRequestId();
  3140. try {
  3141. nlohmann::json requestJson = nlohmann::json::parse(req.body);
  3142. // Validate parameters
  3143. auto [isValid, errorMessage] = validateGenerationParameters(requestJson);
  3144. nlohmann::json response = {
  3145. {"request_id", requestId},
  3146. {"valid", isValid},
  3147. {"message", isValid ? "Parameters are valid" : errorMessage},
  3148. {"errors", isValid ? nlohmann::json::array() : nlohmann::json::array({errorMessage})}};
  3149. sendJsonResponse(res, response, isValid ? 200 : 400);
  3150. } catch (const nlohmann::json::parse_error& e) {
  3151. sendErrorResponse(res, std::string("Invalid JSON: ") + e.what(), 400, "JSON_PARSE_ERROR", requestId);
  3152. } catch (const std::exception& e) {
  3153. sendErrorResponse(res, std::string("Validation failed: ") + e.what(), 500, "INTERNAL_ERROR", requestId);
  3154. }
  3155. }
  3156. void Server::handleEstimate(const httplib::Request& req, httplib::Response& res) {
  3157. std::string requestId = generateRequestId();
  3158. try {
  3159. nlohmann::json requestJson = nlohmann::json::parse(req.body);
  3160. // Validate parameters first
  3161. auto [isValid, errorMessage] = validateGenerationParameters(requestJson);
  3162. if (!isValid) {
  3163. sendErrorResponse(res, errorMessage, 400, "INVALID_PARAMETERS", requestId);
  3164. return;
  3165. }
  3166. // Create a temporary request to estimate
  3167. GenerationRequest genRequest;
  3168. genRequest.prompt = requestJson["prompt"];
  3169. genRequest.width = requestJson.value("width", 512);
  3170. genRequest.height = requestJson.value("height", 512);
  3171. genRequest.batchCount = requestJson.value("batch_count", 1);
  3172. genRequest.steps = requestJson.value("steps", 20);
  3173. genRequest.diffusionFlashAttn = requestJson.value("diffusion_flash_attn", false);
  3174. genRequest.controlNetPath = requestJson.value("control_net_path", "");
  3175. if (requestJson.contains("sampling_method")) {
  3176. genRequest.samplingMethod = parseSamplingMethod(requestJson["sampling_method"]);
  3177. }
  3178. // Calculate estimates
  3179. uint64_t estimatedTime = estimateGenerationTime(genRequest);
  3180. size_t estimatedMemory = estimateMemoryUsage(genRequest);
  3181. nlohmann::json response = {
  3182. {"request_id", requestId},
  3183. {"estimated_time_seconds", estimatedTime / 1000},
  3184. {"estimated_memory_mb", estimatedMemory / (1024 * 1024)},
  3185. {"parameters", {{"resolution", std::to_string(genRequest.width) + "x" + std::to_string(genRequest.height)}, {"steps", genRequest.steps}, {"batch_count", genRequest.batchCount}, {"sampling_method", samplingMethodToString(genRequest.samplingMethod)}}}};
  3186. sendJsonResponse(res, response);
  3187. } catch (const nlohmann::json::parse_error& e) {
  3188. sendErrorResponse(res, std::string("Invalid JSON: ") + e.what(), 400, "JSON_PARSE_ERROR", requestId);
  3189. } catch (const std::exception& e) {
  3190. sendErrorResponse(res, std::string("Estimation failed: ") + e.what(), 500, "INTERNAL_ERROR", requestId);
  3191. }
  3192. }
  3193. void Server::handleConfig(const httplib::Request& /*req*/, httplib::Response& res) {
  3194. std::string requestId = generateRequestId();
  3195. try {
  3196. // Get current configuration
  3197. nlohmann::json config = {
  3198. {"request_id", requestId},
  3199. {"config", {{"server", {{"host", m_host}, {"port", m_port}, {"max_concurrent_generations", 1}}}, {"generation", {{"default_width", 512}, {"default_height", 512}, {"default_steps", 20}, {"default_cfg_scale", 7.5}, {"max_batch_count", 100}, {"max_steps", 150}, {"max_resolution", 2048}}}, {"rate_limiting", {{"requests_per_minute", 60}, {"enabled", true}}}}}};
  3200. sendJsonResponse(res, config);
  3201. } catch (const std::exception& e) {
  3202. sendErrorResponse(res, std::string("Config operation failed: ") + e.what(), 500, "INTERNAL_ERROR", requestId);
  3203. }
  3204. }
  3205. void Server::handleSystem(const httplib::Request& /*req*/, httplib::Response& res) {
  3206. try {
  3207. nlohmann::json system = {
  3208. {"system", {{"version", "1.0.0"}, {"build", "stable-diffusion.cpp-rest"}, {"uptime", std::chrono::duration_cast<std::chrono::seconds>(std::chrono::steady_clock::now().time_since_epoch()).count()}, {"capabilities", {{"text2img", true}, {"img2img", true}, {"controlnet", true}, {"batch_generation", true}, {"parameter_validation", true}, {"estimation", true}}}, {"supported_formats", {{"input", {"png", "jpg", "jpeg", "webp"}}, {"output", {"png", "jpg", "jpeg", "webp"}}}}, {"limits", {{"max_resolution", 2048}, {"max_steps", 150}, {"max_batch_count", 100}, {"max_prompt_length", 10000}}}}},
  3209. {"hardware", {{"cpu_threads", std::thread::hardware_concurrency()}}}};
  3210. sendJsonResponse(res, system);
  3211. } catch (const std::exception& e) {
  3212. sendErrorResponse(res, std::string("System info failed: ") + e.what(), 500);
  3213. }
  3214. }
  3215. void Server::handleSystemRestart(const httplib::Request& /*req*/, httplib::Response& res) {
  3216. try {
  3217. nlohmann::json response = {
  3218. {"message", "Server restart initiated. The server will shut down gracefully and exit. Please use a process manager to automatically restart it."},
  3219. {"status", "restarting"}};
  3220. sendJsonResponse(res, response);
  3221. // Schedule server stop after response is sent
  3222. // Using a separate thread to allow the response to be sent first
  3223. std::thread([this]() {
  3224. std::this_thread::sleep_for(std::chrono::seconds(1));
  3225. this->stop();
  3226. // Exit with code 42 to signal restart intent to process manager
  3227. std::exit(42);
  3228. }).detach();
  3229. } catch (const std::exception& e) {
  3230. sendErrorResponse(res, std::string("Restart failed: ") + e.what(), 500);
  3231. }
  3232. }
  3233. // Helper methods for model management
  3234. nlohmann::json Server::getModelCapabilities(ModelType type) {
  3235. nlohmann::json capabilities = nlohmann::json::object();
  3236. switch (type) {
  3237. case ModelType::CHECKPOINT:
  3238. capabilities = {
  3239. {"text2img", true},
  3240. {"img2img", true},
  3241. {"inpainting", true},
  3242. {"outpainting", true},
  3243. {"controlnet", true},
  3244. {"lora", true},
  3245. {"vae", true},
  3246. {"sampling_methods", {"euler", "euler_a", "heun", "dpm2", "dpm++2s_a", "dpm++2m", "dpm++2mv2", "ipndm", "ipndm_v", "lcm", "ddim_trailing", "tcd"}},
  3247. {"schedulers", {"discrete", "karras", "exponential", "ays", "gits", "smoothstep", "sgm_uniform", "simple"}},
  3248. {"recommended_resolution", "512x512"},
  3249. {"max_resolution", "2048x2048"},
  3250. {"supports_batch", true}};
  3251. break;
  3252. case ModelType::LORA:
  3253. capabilities = {
  3254. {"text2img", true},
  3255. {"img2img", true},
  3256. {"inpainting", true},
  3257. {"controlnet", false},
  3258. {"lora", true},
  3259. {"vae", false},
  3260. {"requires_checkpoint", true},
  3261. {"strength_range", {0.0, 2.0}},
  3262. {"recommended_strength", 1.0}};
  3263. break;
  3264. case ModelType::CONTROLNET:
  3265. capabilities = {
  3266. {"text2img", false},
  3267. {"img2img", true},
  3268. {"inpainting", true},
  3269. {"controlnet", true},
  3270. {"requires_checkpoint", true},
  3271. {"control_modes", {"canny", "depth", "pose", "scribble", "hed", "mlsd", "normal", "seg"}},
  3272. {"strength_range", {0.0, 1.0}},
  3273. {"recommended_strength", 0.9}};
  3274. break;
  3275. case ModelType::VAE:
  3276. capabilities = {
  3277. {"text2img", false},
  3278. {"img2img", false},
  3279. {"inpainting", false},
  3280. {"vae", true},
  3281. {"requires_checkpoint", true},
  3282. {"encoding", true},
  3283. {"decoding", true},
  3284. {"precision", {"fp16", "fp32"}}};
  3285. break;
  3286. case ModelType::EMBEDDING:
  3287. capabilities = {
  3288. {"text2img", true},
  3289. {"img2img", true},
  3290. {"inpainting", true},
  3291. {"embedding", true},
  3292. {"requires_checkpoint", true},
  3293. {"token_count", 1},
  3294. {"compatible_with", {"checkpoint", "lora"}}};
  3295. break;
  3296. case ModelType::TAESD:
  3297. capabilities = {
  3298. {"text2img", false},
  3299. {"img2img", false},
  3300. {"inpainting", false},
  3301. {"vae", true},
  3302. {"requires_checkpoint", true},
  3303. {"fast_decoding", true},
  3304. {"real_time", true},
  3305. {"precision", {"fp16", "fp32"}}};
  3306. break;
  3307. case ModelType::ESRGAN:
  3308. capabilities = {
  3309. {"text2img", false},
  3310. {"img2img", false},
  3311. {"inpainting", false},
  3312. {"upscaling", true},
  3313. {"scale_factors", {2, 4}},
  3314. {"models", {"ESRGAN", "RealESRGAN", "SwinIR"}},
  3315. {"supports_alpha", false}};
  3316. break;
  3317. default:
  3318. capabilities = {
  3319. {"text2img", false},
  3320. {"img2img", false},
  3321. {"inpainting", false},
  3322. {"capabilities", {}}};
  3323. break;
  3324. }
  3325. return capabilities;
  3326. }
  3327. nlohmann::json Server::getModelTypeStatistics() {
  3328. if (!m_modelManager)
  3329. return nlohmann::json::object();
  3330. nlohmann::json stats = nlohmann::json::object();
  3331. auto allModels = m_modelManager->getAllModels();
  3332. // Initialize counters for each type
  3333. std::map<ModelType, int> typeCounts;
  3334. std::map<ModelType, int> loadedCounts;
  3335. std::map<ModelType, size_t> sizeByType;
  3336. for (const auto& pair : allModels) {
  3337. ModelType type = pair.second.type;
  3338. typeCounts[type]++;
  3339. if (pair.second.isLoaded) {
  3340. loadedCounts[type]++;
  3341. }
  3342. sizeByType[type] += pair.second.fileSize;
  3343. }
  3344. // Build statistics JSON
  3345. for (const auto& count : typeCounts) {
  3346. std::string typeName = ModelManager::modelTypeToString(count.first);
  3347. stats[typeName] = {
  3348. {"total_count", count.second},
  3349. {"loaded_count", loadedCounts[count.first]},
  3350. {"total_size_bytes", sizeByType[count.first]},
  3351. {"total_size_mb", sizeByType[count.first] / (1024.0 * 1024.0)},
  3352. {"average_size_mb", count.second > 0 ? (sizeByType[count.first] / (1024.0 * 1024.0)) / count.second : 0.0}};
  3353. }
  3354. return stats;
  3355. }
  3356. // Additional helper methods for model management
  3357. nlohmann::json Server::getModelCompatibility(const ModelManager::ModelInfo& modelInfo) {
  3358. nlohmann::json compatibility = {
  3359. {"is_compatible", true},
  3360. {"compatibility_score", 100},
  3361. {"issues", nlohmann::json::array()},
  3362. {"warnings", nlohmann::json::array()},
  3363. {"requirements", {{"min_memory_mb", 1024}, {"recommended_memory_mb", 2048}, {"supported_formats", {"safetensors", "ckpt", "gguf"}}, {"required_dependencies", {}}}}};
  3364. // Check for specific compatibility issues based on model type
  3365. if (modelInfo.type == ModelType::LORA) {
  3366. compatibility["requirements"]["required_dependencies"] = {"checkpoint"};
  3367. } else if (modelInfo.type == ModelType::CONTROLNET) {
  3368. compatibility["requirements"]["required_dependencies"] = {"checkpoint"};
  3369. } else if (modelInfo.type == ModelType::VAE) {
  3370. compatibility["requirements"]["required_dependencies"] = {"checkpoint"};
  3371. }
  3372. return compatibility;
  3373. }
  3374. nlohmann::json Server::getModelRequirements(ModelType type) {
  3375. nlohmann::json requirements = {
  3376. {"min_memory_mb", 1024},
  3377. {"recommended_memory_mb", 2048},
  3378. {"min_disk_space_mb", 1024},
  3379. {"supported_formats", {"safetensors", "ckpt", "gguf"}},
  3380. {"required_dependencies", nlohmann::json::array()},
  3381. {"optional_dependencies", nlohmann::json::array()},
  3382. {"system_requirements", {{"cpu_cores", 4}, {"cpu_architecture", "x86_64"}, {"os", "Linux/Windows/macOS"}, {"gpu_memory_mb", 2048}, {"gpu_compute_capability", "3.5+"}}}};
  3383. switch (type) {
  3384. case ModelType::CHECKPOINT:
  3385. requirements["min_memory_mb"] = 2048;
  3386. requirements["recommended_memory_mb"] = 4096;
  3387. requirements["min_disk_space_mb"] = 2048;
  3388. requirements["supported_formats"] = {"safetensors", "ckpt", "gguf"};
  3389. break;
  3390. case ModelType::LORA:
  3391. requirements["min_memory_mb"] = 512;
  3392. requirements["recommended_memory_mb"] = 1024;
  3393. requirements["min_disk_space_mb"] = 100;
  3394. requirements["supported_formats"] = {"safetensors", "ckpt"};
  3395. requirements["required_dependencies"] = {"checkpoint"};
  3396. break;
  3397. case ModelType::CONTROLNET:
  3398. requirements["min_memory_mb"] = 1024;
  3399. requirements["recommended_memory_mb"] = 2048;
  3400. requirements["min_disk_space_mb"] = 500;
  3401. requirements["supported_formats"] = {"safetensors", "pth"};
  3402. requirements["required_dependencies"] = {"checkpoint"};
  3403. break;
  3404. case ModelType::VAE:
  3405. requirements["min_memory_mb"] = 512;
  3406. requirements["recommended_memory_mb"] = 1024;
  3407. requirements["min_disk_space_mb"] = 200;
  3408. requirements["supported_formats"] = {"safetensors", "pt", "ckpt", "gguf"};
  3409. requirements["required_dependencies"] = {"checkpoint"};
  3410. break;
  3411. case ModelType::EMBEDDING:
  3412. requirements["min_memory_mb"] = 64;
  3413. requirements["recommended_memory_mb"] = 256;
  3414. requirements["min_disk_space_mb"] = 10;
  3415. requirements["supported_formats"] = {"safetensors", "pt"};
  3416. requirements["required_dependencies"] = {"checkpoint"};
  3417. break;
  3418. case ModelType::TAESD:
  3419. requirements["min_memory_mb"] = 256;
  3420. requirements["recommended_memory_mb"] = 512;
  3421. requirements["min_disk_space_mb"] = 100;
  3422. requirements["supported_formats"] = {"safetensors", "pth", "gguf"};
  3423. requirements["required_dependencies"] = {"checkpoint"};
  3424. break;
  3425. case ModelType::ESRGAN:
  3426. requirements["min_memory_mb"] = 1024;
  3427. requirements["recommended_memory_mb"] = 2048;
  3428. requirements["min_disk_space_mb"] = 500;
  3429. requirements["supported_formats"] = {"pth", "pt"};
  3430. requirements["optional_dependencies"] = {"checkpoint"};
  3431. break;
  3432. default:
  3433. break;
  3434. }
  3435. return requirements;
  3436. }
  3437. nlohmann::json Server::getRecommendedUsage(ModelType type) {
  3438. nlohmann::json usage = {
  3439. {"text2img", false},
  3440. {"img2img", false},
  3441. {"inpainting", false},
  3442. {"controlnet", false},
  3443. {"lora", false},
  3444. {"vae", false},
  3445. {"recommended_resolution", "512x512"},
  3446. {"recommended_steps", 20},
  3447. {"recommended_cfg_scale", 7.5},
  3448. {"recommended_batch_size", 1}};
  3449. switch (type) {
  3450. case ModelType::CHECKPOINT:
  3451. usage = {
  3452. {"text2img", true},
  3453. {"img2img", true},
  3454. {"inpainting", true},
  3455. {"controlnet", true},
  3456. {"lora", true},
  3457. {"vae", true},
  3458. {"recommended_resolution", "512x512"},
  3459. {"recommended_steps", 20},
  3460. {"recommended_cfg_scale", 7.5},
  3461. {"recommended_batch_size", 1}};
  3462. break;
  3463. case ModelType::LORA:
  3464. usage = {
  3465. {"text2img", true},
  3466. {"img2img", true},
  3467. {"inpainting", true},
  3468. {"controlnet", false},
  3469. {"lora", true},
  3470. {"vae", false},
  3471. {"recommended_strength", 1.0},
  3472. {"recommended_usage", "Style transfer, character customization"}};
  3473. break;
  3474. case ModelType::CONTROLNET:
  3475. usage = {
  3476. {"text2img", false},
  3477. {"img2img", true},
  3478. {"inpainting", true},
  3479. {"controlnet", true},
  3480. {"lora", false},
  3481. {"vae", false},
  3482. {"recommended_strength", 0.9},
  3483. {"recommended_usage", "Precise control over output"}};
  3484. break;
  3485. case ModelType::VAE:
  3486. usage = {
  3487. {"text2img", false},
  3488. {"img2img", false},
  3489. {"inpainting", false},
  3490. {"controlnet", false},
  3491. {"lora", false},
  3492. {"vae", true},
  3493. {"recommended_usage", "Improved encoding/decoding quality"}};
  3494. break;
  3495. case ModelType::EMBEDDING:
  3496. usage = {
  3497. {"text2img", true},
  3498. {"img2img", true},
  3499. {"inpainting", true},
  3500. {"controlnet", false},
  3501. {"lora", false},
  3502. {"vae", false},
  3503. {"embedding", true},
  3504. {"recommended_usage", "Concept control, style words"}};
  3505. break;
  3506. case ModelType::TAESD:
  3507. usage = {
  3508. {"text2img", false},
  3509. {"img2img", false},
  3510. {"inpainting", false},
  3511. {"controlnet", false},
  3512. {"lora", false},
  3513. {"vae", true},
  3514. {"recommended_usage", "Real-time decoding"}};
  3515. break;
  3516. case ModelType::ESRGAN:
  3517. usage = {
  3518. {"text2img", false},
  3519. {"img2img", false},
  3520. {"inpainting", false},
  3521. {"controlnet", false},
  3522. {"lora", false},
  3523. {"vae", false},
  3524. {"upscaling", true},
  3525. {"recommended_usage", "Image upscaling and quality enhancement"}};
  3526. break;
  3527. default:
  3528. break;
  3529. }
  3530. return usage;
  3531. }
  3532. std::string Server::getModelTypeFromDirectoryName(const std::string& dirName) {
  3533. if (dirName == "stable-diffusion" || dirName == "checkpoints") {
  3534. return "checkpoint";
  3535. } else if (dirName == "lora") {
  3536. return "lora";
  3537. } else if (dirName == "controlnet") {
  3538. return "controlnet";
  3539. } else if (dirName == "vae") {
  3540. return "vae";
  3541. } else if (dirName == "taesd") {
  3542. return "taesd";
  3543. } else if (dirName == "esrgan" || dirName == "upscaler") {
  3544. return "esrgan";
  3545. } else if (dirName == "embeddings" || dirName == "textual-inversion") {
  3546. return "embedding";
  3547. } else {
  3548. return "unknown";
  3549. }
  3550. }
  3551. std::string Server::getDirectoryDescription(const std::string& dirName) {
  3552. if (dirName == "stable-diffusion" || dirName == "checkpoints") {
  3553. return "Main stable diffusion model files";
  3554. } else if (dirName == "lora") {
  3555. return "LoRA adapter models for style transfer";
  3556. } else if (dirName == "controlnet") {
  3557. return "ControlNet models for precise control";
  3558. } else if (dirName == "vae") {
  3559. return "VAE models for improved encoding/decoding";
  3560. } else if (dirName == "taesd") {
  3561. return "TAESD models for real-time decoding";
  3562. } else if (dirName == "esrgan" || dirName == "upscaler") {
  3563. return "ESRGAN models for image upscaling";
  3564. } else if (dirName == "embeddings" || dirName == "textual-inversion") {
  3565. return "Text embeddings for concept control";
  3566. } else {
  3567. return "Unknown model directory";
  3568. }
  3569. }
  3570. nlohmann::json Server::getDirectoryContents(const std::string& dirPath) {
  3571. nlohmann::json contents = nlohmann::json::array();
  3572. try {
  3573. if (std::filesystem::exists(dirPath) && std::filesystem::is_directory(dirPath)) {
  3574. for (const auto& entry : std::filesystem::directory_iterator(dirPath)) {
  3575. if (entry.is_regular_file()) {
  3576. nlohmann::json file = {
  3577. {"name", entry.path().filename().string()},
  3578. {"path", entry.path().string()},
  3579. {"size", std::filesystem::file_size(entry.path())},
  3580. {"size_mb", std::filesystem::file_size(entry.path()) / (1024.0 * 1024.0)},
  3581. {"last_modified", std::chrono::duration_cast<std::chrono::seconds>(
  3582. std::filesystem::last_write_time(entry.path()).time_since_epoch())
  3583. .count()}};
  3584. contents.push_back(file);
  3585. }
  3586. }
  3587. }
  3588. } catch (const std::exception& e) {
  3589. // Return empty array if directory access fails
  3590. }
  3591. return contents;
  3592. }
  3593. nlohmann::json Server::getLargestModel(const std::map<std::string, ModelManager::ModelInfo>& allModels) {
  3594. nlohmann::json largest = nlohmann::json::object();
  3595. size_t maxSize = 0;
  3596. std::string largestName;
  3597. for (const auto& pair : allModels) {
  3598. if (pair.second.fileSize > maxSize) {
  3599. maxSize = pair.second.fileSize;
  3600. largestName = pair.second.name;
  3601. }
  3602. }
  3603. if (!largestName.empty()) {
  3604. largest = {
  3605. {"name", largestName},
  3606. {"size", maxSize},
  3607. {"size_mb", maxSize / (1024.0 * 1024.0)},
  3608. {"type", ModelManager::modelTypeToString(allModels.at(largestName).type)}};
  3609. }
  3610. return largest;
  3611. }
  3612. nlohmann::json Server::getSmallestModel(const std::map<std::string, ModelManager::ModelInfo>& allModels) {
  3613. nlohmann::json smallest = nlohmann::json::object();
  3614. size_t minSize = SIZE_MAX;
  3615. std::string smallestName;
  3616. for (const auto& pair : allModels) {
  3617. if (pair.second.fileSize < minSize) {
  3618. minSize = pair.second.fileSize;
  3619. smallestName = pair.second.name;
  3620. }
  3621. }
  3622. if (!smallestName.empty()) {
  3623. smallest = {
  3624. {"name", smallestName},
  3625. {"size", minSize},
  3626. {"size_mb", minSize / (1024.0 * 1024.0)},
  3627. {"type", ModelManager::modelTypeToString(allModels.at(smallestName).type)}};
  3628. }
  3629. return smallest;
  3630. }
  3631. nlohmann::json Server::validateModelFile(const std::string& modelPath, const std::string& modelType) {
  3632. nlohmann::json validation = {
  3633. {"is_valid", false},
  3634. {"errors", nlohmann::json::array()},
  3635. {"warnings", nlohmann::json::array()},
  3636. {"file_info", nlohmann::json::object()},
  3637. {"compatibility", nlohmann::json::object()},
  3638. {"recommendations", nlohmann::json::array()}};
  3639. try {
  3640. if (!std::filesystem::exists(modelPath)) {
  3641. validation["errors"].push_back("File does not exist");
  3642. return validation;
  3643. }
  3644. if (!std::filesystem::is_regular_file(modelPath)) {
  3645. validation["errors"].push_back("Path is not a regular file");
  3646. return validation;
  3647. }
  3648. // Check file extension
  3649. std::string extension = std::filesystem::path(modelPath).extension().string();
  3650. if (extension.empty()) {
  3651. validation["errors"].push_back("Missing file extension");
  3652. return validation;
  3653. }
  3654. // Remove dot and convert to lowercase
  3655. if (extension[0] == '.') {
  3656. extension = extension.substr(1);
  3657. }
  3658. std::transform(extension.begin(), extension.end(), extension.begin(), ::tolower);
  3659. // Validate extension based on model type
  3660. ModelType type = ModelManager::stringToModelType(modelType);
  3661. bool validExtension = false;
  3662. switch (type) {
  3663. case ModelType::CHECKPOINT:
  3664. validExtension = (extension == "safetensors" || extension == "ckpt" || extension == "gguf");
  3665. break;
  3666. case ModelType::LORA:
  3667. validExtension = (extension == "safetensors" || extension == "ckpt");
  3668. break;
  3669. case ModelType::CONTROLNET:
  3670. validExtension = (extension == "safetensors" || extension == "pth");
  3671. break;
  3672. case ModelType::VAE:
  3673. validExtension = (extension == "safetensors" || extension == "pt" || extension == "ckpt" || extension == "gguf");
  3674. break;
  3675. case ModelType::EMBEDDING:
  3676. validExtension = (extension == "safetensors" || extension == "pt");
  3677. break;
  3678. case ModelType::TAESD:
  3679. validExtension = (extension == "safetensors" || extension == "pth" || extension == "gguf");
  3680. break;
  3681. case ModelType::ESRGAN:
  3682. validExtension = (extension == "pth" || extension == "pt");
  3683. break;
  3684. default:
  3685. break;
  3686. }
  3687. if (!validExtension) {
  3688. validation["errors"].push_back("Invalid file extension for model type: " + extension);
  3689. }
  3690. // Check file size
  3691. size_t fileSize = std::filesystem::file_size(modelPath);
  3692. if (fileSize == 0) {
  3693. validation["errors"].push_back("File is empty");
  3694. } else if (fileSize > 8ULL * 1024 * 1024 * 1024) { // 8GB
  3695. validation["warnings"].push_back("Very large file may cause performance issues");
  3696. }
  3697. // Build file info
  3698. validation["file_info"] = {
  3699. {"path", modelPath},
  3700. {"size", fileSize},
  3701. {"size_mb", fileSize / (1024.0 * 1024.0)},
  3702. {"extension", extension},
  3703. {"last_modified", std::chrono::duration_cast<std::chrono::seconds>(
  3704. std::filesystem::last_write_time(modelPath).time_since_epoch())
  3705. .count()}};
  3706. // Check compatibility
  3707. validation["compatibility"] = {
  3708. {"extension_valid", validExtension},
  3709. {"size_appropriate", fileSize <= 4ULL * 1024 * 1024 * 1024}, // 4GB
  3710. {"recommended_format", "safetensors"}};
  3711. // Add recommendations
  3712. if (!validExtension) {
  3713. validation["recommendations"].push_back("Convert to SafeTensors format for better security and performance");
  3714. }
  3715. if (fileSize > 2ULL * 1024 * 1024 * 1024) { // 2GB
  3716. validation["recommendations"].push_back("Consider using a smaller model for better performance");
  3717. }
  3718. // If no errors found, mark as valid
  3719. if (validation["errors"].empty()) {
  3720. validation["is_valid"] = true;
  3721. }
  3722. } catch (const std::exception& e) {
  3723. validation["errors"].push_back("Validation failed: " + std::string(e.what()));
  3724. }
  3725. return validation;
  3726. }
  3727. nlohmann::json Server::checkModelCompatibility(const ModelManager::ModelInfo& modelInfo, const std::string& systemInfo) {
  3728. nlohmann::json compatibility = {
  3729. {"is_compatible", true},
  3730. {"compatibility_score", 100},
  3731. {"issues", nlohmann::json::array()},
  3732. {"warnings", nlohmann::json::array()},
  3733. {"requirements", nlohmann::json::object()},
  3734. {"recommendations", nlohmann::json::array()},
  3735. {"system_info", nlohmann::json::object()}};
  3736. // Check system compatibility
  3737. if (systemInfo == "auto") {
  3738. compatibility["system_info"] = {
  3739. {"cpu_cores", std::thread::hardware_concurrency()}};
  3740. }
  3741. // Check model-specific compatibility issues
  3742. if (modelInfo.type == ModelType::CHECKPOINT) {
  3743. if (modelInfo.fileSize > 4ULL * 1024 * 1024 * 1024) { // 4GB
  3744. compatibility["warnings"].push_back("Large checkpoint model may require significant memory");
  3745. compatibility["compatibility_score"] = 80;
  3746. }
  3747. if (modelInfo.fileSize < 500 * 1024 * 1024) { // 500MB
  3748. compatibility["warnings"].push_back("Small checkpoint model may have limited capabilities");
  3749. compatibility["compatibility_score"] = 85;
  3750. }
  3751. } else if (modelInfo.type == ModelType::LORA) {
  3752. if (modelInfo.fileSize > 500 * 1024 * 1024) { // 500MB
  3753. compatibility["warnings"].push_back("Large LoRA may impact performance");
  3754. compatibility["compatibility_score"] = 75;
  3755. }
  3756. }
  3757. return compatibility;
  3758. }
  3759. nlohmann::json Server::calculateSpecificRequirements(const std::string& modelType, const std::string& resolution, const std::string& batchSize) {
  3760. (void)modelType; // Suppress unused parameter warning
  3761. nlohmann::json specific = {
  3762. {"memory_requirements", nlohmann::json::object()},
  3763. {"performance_impact", nlohmann::json::object()},
  3764. {"quality_expectations", nlohmann::json::object()}};
  3765. // Parse resolution
  3766. int width = 512, height = 512;
  3767. try {
  3768. size_t xPos = resolution.find('x');
  3769. if (xPos != std::string::npos) {
  3770. width = std::stoi(resolution.substr(0, xPos));
  3771. height = std::stoi(resolution.substr(xPos + 1));
  3772. }
  3773. } catch (...) {
  3774. // Use defaults if parsing fails
  3775. }
  3776. // Parse batch size
  3777. int batch = 1;
  3778. try {
  3779. batch = std::stoi(batchSize);
  3780. } catch (...) {
  3781. // Use default if parsing fails
  3782. }
  3783. // Calculate memory requirements based on resolution and batch
  3784. size_t pixels = width * height;
  3785. size_t baseMemory = 1024 * 1024 * 1024; // 1GB base
  3786. size_t resolutionMemory = (pixels * 4) / (512 * 512); // Scale based on 512x512
  3787. size_t batchMemory = (batch - 1) * baseMemory * 0.5; // Additional memory for batch
  3788. specific["memory_requirements"] = {
  3789. {"base_memory_mb", baseMemory / (1024 * 1024)},
  3790. {"resolution_memory_mb", resolutionMemory / (1024 * 1024)},
  3791. {"batch_memory_mb", batchMemory / (1024 * 1024)},
  3792. {"total_memory_mb", (baseMemory + resolutionMemory + batchMemory) / (1024 * 1024)}};
  3793. // Calculate performance impact
  3794. double performanceFactor = 1.0;
  3795. if (pixels > 512 * 512) {
  3796. performanceFactor = 1.5;
  3797. }
  3798. if (batch > 1) {
  3799. performanceFactor *= 1.2;
  3800. }
  3801. specific["performance_impact"] = {
  3802. {"resolution_factor", pixels > 512 * 512 ? 1.5 : 1.0},
  3803. {"batch_factor", batch > 1 ? 1.2 : 1.0},
  3804. {"overall_factor", performanceFactor}};
  3805. return specific;
  3806. }
  3807. // Enhanced model management endpoint implementations
  3808. void Server::handleModelInfo(const httplib::Request& req, httplib::Response& res) {
  3809. std::string requestId = generateRequestId();
  3810. try {
  3811. if (!m_modelManager) {
  3812. sendErrorResponse(res, "Model manager not available", 500, "MODEL_MANAGER_UNAVAILABLE", requestId);
  3813. return;
  3814. }
  3815. // Extract model ID from URL path
  3816. std::string modelId = req.matches[1].str();
  3817. // DEBUG: Log what model ID we received
  3818. if (modelId == "types") {
  3819. nlohmann::json debugResponse = {
  3820. {"debug", "handleModelInfo called with modelId: " + modelId},
  3821. {"request_id", requestId}};
  3822. sendJsonResponse(res, debugResponse);
  3823. return;
  3824. }
  3825. if (modelId.empty()) {
  3826. sendErrorResponse(res, "Missing model ID", 400, "MISSING_MODEL_ID", requestId);
  3827. return;
  3828. }
  3829. // Get model information
  3830. auto modelInfo = m_modelManager->getModelInfo(modelId);
  3831. if (modelInfo.name.empty()) {
  3832. sendErrorResponse(res, "Model not found", 404, "MODEL_NOT_FOUND", requestId);
  3833. return;
  3834. }
  3835. // Build comprehensive model information
  3836. nlohmann::json response = {
  3837. {"model", {{"name", modelInfo.name}, {"path", modelInfo.path}, {"type", ModelManager::modelTypeToString(modelInfo.type)}, {"is_loaded", modelInfo.isLoaded}, {"file_size", modelInfo.fileSize}, {"file_size_mb", modelInfo.fileSize / (1024.0 * 1024.0)}, {"description", modelInfo.description}, {"metadata", modelInfo.metadata}, {"capabilities", getModelCapabilities(modelInfo.type)}, {"compatibility", getModelCompatibility(modelInfo)}, {"requirements", getModelRequirements(modelInfo.type)}, {"recommended_usage", getRecommendedUsage(modelInfo.type)}, {"last_modified", std::chrono::duration_cast<std::chrono::seconds>(modelInfo.modifiedAt.time_since_epoch()).count()}}},
  3838. {"request_id", requestId}};
  3839. sendJsonResponse(res, response);
  3840. } catch (const std::exception& e) {
  3841. sendErrorResponse(res, std::string("Failed to get model info: ") + e.what(), 500, "MODEL_INFO_ERROR", requestId);
  3842. }
  3843. }
  3844. void Server::handleLoadModelById(const httplib::Request& req, httplib::Response& res) {
  3845. std::string requestId = generateRequestId();
  3846. try {
  3847. if (!m_modelManager) {
  3848. sendErrorResponse(res, "Model manager not available", 500, "MODEL_MANAGER_UNAVAILABLE", requestId);
  3849. return;
  3850. }
  3851. // Extract model hash from URL path (must be a hash)
  3852. std::string modelIdentifier = req.matches[1].str();
  3853. if (modelIdentifier.empty()) {
  3854. sendErrorResponse(res, "Missing model identifier", 400, "MISSING_MODEL_ID", requestId);
  3855. return;
  3856. }
  3857. // Validate that the identifier is a hash (10+ hexadecimal characters)
  3858. if (modelIdentifier.length() < 10 ||
  3859. !std::all_of(modelIdentifier.begin(), modelIdentifier.end(),
  3860. [](char c) { return std::isxdigit(c); })) {
  3861. sendErrorResponse(res, "Invalid model identifier: must be a hash (10+ hexadecimal characters)", 400, "INVALID_MODEL_IDENTIFIER", requestId);
  3862. return;
  3863. }
  3864. // Find model by hash
  3865. std::string foundName = m_modelManager->findModelByHash(modelIdentifier);
  3866. if (foundName.empty()) {
  3867. sendErrorResponse(res, "Model not found for hash: " + modelIdentifier, 404, "MODEL_NOT_FOUND", requestId);
  3868. return;
  3869. }
  3870. std::string modelId = foundName;
  3871. LOG_DEBUG("Resolved hash " + modelIdentifier + " to model: " + modelId);
  3872. // Parse optional parameters from request body
  3873. nlohmann::json requestJson;
  3874. if (!req.body.empty()) {
  3875. try {
  3876. requestJson = nlohmann::json::parse(req.body);
  3877. } catch (const nlohmann::json::parse_error& e) {
  3878. sendErrorResponse(res, std::string("Invalid JSON: ") + e.what(), 400, "JSON_PARSE_ERROR", requestId);
  3879. return;
  3880. }
  3881. }
  3882. // Get model type information to determine unload behavior
  3883. auto modelInfo = m_modelManager->getModelInfo(modelId);
  3884. ModelType modelType = modelInfo.type;
  3885. // Unload previous model of the same type if one is loaded
  3886. std::string& currentModelField = getModelField(modelType);
  3887. {
  3888. std::lock_guard<std::mutex> lock(m_loadedModelsMutex);
  3889. if (!currentModelField.empty() && currentModelField != modelId) {
  3890. LOG_DEBUG("Unloading previous " + ModelManager::modelTypeToString(modelType) +
  3891. " model: " + currentModelField);
  3892. m_modelManager->unloadModel(currentModelField);
  3893. }
  3894. }
  3895. // Load model
  3896. bool success = m_modelManager->loadModel(modelId);
  3897. if (success) {
  3898. // Update currently loaded model of this type
  3899. {
  3900. std::lock_guard<std::mutex> lock(m_loadedModelsMutex);
  3901. currentModelField = modelId;
  3902. }
  3903. // Refresh model info after loading
  3904. modelInfo = m_modelManager->getModelInfo(modelId);
  3905. nlohmann::json response = {
  3906. {"status", "success"},
  3907. {"model", {{"name", modelInfo.name}, {"path", modelInfo.path}, {"type", ModelManager::modelTypeToString(modelInfo.type)}, {"is_loaded", modelInfo.isLoaded}}},
  3908. {"request_id", requestId}};
  3909. sendJsonResponse(res, response);
  3910. } else {
  3911. sendErrorResponse(res, "Failed to load model", 400, "MODEL_LOAD_FAILED", requestId);
  3912. }
  3913. } catch (const std::exception& e) {
  3914. sendErrorResponse(res, std::string("Model load failed: ") + e.what(), 500, "MODEL_LOAD_ERROR", requestId);
  3915. }
  3916. }
  3917. void Server::handleUnloadModelById(const httplib::Request& req, httplib::Response& res) {
  3918. std::string requestId = generateRequestId();
  3919. try {
  3920. if (!m_modelManager) {
  3921. sendErrorResponse(res, "Model manager not available", 500, "MODEL_MANAGER_UNAVAILABLE", requestId);
  3922. return;
  3923. }
  3924. // Extract model ID from URL path
  3925. std::string modelId = req.matches[1].str();
  3926. if (modelId.empty()) {
  3927. sendErrorResponse(res, "Missing model ID", 400, "MISSING_MODEL_ID", requestId);
  3928. return;
  3929. }
  3930. // Get model type information before unloading
  3931. auto modelInfo = m_modelManager->getModelInfo(modelId);
  3932. ModelType modelType = modelInfo.type;
  3933. // Unload model
  3934. bool success = m_modelManager->unloadModel(modelId);
  3935. if (success) {
  3936. // Clear currently loaded model of this type if it matches
  3937. {
  3938. std::lock_guard<std::mutex> lock(m_loadedModelsMutex);
  3939. std::string& currentModelField = getModelField(modelType);
  3940. if (currentModelField == modelId) {
  3941. currentModelField = "";
  3942. }
  3943. }
  3944. nlohmann::json response = {
  3945. {"status", "success"},
  3946. {"model", {{"name", modelId}, {"is_loaded", false}}},
  3947. {"request_id", requestId}};
  3948. sendJsonResponse(res, response);
  3949. } else {
  3950. sendErrorResponse(res, "Failed to unload model or model not found", 404, "MODEL_UNLOAD_FAILED", requestId);
  3951. }
  3952. } catch (const std::exception& e) {
  3953. sendErrorResponse(res, std::string("Model unload failed: ") + e.what(), 500, "MODEL_UNLOAD_ERROR", requestId);
  3954. }
  3955. }
  3956. void Server::handleModelTypes(const httplib::Request& /*req*/, httplib::Response& res) {
  3957. std::string requestId = generateRequestId();
  3958. try {
  3959. nlohmann::json types = {
  3960. {"model_types", {{{"type", "checkpoint"}, {"description", "Main stable diffusion model files for text-to-image, image-to-image, and inpainting"}, {"extensions", {"safetensors", "ckpt", "gguf"}}, {"capabilities", {"text2img", "img2img", "inpainting", "controlnet", "lora", "vae"}}, {"recommended_for", "General purpose image generation"}}, {{"type", "lora"}, {"description", "LoRA adapter models for style transfer and character customization"}, {"extensions", {"safetensors", "ckpt"}}, {"capabilities", {"style_transfer", "character_customization"}}, {"requires", {"checkpoint"}}, {"recommended_for", "Style modification and character-specific generation"}}, {{"type", "controlnet"}, {"description", "ControlNet models for precise control over output composition"}, {"extensions", {"safetensors", "pth"}}, {"capabilities", {"precise_control", "composition_control"}}, {"requires", {"checkpoint"}}, {"recommended_for", "Precise control over image generation"}}, {{"type", "vae"}, {"description", "VAE models for improved encoding and decoding quality"}, {"extensions", {"safetensors", "pt", "ckpt", "gguf"}}, {"capabilities", {"encoding", "decoding", "quality_improvement"}}, {"requires", {"checkpoint"}}, {"recommended_for", "Improved image quality and encoding"}}, {{"type", "embedding"}, {"description", "Text embeddings for concept control and style words"}, {"extensions", {"safetensors", "pt"}}, {"capabilities", {"concept_control", "style_words"}}, {"requires", {"checkpoint"}}, {"recommended_for", "Concept control and specific styles"}}, {{"type", "taesd"}, {"description", "TAESD models for real-time decoding"}, {"extensions", {"safetensors", "pth", "gguf"}}, {"capabilities", {"real_time_decoding", "fast_preview"}}, {"requires", {"checkpoint"}}, {"recommended_for", "Real-time applications and fast previews"}}, {{"type", "esrgan"}, {"description", "ESRGAN models for image upscaling and enhancement"}, {"extensions", {"pth", "pt"}}, {"capabilities", {"upscaling", "enhancement", "quality_improvement"}}, {"recommended_for", "Image upscaling and quality enhancement"}}}},
  3961. {"request_id", requestId}};
  3962. sendJsonResponse(res, types);
  3963. } catch (const std::exception& e) {
  3964. sendErrorResponse(res, std::string("Failed to get model types: ") + e.what(), 500, "MODEL_TYPES_ERROR", requestId);
  3965. }
  3966. }
  3967. void Server::handleModelDirectories(const httplib::Request& /*req*/, httplib::Response& res) {
  3968. std::string requestId = generateRequestId();
  3969. try {
  3970. if (!m_modelManager) {
  3971. sendErrorResponse(res, "Model manager not available", 500, "MODEL_MANAGER_UNAVAILABLE", requestId);
  3972. return;
  3973. }
  3974. std::string modelsDir = m_modelManager->getModelsDirectory();
  3975. nlohmann::json directories = nlohmann::json::array();
  3976. // Define expected model directories
  3977. std::vector<std::string> modelDirs = {
  3978. "stable-diffusion", "checkpoints", "lora", "controlnet",
  3979. "vae", "taesd", "esrgan", "embeddings"};
  3980. for (const auto& dirName : modelDirs) {
  3981. std::string dirPath = modelsDir + "/" + dirName;
  3982. std::string type = getModelTypeFromDirectoryName(dirName);
  3983. std::string description = getDirectoryDescription(dirName);
  3984. nlohmann::json dirInfo = {
  3985. {"name", dirName},
  3986. {"path", dirPath},
  3987. {"type", type},
  3988. {"description", description},
  3989. {"exists", std::filesystem::exists(dirPath) && std::filesystem::is_directory(dirPath)},
  3990. {"contents", getDirectoryContents(dirPath)}};
  3991. directories.push_back(dirInfo);
  3992. }
  3993. nlohmann::json response = {
  3994. {"models_directory", modelsDir},
  3995. {"directories", directories},
  3996. {"request_id", requestId}};
  3997. sendJsonResponse(res, response);
  3998. } catch (const std::exception& e) {
  3999. sendErrorResponse(res, std::string("Failed to get model directories: ") + e.what(), 500, "MODEL_DIRECTORIES_ERROR", requestId);
  4000. }
  4001. }
  4002. void Server::handleRefreshModels(const httplib::Request& /*req*/, httplib::Response& res) {
  4003. std::string requestId = generateRequestId();
  4004. try {
  4005. if (!m_modelManager) {
  4006. sendErrorResponse(res, "Model manager not available", 500, "MODEL_MANAGER_UNAVAILABLE", requestId);
  4007. return;
  4008. }
  4009. // Force refresh of model cache
  4010. bool success = m_modelManager->scanModelsDirectory();
  4011. if (success) {
  4012. nlohmann::json response = {
  4013. {"status", "success"},
  4014. {"message", "Model cache refreshed successfully"},
  4015. {"models_found", m_modelManager->getAvailableModelsCount()},
  4016. {"models_loaded", m_modelManager->getLoadedModelsCount()},
  4017. {"models_directory", m_modelManager->getModelsDirectory()},
  4018. {"request_id", requestId}};
  4019. sendJsonResponse(res, response);
  4020. } else {
  4021. sendErrorResponse(res, "Failed to refresh model cache", 500, "MODEL_REFRESH_FAILED", requestId);
  4022. }
  4023. } catch (const std::exception& e) {
  4024. sendErrorResponse(res, std::string("Model refresh failed: ") + e.what(), 500, "MODEL_REFRESH_ERROR", requestId);
  4025. }
  4026. }
  4027. void Server::handleHashModels(const httplib::Request& req, httplib::Response& res) {
  4028. std::string requestId = generateRequestId();
  4029. try {
  4030. if (!m_generationQueue || !m_modelManager) {
  4031. sendErrorResponse(res, "Services not available", 500, "SERVICE_UNAVAILABLE", requestId);
  4032. return;
  4033. }
  4034. // Parse request body
  4035. nlohmann::json requestJson;
  4036. if (!req.body.empty()) {
  4037. requestJson = nlohmann::json::parse(req.body);
  4038. }
  4039. HashRequest hashReq;
  4040. hashReq.id = requestId;
  4041. hashReq.forceRehash = requestJson.value("force_rehash", false);
  4042. if (requestJson.contains("models") && requestJson["models"].is_array()) {
  4043. for (const auto& model : requestJson["models"]) {
  4044. hashReq.modelNames.push_back(model.get<std::string>());
  4045. }
  4046. }
  4047. // Enqueue hash request
  4048. auto future = m_generationQueue->enqueueHashRequest(hashReq);
  4049. nlohmann::json response = {
  4050. {"request_id", requestId},
  4051. {"status", "queued"},
  4052. {"message", "Hash job queued successfully"},
  4053. {"models_to_hash", hashReq.modelNames.empty() ? "all_unhashed" : std::to_string(hashReq.modelNames.size())}};
  4054. sendJsonResponse(res, response, 202);
  4055. } catch (const nlohmann::json::parse_error& e) {
  4056. sendErrorResponse(res, std::string("Invalid JSON: ") + e.what(), 400, "JSON_PARSE_ERROR", requestId);
  4057. } catch (const std::exception& e) {
  4058. sendErrorResponse(res, std::string("Hash request failed: ") + e.what(), 500, "INTERNAL_ERROR", requestId);
  4059. }
  4060. }
  4061. void Server::handleConvertModel(const httplib::Request& req, httplib::Response& res) {
  4062. std::string requestId = generateRequestId();
  4063. try {
  4064. if (!m_generationQueue || !m_modelManager) {
  4065. sendErrorResponse(res, "Services not available", 500, "SERVICE_UNAVAILABLE", requestId);
  4066. return;
  4067. }
  4068. // Parse request body
  4069. nlohmann::json requestJson;
  4070. try {
  4071. requestJson = nlohmann::json::parse(req.body);
  4072. } catch (const nlohmann::json::parse_error& e) {
  4073. sendErrorResponse(res, std::string("Invalid JSON: ") + e.what(), 400, "JSON_PARSE_ERROR", requestId);
  4074. return;
  4075. }
  4076. // Validate required fields
  4077. if (!requestJson.contains("model_name")) {
  4078. sendErrorResponse(res, "Missing required field: model_name", 400, "MISSING_FIELD", requestId);
  4079. return;
  4080. }
  4081. if (!requestJson.contains("quantization_type")) {
  4082. sendErrorResponse(res, "Missing required field: quantization_type", 400, "MISSING_FIELD", requestId);
  4083. return;
  4084. }
  4085. std::string modelName = requestJson["model_name"].get<std::string>();
  4086. std::string quantizationType = requestJson["quantization_type"].get<std::string>();
  4087. // Validate quantization type
  4088. const std::vector<std::string> validTypes = {"f32", "f16", "q4_0", "q4_1", "q5_0", "q5_1", "q8_0", "q2_K", "q3_K", "q4_K"};
  4089. if (std::find(validTypes.begin(), validTypes.end(), quantizationType) == validTypes.end()) {
  4090. sendErrorResponse(res, "Invalid quantization_type. Valid types: f32, f16, q4_0, q4_1, q5_0, q5_1, q8_0, q2_K, q3_K, q4_K",
  4091. 400, "INVALID_QUANTIZATION_TYPE", requestId);
  4092. return;
  4093. }
  4094. // Get model info to find the full path
  4095. auto modelInfo = m_modelManager->getModelInfo(modelName);
  4096. if (modelInfo.name.empty()) {
  4097. sendErrorResponse(res, "Model not found: " + modelName, 404, "MODEL_NOT_FOUND", requestId);
  4098. return;
  4099. }
  4100. // Check if model is already GGUF
  4101. if (modelInfo.fullPath.find(".gguf") != std::string::npos) {
  4102. sendErrorResponse(res, "Model is already in GGUF format. Cannot convert GGUF to GGUF.",
  4103. 400, "ALREADY_GGUF", requestId);
  4104. return;
  4105. }
  4106. // Build output path
  4107. std::string outputPath = requestJson.value("output_path", "");
  4108. if (outputPath.empty()) {
  4109. // Generate default output path: model_name_quantization.gguf
  4110. namespace fs = std::filesystem;
  4111. fs::path inputPath(modelInfo.fullPath);
  4112. std::string baseName = inputPath.stem().string();
  4113. std::string outputDir = inputPath.parent_path().string();
  4114. outputPath = outputDir + "/" + baseName + "_" + quantizationType + ".gguf";
  4115. }
  4116. // Create conversion request
  4117. ConversionRequest convReq;
  4118. convReq.id = requestId;
  4119. convReq.modelName = modelName;
  4120. convReq.modelPath = modelInfo.fullPath;
  4121. convReq.outputPath = outputPath;
  4122. convReq.quantizationType = quantizationType;
  4123. // Enqueue conversion request
  4124. auto future = m_generationQueue->enqueueConversionRequest(convReq);
  4125. nlohmann::json response = {
  4126. {"request_id", requestId},
  4127. {"status", "queued"},
  4128. {"message", "Model conversion queued successfully"},
  4129. {"model_name", modelName},
  4130. {"input_path", modelInfo.fullPath},
  4131. {"output_path", outputPath},
  4132. {"quantization_type", quantizationType}};
  4133. sendJsonResponse(res, response, 202);
  4134. } catch (const std::exception& e) {
  4135. sendErrorResponse(res, std::string("Conversion request failed: ") + e.what(), 500, "INTERNAL_ERROR", requestId);
  4136. }
  4137. }
  4138. void Server::handleModelStats(const httplib::Request& /*req*/, httplib::Response& res) {
  4139. std::string requestId = generateRequestId();
  4140. try {
  4141. if (!m_modelManager) {
  4142. sendErrorResponse(res, "Model manager not available", 500, "MODEL_MANAGER_UNAVAILABLE", requestId);
  4143. return;
  4144. }
  4145. auto allModels = m_modelManager->getAllModels();
  4146. nlohmann::json response = {
  4147. {"statistics", {{"total_models", allModels.size()}, {"loaded_models", m_modelManager->getLoadedModelsCount()}, {"available_models", m_modelManager->getAvailableModelsCount()}, {"model_types", getModelTypeStatistics()}, {"largest_model", getLargestModel(allModels)}, {"smallest_model", getSmallestModel(allModels)}}},
  4148. {"request_id", requestId}};
  4149. sendJsonResponse(res, response);
  4150. } catch (const std::exception& e) {
  4151. sendErrorResponse(res, std::string("Failed to get model stats: ") + e.what(), 500, "MODEL_STATS_ERROR", requestId);
  4152. }
  4153. }
  4154. void Server::handleBatchModels(const httplib::Request& req, httplib::Response& res) {
  4155. std::string requestId = generateRequestId();
  4156. try {
  4157. if (!m_modelManager) {
  4158. sendErrorResponse(res, "Model manager not available", 500, "MODEL_MANAGER_UNAVAILABLE", requestId);
  4159. return;
  4160. }
  4161. // Parse JSON request body
  4162. nlohmann::json requestJson = nlohmann::json::parse(req.body);
  4163. if (!requestJson.contains("operation") || !requestJson["operation"].is_string()) {
  4164. sendErrorResponse(res, "Missing or invalid 'operation' field", 400, "INVALID_OPERATION", requestId);
  4165. return;
  4166. }
  4167. if (!requestJson.contains("models") || !requestJson["models"].is_array()) {
  4168. sendErrorResponse(res, "Missing or invalid 'models' field", 400, "INVALID_MODELS", requestId);
  4169. return;
  4170. }
  4171. std::string operation = requestJson["operation"];
  4172. nlohmann::json models = requestJson["models"];
  4173. nlohmann::json results = nlohmann::json::array();
  4174. for (const auto& model : models) {
  4175. if (!model.is_string()) {
  4176. results.push_back({{"model", model},
  4177. {"success", false},
  4178. {"error", "Invalid model name"}});
  4179. continue;
  4180. }
  4181. std::string modelName = model;
  4182. bool success = false;
  4183. std::string error = "";
  4184. if (operation == "load") {
  4185. success = m_modelManager->loadModel(modelName);
  4186. if (!success)
  4187. error = "Failed to load model";
  4188. } else if (operation == "unload") {
  4189. success = m_modelManager->unloadModel(modelName);
  4190. if (!success)
  4191. error = "Failed to unload model";
  4192. } else {
  4193. error = "Unsupported operation";
  4194. }
  4195. results.push_back({{"model", modelName},
  4196. {"success", success},
  4197. {"error", error.empty() ? nlohmann::json(nullptr) : nlohmann::json(error)}});
  4198. }
  4199. nlohmann::json response = {
  4200. {"operation", operation},
  4201. {"results", results},
  4202. {"successful_count", std::count_if(results.begin(), results.end(),
  4203. [](const nlohmann::json& result) { return result["success"].get<bool>(); })},
  4204. {"failed_count", std::count_if(results.begin(), results.end(),
  4205. [](const nlohmann::json& result) { return !result["success"].get<bool>(); })},
  4206. {"request_id", requestId}};
  4207. sendJsonResponse(res, response);
  4208. } catch (const nlohmann::json::parse_error& e) {
  4209. sendErrorResponse(res, std::string("Invalid JSON: ") + e.what(), 400, "JSON_PARSE_ERROR", requestId);
  4210. } catch (const std::exception& e) {
  4211. sendErrorResponse(res, std::string("Batch operation failed: ") + e.what(), 500, "BATCH_OPERATION_ERROR", requestId);
  4212. }
  4213. }
  4214. void Server::handleValidateModel(const httplib::Request& req, httplib::Response& res) {
  4215. std::string requestId = generateRequestId();
  4216. try {
  4217. // Parse JSON request body
  4218. nlohmann::json requestJson = nlohmann::json::parse(req.body);
  4219. if (!requestJson.contains("model_path") || !requestJson["model_path"].is_string()) {
  4220. sendErrorResponse(res, "Missing or invalid 'model_path' field", 400, "INVALID_MODEL_PATH", requestId);
  4221. return;
  4222. }
  4223. std::string modelPath = requestJson["model_path"];
  4224. std::string modelType = requestJson.value("model_type", "checkpoint");
  4225. // Validate model file
  4226. nlohmann::json validation = validateModelFile(modelPath, modelType);
  4227. nlohmann::json response = {
  4228. {"validation", validation},
  4229. {"request_id", requestId}};
  4230. sendJsonResponse(res, response);
  4231. } catch (const nlohmann::json::parse_error& e) {
  4232. sendErrorResponse(res, std::string("Invalid JSON: ") + e.what(), 400, "JSON_PARSE_ERROR", requestId);
  4233. } catch (const std::exception& e) {
  4234. sendErrorResponse(res, std::string("Model validation failed: ") + e.what(), 500, "MODEL_VALIDATION_ERROR", requestId);
  4235. }
  4236. }
  4237. void Server::handleCheckCompatibility(const httplib::Request& req, httplib::Response& res) {
  4238. std::string requestId = generateRequestId();
  4239. try {
  4240. if (!m_modelManager) {
  4241. sendErrorResponse(res, "Model manager not available", 500, "MODEL_MANAGER_UNAVAILABLE", requestId);
  4242. return;
  4243. }
  4244. // Parse JSON request body
  4245. nlohmann::json requestJson = nlohmann::json::parse(req.body);
  4246. if (!requestJson.contains("model_name") || !requestJson["model_name"].is_string()) {
  4247. sendErrorResponse(res, "Missing or invalid 'model_name' field", 400, "INVALID_MODEL_NAME", requestId);
  4248. return;
  4249. }
  4250. std::string modelName = requestJson["model_name"];
  4251. std::string systemInfo = requestJson.value("system_info", "auto");
  4252. // Get model information
  4253. auto modelInfo = m_modelManager->getModelInfo(modelName);
  4254. if (modelInfo.name.empty()) {
  4255. sendErrorResponse(res, "Model not found", 404, "MODEL_NOT_FOUND", requestId);
  4256. return;
  4257. }
  4258. // Check compatibility
  4259. nlohmann::json compatibility = checkModelCompatibility(modelInfo, systemInfo);
  4260. nlohmann::json response = {
  4261. {"model", modelName},
  4262. {"compatibility", compatibility},
  4263. {"request_id", requestId}};
  4264. sendJsonResponse(res, response);
  4265. } catch (const nlohmann::json::parse_error& e) {
  4266. sendErrorResponse(res, std::string("Invalid JSON: ") + e.what(), 400, "JSON_PARSE_ERROR", requestId);
  4267. } catch (const std::exception& e) {
  4268. sendErrorResponse(res, std::string("Compatibility check failed: ") + e.what(), 500, "COMPATIBILITY_CHECK_ERROR", requestId);
  4269. }
  4270. }
  4271. void Server::handleModelRequirements(const httplib::Request& req, httplib::Response& res) {
  4272. std::string requestId = generateRequestId();
  4273. try {
  4274. // Parse JSON request body
  4275. nlohmann::json requestJson = nlohmann::json::parse(req.body);
  4276. std::string modelType = requestJson.value("model_type", "checkpoint");
  4277. std::string resolution = requestJson.value("resolution", "512x512");
  4278. std::string batchSize = requestJson.value("batch_size", "1");
  4279. // Calculate specific requirements
  4280. nlohmann::json requirements = calculateSpecificRequirements(modelType, resolution, batchSize);
  4281. // Get general requirements for model type
  4282. ModelType type = ModelManager::stringToModelType(modelType);
  4283. nlohmann::json generalRequirements = getModelRequirements(type);
  4284. nlohmann::json response = {
  4285. {"model_type", modelType},
  4286. {"configuration", {{"resolution", resolution}, {"batch_size", batchSize}}},
  4287. {"specific_requirements", requirements},
  4288. {"general_requirements", generalRequirements},
  4289. {"request_id", requestId}};
  4290. sendJsonResponse(res, response);
  4291. } catch (const nlohmann::json::parse_error& e) {
  4292. sendErrorResponse(res, std::string("Invalid JSON: ") + e.what(), 400, "JSON_PARSE_ERROR", requestId);
  4293. } catch (const std::exception& e) {
  4294. sendErrorResponse(res, std::string("Requirements calculation failed: ") + e.what(), 500, "REQUIREMENTS_ERROR", requestId);
  4295. }
  4296. }
  4297. void Server::serverThreadFunction(const std::string& host, int port) {
  4298. try {
  4299. LOG_INFO("Server thread starting, attempting to bind to " + host + ":" + std::to_string(port));
  4300. // Check if port is available before attempting to bind
  4301. LOG_INFO("Checking if port " + std::to_string(port) + " is available...");
  4302. // Try to create a test socket to check if port is in use
  4303. int test_socket = socket(AF_INET, SOCK_STREAM, 0);
  4304. if (test_socket >= 0) {
  4305. // Set SO_REUSEADDR to avoid TIME_WAIT issues
  4306. int opt = 1;
  4307. if (setsockopt(test_socket, SOL_SOCKET, SO_REUSEADDR, &opt, sizeof(opt)) < 0) {
  4308. LOG_WARNING("Failed to set SO_REUSEADDR on test socket: " + std::string(strerror(errno)));
  4309. }
  4310. // Also set SO_REUSEPORT if available (for better concurrent binding handling)
  4311. #ifdef SO_REUSEPORT
  4312. int reuseport = 1;
  4313. if (setsockopt(test_socket, SOL_SOCKET, SO_REUSEPORT, &reuseport, sizeof(reuseport)) < 0) {
  4314. LOG_WARNING("Failed to set SO_REUSEPORT on test socket: " + std::string(strerror(errno)));
  4315. }
  4316. #endif
  4317. struct sockaddr_in addr;
  4318. addr.sin_family = AF_INET;
  4319. addr.sin_port = htons(port);
  4320. addr.sin_addr.s_addr = INADDR_ANY;
  4321. // Try to bind to the port
  4322. if (bind(test_socket, (struct sockaddr*)&addr, sizeof(addr)) < 0) {
  4323. close(test_socket);
  4324. LOG_ERROR("Port " + std::to_string(port) + " is already in use! Cannot start server.");
  4325. LOG_ERROR("This could be due to:");
  4326. LOG_ERROR("1. Another instance is already running on this port");
  4327. LOG_ERROR("2. A previous instance crashed and the socket is in TIME_WAIT state");
  4328. LOG_ERROR("3. The port is being used by another application");
  4329. LOG_ERROR("Solutions:");
  4330. LOG_ERROR("- Wait 30-60 seconds for TIME_WAIT to expire (if server crashed)");
  4331. LOG_ERROR("- Kill any existing processes: sudo lsof -ti:" + std::to_string(port) + " | xargs kill -9");
  4332. LOG_ERROR("- Use a different port with -p <port>");
  4333. m_isRunning.store(false);
  4334. m_startupFailed.store(true);
  4335. return;
  4336. }
  4337. close(test_socket);
  4338. }
  4339. LOG_INFO("Port " + std::to_string(port) + " is available, proceeding with server startup...");
  4340. LOG_INFO("Calling listen()...");
  4341. // We need to set m_isRunning after successful bind but before blocking
  4342. // cpp-httplib doesn't provide a callback, so we set it optimistically
  4343. // and clear it if listen() returns false
  4344. m_isRunning.store(true);
  4345. bool listenResult = m_httpServer->listen(host.c_str(), port);
  4346. LOG_INFO("listen() returned: " + std::string(listenResult ? "true" : "false"));
  4347. // If we reach here, server has stopped (either normally or due to error)
  4348. m_isRunning.store(false);
  4349. if (!listenResult) {
  4350. LOG_ERROR("Server listen failed! This usually means port is in use or permission denied.");
  4351. }
  4352. } catch (const std::exception& e) {
  4353. LOG_ERROR("Exception in server thread: " + std::string(e.what()));
  4354. m_isRunning.store(false);
  4355. }
  4356. }
  4357. std::string Server::generateThumbnail(const std::string& imagePath, int size) {
  4358. try {
  4359. // Check if file exists and is accessible
  4360. if (!std::filesystem::exists(imagePath)) {
  4361. LOG_ERROR("Image file not found for thumbnail generation: " + imagePath);
  4362. return "";
  4363. }
  4364. // Load image using existing infrastructure
  4365. auto [imageData, sourceWidth, sourceHeight, sourceChannels, success, loadError] = loadImageFromInput(imagePath);
  4366. if (!success) {
  4367. LOG_ERROR("Failed to load image for thumbnail generation: " + loadError);
  4368. return "";
  4369. }
  4370. // Don't thumbnail if image is already small enough
  4371. if (sourceWidth <= size && sourceHeight <= size) {
  4372. // Return original file content if it's already small
  4373. std::ifstream file(imagePath, std::ios::binary);
  4374. if (file.is_open()) {
  4375. std::stringstream buffer;
  4376. buffer << file.rdbuf();
  4377. std::string content = buffer.str();
  4378. return content;
  4379. }
  4380. return "";
  4381. }
  4382. // Calculate thumbnail dimensions maintaining aspect ratio
  4383. int thumbnailWidth, thumbnailHeight;
  4384. if (sourceWidth > sourceHeight) {
  4385. thumbnailWidth = size;
  4386. thumbnailHeight = static_cast<int>(static_cast<double>(sourceHeight) * size / sourceWidth);
  4387. } else {
  4388. thumbnailHeight = size;
  4389. thumbnailWidth = static_cast<int>(static_cast<double>(sourceWidth) * size / sourceHeight);
  4390. }
  4391. // Ensure minimum dimensions
  4392. thumbnailWidth = std::max(1, thumbnailWidth);
  4393. thumbnailHeight = std::max(1, thumbnailHeight);
  4394. // For now, return a simple fallback placeholder thumbnail
  4395. // In a real implementation, you'd want to encode the resized image to JPEG
  4396. static const std::string placeholderThumbnail =
  4397. "\xFF\xD8\xFF\xE0\x00\x10JFIF\x00\x01\x01\x01\x00H\x00H\x00\x00\xFF\xDB\x00C\x00\x08\x06\x06\x07\x06\x05\x08\x07\x07\x07\t\t\x08\n\x0C\x14\r\x0C\x0B\x0B\x0C\x19\x12\x13\x0F\x14\x1D\x1A\x1F\x1E\x1D\x1A\x1C\x1C $.' \",#\x1C\x1C(7),01444\x1F'9=82<.342\xFF\xC0\x00\x11\x08\x00\x01\x00\x01\x01\x11\x00\x02\x11\x01\x03\x11\x01\xFF\xC4\x00\x14\x00\x01\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x08\xFF\xC4\x00\x14\x10\x01\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\xFF\xDA\x00\x0C\x03\x01\x00\x02\x11\x03\x11\x00\x3F\x00\xAA\xFF\xD9";
  4398. LOG_DEBUG("Generated placeholder thumbnail for: " + imagePath +
  4399. " (" + std::to_string(sourceWidth) + "x" + std::to_string(sourceHeight) +
  4400. " -> " + std::to_string(thumbnailWidth) + "x" + std::to_string(thumbnailHeight) + ")");
  4401. return placeholderThumbnail;
  4402. } catch (const std::exception& e) {
  4403. LOG_ERROR("Exception in generateThumbnail: " + std::string(e.what()));
  4404. return "";
  4405. }
  4406. }
  4407. void Server::logHttpAccess(const httplib::Request& req, const httplib::Response& res, const std::string& endpoint) {
  4408. std::string clientIP = req.get_header_value("X-Forwarded-For");
  4409. if (clientIP.empty()) {
  4410. clientIP = req.remote_addr;
  4411. }
  4412. std::string userAgent = req.get_header_value("User-Agent");
  4413. if (userAgent.length() > 100) {
  4414. userAgent = userAgent.substr(0, 100) + "...";
  4415. }
  4416. std::string logMessage = clientIP + " " + req.method + " " + req.path +
  4417. " -> " + std::to_string(res.status) +
  4418. " (" + std::to_string(res.body.length()) + " bytes)";
  4419. if (!endpoint.empty()) {
  4420. logMessage += " [" + endpoint + "]";
  4421. }
  4422. if (res.status != 200) {
  4423. LOG_ERROR("HTTP: " + logMessage);
  4424. } else {
  4425. LOG_INFO("HTTP: " + logMessage);
  4426. }
  4427. }
  4428. std::string& Server::getModelField(ModelType type) {
  4429. switch (type) {
  4430. case ModelType::CHECKPOINT:
  4431. case ModelType::DIFFUSION_MODELS:
  4432. return m_loadedModels.checkpoint;
  4433. case ModelType::ESRGAN:
  4434. case ModelType::UPSCALER:
  4435. return m_loadedModels.esrgan;
  4436. default:
  4437. // For other model types (VAE, LoRA, ControlNet), return checkpoint as default
  4438. // These are handled internally by stable-diffusion.cpp
  4439. return m_loadedModels.checkpoint;
  4440. }
  4441. }