server.cpp 228 KB

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