AnimeService.php 380 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695705715725735745755765775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206216226236246256266276286296306316326336346356366376386396406416426436446456466476486496506516526536546556566576586596606616626636646656666676686696706716726736746756766776786796806816826836846856866876886896906916926936946956966976986997007017027037047057067077087097107117127137147157167177187197207217227237247257267277287297307317327337347357367377387397407417427437447457467477487497507517527537547557567577587597607617627637647657667677687697707717727737747757767777787797807817827837847857867877887897907917927937947957967977987998008018028038048058068078088098108118128138148158168178188198208218228238248258268278288298308318328338348358368378388398408418428438448458468478488498508518528538548558568578588598608618628638648658668678688698708718728738748758768778788798808818828838848858868878888898908918928938948958968978988999009019029039049059069079089099109119129139149159169179189199209219229239249259269279289299309319329339349359369379389399409419429439449459469479489499509519529539549559569579589599609619629639649659669679689699709719729739749759769779789799809819829839849859869879889899909919929939949959969979989991000100110021003100410051006100710081009101010111012101310141015101610171018101910201021102210231024102510261027102810291030103110321033103410351036103710381039104010411042104310441045104610471048104910501051105210531054105510561057105810591060106110621063106410651066106710681069107010711072107310741075107610771078107910801081108210831084108510861087108810891090109110921093109410951096109710981099110011011102110311041105110611071108110911101111111211131114111511161117111811191120112111221123112411251126112711281129113011311132113311341135113611371138113911401141114211431144114511461147114811491150115111521153115411551156115711581159116011611162116311641165116611671168116911701171117211731174117511761177117811791180118111821183118411851186118711881189119011911192119311941195119611971198119912001201120212031204120512061207120812091210121112121213121412151216121712181219122012211222122312241225122612271228122912301231123212331234123512361237123812391240124112421243124412451246124712481249125012511252125312541255125612571258125912601261126212631264126512661267126812691270127112721273127412751276127712781279128012811282128312841285128612871288128912901291129212931294129512961297129812991300130113021303130413051306130713081309131013111312131313141315131613171318131913201321132213231324132513261327132813291330133113321333133413351336133713381339134013411342134313441345134613471348134913501351135213531354135513561357135813591360136113621363136413651366136713681369137013711372137313741375137613771378137913801381138213831384138513861387138813891390139113921393139413951396139713981399140014011402140314041405140614071408140914101411141214131414141514161417141814191420142114221423142414251426142714281429143014311432143314341435143614371438143914401441144214431444144514461447144814491450145114521453145414551456145714581459146014611462146314641465146614671468146914701471147214731474147514761477147814791480148114821483148414851486148714881489149014911492149314941495149614971498149915001501150215031504150515061507150815091510151115121513151415151516151715181519152015211522152315241525152615271528152915301531153215331534153515361537153815391540154115421543154415451546154715481549155015511552155315541555155615571558155915601561156215631564156515661567156815691570157115721573157415751576157715781579158015811582158315841585158615871588158915901591159215931594159515961597159815991600160116021603160416051606160716081609161016111612161316141615161616171618161916201621162216231624162516261627162816291630163116321633163416351636163716381639164016411642164316441645164616471648164916501651165216531654165516561657165816591660166116621663166416651666166716681669167016711672167316741675167616771678167916801681168216831684168516861687168816891690169116921693169416951696169716981699170017011702170317041705170617071708170917101711171217131714171517161717171817191720172117221723172417251726172717281729173017311732173317341735173617371738173917401741174217431744174517461747174817491750175117521753175417551756175717581759176017611762176317641765176617671768176917701771177217731774177517761777177817791780178117821783178417851786178717881789179017911792179317941795179617971798179918001801180218031804180518061807180818091810181118121813181418151816181718181819182018211822182318241825182618271828182918301831183218331834183518361837183818391840184118421843184418451846184718481849185018511852185318541855185618571858185918601861186218631864186518661867186818691870187118721873187418751876187718781879188018811882188318841885188618871888188918901891189218931894189518961897189818991900190119021903190419051906190719081909191019111912191319141915191619171918191919201921192219231924192519261927192819291930193119321933193419351936193719381939194019411942194319441945194619471948194919501951195219531954195519561957195819591960196119621963196419651966196719681969197019711972197319741975197619771978197919801981198219831984198519861987198819891990199119921993199419951996199719981999200020012002200320042005200620072008200920102011201220132014201520162017201820192020202120222023202420252026202720282029203020312032203320342035203620372038203920402041204220432044204520462047204820492050205120522053205420552056205720582059206020612062206320642065206620672068206920702071207220732074207520762077207820792080208120822083208420852086208720882089209020912092209320942095209620972098209921002101210221032104210521062107210821092110211121122113211421152116211721182119212021212122212321242125212621272128212921302131213221332134213521362137213821392140214121422143214421452146214721482149215021512152215321542155215621572158215921602161216221632164216521662167216821692170217121722173217421752176217721782179218021812182218321842185218621872188218921902191219221932194219521962197219821992200220122022203220422052206220722082209221022112212221322142215221622172218221922202221222222232224222522262227222822292230223122322233223422352236223722382239224022412242224322442245224622472248224922502251225222532254225522562257225822592260226122622263226422652266226722682269227022712272227322742275227622772278227922802281228222832284228522862287228822892290229122922293229422952296229722982299230023012302230323042305230623072308230923102311231223132314231523162317231823192320232123222323232423252326232723282329233023312332233323342335233623372338233923402341234223432344234523462347234823492350235123522353235423552356235723582359236023612362236323642365236623672368236923702371237223732374237523762377237823792380238123822383238423852386238723882389239023912392239323942395239623972398239924002401240224032404240524062407240824092410241124122413241424152416241724182419242024212422242324242425242624272428242924302431243224332434243524362437243824392440244124422443244424452446244724482449245024512452245324542455245624572458245924602461246224632464246524662467246824692470247124722473247424752476247724782479248024812482248324842485248624872488248924902491249224932494249524962497249824992500250125022503250425052506250725082509251025112512251325142515251625172518251925202521252225232524252525262527252825292530253125322533253425352536253725382539254025412542254325442545254625472548254925502551255225532554255525562557255825592560256125622563256425652566256725682569257025712572257325742575257625772578257925802581258225832584258525862587258825892590259125922593259425952596259725982599260026012602260326042605260626072608260926102611261226132614261526162617261826192620262126222623262426252626262726282629263026312632263326342635263626372638263926402641264226432644264526462647264826492650265126522653265426552656265726582659266026612662266326642665266626672668266926702671267226732674267526762677267826792680268126822683268426852686268726882689269026912692269326942695269626972698269927002701270227032704270527062707270827092710271127122713271427152716271727182719272027212722272327242725272627272728272927302731273227332734273527362737273827392740274127422743274427452746274727482749275027512752275327542755275627572758275927602761276227632764276527662767276827692770277127722773277427752776277727782779278027812782278327842785278627872788278927902791279227932794279527962797279827992800280128022803280428052806280728082809281028112812281328142815281628172818281928202821282228232824282528262827282828292830283128322833283428352836283728382839284028412842284328442845284628472848284928502851285228532854285528562857285828592860286128622863286428652866286728682869287028712872287328742875287628772878287928802881288228832884288528862887288828892890289128922893289428952896289728982899290029012902290329042905290629072908290929102911291229132914291529162917291829192920292129222923292429252926292729282929293029312932293329342935293629372938293929402941294229432944294529462947294829492950295129522953295429552956295729582959296029612962296329642965296629672968296929702971297229732974297529762977297829792980298129822983298429852986298729882989299029912992299329942995299629972998299930003001300230033004300530063007300830093010301130123013301430153016301730183019302030213022302330243025302630273028302930303031303230333034303530363037303830393040304130423043304430453046304730483049305030513052305330543055305630573058305930603061306230633064306530663067306830693070307130723073307430753076307730783079308030813082308330843085308630873088308930903091309230933094309530963097309830993100310131023103310431053106310731083109311031113112311331143115311631173118311931203121312231233124312531263127312831293130313131323133313431353136313731383139314031413142314331443145314631473148314931503151315231533154315531563157315831593160316131623163316431653166316731683169317031713172317331743175317631773178317931803181318231833184318531863187318831893190319131923193319431953196319731983199320032013202320332043205320632073208320932103211321232133214321532163217321832193220322132223223322432253226322732283229323032313232323332343235323632373238323932403241324232433244324532463247324832493250325132523253325432553256325732583259326032613262326332643265326632673268326932703271327232733274327532763277327832793280328132823283328432853286328732883289329032913292329332943295329632973298329933003301330233033304330533063307330833093310331133123313331433153316331733183319332033213322332333243325332633273328332933303331333233333334333533363337333833393340334133423343334433453346334733483349335033513352335333543355335633573358335933603361336233633364336533663367336833693370337133723373337433753376337733783379338033813382338333843385338633873388338933903391339233933394339533963397339833993400340134023403340434053406340734083409341034113412341334143415341634173418341934203421342234233424342534263427342834293430343134323433343434353436343734383439344034413442344334443445344634473448344934503451345234533454345534563457345834593460346134623463346434653466346734683469347034713472347334743475347634773478347934803481348234833484348534863487348834893490349134923493349434953496349734983499350035013502350335043505350635073508350935103511351235133514351535163517351835193520352135223523352435253526352735283529353035313532353335343535353635373538353935403541354235433544354535463547354835493550355135523553355435553556355735583559356035613562356335643565356635673568356935703571357235733574357535763577357835793580358135823583358435853586358735883589359035913592359335943595359635973598359936003601360236033604360536063607360836093610361136123613361436153616361736183619362036213622362336243625362636273628362936303631363236333634363536363637363836393640364136423643364436453646364736483649365036513652365336543655365636573658365936603661366236633664366536663667366836693670367136723673367436753676367736783679368036813682368336843685368636873688368936903691369236933694369536963697369836993700370137023703370437053706370737083709371037113712371337143715371637173718371937203721372237233724372537263727372837293730373137323733373437353736373737383739374037413742374337443745374637473748374937503751375237533754375537563757375837593760376137623763376437653766376737683769377037713772377337743775377637773778377937803781378237833784378537863787378837893790379137923793379437953796379737983799380038013802380338043805380638073808380938103811381238133814381538163817381838193820382138223823382438253826382738283829383038313832383338343835383638373838383938403841384238433844384538463847384838493850385138523853385438553856385738583859386038613862386338643865386638673868386938703871387238733874387538763877387838793880388138823883388438853886388738883889389038913892389338943895389638973898389939003901390239033904390539063907390839093910391139123913391439153916391739183919392039213922392339243925392639273928392939303931393239333934393539363937393839393940394139423943394439453946394739483949395039513952395339543955395639573958395939603961396239633964396539663967396839693970397139723973397439753976397739783979398039813982398339843985398639873988398939903991399239933994399539963997399839994000400140024003400440054006400740084009401040114012401340144015401640174018401940204021402240234024402540264027402840294030403140324033403440354036403740384039404040414042404340444045404640474048404940504051405240534054405540564057405840594060406140624063406440654066406740684069407040714072407340744075407640774078407940804081408240834084408540864087408840894090409140924093409440954096409740984099410041014102410341044105410641074108410941104111411241134114411541164117411841194120412141224123412441254126412741284129413041314132413341344135413641374138413941404141414241434144414541464147414841494150415141524153415441554156415741584159416041614162416341644165416641674168416941704171417241734174417541764177417841794180418141824183418441854186418741884189419041914192419341944195419641974198419942004201420242034204420542064207420842094210421142124213421442154216421742184219422042214222422342244225422642274228422942304231423242334234423542364237423842394240424142424243424442454246424742484249425042514252425342544255425642574258425942604261426242634264426542664267426842694270427142724273427442754276427742784279428042814282428342844285428642874288428942904291429242934294429542964297429842994300430143024303430443054306430743084309431043114312431343144315431643174318431943204321432243234324432543264327432843294330433143324333433443354336433743384339434043414342434343444345434643474348434943504351435243534354435543564357435843594360436143624363436443654366436743684369437043714372437343744375437643774378437943804381438243834384438543864387438843894390439143924393439443954396439743984399440044014402440344044405440644074408440944104411441244134414441544164417441844194420442144224423442444254426442744284429443044314432443344344435443644374438443944404441444244434444444544464447444844494450445144524453445444554456445744584459446044614462446344644465446644674468446944704471447244734474447544764477447844794480448144824483448444854486448744884489449044914492449344944495449644974498449945004501450245034504450545064507450845094510451145124513451445154516451745184519452045214522452345244525452645274528452945304531453245334534453545364537453845394540454145424543454445454546454745484549455045514552455345544555455645574558455945604561456245634564456545664567456845694570457145724573457445754576457745784579458045814582458345844585458645874588458945904591459245934594459545964597459845994600460146024603460446054606460746084609461046114612461346144615461646174618461946204621462246234624462546264627462846294630463146324633463446354636463746384639464046414642464346444645464646474648464946504651465246534654465546564657465846594660466146624663466446654666466746684669467046714672467346744675467646774678467946804681468246834684468546864687468846894690469146924693469446954696469746984699470047014702470347044705470647074708470947104711471247134714471547164717471847194720472147224723472447254726472747284729473047314732473347344735473647374738473947404741474247434744474547464747474847494750475147524753475447554756475747584759476047614762476347644765476647674768476947704771477247734774477547764777477847794780478147824783478447854786478747884789479047914792479347944795479647974798479948004801480248034804480548064807480848094810481148124813481448154816481748184819482048214822482348244825482648274828482948304831483248334834483548364837483848394840484148424843484448454846484748484849485048514852485348544855485648574858485948604861486248634864486548664867486848694870487148724873487448754876487748784879488048814882488348844885488648874888488948904891489248934894489548964897489848994900490149024903490449054906490749084909491049114912491349144915491649174918491949204921492249234924492549264927492849294930493149324933493449354936493749384939494049414942494349444945494649474948494949504951495249534954495549564957495849594960496149624963496449654966496749684969497049714972497349744975497649774978497949804981498249834984498549864987498849894990499149924993499449954996499749984999500050015002500350045005500650075008500950105011501250135014501550165017501850195020502150225023502450255026502750285029503050315032503350345035503650375038503950405041504250435044504550465047504850495050505150525053505450555056505750585059506050615062506350645065506650675068506950705071507250735074507550765077507850795080508150825083508450855086508750885089509050915092509350945095509650975098509951005101510251035104510551065107510851095110511151125113511451155116511751185119512051215122512351245125512651275128512951305131513251335134513551365137513851395140514151425143514451455146514751485149515051515152515351545155515651575158515951605161516251635164516551665167516851695170517151725173517451755176517751785179518051815182518351845185518651875188518951905191519251935194519551965197519851995200520152025203520452055206520752085209521052115212521352145215521652175218521952205221522252235224522552265227522852295230523152325233523452355236523752385239524052415242524352445245524652475248524952505251525252535254525552565257525852595260526152625263526452655266526752685269527052715272527352745275527652775278527952805281528252835284528552865287528852895290529152925293529452955296529752985299530053015302530353045305530653075308530953105311531253135314531553165317531853195320532153225323532453255326532753285329533053315332533353345335533653375338533953405341534253435344534553465347534853495350535153525353535453555356535753585359536053615362536353645365536653675368536953705371537253735374537553765377537853795380538153825383538453855386538753885389539053915392539353945395539653975398539954005401540254035404540554065407540854095410541154125413541454155416541754185419542054215422542354245425542654275428542954305431543254335434543554365437543854395440544154425443544454455446544754485449545054515452545354545455545654575458545954605461546254635464546554665467546854695470547154725473547454755476547754785479548054815482548354845485548654875488548954905491549254935494549554965497549854995500550155025503550455055506550755085509551055115512551355145515551655175518551955205521552255235524552555265527552855295530553155325533553455355536553755385539554055415542554355445545554655475548554955505551555255535554555555565557555855595560556155625563556455655566556755685569557055715572557355745575557655775578557955805581558255835584558555865587558855895590559155925593559455955596559755985599560056015602560356045605560656075608560956105611561256135614561556165617561856195620562156225623562456255626562756285629563056315632563356345635563656375638563956405641564256435644564556465647564856495650565156525653565456555656565756585659566056615662566356645665566656675668566956705671567256735674567556765677567856795680568156825683568456855686568756885689569056915692569356945695569656975698569957005701570257035704570557065707570857095710571157125713571457155716571757185719572057215722572357245725572657275728572957305731573257335734573557365737573857395740574157425743574457455746574757485749575057515752575357545755575657575758575957605761576257635764576557665767576857695770577157725773577457755776577757785779578057815782578357845785578657875788578957905791579257935794579557965797579857995800580158025803580458055806580758085809581058115812581358145815581658175818581958205821582258235824582558265827582858295830583158325833583458355836583758385839584058415842584358445845584658475848584958505851585258535854585558565857585858595860586158625863586458655866586758685869587058715872587358745875587658775878587958805881588258835884588558865887588858895890589158925893589458955896589758985899590059015902590359045905590659075908590959105911591259135914591559165917591859195920592159225923592459255926592759285929593059315932593359345935593659375938593959405941594259435944594559465947594859495950595159525953595459555956595759585959596059615962596359645965596659675968596959705971597259735974597559765977597859795980598159825983598459855986598759885989599059915992599359945995599659975998599960006001600260036004600560066007600860096010601160126013601460156016601760186019602060216022602360246025602660276028602960306031603260336034603560366037603860396040604160426043604460456046604760486049605060516052605360546055605660576058605960606061606260636064606560666067606860696070607160726073607460756076607760786079608060816082608360846085608660876088608960906091609260936094609560966097609860996100610161026103610461056106610761086109611061116112611361146115611661176118611961206121612261236124612561266127612861296130613161326133613461356136613761386139614061416142614361446145614661476148614961506151615261536154615561566157615861596160616161626163616461656166616761686169617061716172617361746175617661776178617961806181618261836184618561866187618861896190619161926193619461956196619761986199620062016202620362046205620662076208620962106211621262136214621562166217621862196220622162226223622462256226622762286229623062316232623362346235623662376238623962406241624262436244624562466247624862496250625162526253625462556256625762586259626062616262626362646265626662676268626962706271627262736274627562766277627862796280628162826283628462856286628762886289629062916292629362946295629662976298629963006301630263036304630563066307630863096310631163126313631463156316631763186319632063216322632363246325632663276328632963306331633263336334633563366337633863396340634163426343634463456346634763486349635063516352635363546355635663576358635963606361636263636364636563666367636863696370637163726373637463756376637763786379638063816382638363846385638663876388638963906391639263936394639563966397639863996400640164026403640464056406640764086409641064116412641364146415641664176418641964206421642264236424642564266427642864296430643164326433643464356436643764386439644064416442644364446445644664476448644964506451645264536454645564566457645864596460646164626463646464656466646764686469647064716472647364746475647664776478647964806481648264836484648564866487648864896490649164926493649464956496649764986499650065016502650365046505650665076508650965106511651265136514651565166517651865196520652165226523652465256526652765286529653065316532653365346535653665376538653965406541654265436544654565466547654865496550655165526553655465556556655765586559656065616562656365646565656665676568656965706571657265736574657565766577657865796580658165826583658465856586658765886589659065916592659365946595659665976598659966006601660266036604660566066607660866096610661166126613661466156616661766186619662066216622662366246625662666276628662966306631663266336634663566366637663866396640664166426643664466456646664766486649665066516652665366546655665666576658665966606661666266636664666566666667666866696670667166726673667466756676667766786679668066816682668366846685668666876688668966906691669266936694669566966697669866996700670167026703670467056706670767086709671067116712671367146715671667176718671967206721672267236724672567266727672867296730673167326733673467356736673767386739674067416742674367446745674667476748674967506751675267536754675567566757675867596760676167626763676467656766676767686769677067716772677367746775677667776778677967806781678267836784678567866787678867896790679167926793679467956796679767986799680068016802680368046805680668076808680968106811681268136814681568166817681868196820682168226823682468256826682768286829683068316832683368346835683668376838683968406841684268436844684568466847684868496850685168526853685468556856685768586859686068616862686368646865686668676868686968706871687268736874687568766877687868796880688168826883688468856886688768886889689068916892689368946895689668976898689969006901690269036904690569066907690869096910691169126913691469156916691769186919692069216922692369246925692669276928692969306931693269336934693569366937693869396940694169426943694469456946694769486949695069516952695369546955695669576958695969606961696269636964696569666967696869696970697169726973697469756976697769786979698069816982698369846985698669876988698969906991699269936994699569966997699869997000700170027003700470057006700770087009701070117012701370147015701670177018701970207021702270237024702570267027702870297030703170327033703470357036703770387039704070417042704370447045704670477048704970507051705270537054705570567057705870597060706170627063706470657066706770687069707070717072707370747075707670777078707970807081708270837084708570867087708870897090709170927093709470957096709770987099710071017102710371047105710671077108710971107111711271137114711571167117711871197120712171227123712471257126712771287129713071317132713371347135713671377138713971407141714271437144714571467147714871497150715171527153715471557156715771587159716071617162716371647165716671677168716971707171717271737174717571767177717871797180718171827183718471857186718771887189719071917192719371947195719671977198719972007201720272037204720572067207720872097210721172127213721472157216721772187219722072217222722372247225722672277228722972307231723272337234723572367237723872397240724172427243724472457246724772487249725072517252725372547255725672577258725972607261726272637264726572667267726872697270727172727273727472757276727772787279728072817282728372847285728672877288728972907291729272937294729572967297729872997300730173027303730473057306730773087309731073117312731373147315731673177318731973207321732273237324732573267327732873297330733173327333733473357336733773387339734073417342734373447345734673477348734973507351735273537354735573567357735873597360736173627363736473657366736773687369737073717372737373747375737673777378737973807381738273837384738573867387738873897390739173927393739473957396739773987399740074017402740374047405740674077408740974107411741274137414741574167417741874197420742174227423742474257426742774287429743074317432743374347435743674377438743974407441744274437444744574467447744874497450745174527453745474557456745774587459746074617462746374647465746674677468746974707471747274737474747574767477747874797480748174827483748474857486748774887489749074917492749374947495749674977498749975007501750275037504750575067507750875097510751175127513751475157516751775187519752075217522752375247525752675277528752975307531753275337534753575367537753875397540754175427543754475457546754775487549755075517552755375547555755675577558755975607561756275637564756575667567756875697570757175727573757475757576757775787579758075817582758375847585758675877588758975907591759275937594759575967597759875997600760176027603760476057606760776087609761076117612761376147615761676177618761976207621762276237624762576267627762876297630763176327633763476357636763776387639764076417642764376447645764676477648764976507651765276537654765576567657765876597660766176627663766476657666766776687669767076717672767376747675767676777678767976807681768276837684768576867687768876897690769176927693769476957696769776987699770077017702770377047705770677077708770977107711771277137714771577167717771877197720772177227723772477257726772777287729773077317732773377347735773677377738773977407741774277437744774577467747774877497750775177527753775477557756775777587759776077617762776377647765776677677768776977707771777277737774777577767777777877797780778177827783778477857786778777887789779077917792779377947795779677977798779978007801780278037804780578067807780878097810781178127813781478157816781778187819782078217822782378247825782678277828782978307831783278337834783578367837783878397840784178427843784478457846784778487849785078517852785378547855785678577858785978607861786278637864786578667867786878697870787178727873787478757876787778787879788078817882788378847885788678877888788978907891789278937894789578967897789878997900790179027903790479057906790779087909791079117912791379147915791679177918791979207921792279237924792579267927792879297930793179327933793479357936793779387939794079417942794379447945794679477948794979507951795279537954795579567957795879597960796179627963796479657966796779687969797079717972797379747975797679777978797979807981798279837984798579867987798879897990799179927993799479957996799779987999800080018002800380048005800680078008800980108011801280138014801580168017801880198020802180228023802480258026802780288029803080318032803380348035803680378038803980408041804280438044804580468047804880498050805180528053805480558056805780588059806080618062806380648065806680678068806980708071807280738074807580768077807880798080808180828083808480858086808780888089809080918092809380948095809680978098809981008101810281038104810581068107810881098110811181128113811481158116811781188119812081218122812381248125812681278128812981308131813281338134813581368137813881398140814181428143814481458146814781488149815081518152815381548155815681578158815981608161816281638164816581668167816881698170817181728173817481758176817781788179818081818182818381848185818681878188818981908191819281938194819581968197819881998200820182028203820482058206820782088209821082118212821382148215821682178218821982208221822282238224822582268227822882298230823182328233823482358236823782388239824082418242824382448245824682478248824982508251825282538254825582568257825882598260826182628263826482658266826782688269827082718272827382748275827682778278827982808281828282838284828582868287828882898290829182928293829482958296829782988299830083018302830383048305830683078308830983108311831283138314831583168317831883198320832183228323832483258326832783288329833083318332833383348335833683378338833983408341834283438344834583468347834883498350835183528353835483558356835783588359836083618362836383648365836683678368836983708371837283738374837583768377837883798380838183828383838483858386838783888389839083918392839383948395839683978398839984008401840284038404840584068407840884098410841184128413841484158416841784188419842084218422842384248425842684278428842984308431843284338434843584368437843884398440844184428443844484458446844784488449845084518452845384548455845684578458845984608461846284638464846584668467846884698470847184728473847484758476847784788479848084818482848384848485848684878488848984908491849284938494849584968497849884998500850185028503850485058506850785088509851085118512851385148515851685178518851985208521852285238524852585268527852885298530853185328533853485358536853785388539854085418542854385448545854685478548854985508551855285538554855585568557855885598560856185628563856485658566856785688569857085718572857385748575857685778578857985808581858285838584858585868587858885898590859185928593859485958596859785988599860086018602860386048605860686078608860986108611861286138614861586168617861886198620862186228623862486258626862786288629863086318632863386348635863686378638863986408641864286438644864586468647864886498650865186528653865486558656865786588659866086618662866386648665866686678668866986708671867286738674867586768677867886798680868186828683868486858686868786888689869086918692869386948695869686978698869987008701870287038704870587068707870887098710871187128713871487158716871787188719872087218722872387248725872687278728872987308731873287338734873587368737873887398740874187428743874487458746874787488749875087518752875387548755875687578758875987608761876287638764876587668767876887698770877187728773877487758776877787788779878087818782878387848785878687878788878987908791879287938794
  1. <?php
  2. namespace App\Services\Anime;
  3. use App\Consts\BaseConst;
  4. use App\Consts\ErrorConst;
  5. use App\Facade\Site;
  6. use App\Libs\Utils;
  7. use App\Models\MpGeneratePicTask;
  8. use App\Services\AIGeneration\AIImageGenerationService;
  9. use App\Services\AIGeneration\AIVideoGenerationService;
  10. use App\Services\DeepSeek\DeepSeekService;
  11. use Dflydev\DotAccessData\Util;
  12. use GuzzleHttp\Client;
  13. use Illuminate\Support\Facades\DB;
  14. use Illuminate\Support\Facades\Log;
  15. use Illuminate\Support\Facades\Redis;
  16. use OSS\Core\OssException;
  17. use OSS\OssClient;
  18. class AnimeService
  19. {
  20. protected $aiImageGenerationService;
  21. protected $aiVideoGenerationService;
  22. protected $DeepSeekService;
  23. private $url;
  24. private $api_key;
  25. private $headers;
  26. public function __construct(
  27. AIImageGenerationService $aiImageGenerationService,
  28. AIVideoGenerationService $aiVideoGenerationService,
  29. DeepSeekService $DeepSeekService
  30. ) {
  31. $this->aiImageGenerationService = $aiImageGenerationService;
  32. $this->aiVideoGenerationService = $aiVideoGenerationService;
  33. $this->DeepSeekService = $DeepSeekService;
  34. $this->url = 'https://api.deepseek.com/chat/completions';
  35. $this->api_key = env('DEEPSEEK_API_KEY');
  36. $this->headers = [
  37. 'Authorization' => 'Bearer '.$this->api_key,
  38. 'Content-Type' => 'application/json; charset=UTF-8'
  39. ];
  40. }
  41. /**
  42. * 构建统一的分镜数据结构(episodeInfo格式)
  43. * @param array $segments 分镜数据数组
  44. * @return array 返回包含acts和total_duration的数组
  45. */
  46. public function buildEpisodeSegmentsStructure($segments) {
  47. $acts = [];
  48. $totalDuration = 0; // 初始化总时长
  49. foreach($segments as $segment) {
  50. // 计算分镜时长,优先级:video_duration > audio_duration > 默认5秒
  51. $videoDuration = getProp($segment, 'video_duration');
  52. $audioDuration = getProp($segment, 'audio_duration');
  53. if (!empty($videoDuration) && is_numeric($videoDuration)) {
  54. $totalDuration += floatval($videoDuration);
  55. } elseif (!empty($audioDuration) && is_numeric($audioDuration)) {
  56. $totalDuration += floatval($audioDuration);
  57. } else {
  58. $totalDuration += 5; // 默认5秒
  59. }
  60. $segment_content = getProp($segment, 'segment_content');
  61. // 判断是否有尾帧描述,如果有则去掉这部分内容
  62. if (strpos($segment_content, '尾帧') !== false) {
  63. // 使用正则表达式匹配"尾帧"及其后面的内容并移除(s修饰符让.匹配换行符)
  64. $segment_content = preg_replace('/尾帧.*$/s', '', $segment_content);
  65. }
  66. // 构建分镜信息
  67. $segmentInfo = [
  68. 'segment_id' => getProp($segment, 'segment_id'),
  69. 'segment_number' => getProp($segment, 'segment_number'),
  70. 'segment_content' => $segment_content,
  71. 'description' => getProp($segment, 'description'),
  72. 'composition' => getProp($segment, 'composition'),
  73. 'camera_movement' => getProp($segment, 'camera_movement'),
  74. 'voice_actor' => getProp($segment, 'voice_actor'),
  75. 'dialogue' => getProp($segment, 'dialogue'),
  76. 'frame_type' => getProp($segment, 'frame_type'),
  77. 'scene' => getProp($segment, 'scene'),
  78. 'characters' => getProp($segment, 'characters'),
  79. 'tail_frame' => getProp($segment, 'tail_frame'),
  80. 'emotion' => getProp($segment, 'emotion'),
  81. 'emotion_type' => getProp($segment, 'emotion_type'),
  82. 'gender' => getProp($segment, 'gender'),
  83. 'speed_ratio' => getProp($segment, 'speed_ratio'),
  84. 'loudness_ratio' => getProp($segment, 'loudness_ratio'),
  85. 'emotion_scale' => getProp($segment, 'emotion_scale'),
  86. 'pitch' => getProp($segment, 'pitch'),
  87. 'voice_name' => getProp($segment, 'voice_name'),
  88. 'voice_type' => getProp($segment, 'voice_type'),
  89. 'voice_audio_url' => getProp($segment, 'voice_audio_url'),
  90. 'img_url' => getProp($segment, 'img_url'),
  91. 'audio_url' => getProp($segment, 'audio_url'),
  92. 'audio_duration' => getProp($segment, 'audio_duration', 0),
  93. 'video_url' => getProp($segment, 'video_url'),
  94. 'video_duration' => getProp($segment, 'video_duration', 0),
  95. 'video_time_point_start' => getProp($segment, 'video_time_point_start', 0),
  96. 'video_time_point_end' => getProp($segment, 'video_time_point_end', getProp($segment, 'video_duration', 0)),
  97. 'last_frame_url' => getProp($segment, 'last_frame_url'),
  98. 'current_type' => getProp($segment, 'current_type'),
  99. ];
  100. $actNumber = getProp($segment, 'act_number');
  101. if (isset($acts[$actNumber])) {
  102. $acts[$actNumber]['segments'][] = $segmentInfo;
  103. } else {
  104. $acts[$actNumber] = [
  105. 'act_number' => $actNumber,
  106. 'act_title' => getProp($segment, 'act_title'),
  107. 'act_duration' => getProp($segment, 'act_duration'),
  108. 'segments' => [$segmentInfo]
  109. ];
  110. }
  111. }
  112. return [
  113. 'acts' => array_values($acts),
  114. 'total_duration' => intval(round($totalDuration))
  115. ];
  116. }
  117. /**
  118. * 构建统一的分段数据结构(episodeInfoForAce格式)
  119. * @param array $segments 分段数据数组
  120. * @return array 返回包含acts和total_duration的数组
  121. */
  122. public function buildEpisodeActsStructureForAce($segments) {
  123. $acts = [];
  124. $totalDuration = 0; // 初始化总时长
  125. foreach($segments as $segment) {
  126. // 计算分镜时长,优先级:video_duration > act_duration > 默认5秒
  127. $videoDuration = getProp($segment, 'video_duration');
  128. $actDuration = getProp($segment, 'act_duration');
  129. if (!empty($videoDuration) && is_numeric($videoDuration)) {
  130. $totalDuration += floatval($videoDuration);
  131. } elseif (!empty($actDuration) && is_numeric($actDuration)) {
  132. $totalDuration += floatval($actDuration);
  133. } else {
  134. $totalDuration += 5; // 默认5秒
  135. }
  136. // 构建分镜信息
  137. $segmentInfo = [
  138. 'act_id' => getProp($segment, 'id'),
  139. 'act_number' => getProp($segment, 'act_number'),
  140. 'act_title' => getProp($segment, 'act_title'),
  141. 'act_duration' => getProp($segment, 'act_duration'),
  142. 'act_content' => getProp($segment, 'act_content'),
  143. 'video_url' => getProp($segment, 'video_url'),
  144. 'video_duration' => getProp($segment, 'video_duration', 0),
  145. 'video_time_point_start' => getProp($segment, 'video_time_point_start', 0),
  146. 'video_time_point_end' => getProp($segment, 'video_time_point_end', getProp($segment, 'video_duration', 0)),
  147. 'last_frame_url' => getProp($segment, 'last_frame_url'),
  148. 'current_type' => getProp($segment, 'current_type'),
  149. ];
  150. $acts[] = $segmentInfo;
  151. }
  152. return [
  153. 'acts' => array_values($acts),
  154. 'total_duration' => intval(round($totalDuration))
  155. ];
  156. }
  157. /**
  158. * 验证画面比例是否有效
  159. * @param string $ratio 画面比例
  160. * @return bool
  161. */
  162. public function validateRatio($ratio) {
  163. return isset(BaseConst::IMAGE_RATIOS[$ratio]);
  164. }
  165. /**
  166. * 获取画面比例对应的宽高
  167. * @param string $ratio 画面比例
  168. * @return array ['width' => int, 'height' => int]
  169. * @throws \Exception
  170. */
  171. private function getRatioDimensions($ratio) {
  172. if ($ratio && !$this->validateRatio($ratio)) {
  173. $validRatios = implode('、', array_keys(BaseConst::IMAGE_RATIOS));
  174. Utils::throwError("1002:画面比例选择不正确,只支持{$validRatios}");
  175. }
  176. return isset(BaseConst::IMAGE_RATIOS[$ratio]) ? BaseConst::IMAGE_RATIOS[$ratio] : ['width' => 1600, 'height' => 2848];
  177. }
  178. public function createAnime($data) {
  179. $uid = Site::getUid();
  180. $cpid = Site::getCpid();
  181. $input_art_style = getProp($data, 'art_style');
  182. $file = getProp($data, 'file');
  183. $content = getProp($data, 'content', '');
  184. $bid = getProp($data, 'bid', 0);
  185. $script_id = getProp($data, 'script_id', 0);
  186. $ace_mode = getProp($data, 'ace_mode', 0);
  187. $extra_products = getProp($data, 'products', []);
  188. if (is_string($extra_products)) $extra_products = json_decode($extra_products, true);
  189. if (!is_array($extra_products)) {
  190. Utils::throwError('20003:传入的资产格式不正确');
  191. }
  192. // 替换美术风格
  193. $mappedArtStyle = $this->DeepSeekService->getArtStylePromptByInput($input_art_style);
  194. // 提取文件内容
  195. if ($file) {
  196. $content = $this->DeepSeekService->extractFileContent($file);
  197. if (!$content) {
  198. Utils::throwError('20003:无法提取文件内容,请检查文件格式');
  199. }
  200. } elseif ($script_id) {
  201. $content = $this->DeepSeekService->getContentByScriptId($script_id);
  202. if (!$content) {
  203. Utils::throwError('20003:无法获取剧本内容,请检查剧本');
  204. }
  205. } elseif ($bid) {
  206. $content = $this->DeepSeekService->getContentByBid($bid);
  207. if (!$content) {
  208. Utils::throwError('20003:无法获取书籍内容,请检查书籍');
  209. }
  210. } elseif ($content) {
  211. $content = filterContent($content);
  212. }else {
  213. $content = '';
  214. }
  215. $anime_data = [
  216. 'user_id' => $uid,
  217. 'cpid' => $cpid,
  218. 'anime_name' => '新剧本策划',
  219. 'is_multi' => getProp($data, 'is_multi', 1),
  220. 'content' => $content,
  221. 'art_style_type' => $input_art_style,
  222. 'ace_mode' => $ace_mode,
  223. 'script_id' => $script_id,
  224. 'extra_products' => json_encode($extra_products, 256),
  225. 'created_at' => date('Y-m-d H:i:s'),
  226. 'updated_at' => date('Y-m-d H:i:s'),
  227. ];
  228. // 处理文本模型
  229. $model = getProp($data, 'model');
  230. if (!$model) {
  231. // 用户没有输入,使用默认值
  232. $model = 'deepseek-v4-pro';
  233. }
  234. // 验证模型是否在可用模型表中
  235. if (!DB::table('mp_text_models')->where('model', $model)->where('is_enabled', 1)->exists()) {
  236. $model = 'deepseek-v4-pro';
  237. }
  238. $anime_data['model'] = $model;
  239. if ($mappedArtStyle) $anime_data['art_style'] = $mappedArtStyle;
  240. return DB::table('mp_animes')->insertGetId($anime_data);
  241. }
  242. public function chatList($data) {
  243. $uid = Site::getUid();
  244. $anime_name = getProp($data, 'anime_name');
  245. $query = DB::table('mp_animes')->where('is_deleted', 0)->where('user_id', $uid);
  246. if ($anime_name) {
  247. $query->where('anime_name', 'like', "%$anime_name%");
  248. }
  249. return $query->orderBy('id', 'desc')->paginate();
  250. }
  251. public function chatHistory($data) {
  252. $anime_id = getProp($data, 'anime_id');
  253. $sequence = getProp($data, 'sequence', 0);
  254. if (!$anime_id) Utils::throwError('20003:请选择对话!');
  255. $query = DB::table('mp_anime_records as ar')->leftJoin('mp_anime_episodes as ae', 'ar.episode_id', '=', 'ae.id')->where('ar.anime_id', $anime_id)
  256. ->where('ar.sequence', $sequence)->where('segment_id', 0)->where('act_id', 0)->select('ar.role', 'ar.content', 'ar.created_at', 'ar.episode_id', 'ae.title as episode_title', 'ae.created_at as episode_created_at');
  257. return $query->orderBy('ar.id')->get()->map(function ($value) {
  258. $value = (array)$value;
  259. if ($value['role'] == 'assistant') $value['content'] = filterScriptContent($value['content']);
  260. $value['created_at'] = transDate($value['created_at']);
  261. $value['episode_created_at'] = transDate($value['episode_created_at']);
  262. return $value;
  263. })->toArray();
  264. }
  265. public function batchSetRoleImg($data) {
  266. $episode_id = getProp($data, 'episode_id');
  267. if (!$episode_id) Utils::throwError('1002:请选择分集');
  268. $episode = DB::table('mp_anime_episodes')->where('id', $episode_id)->first();
  269. $roles = json_decode(getProp($data, 'roles'), true) ?: [];
  270. $art_style = getProp($episode, 'art_style');
  271. $anime_id = getProp($episode, 'anime_id');
  272. $anime = DB::table('mp_animes')->where('id', $anime_id)->first();
  273. $art_style_type = getProp($anime, 'art_style_type');
  274. $character_prefix = '';
  275. $scene_prefix = '';
  276. if ($art_style_type) {
  277. $art_style_arr = $this->DeepSeekService->getArtStyleShortPromptByInput($art_style_type);
  278. $character_prefix = isset($art_style_arr['character_prefix']) ? $art_style_arr['character_prefix'] : '';
  279. $scene_prefix = isset($art_style_arr['scene_prefix']) ? $art_style_arr['scene_prefix'] : '';
  280. }
  281. foreach ($roles as &$role) {
  282. $role_name = getProp($role, 'role');
  283. if ($role_name == '旁白') continue;
  284. // 优先使用 pic_prompt,如果没有则使用 description
  285. $pic_prompt = getProp($role, 'pic_prompt');
  286. $description = !empty($pic_prompt) ? trim((string)$pic_prompt) : getProp($role, 'description');
  287. // if ($art_style) $description = "美术风格:\n{$art_style}\n主体描述:{$description}\n图片要求:图片侧重点是人物,不要出现场景或背景,并且只能生成一个人物";
  288. $description = "{$character_prefix}。\n主体描述:{$description}\n超高清,高细节,主体突出,构图合理,画面干净,无场景或背景,单人物,无文字,无水印,无字幕,电影级光影,视觉焦点明确";
  289. // 参考图地址
  290. $ref_img_url = getProp($role, 'url');
  291. if ($ref_img_url) continue; // 已有图片则跳过
  292. // 此处调用AIImageGenerationService的生成图片任务接口: createImageGenerationTask(注意使用默认参数,prompt使用角色描述),并返回任务id
  293. try {
  294. $params = [
  295. 'prompt' => $description,
  296. 'ref_img_urls' => !empty($ref_img_url) ? [$ref_img_url] : []
  297. ];
  298. $task = $this->aiImageGenerationService->createImageGenerationTask($params);
  299. $task_id = $task->id;
  300. if (!$task_id) {
  301. Utils::throwError("20003:角色({$role_name})生成图片失败");
  302. }
  303. $role['task_id'] = $task_id;
  304. $role['task_status'] = 'processing';
  305. } catch (\Exception $e) {
  306. logDB('anime', 'error', "角色({$role_name})生成图片失败", ['error' => $e->getMessage()]);
  307. Utils::throwError("20003:" . $e->getMessage());
  308. }
  309. }
  310. // 保存角色信息
  311. $boolen = DB::table('mp_anime_episodes')->where('id', $episode_id)->update([
  312. 'roles' => json_encode($roles, 256),
  313. 'generate_status' => '执行中',
  314. 'generate_at' => date('Y-m-d H:i:s'),
  315. 'updated_at' => date('Y-m-d H:i:s')
  316. ]);
  317. if (!$boolen) {
  318. Utils::throwError('20003:保存角色信息失败');
  319. }
  320. return $boolen;
  321. }
  322. public function batchSetSceneImg($data) {
  323. $episode_id = getProp($data, 'episode_id');
  324. if (!$episode_id) Utils::throwError('1002:请选择分集');
  325. $episode = DB::table('mp_anime_episodes')->where('id', $episode_id)->first();
  326. $scenes = json_decode(getProp($episode, 'scenes'), true);
  327. $art_style = getProp($episode, 'art_style');
  328. $target_scene = getProp($data, 'target_scene');
  329. $anime_id = getProp($episode, 'anime_id');
  330. $anime = DB::table('mp_animes')->where('id', $anime_id)->first();
  331. $art_style_type = getProp($anime, 'art_style_type');
  332. $character_prefix = '';
  333. $scene_prefix = '';
  334. if ($art_style_type) {
  335. $art_style_arr = $this->DeepSeekService->getArtStyleShortPromptByInput($art_style_type);
  336. $character_prefix = isset($art_style_arr['character_prefix']) ? $art_style_arr['character_prefix'] : '';
  337. $scene_prefix = isset($art_style_arr['scene_prefix']) ? $art_style_arr['scene_prefix'] : '';
  338. }
  339. foreach ($scenes as &$scene) {
  340. $scene_name = getProp($scene, 'scene');
  341. if ($scene_name != $target_scene) continue;
  342. // 优先使用 pic_prompt,如果没有则使用 description
  343. $pic_prompt = getProp($scene, 'pic_prompt');
  344. $description = !empty($pic_prompt) ? trim((string)$pic_prompt) : getProp($scene, 'description');
  345. // if ($art_style) $description = "美术风格:\n{$art_style}\n\n场景描述:{$description}\n图片要求: 图片侧重点是场景,生成的是场景环境图片,不要出现人物(此为第一优先要求)";
  346. $description = "{$scene_prefix}。\n场景描述:{$description}\n无人物,超高清,高细节,主体突出,构图合理,画面干净,无文字,无水印,无字幕,电影级光影,视觉焦点明确";
  347. // 参考图地址
  348. $ref_img_url = getProp($scene, 'url');
  349. if ($ref_img_url) continue; // 已有图片则跳过
  350. // 此处调用AIImageGenerationService的生成图片任务接口: createImageGenerationTask(注意使用默认参数,prompt使用角色描述),并返回任务id
  351. try {
  352. $params = [
  353. 'prompt' => $description,
  354. 'ref_img_urls' => !empty($ref_img_url) ? [$ref_img_url] : []
  355. ];
  356. $task = $this->aiImageGenerationService->createImageGenerationTask($params);
  357. $task_id = $task->id;
  358. if (!$task_id) {
  359. Utils::throwError("20003:场景({$scene_name})生成图片失败");
  360. }
  361. $scene['task_id'] = $task_id;
  362. $scene['task_status'] = 'processing';
  363. } catch (\Exception $e) {
  364. logDB('anime', 'error', "场景({$scene_name})生成图片失败", ['error' => $e->getMessage()]);
  365. Utils::throwError("20003:" . $e->getMessage());
  366. }
  367. }
  368. // 保存场景信息
  369. $boolen = DB::table('mp_anime_episodes')->where('id', $episode_id)->update([
  370. 'scenes' => json_encode($scenes, 256),
  371. 'generate_status' => '执行中',
  372. 'generate_at' => date('Y-m-d H:i:s'),
  373. 'updated_at' => date('Y-m-d H:i:s')
  374. ]);
  375. if (!$boolen) {
  376. Utils::throwError('20003:保存角色信息失败');
  377. }
  378. return $boolen;
  379. }
  380. public function editAnime($data) {
  381. $anime_id = getProp($data, 'anime_id');
  382. $anime_name = trim(getProp($data, 'anime_name'));
  383. // 确认对话名称唯一性
  384. if ($id = DB::table('mp_animes')->where('anime_name', $anime_name)->value('id')) {
  385. if ($id != $anime_id) $anime_name = $anime_name . '_' . date('YmdHis');
  386. }
  387. if (!$anime_id || !$anime_name) {
  388. Utils::throwError('20003:参数异常');
  389. }
  390. return DB::table('mp_animes')->where('id', $anime_id)->update([
  391. 'anime_name' => $anime_name,
  392. 'updated_at' => date('Y-m-d H:i:s')
  393. ]);
  394. // $script_arr =getProp($data, 'script', []);
  395. // if (!$script_arr) Utils::throwError('20003:剧本内容不能为空');
  396. // $start_episode_sequence = getProp($data, 'start_episode_sequence', 1);
  397. // $anime_id = getProp($data, 'anime_id');
  398. // try {
  399. // DB::beginTransaction();
  400. // $table_data = [
  401. // 'intro' => isset($script_arr['intro']) ? $script_arr['intro'] : '',
  402. // 'highlights' => isset($script_arr['highlights']) ? $script_arr['highlights'] : '',
  403. // 'role_relationship' => isset($script_arr['role_relationship']) ? $script_arr['role_relationship'] : '',
  404. // 'core_contradiction' => isset($script_arr['core_contradiction']) ? $script_arr['core_contradiction'] : '',
  405. // 'roles' => isset($script_arr['roles']) ? json_encode($script_arr['roles'], 256) : '',
  406. // 'art_style' => isset($script_arr['art_style']) ? $script_arr['art_style'] : '',
  407. // 'scenes' => isset($script_arr['scenes']) ? json_encode($script_arr['scenes'], 256) : '',
  408. // 'status' => 3,
  409. // 'start_episode_sequence' => $start_episode_sequence,
  410. // 'end_episode_sequence' => $start_episode_sequence + count($script_arr['episodes']) - 1,
  411. // 'episode_num' => count($script_arr['episodes']),
  412. // 'updated_at' => date('Y-m-d H:i:s')
  413. // ];
  414. // // 保存剧本内容
  415. // if (!empty($anime_id)) {
  416. // $boolen = DB::table('mp_animes')->where('id', $anime_id)->update($table_data);
  417. // if (!$boolen) {
  418. // dLog('anime')->info('对话保存失败', $table_data);
  419. // Utils::throwError('20003:对话保存失败');
  420. // }
  421. // }else {
  422. // $table['created_at'] = $table_data['updated_at'];
  423. // $anime_id = DB::table('mp_animes')->insertGetId($table_data);
  424. // if (!$anime_id) {
  425. // dLog('anime')->info('对话保存失败', $table_data);
  426. // Utils::throwError('20003:对话保存失败');
  427. // }
  428. // }
  429. // // 保存分集内容
  430. // // 删除历史分集内容
  431. // $boolen1 = DB::table('mp_anime_episodes')->where('anime_id', $anime_id)->delete();
  432. // $episodes = [];
  433. // $sequence = 1;
  434. // foreach ($script_arr['episodes'] as $episode) {
  435. // $segment_number = 1;
  436. // foreach($episode['segments'] as $segment) {
  437. // $episodes[] = [
  438. // 'anime_id' => $anime_id,
  439. // 'episode_number' => $episode['episode_number'],
  440. // 'title' => $episode['title'],
  441. // // 'content' => $episode['content'],
  442. // 'content' => '',
  443. // 'segment_number' => $segment_number,
  444. // 'segment_content' => $segment['segment_content'],
  445. // 'sequence' => $sequence,
  446. // 'created_at' => date('Y-m-d H:i:s'),
  447. // 'updated_at' => date('Y-m-d H:i:s')
  448. // ];
  449. // $sequence++;
  450. // $segment_number++;
  451. // }
  452. // }
  453. // $boolen2 = DB::table('mp_anime_episodes')->insert($episodes);
  454. // if (!$boolen2) {
  455. // dLog('deepseek')->info('分集内容保存失败', $episodes);
  456. // logDB('deepseek', 'error', '分集内容保存失败', ['episodes_count' => count($episodes)]);
  457. // Utils::throwError('20003:分集内容保存失败');
  458. // }
  459. // } catch (\Exception $e) {
  460. // DB::rollBack();
  461. // Utils::throwError('20003:'.$e->getMessage());
  462. // }
  463. // DB::commit();
  464. // return true;
  465. }
  466. public function delAnime($data) {
  467. $anime_id = getProp($data, 'anime_id');
  468. if (!$anime_id) {
  469. Utils::throwError('20003:请选择剧本');
  470. }
  471. return DB::table('mp_animes')->where('id', $anime_id)->update([
  472. 'is_deleted' => 1,
  473. 'updated_at' => date('Y-m-d H:i:s')
  474. ]);
  475. }
  476. public function animeDetail($data) {
  477. $uid = Site::getUid();
  478. $anime_id = getProp($data, 'anime_id');
  479. $anime = DB::table('mp_animes')->where('id', $anime_id)->where('is_deleted', 0)->where('user_id', $uid)
  480. ->selectRaw('id as anime_id, anime_name, intro, highlights, roles, role_relationship, core_contradiction, art_style, scenes, status, remark, generate_status, created_at, ace_mode, end_episode_sequence')->first();
  481. if (!$anime) Utils::throwError('20003:权限不足');
  482. $anime = (array)$anime;
  483. $anime['roles'] = json_decode($anime['roles']);
  484. $anime['scenes'] = json_decode($anime['scenes']);
  485. // 获取分集信息
  486. $episodes = DB::table('mp_anime_episodes')->where('anime_id', $anime_id)->where('is_default', 1)
  487. ->select('id as episode_id', 'episode_number', 'title', 'is_generated', DB::raw("(select es.img_url from mp_episode_segments as es where es.episode_id = mp_anime_episodes.id order by es.segment_number limit 1) as first_frame_url"))
  488. ->orderBy('episode_number')->get()->map(function ($value) {
  489. return (array)$value;
  490. })->toArray();
  491. $anime['episodes'] = $episodes;
  492. return $anime;
  493. }
  494. public function episodeInfo($data) {
  495. $uid = Site::getUid();
  496. $anime_id = getProp($data, 'anime_id');
  497. $episode_id = getProp($data, 'episode_id');
  498. if (!$anime_id || !$episode_id) {
  499. Utils::throwError('1002:请选择剧集');
  500. }
  501. // 验证用户权限
  502. $anime = DB::table('mp_animes')->where('id', $anime_id)->where('user_id', $uid)->where('is_deleted', 0)->first();
  503. if (!$anime) Utils::throwError('20003:权限不足');
  504. $episode = DB::table('mp_anime_episodes')->where('anime_id', $anime_id)->where('id', $episode_id)->select('id as episode_id', 'anime_id', 'episode_number', 'title', 'intro', 'art_style', 'roles', 'scenes', 'is_generated')->first();
  505. if (!$episode) Utils::throwError('20003:该剧集不存在!');
  506. $episode = (array)$episode;
  507. $episode['roles'] = json_decode($episode['roles'], true);
  508. // foreach($episode['roles'] as &$item) {
  509. // if (isset($item['pic_prompt']) && mb_substr($item['pic_prompt'], 0, 11) != '写实。全景,正面拍摄。') $item['pic_prompt'] = '写实。全景,正面拍摄。'.$item['pic_prompt'];
  510. // }
  511. $episode['scenes'] = json_decode($episode['scenes'], true);
  512. // foreach($episode['scenes'] as &$item) {
  513. // if (isset($item['pic_prompt']) && mb_substr($item['pic_prompt'], 0, 3) != '写实。') $item['pic_prompt'] = '写实。'.$item['pic_prompt'];
  514. // }
  515. // 获取分镜信息
  516. $segments = DB::table('mp_episode_segments')->where('anime_id', $anime_id)->where('episode_id', getProp($episode, 'episode_id'))->orderBy('segment_number')
  517. ->select('*')->get()->map(function ($value) {
  518. return (array)$value;
  519. })->toArray();
  520. // 使用公共方法构建分镜结构
  521. $segmentsStructure = $this->buildEpisodeSegmentsStructure($segments);
  522. $episode['acts'] = $segmentsStructure['acts'];
  523. $episode['total_duration'] = $segmentsStructure['total_duration'];
  524. return $episode;
  525. }
  526. public function episodeInfoForAce($data) {
  527. $anime_id = getProp($data, 'anime_id');
  528. $episode_id = getProp($data, 'episode_id');
  529. if (!$anime_id || !$episode_id) {
  530. Utils::throwError('1002:请选择剧集');
  531. }
  532. $episode = DB::table('mp_anime_episodes')->where('anime_id', $anime_id)->where('id', $episode_id)->select('id as episode_id', 'anime_id', 'episode_number', 'title', 'intro', 'art_style', 'roles', 'scenes', 'props', 'is_generated')->first();
  533. if (!$episode) Utils::throwError('20003:该剧集不存在!');
  534. $episode = (array)$episode;
  535. $episode['roles'] = json_decode($episode['roles'], true);
  536. // foreach($episode['roles'] as &$item) {
  537. // if (isset($item['pic_prompt']) && mb_substr($item['pic_prompt'], 0, 11) != '写实。全景,正面拍摄。') $item['pic_prompt'] = '写实。全景,正面拍摄。'.$item['pic_prompt'];
  538. // }
  539. $episode['scenes'] = json_decode($episode['scenes'], true);
  540. // foreach($episode['scenes'] as &$item) {
  541. // if (isset($item['pic_prompt']) && mb_substr($item['pic_prompt'], 0, 3) != '写实。') $item['pic_prompt'] = '写实。'.$item['pic_prompt'];
  542. // }
  543. $episode['props'] = $episode['props'] ? json_decode($episode['props'], true) : [];
  544. // 获取分镜信息
  545. $segments = DB::table('mp_episode_segments')->where('anime_id', $anime_id)->where('episode_id', getProp($episode, 'episode_id'))->orderBy('act_number')
  546. ->select('*')->get()->map(function ($value) {
  547. return (array)$value;
  548. })->toArray();
  549. $segmentsStructure = $this->buildEpisodeActsStructureForAce($segments);
  550. $episode['acts'] = $segmentsStructure['acts'];
  551. $episode['total_duration'] = $segmentsStructure['total_duration'];
  552. // 获取mp_animes表中的视频参数
  553. $anime = DB::table('mp_animes')->where('id', $anime_id)->first(['video_model', 'video_resolution', 'video_ratio']);
  554. $episode['video_params'] = [
  555. 'video_model' => getProp($anime, 'video_model'),
  556. 'video_resolution' => getProp($anime, 'video_resolution'),
  557. 'ratio' => getProp($anime, 'video_ratio'),
  558. ];
  559. return $episode;
  560. }
  561. public function segmentInfo($data) {
  562. $uid = Site::getUid();
  563. $segment_id = getProp($data, 'segment_id');
  564. if (!$segment_id) {
  565. Utils::throwError('1002:请选择分镜');
  566. }
  567. // 获取分镜信息
  568. $segment = DB::table('mp_episode_segments')->where('segment_id', $segment_id)->first();
  569. // 验证用户权限
  570. if ($segment) {
  571. $anime = DB::table('mp_animes')->where('id', getProp($segment, 'anime_id'))->where('user_id', $uid)->where('is_deleted', 0)->first();
  572. if (!$anime) Utils::throwError('20003:权限不足');
  573. }
  574. $result = [
  575. 'segment_id' => getProp($segment, 'segment_id'),
  576. 'segment_number' => getProp($segment, 'segment_number'),
  577. 'segment_content' => getProp($segment, 'segment_content'),
  578. 'description' => getProp($segment, 'description'),
  579. 'composition' => getProp($segment, 'composition'),
  580. 'camera_movement' => getProp($segment, 'camera_movement'),
  581. 'voice_actor' => getProp($segment, 'voice_actor'),
  582. 'dialogue' => getProp($segment, 'dialogue'),
  583. 'frame_type' => getProp($segment, 'frame_type'),
  584. 'scene' => getProp($segment, 'scene'),
  585. 'characters' => getProp($segment, 'characters'),
  586. 'tail_frame' => getProp($segment, 'tail_frame'),
  587. 'emotion' => getProp($segment, 'emotion'),
  588. 'emotion_type' => getProp($segment, 'emotion_type'),
  589. 'gender' => getProp($segment, 'gender'),
  590. 'speed_ratio' => getProp($segment, 'speed_ratio'),
  591. 'loudness_ratio' => getProp($segment, 'loudness_ratio'),
  592. 'emotion_scale' => getProp($segment, 'emotion_scale'),
  593. 'pitch' => getProp($segment, 'pitch'),
  594. 'voice_name' => getProp($segment, 'voice_name'),
  595. 'voice_type' => getProp($segment, 'voice_type'),
  596. 'voice_audio_url' => getProp($segment, 'voice_audio_url'),
  597. 'img_url' => getProp($segment, 'img_url'),
  598. 'video_url' => getProp($segment, 'video_url'),
  599. 'last_frame_url' => getProp($segment, 'last_frame_url'),
  600. ];
  601. return $result;
  602. }
  603. public function copyEpisodeVersion($data) {
  604. $episode_id = getProp($data, 'episode_id');
  605. $uid = Site::getUid();
  606. $cpid = Site::getCpid();
  607. $episode = DB::table('mp_anime_episodes')->where('id', $episode_id)->first();
  608. if (!$episode) Utils::throwError('20003:该剧集不存在');
  609. $episode = (array)$episode;
  610. $anime_id = $episode['anime_id'];
  611. $episode_number = $episode['episode_number'];
  612. $count = DB::table('mp_anime_episodes')->where('anime_id', $anime_id)->where('episode_number', $episode_number)->count('id');
  613. $sequence = $count + 1;
  614. unset($episode['id']);
  615. $now = date('Y-m-d H:i:s');
  616. $episode['created_at'] = $now;
  617. $episode['updated_at'] = $now;
  618. $episode['is_default'] = 1;
  619. // 获取版本中含有"(副本"字样的个数
  620. $copy_count = DB::table('mp_anime_episodes')->where('anime_id', $anime_id)->where('episode_number', $episode_number)->where('title', 'like', '%(副本%')->count('id');
  621. $episode['title'] = $copy_count > 0 ? $episode['title']."(副本{$copy_count})" : $episode['title']."(副本)"; // 生成带(副本)字样的标题
  622. $episode['sequence'] = $sequence;
  623. $episode['is_generated'] = 0;
  624. $episode['cpid'] = $cpid;
  625. // 获取ace_mode
  626. $ace_mode = DB::table('mp_animes')->where('id', $anime_id)->value('ace_mode');
  627. try {
  628. DB::beginTransaction();
  629. DB::table('mp_anime_episodes')->where('anime_id', $anime_id)->where('episode_number', $episode_number)->update(['is_default' => 0, 'updated_at'=>$now]);
  630. // 新增副本
  631. $new_episode_id = DB::table('mp_anime_episodes')->insertGetId($episode);
  632. if (!$new_episode_id) {
  633. Utils::throwError('20003:创建副本失败!');
  634. }
  635. // 获取分镜数据并准备插入
  636. $segments_for_insert = DB::table('mp_episode_segments')
  637. ->select('anime_id', 'episode_number', 'act_number', 'act_title', 'act_duration', 'act_content', 'segment_number', 'segment_content', 'description', 'composition', 'camera_movement', 'voice_actor', 'dialogue', 'frame_type', 'scene', 'characters', 'tail_frame', 'voice_name', 'voice_type', 'voice_audio_url', 'emotion', 'emotion_type', 'gender', 'speed_ratio', 'loudness_ratio', 'emotion_scale', 'pitch')
  638. ->where('episode_id', $episode_id)->orderBy('segment_number')->get()->map(function($item) use ($new_episode_id,$ace_mode) {
  639. $item = (array)$item;
  640. $item['episode_id'] = $new_episode_id;
  641. if ((int)$ace_mode !== 1) $item['segment_id'] = date('YmdHis').mt_rand(1000,9999).str_pad($item['segment_number'], 3, "0", STR_PAD_LEFT);
  642. $item['created_at'] = $item['updated_at'] = date('Y-m-d H:i:s');
  643. return $item;
  644. })->toArray();
  645. // 写入分镜数据
  646. $boolen2 = DB::table('mp_episode_segments')->insert($segments_for_insert);
  647. if (!$boolen2) {
  648. Utils::throwError('20003:写入分镜数据失败!');
  649. }
  650. // 写入对话历史
  651. $records = [
  652. [
  653. 'uid' => $uid,
  654. 'anime_id' => $anime_id,
  655. 'role' => 'user',
  656. 'content' => '创建副本',
  657. 'sequence' => $episode_number,
  658. 'episode_id' => $new_episode_id,
  659. 'created_at' => $now,
  660. 'updated_at' => $now
  661. ],
  662. [
  663. 'uid' => $uid,
  664. 'anime_id' => $anime_id,
  665. 'role' => 'assistant',
  666. 'content' => '好的,已为您创建副本',
  667. 'sequence' => $episode_number,
  668. 'episode_id' => $new_episode_id,
  669. 'created_at' => $now,
  670. 'updated_at' => $now
  671. ]
  672. ];
  673. $boolen3 = DB::table('mp_anime_records')->insert($records);
  674. if (!$boolen3) {
  675. Utils::throwError('20003:对话记录保存失败');
  676. }
  677. }catch (\Exception $e) {
  678. DB::rollBack();
  679. Utils::throwError('20003:'.$e->getMessage());
  680. }
  681. DB::commit();
  682. // 构建与 episodeInfo 方法一致的返回数据结构
  683. $result = [
  684. 'episode_id' => $new_episode_id,
  685. 'anime_id' => $anime_id,
  686. 'episode_number' => $episode_number,
  687. 'title' => $episode['title'],
  688. 'intro' => $episode['intro'],
  689. 'art_style' => $episode['art_style'],
  690. 'roles' => json_decode($episode['roles'], true),
  691. 'scenes' => json_decode($episode['scenes'], true),
  692. 'is_generated' => (int)$episode['is_generated']
  693. ];
  694. if ((int)$ace_mode === 1) {
  695. // 获取分镜信息
  696. $segments = DB::table('mp_episode_segments')->where('anime_id', $anime_id)->where('episode_id', $new_episode_id)->orderBy('act_number')
  697. ->select('*')->get()->map(function ($value) {
  698. return (array)$value;
  699. })->toArray();
  700. $segmentsStructure = $this->buildEpisodeActsStructureForAce($segments);
  701. }else {
  702. // 复用已有的分镜数据,按 act 分组(避免重复查询数据库)
  703. $segmentsStructure = $this->buildEpisodeSegmentsStructure($segments_for_insert);
  704. }
  705. $result['acts'] = $segmentsStructure['acts'];
  706. $result['total_duration'] = $segmentsStructure['total_duration'];
  707. return $result;
  708. }
  709. public function episodeVersions($data) {
  710. $anime_id = getProp($data, 'anime_id');
  711. $episode_id = getProp($data, 'episode_id');
  712. if (!$anime_id || !$episode_id) {
  713. Utils::throwError('1002:请选择剧集');
  714. }
  715. $episode_number = DB::table('mp_anime_episodes')->where('anime_id', $anime_id)->where('id', $episode_id)->value('episode_number');
  716. $episodes = DB::table('mp_anime_episodes')->where('anime_id', $anime_id)->where('episode_number', $episode_number)->select('id as episode_id', 'anime_id', 'episode_number', 'sequence', 'title', 'intro', 'art_style', 'roles', 'scenes', 'is_generated')->orderBy('sequence', 'desc')->get()->map(function($value) {
  717. return (array)$value;
  718. })->toArray();
  719. if (!$episodes) Utils::throwError('20003:该剧集不存在!');
  720. foreach($episodes as &$episode) {
  721. $episode['version'] = 'V'.$episode['sequence'];
  722. $episode['roles'] = json_decode($episode['roles'], true);
  723. $episode['scenes'] = json_decode($episode['scenes'], true);
  724. // 获取分镜信息
  725. $segments = DB::table('mp_episode_segments')->where('anime_id', $anime_id)->where('episode_id', getProp($episode, 'episode_id'))->orderBy('segment_number')
  726. ->select('*')->get()->map(function ($value) {
  727. return (array)$value;
  728. })->toArray();
  729. // 使用公共方法构建分镜结构
  730. $segmentsStructure = $this->buildEpisodeSegmentsStructure($segments);
  731. $episode['acts'] = $segmentsStructure['acts'];
  732. $episode['total_duration'] = $segmentsStructure['total_duration'];
  733. }
  734. return $episodes;
  735. }
  736. public function bindEpisodeVersion($data) {
  737. $episode_id = getProp($data, 'episode_id');
  738. $episode = DB::table('mp_anime_episodes')->where('id', $episode_id)->first();
  739. if (!$episode) Utils::throwError('20003:该剧集不存在');
  740. $episode = (array)$episode;
  741. if ((int)$episode['is_default'] === 1) return true;
  742. try {
  743. DB::beginTransaction();
  744. // 移除is_default标志
  745. $boolen = DB::table('mp_anime_episodes')->where('anime_id', $episode['anime_id'])->where('episode_number', $episode['episode_number'])->update(['is_default' => 0, 'updated_at'=>date('Y-m-d H:i:s')]);
  746. if (!$boolen) {
  747. Utils::throwError('20003:更新失败!');
  748. }
  749. // 绑定副本
  750. $boolen2 = DB::table('mp_anime_episodes')->where('id', $episode_id)->update(['is_default' => 1, 'updated_at'=>date('Y-m-d H:i:s')]);
  751. if (!$boolen2) {
  752. Utils::throwError('20003:绑定失败!');
  753. }
  754. }catch (\Exception $e) {
  755. DB::rollBack();
  756. Utils::throwError('20003:'.$e->getMessage());
  757. }
  758. DB::commit();
  759. return true;
  760. }
  761. public function chatChangeImg($data) {
  762. $segment_id = getProp($data, 'segment_id');
  763. $type = getProp($data, 'type', 1); // 类型: 1.对话改图 2.图片生成
  764. $prompt = getProp($data, 'prompt');
  765. if (!$prompt || !$segment_id) {
  766. Utils::throwError('1002:请输入提示词,并且选择分镜');
  767. }
  768. $segment = DB::table("mp_episode_segments")->where('segment_id', $segment_id)->first();
  769. if (!$segment) Utils::throwError('20003:该分镜不存在!');
  770. if ((int)$type === 1) $ref_img_url = getProp($segment, 'img_url');
  771. else $ref_img_url = '';
  772. // $ref_img_url = '';
  773. if (empty($prompt)) {
  774. if (empty($ref_img_url)) {
  775. $prompt = getProp($segment, 'segment_content');
  776. }else {
  777. $prompt = '请根据图片生成';
  778. }
  779. }
  780. $anime_id = getProp($segment, 'anime_id');
  781. $episode_id = getProp($segment, 'episode_id');
  782. $episode_number = getProp($segment, 'episode_number');
  783. $episode = DB::table('mp_anime_episodes')->where('id', $episode_id)->first();
  784. $ratio = getProp($data, 'ratio');
  785. if (!$ratio) {
  786. $ratio = getProp($episode, 'ratio');
  787. if (!$ratio) $ratio = '9:16';
  788. }
  789. $art_style = getProp($episode, 'art_style');
  790. if ($art_style) {
  791. $prompt = "美术风格:{$art_style}\n{$prompt}";
  792. }
  793. $dimensions = $this->getRatioDimensions($ratio);
  794. $width = $dimensions['width'];
  795. $height = $dimensions['height'];
  796. try {
  797. $params = [
  798. 'alias_segment_id' => $segment_id,
  799. 'prompt' => $prompt,
  800. 'ref_img_urls' => !empty($ref_img_url) ? [$ref_img_url] : [],
  801. 'width' => $width,
  802. 'height' => $height
  803. ];
  804. // 优化提示词(不要生成字幕)
  805. $params['prompt'] = "前置要求:图片中不要带有任何对话台词或字幕信息\n".$params['prompt'];
  806. $task = $this->aiImageGenerationService->createImageGenerationTask($params);
  807. $task_id = $task->id;
  808. if (!$task_id) {
  809. Utils::throwError("20003:生成图片失败");
  810. }
  811. // 更新任务ID
  812. $boolen = DB::table('mp_episode_segments')->where('segment_id', $segment_id)->update(['pic_task_id' => $task_id, 'pic_task_status' => '生成中', 'updated_at' => date('Y-m-d H:i:s')]);
  813. if (!$boolen) Utils::throwError('20003:更新任务ID失败');
  814. } catch (\Exception $e) {
  815. Utils::throwError("20003:" . $e->getMessage());
  816. }
  817. // 创建任务之后先暂停10s等待异步任务完成
  818. sleep(10);
  819. $img_url = $this->loopGetPicTaskResult($task_id);
  820. if (!$img_url) Utils::throwError('20003:图片生成中,请稍后刷新');
  821. // 图片生成后新增对话记录
  822. try {
  823. $uid = Site::getUid();
  824. $now = date('Y-m-d H:i:s');
  825. // 使用AI反推图片提示词
  826. $pic_prompt = $this->generateImagePromptFromUrl($img_url);
  827. // 保存对话记录
  828. $records = [
  829. [
  830. 'uid' => $uid,
  831. 'anime_id' => $anime_id,
  832. 'sequence' => $episode_number,
  833. 'role' => 'user',
  834. 'content' => $prompt,
  835. 'segment_id' => $segment_id,
  836. 'image_url' => '',
  837. 'created_at' => $now,
  838. 'updated_at' => $now
  839. ],
  840. [
  841. 'uid' => $uid,
  842. 'anime_id' => $anime_id,
  843. 'sequence' => $episode_number,
  844. 'role' => 'assistant',
  845. 'content' => $pic_prompt,
  846. 'segment_id' => $segment_id,
  847. 'image_url' => $img_url,
  848. 'created_at' => $now,
  849. 'updated_at' => $now
  850. ]
  851. ];
  852. DB::table('mp_anime_records')->insert($records);
  853. } catch (\Exception $e) {
  854. // 记录日志但不影响主流程
  855. dLog('anime')->error('保存对话记录失败: ' . $e->getMessage(), [
  856. 'segment_id' => $segment_id,
  857. 'img_url' => $img_url
  858. ]);
  859. logDB('anime', 'error', '保存对话记录失败', [
  860. 'segment_id' => $segment_id,
  861. 'img_url' => $img_url,
  862. 'error' => $e->getMessage()
  863. ]);
  864. }
  865. return $img_url;
  866. }
  867. public function segmentChatHistory($data) {
  868. $segment_id = getProp($data, 'segment_id');
  869. if (!$segment_id) Utils::throwError('20003:请选择分镜!');
  870. $query = DB::table('mp_anime_records')->where('segment_id', $segment_id)->select('role', 'content', 'segment_id', 'image_url', 'video_url', 'created_at');
  871. $chat = $query->orderBy('id')->get()->map(function ($value) {
  872. $value = (array)$value;
  873. $value['created_at'] = transDate($value['created_at']);
  874. return $value;
  875. })->toArray();
  876. // 获取历史图片
  877. $url = [];
  878. $pic_history = DB::table('mp_generate_pic_tasks')->where('alias_segment_id', $segment_id)->where('status', 'success')->orderBy('created_at', 'desc')->get();
  879. foreach($pic_history as $task) {
  880. $result_url = getProp($task, 'result_url');
  881. if (is_json($result_url)) {
  882. $url = array_merge($url, json_decode($result_url, true));
  883. }else {
  884. $url[] = $result_url;
  885. }
  886. }
  887. // 获取历史视频
  888. $video_history = DB::table('mp_generate_video_tasks')->where('alias_segment_id', $segment_id)->where('status', 'success')->orderBy('created_at', 'desc')->get();
  889. foreach($video_history as $task) {
  890. $result_url = getProp($task, 'compressed_url');
  891. if (is_json($result_url)) {
  892. $url = array_merge($url, json_decode($result_url, true));
  893. }else {
  894. $url[] = $result_url;
  895. }
  896. }
  897. return compact('chat', 'url');
  898. }
  899. public function changeEpisodeRoles($data) {
  900. $anime_id = getProp($data, 'anime_id');
  901. $episode_id = getProp($data, 'episode_id');
  902. $target_roles = getProp($data, 'roles');
  903. $is_deleted = getProp($data, 'is_deleted', 0);
  904. // 参数验证
  905. if (!$anime_id) Utils::throwError('20003:请提供动漫ID');
  906. if (!$episode_id) Utils::throwError('20003:请提供剧集ID');
  907. if (!$target_roles) Utils::throwError('20003:请提供角色信息');
  908. // 验证剧集是否存在
  909. $episode = DB::table('mp_anime_episodes')
  910. ->where('anime_id', $anime_id)
  911. ->where('id', $episode_id)
  912. ->first();
  913. if (!$episode) Utils::throwError('20003:该剧集不存在');
  914. $roles = json_decode(getProp($episode, 'roles'), true);
  915. // 获取anime信息,检查是否有关联的script_id
  916. $anime = DB::table('mp_animes')->where('id', $anime_id)->first();
  917. if (!$anime) Utils::throwError('20003:动漫不存在');
  918. $script_id = getProp($anime, 'script_id');
  919. $episode_number = getProp($episode, 'episode_number', 1);
  920. $uid = Site::getUid();
  921. $cpid = Site::getCpid();
  922. try {
  923. $target_role_name = getProp($target_roles, 'role');
  924. // 如果是删除操作
  925. if ($is_deleted == 1) {
  926. // 从角色列表中移除该角色
  927. $roles = array_values(array_filter($roles, function($role) use ($target_role_name) {
  928. return getProp($role, 'role') !== $target_role_name;
  929. }));
  930. // 更新角色列表
  931. $result = DB::table('mp_anime_episodes')
  932. ->where('anime_id', $anime_id)
  933. ->where('id', $episode_id)
  934. ->update([
  935. 'roles' => json_encode($roles, 256),
  936. 'updated_at' => date('Y-m-d H:i:s')
  937. ]);
  938. if ($result === false) {
  939. Utils::throwError('20003:删除角色失败');
  940. }
  941. } else {
  942. // 新增或更新操作
  943. $role_found = false;
  944. $is_new_role = false;
  945. // 查找并更新已存在的角色
  946. foreach($roles as &$role) {
  947. if (getProp($role, 'role') === $target_role_name) {
  948. $role = $target_roles;
  949. $role_found = true;
  950. break;
  951. }
  952. }
  953. // 如果角色不存在,则新增
  954. if (!$role_found) {
  955. $roles[] = $target_roles;
  956. $is_new_role = true;
  957. }
  958. // 更新角色列表
  959. $result = DB::table('mp_anime_episodes')
  960. ->where('anime_id', $anime_id)
  961. ->where('id', $episode_id)
  962. ->update([
  963. 'roles' => json_encode($roles, 256),
  964. 'updated_at' => date('Y-m-d H:i:s')
  965. ]);
  966. if ($result === false) {
  967. Utils::throwError('20003:更新角色列表失败');
  968. }
  969. // 同步更新分镜表中对应主体的音色信息
  970. $voice_name = getProp($target_roles, 'voice_name');
  971. $voice_type = getProp($target_roles, 'voice_type');
  972. $voice_audio_url = getProp($target_roles, 'voice_audio_url');
  973. DB::table('mp_episode_segments')
  974. ->where('anime_id', $anime_id)
  975. ->where('episode_id', $episode_id)
  976. ->where('voice_actor', $target_role_name)
  977. ->update([
  978. 'voice_name' => $voice_name,
  979. 'voice_type' => $voice_type,
  980. 'voice_audio_url' => $voice_audio_url,
  981. 'updated_at' => date('Y-m-d H:i:s')
  982. ]);
  983. // 如果有关联的script_id,则同步到mp_products表
  984. if ($script_id) {
  985. // 查询剧本信息
  986. $script = DB::table('mp_scripts')
  987. ->where('id', $script_id)
  988. ->where('is_deleted', 0)
  989. ->first();
  990. if ($script) {
  991. $script_name = $script->script_name ?? 'script_' . $script_id;
  992. $product_name = getProp($target_roles, 'role');
  993. $pic_prompt = getProp($target_roles, 'pic_prompt', '');
  994. $url = getProp($target_roles, 'url', '');
  995. $product_type = 1; // 1=角色
  996. // 查找或创建以script_name命名的文件夹
  997. $folder = DB::table('mp_products')
  998. ->where('cpid', $cpid)
  999. ->where('type', 2) // 文件夹类型
  1000. ->where('product', $product_type) // 角色类型
  1001. ->where('product_name', $script_name)
  1002. ->where('parent_id', 0)
  1003. ->where('is_deleted', 0)
  1004. ->first();
  1005. if (!$folder) {
  1006. // 创建文件夹
  1007. $folder_id = DB::table('mp_products')->insertGetId([
  1008. 'user_id' => $uid,
  1009. 'cpid' => $cpid,
  1010. 'type' => 2, // 文件夹
  1011. 'product' => $product_type, // 角色类型
  1012. 'parent_id' => 0,
  1013. 'level' => 1,
  1014. 'product_name' => $script_name,
  1015. 'sort_order' => time(),
  1016. 'is_deleted' => 0,
  1017. 'created_at' => date('Y-m-d H:i:s'),
  1018. 'updated_at' => date('Y-m-d H:i:s')
  1019. ]);
  1020. } else {
  1021. $folder_id = $folder->id;
  1022. }
  1023. // 查找该文件夹下是否已存在同名资产
  1024. $existing_product = DB::table('mp_products')
  1025. ->where('cpid', $cpid)
  1026. ->where('type', 1) // 资产类型
  1027. ->where('product', $product_type)
  1028. ->where('parent_id', $folder_id)
  1029. ->where('product_name', $product_name)
  1030. ->where('is_deleted', 0)
  1031. ->first();
  1032. if ($existing_product) {
  1033. // 更新已存在的资产
  1034. $updateData = [
  1035. 'pic_task_status' => '生成成功',
  1036. ];
  1037. if ($pic_prompt) $updateData['pic_prompt'] = $pic_prompt;
  1038. if ($url) $updateData['url'] = $url;
  1039. // 处理versions字段
  1040. $versions = getProp($target_roles, 'versions', []);
  1041. if ($versions && is_array($versions)) {
  1042. $updateData['versions'] = json_encode($versions, 256);
  1043. }
  1044. $updateData['updated_at'] = date('Y-m-d H:i:s');
  1045. DB::table('mp_products')
  1046. ->where('id', $existing_product->id)
  1047. ->update($updateData);
  1048. $product_id = $existing_product->id;
  1049. } else {
  1050. // 创建新资产
  1051. $versions = getProp($target_roles, 'versions', []);
  1052. $product_id = DB::table('mp_products')->insertGetId([
  1053. 'user_id' => $uid,
  1054. 'cpid' => $cpid,
  1055. 'type' => 1, // 资产
  1056. 'product' => $product_type, // 角色
  1057. 'parent_id' => $folder_id,
  1058. 'level' => 2,
  1059. 'product_name' => $product_name,
  1060. 'url' => $url,
  1061. 'pic_prompt' => $pic_prompt,
  1062. 'versions' => is_array($versions) ? json_encode($versions, 256) : '[]',
  1063. 'sort_order' => time(),
  1064. 'is_deleted' => 0,
  1065. 'pic_task_status' => '生成成功',
  1066. 'created_at' => date('Y-m-d H:i:s'),
  1067. 'updated_at' => date('Y-m-d H:i:s')
  1068. ]);
  1069. }
  1070. // 建立或更新绑定关系
  1071. $existing_mapping = DB::table('mp_script_product_mappings')
  1072. ->where('script_id', $script_id)
  1073. ->where('product_id', $product_id)
  1074. ->where('episode_number', $episode_number)
  1075. ->first();
  1076. if (!$existing_mapping) {
  1077. // 创建绑定关系
  1078. DB::table('mp_script_product_mappings')->insert([
  1079. 'script_id' => $script_id,
  1080. 'product_id' => $product_id,
  1081. 'episode_number' => $episode_number,
  1082. 'created_at' => date('Y-m-d H:i:s'),
  1083. 'updated_at' => date('Y-m-d H:i:s')
  1084. ]);
  1085. }
  1086. }
  1087. }
  1088. }
  1089. } catch (\Exception $e) {
  1090. dLog('anime')->error('更新剧集角色失败', [
  1091. 'anime_id' => $anime_id,
  1092. 'episode_id' => $episode_id,
  1093. 'error' => $e->getMessage()
  1094. ]);
  1095. Utils::throwError('20003:更新角色列表失败 ' . $e->getMessage());
  1096. }
  1097. return true;
  1098. }
  1099. public function changeEpisodeScenes($data) {
  1100. $anime_id = getProp($data, 'anime_id');
  1101. $episode_id = getProp($data, 'episode_id');
  1102. $target_scenes = getProp($data, 'scenes');
  1103. $is_deleted = getProp($data, 'is_deleted', 0);
  1104. // 参数验证
  1105. if (!$anime_id) Utils::throwError('20003:请提供动漫ID');
  1106. if (!$episode_id) Utils::throwError('20003:请提供剧集ID');
  1107. if (!$target_scenes) Utils::throwError('20003:请提供场景信息');
  1108. // 验证剧集是否存在
  1109. $episode = DB::table('mp_anime_episodes')
  1110. ->where('anime_id', $anime_id)
  1111. ->where('id', $episode_id)
  1112. ->first();
  1113. if (!$episode) Utils::throwError('20003:该剧集不存在');
  1114. $scenes = json_decode(getProp($episode, 'scenes'), true);
  1115. // 获取anime信息,检查是否有关联的script_id
  1116. $anime = DB::table('mp_animes')->where('id', $anime_id)->first();
  1117. if (!$anime) Utils::throwError('20003:动漫不存在');
  1118. $script_id = getProp($anime, 'script_id');
  1119. $episode_number = getProp($episode, 'episode_number', 1);
  1120. $uid = Site::getUid();
  1121. $cpid = Site::getCpid();
  1122. try {
  1123. $target_scene_name = getProp($target_scenes, 'scene');
  1124. // 如果是删除操作
  1125. if ($is_deleted == 1) {
  1126. // 从场景列表中移除该场景
  1127. $scenes = array_values(array_filter($scenes, function($scene) use ($target_scene_name) {
  1128. return getProp($scene, 'scene') !== $target_scene_name;
  1129. }));
  1130. // 更新场景列表
  1131. $result = DB::table('mp_anime_episodes')
  1132. ->where('anime_id', $anime_id)
  1133. ->where('id', $episode_id)
  1134. ->update([
  1135. 'scenes' => json_encode($scenes, 256),
  1136. 'updated_at' => date('Y-m-d H:i:s')
  1137. ]);
  1138. if ($result === false) {
  1139. Utils::throwError('20003:删除场景失败');
  1140. }
  1141. } else {
  1142. // 新增或更新操作
  1143. $scene_found = false;
  1144. $is_new_scene = false;
  1145. // 查找并更新已存在的场景
  1146. foreach($scenes as &$scene) {
  1147. if (getProp($scene, 'scene') === $target_scene_name) {
  1148. $scene = $target_scenes;
  1149. $scene_found = true;
  1150. break;
  1151. }
  1152. }
  1153. // 如果场景不存在,则新增
  1154. if (!$scene_found) {
  1155. $scenes[] = $target_scenes;
  1156. $is_new_scene = true;
  1157. }
  1158. // 更新场景列表
  1159. $result = DB::table('mp_anime_episodes')
  1160. ->where('anime_id', $anime_id)
  1161. ->where('id', $episode_id)
  1162. ->update([
  1163. 'scenes' => json_encode($scenes, 256),
  1164. 'updated_at' => date('Y-m-d H:i:s')
  1165. ]);
  1166. if ($result === false) {
  1167. Utils::throwError('20003:更新场景列表失败');
  1168. }
  1169. // 如果有关联的script_id,则同步到mp_products表
  1170. if ($script_id) {
  1171. // 查询剧本信息
  1172. $script = DB::table('mp_scripts')
  1173. ->where('id', $script_id)
  1174. ->where('is_deleted', 0)
  1175. ->first();
  1176. if ($script) {
  1177. $script_name = $script->script_name ?? 'script_' . $script_id;
  1178. $product_name = getProp($target_scenes, 'scene');
  1179. $pic_prompt = getProp($target_scenes, 'pic_prompt', '');
  1180. $url = getProp($target_scenes, 'url', '');
  1181. $product_type = 2; // 2=场景
  1182. // 查找或创建以script_name命名的文件夹
  1183. $folder = DB::table('mp_products')
  1184. ->where('cpid', $cpid)
  1185. ->where('type', 2) // 文件夹类型
  1186. ->where('product', $product_type) // 场景类型
  1187. ->where('product_name', $script_name)
  1188. ->where('parent_id', 0)
  1189. ->where('is_deleted', 0)
  1190. ->first();
  1191. if (!$folder) {
  1192. // 创建文件夹
  1193. $folder_id = DB::table('mp_products')->insertGetId([
  1194. 'user_id' => $uid,
  1195. 'cpid' => $cpid,
  1196. 'type' => 2, // 文件夹
  1197. 'product' => $product_type, // 场景类型
  1198. 'parent_id' => 0,
  1199. 'level' => 1,
  1200. 'product_name' => $script_name,
  1201. 'sort_order' => time(),
  1202. 'is_deleted' => 0,
  1203. 'created_at' => date('Y-m-d H:i:s'),
  1204. 'updated_at' => date('Y-m-d H:i:s')
  1205. ]);
  1206. } else {
  1207. $folder_id = $folder->id;
  1208. }
  1209. // 查找该文件夹下是否已存在同名资产
  1210. $existing_product = DB::table('mp_products')
  1211. ->where('cpid', $cpid)
  1212. ->where('type', 1) // 资产类型
  1213. ->where('product', $product_type)
  1214. ->where('parent_id', $folder_id)
  1215. ->where('product_name', $product_name)
  1216. ->where('is_deleted', 0)
  1217. ->first();
  1218. if ($existing_product) {
  1219. // 更新已存在的资产
  1220. $updateData = [
  1221. 'pic_task_status' => '生成成功'
  1222. ];
  1223. if ($pic_prompt) $updateData['pic_prompt'] = $pic_prompt;
  1224. if ($url) $updateData['url'] = $url;
  1225. // 处理versions字段
  1226. $versions = getProp($target_scenes, 'versions', []);
  1227. if ($versions && is_array($versions)) {
  1228. $updateData['versions'] = json_encode($versions, 256);
  1229. }
  1230. $updateData['updated_at'] = date('Y-m-d H:i:s');
  1231. DB::table('mp_products')
  1232. ->where('id', $existing_product->id)
  1233. ->update($updateData);
  1234. $product_id = $existing_product->id;
  1235. } else {
  1236. // 创建新资产
  1237. $versions = getProp($target_scenes, 'versions', []);
  1238. $product_id = DB::table('mp_products')->insertGetId([
  1239. 'user_id' => $uid,
  1240. 'cpid' => $cpid,
  1241. 'type' => 1, // 资产
  1242. 'product' => $product_type, // 场景
  1243. 'parent_id' => $folder_id,
  1244. 'level' => 2,
  1245. 'product_name' => $product_name,
  1246. 'url' => $url,
  1247. 'pic_prompt' => $pic_prompt,
  1248. 'versions' => is_array($versions) ? json_encode($versions, 256) : '[]',
  1249. 'sort_order' => time(),
  1250. 'is_deleted' => 0,
  1251. 'pic_task_status' => '生成成功',
  1252. 'created_at' => date('Y-m-d H:i:s'),
  1253. 'updated_at' => date('Y-m-d H:i:s')
  1254. ]);
  1255. }
  1256. // 建立或更新绑定关系
  1257. $existing_mapping = DB::table('mp_script_product_mappings')
  1258. ->where('script_id', $script_id)
  1259. ->where('product_id', $product_id)
  1260. ->where('episode_number', $episode_number)
  1261. ->first();
  1262. if (!$existing_mapping) {
  1263. // 创建绑定关系
  1264. DB::table('mp_script_product_mappings')->insert([
  1265. 'script_id' => $script_id,
  1266. 'product_id' => $product_id,
  1267. 'episode_number' => $episode_number,
  1268. 'created_at' => date('Y-m-d H:i:s'),
  1269. 'updated_at' => date('Y-m-d H:i:s')
  1270. ]);
  1271. }
  1272. }
  1273. }
  1274. }
  1275. } catch (\Exception $e) {
  1276. dLog('anime')->error('更新剧集场景失败', [
  1277. 'anime_id' => $anime_id,
  1278. 'episode_id' => $episode_id,
  1279. 'error' => $e->getMessage()
  1280. ]);
  1281. Utils::throwError('20003:更新场景列表失败 ' . $e->getMessage());
  1282. }
  1283. return true;
  1284. }
  1285. public function changeEpisodeProps($data) {
  1286. $anime_id = getProp($data, 'anime_id');
  1287. $episode_id = getProp($data, 'episode_id');
  1288. $target_props = getProp($data, 'props');
  1289. $is_deleted = getProp($data, 'is_deleted', 0);
  1290. // 参数验证
  1291. if (!$anime_id) Utils::throwError('20003:请提供动漫ID');
  1292. if (!$episode_id) Utils::throwError('20003:请提供剧集ID');
  1293. if (!$target_props) Utils::throwError('20003:请提供道具信息');
  1294. // 验证剧集是否存在
  1295. $episode = DB::table('mp_anime_episodes')
  1296. ->where('anime_id', $anime_id)
  1297. ->where('id', $episode_id)
  1298. ->first();
  1299. if (!$episode) Utils::throwError('20003:该剧集不存在');
  1300. $props = json_decode(getProp($episode, 'props'), true);
  1301. // 获取anime信息,检查是否有关联的script_id
  1302. $anime = DB::table('mp_animes')->where('id', $anime_id)->first();
  1303. if (!$anime) Utils::throwError('20003:动漫不存在');
  1304. $script_id = getProp($anime, 'script_id');
  1305. $episode_number = getProp($episode, 'episode_number', 1);
  1306. $uid = Site::getUid();
  1307. $cpid = Site::getCpid();
  1308. try {
  1309. $target_prop_name = getProp($target_props, 'prop');
  1310. // 如果是删除操作
  1311. if ($is_deleted == 1) {
  1312. // 从道具列表中移除该道具
  1313. $props = array_values(array_filter($props, function($prop) use ($target_prop_name) {
  1314. return getProp($prop, 'prop') !== $target_prop_name;
  1315. }));
  1316. // 更新道具列表
  1317. $result = DB::table('mp_anime_episodes')
  1318. ->where('anime_id', $anime_id)
  1319. ->where('id', $episode_id)
  1320. ->update([
  1321. 'props' => json_encode($props, 256),
  1322. 'updated_at' => date('Y-m-d H:i:s')
  1323. ]);
  1324. if ($result === false) {
  1325. Utils::throwError('20003:删除道具失败');
  1326. }
  1327. } else {
  1328. // 新增或更新操作
  1329. $prop_found = false;
  1330. $is_new_prop = false;
  1331. // 查找并更新已存在的道具
  1332. foreach($props as &$prop) {
  1333. if (getProp($prop, 'prop') === $target_prop_name) {
  1334. $prop = $target_props;
  1335. $prop_found = true;
  1336. break;
  1337. }
  1338. }
  1339. // 如果道具不存在,则新增
  1340. if (!$prop_found) {
  1341. $props[] = $target_props;
  1342. $is_new_prop = true;
  1343. }
  1344. // 更新道具列表
  1345. $result = DB::table('mp_anime_episodes')
  1346. ->where('anime_id', $anime_id)
  1347. ->where('id', $episode_id)
  1348. ->update([
  1349. 'props' => json_encode($props, 256),
  1350. 'updated_at' => date('Y-m-d H:i:s')
  1351. ]);
  1352. if ($result === false) {
  1353. Utils::throwError('20003:更新道具列表失败');
  1354. }
  1355. // 如果有关联的script_id,则同步到mp_products表
  1356. if ($script_id) {
  1357. // 查询剧本信息
  1358. $script = DB::table('mp_scripts')
  1359. ->where('id', $script_id)
  1360. ->where('is_deleted', 0)
  1361. ->first();
  1362. if ($script) {
  1363. $script_name = $script->script_name ?? 'script_' . $script_id;
  1364. $product_name = getProp($target_props, 'prop');
  1365. $pic_prompt = getProp($target_props, 'pic_prompt', '');
  1366. $url = getProp($target_props, 'url', '');
  1367. $product_type = 3; // 3=道具
  1368. // 查找或创建以script_name命名的文件夹
  1369. $folder = DB::table('mp_products')
  1370. ->where('cpid', $cpid)
  1371. ->where('type', 2) // 文件夹类型
  1372. ->where('product', $product_type) // 道具类型
  1373. ->where('product_name', $script_name)
  1374. ->where('parent_id', 0)
  1375. ->where('is_deleted', 0)
  1376. ->first();
  1377. if (!$folder) {
  1378. // 创建文件夹
  1379. $folder_id = DB::table('mp_products')->insertGetId([
  1380. 'user_id' => $uid,
  1381. 'cpid' => $cpid,
  1382. 'type' => 2, // 文件夹
  1383. 'product' => $product_type, // 道具类型
  1384. 'parent_id' => 0,
  1385. 'level' => 1,
  1386. 'product_name' => $script_name,
  1387. 'sort_order' => time(),
  1388. 'is_deleted' => 0,
  1389. 'created_at' => date('Y-m-d H:i:s'),
  1390. 'updated_at' => date('Y-m-d H:i:s')
  1391. ]);
  1392. } else {
  1393. $folder_id = $folder->id;
  1394. }
  1395. // 查找该文件夹下是否已存在同名资产
  1396. $existing_product = DB::table('mp_products')
  1397. ->where('cpid', $cpid)
  1398. ->where('type', 1) // 资产类型
  1399. ->where('product', $product_type)
  1400. ->where('parent_id', $folder_id)
  1401. ->where('product_name', $product_name)
  1402. ->where('is_deleted', 0)
  1403. ->first();
  1404. if ($existing_product) {
  1405. // 更新已存在的资产
  1406. $updateData = [
  1407. 'pic_task_status' => '生成成功'
  1408. ];
  1409. if ($pic_prompt) $updateData['pic_prompt'] = $pic_prompt;
  1410. if ($url) $updateData['url'] = $url;
  1411. // 处理versions字段
  1412. $versions = getProp($target_props, 'versions', []);
  1413. if ($versions && is_array($versions)) {
  1414. $updateData['versions'] = json_encode($versions, 256);
  1415. }
  1416. $updateData['updated_at'] = date('Y-m-d H:i:s');
  1417. DB::table('mp_products')
  1418. ->where('id', $existing_product->id)
  1419. ->update($updateData);
  1420. $product_id = $existing_product->id;
  1421. } else {
  1422. // 创建新资产
  1423. $versions = getProp($target_props, 'versions', []);
  1424. $product_id = DB::table('mp_products')->insertGetId([
  1425. 'user_id' => $uid,
  1426. 'cpid' => $cpid,
  1427. 'type' => 1, // 资产
  1428. 'product' => $product_type, // 道具
  1429. 'parent_id' => $folder_id,
  1430. 'level' => 2,
  1431. 'product_name' => $product_name,
  1432. 'url' => $url,
  1433. 'pic_prompt' => $pic_prompt,
  1434. 'versions' => is_array($versions) ? json_encode($versions, 256) : '[]',
  1435. 'sort_order' => time(),
  1436. 'is_deleted' => 0,
  1437. 'pic_task_status' => '生成成功',
  1438. 'created_at' => date('Y-m-d H:i:s'),
  1439. 'updated_at' => date('Y-m-d H:i:s')
  1440. ]);
  1441. }
  1442. // 建立或更新绑定关系
  1443. $existing_mapping = DB::table('mp_script_product_mappings')
  1444. ->where('script_id', $script_id)
  1445. ->where('product_id', $product_id)
  1446. ->where('episode_number', $episode_number)
  1447. ->first();
  1448. if (!$existing_mapping) {
  1449. // 创建绑定关系
  1450. DB::table('mp_script_product_mappings')->insert([
  1451. 'script_id' => $script_id,
  1452. 'product_id' => $product_id,
  1453. 'episode_number' => $episode_number,
  1454. 'created_at' => date('Y-m-d H:i:s'),
  1455. 'updated_at' => date('Y-m-d H:i:s')
  1456. ]);
  1457. }
  1458. }
  1459. }
  1460. }
  1461. } catch (\Exception $e) {
  1462. dLog('anime')->error('更新剧集道具失败', [
  1463. 'anime_id' => $anime_id,
  1464. 'episode_id' => $episode_id,
  1465. 'error' => $e->getMessage()
  1466. ]);
  1467. Utils::throwError('20003:更新道具列表失败 ' . $e->getMessage());
  1468. }
  1469. return true;
  1470. }
  1471. public function editSegment($data) {
  1472. $segment_id = getProp($data, 'segment_id');
  1473. $segment_content = getProp($data, 'segment_content');
  1474. $image_url = getProp($data, 'image_url');
  1475. $video_url = getProp($data, 'video_url');
  1476. // 参数验证
  1477. if (!$segment_id) Utils::throwError('20003:请提供分镜ID');
  1478. // 验证分镜是否存在
  1479. $segment = DB::table('mp_episode_segments')
  1480. ->where('segment_id', $segment_id)
  1481. ->first();
  1482. if (!$segment) Utils::throwError('20003:该分镜不存在');
  1483. $dubTaskId = 0;
  1484. try {
  1485. DB::beginTransaction();
  1486. // 准备更新数据
  1487. $update_data = [
  1488. 'updated_at' => date('Y-m-d H:i:s')
  1489. ];
  1490. if ($segment_content) {
  1491. // 先将segment_content赋值到update_data
  1492. $update_data['segment_content'] = $segment_content;
  1493. // 使用现有方法分析segment_content,提取各个字段
  1494. $this->handleSegmentContent($update_data);
  1495. // 如果有对话内容,创建视频配音合成任务
  1496. $dialogue = getProp($update_data, 'dialogue');
  1497. if (!empty($dialogue)) {
  1498. $now = date('Y-m-d H:i:s');
  1499. $generate_json = [
  1500. 'text' => $dialogue,
  1501. 'role' => getProp($update_data, 'voice_actor'),
  1502. 'voice_type' => getProp($update_data, 'voice_type'),
  1503. 'voice_name' => getProp($update_data, 'voice_name'),
  1504. 'emotion' => getProp($update_data, 'emotion'),
  1505. 'emotion_type' => getProp($update_data, 'emotion_type'),
  1506. 'gender' => getProp($update_data, 'gender'),
  1507. 'speed_ratio' => getProp($update_data, 'speed_ratio', 0),
  1508. 'loudness_ratio' => getProp($update_data, 'loudness_ratio', 0),
  1509. 'emotion_scale' => getProp($update_data, 'emotion_scale', 0),
  1510. 'pitch' => getProp($update_data, 'pitch', 0),
  1511. ];
  1512. // 插入视频配音合成任务
  1513. $dubTaskId = DB::table('mp_dub_video_tasks')->insertGetId([
  1514. 'alias_segment_id' => $segment_id,
  1515. 'generate_status' => '执行中',
  1516. 'audio_url' => '',
  1517. 'generate_json' => json_encode($generate_json, 256),
  1518. 'created_at' => $now,
  1519. 'updated_at' => $now,
  1520. ]);
  1521. if (!$dubTaskId) {
  1522. Utils::throwError('20003:创建配音任务失败!');
  1523. }
  1524. $update_data['audio_url'] = '';
  1525. } else {
  1526. // dialogue为空时,直接写入默认音频信息
  1527. $update_data['audio_url'] = 'https://zw-audiobook.tos-cn-beijing.volces.com/effects/ellipses_2s.mp3';
  1528. $update_data['audio_duration'] = 2.0;
  1529. $update_data['subtitle_info'] = json_encode(['duration' => 2.0, 'words' => []], 256);
  1530. }
  1531. }
  1532. if ($image_url) {
  1533. $update_data['img_url'] = $image_url;
  1534. // 同时写入一个简单的图片生成任务
  1535. $pic_task = [
  1536. 'alias_segment_id' => $segment_id,
  1537. 'ref_img_url' => json_encode([]),
  1538. 'status' => 'success',
  1539. 'result_url' => json_encode([$image_url], 256),
  1540. 'model' => '',
  1541. 'created_at' => date('Y-m-d H:i:s'),
  1542. 'updated_at' => date('Y-m-d H:i:s'),
  1543. ];
  1544. DB::table('mp_generate_pic_tasks')->insert($pic_task);
  1545. }
  1546. if ($video_url) {
  1547. $update_data['origin_video_url'] = $video_url;
  1548. $compressed_video_url = compressVideo($video_url);
  1549. $update_data['current_type'] = 2;
  1550. $update_data['video_url'] = $compressed_video_url ?: $video_url;
  1551. // 同时写入一个简单的视频生成任务
  1552. $video_task = [
  1553. 'alias_segment_id' => $segment_id,
  1554. 'status' => 'success',
  1555. 'result_url' => $update_data['origin_video_url'],
  1556. 'compressed_url' => $update_data['video_url'],
  1557. 'created_at' => date('Y-m-d H:i:s'),
  1558. 'updated_at' => date('Y-m-d H:i:s'),
  1559. ];
  1560. DB::table('mp_generate_video_tasks')->insert($video_task);
  1561. }
  1562. // 更新分镜信息
  1563. $result = DB::table('mp_episode_segments')
  1564. ->where('segment_id', $segment_id)
  1565. ->update($update_data);
  1566. if ($result === false) {
  1567. Utils::throwError('20003:更新分镜剧本失败');
  1568. }
  1569. DB::commit();
  1570. // 如果有创建音频生成任务则调用API
  1571. if ($dubTaskId) {
  1572. // 请求远程服务器执行生成
  1573. $client = new Client(['timeout' => 300, 'verify' => false]);
  1574. $result = $client->get("http://122.9.129.83:5000/api/anime/genAudio?taskId={$dubTaskId}");
  1575. $response = $result->getBody()->getContents();
  1576. $response_arr = json_decode($response, true);
  1577. if (!isset($response_arr['code']) || (int)$response_arr['code'] !== 0) {
  1578. $error_msg = isset($response_arr['msg']) ? $response_arr['msg'] : '未知错误';
  1579. dLog('anime')->error('火山生成音频失败', ['error' => $error_msg, 'task_id' => $dubTaskId, 'segment_id'=>$segment_id]);
  1580. logDB('anime', 'error', '火山生成音频失败', ['error' => $error_msg, 'task_id' => $dubTaskId, 'segment_id'=>$segment_id]);
  1581. Utils::throwError('20003:火山生成音频失败');
  1582. }
  1583. }
  1584. return true;
  1585. } catch (\Exception $e) {
  1586. DB::rollBack();
  1587. dLog('anime')->error('更新分镜剧本失败', [
  1588. 'segment_id' => $segment_id,
  1589. 'error' => $e->getMessage()
  1590. ]);
  1591. Utils::throwError('20003:更新分镜剧本失败 ' . $e->getMessage());
  1592. }
  1593. }
  1594. public function batchSetSegmentPics($data) {
  1595. $anime_id = getProp($data, 'anime_id');
  1596. $episode_id = getProp($data, 'episode_id');
  1597. $ratio = getProp($data, 'ratio');
  1598. $dimensions = $this->getRatioDimensions($ratio);
  1599. $width = $dimensions['width'];
  1600. $height = $dimensions['height'];
  1601. if (!$anime_id || !$episode_id) {
  1602. Utils::throwError('1002:请选择剧集');
  1603. }
  1604. // 获取剧集信息
  1605. $episode = DB::table('mp_anime_episodes')
  1606. ->where('anime_id', $anime_id)
  1607. ->where('id', $episode_id)
  1608. ->where('is_default', 1)
  1609. ->select('id as episode_id', 'anime_id', 'episode_number', 'roles', 'scenes', 'image_model')
  1610. ->first();
  1611. if (!$episode) {
  1612. Utils::throwError('20003:该剧集不存在');
  1613. }
  1614. $model = getProp($data, 'model');
  1615. if (!$model) {
  1616. $model = getProp($episode, 'image_model');
  1617. if (!$model) {
  1618. // episode表也没有,使用默认值
  1619. $model = 'doubao-seedream-5-0-lite-260128';
  1620. }
  1621. }
  1622. // 验证模型是否在可用模型表中
  1623. if (!DB::table('mp_image_models')->where('model', $model)->where('is_enabled', 1)->exists()) {
  1624. $model = 'doubao-seedream-5-0-lite-260128';
  1625. }
  1626. $roles = json_decode(getProp($episode, 'roles'), true);
  1627. if (!$roles) {
  1628. Utils::throwError('20003:角色信息格式错误');
  1629. }
  1630. // 构建角色名称到参考图的映射
  1631. $role_map = [];
  1632. foreach ($roles as $role) {
  1633. $role_name = getProp($role, 'role');
  1634. $role_url = getProp($role, 'url');
  1635. if (!empty($role_name) && !empty($role_url)) {
  1636. // // 处理角色名称,去除装扮后缀(如:许芸-校服装 -> 许芸)- 修复中文乱码问题(弃用,容易产生重复图片)
  1637. // $base_name = preg_replace('/[--].*$/u', '', $role_name);
  1638. // $role_map[$base_name] = $role_url;
  1639. // 同时保存完整名称的映射
  1640. $role_map[$role_name] = $role_url;
  1641. }
  1642. }
  1643. $scenes = json_decode(getProp($episode, 'roles'), true);
  1644. if (!$scenes) {
  1645. Utils::throwError('20003:场景信息格式错误');
  1646. }
  1647. // 构建角色名称到参考图的映射
  1648. $scene_map = [];
  1649. foreach ($scenes as $scene) {
  1650. $scene_name = getProp($scene, 'scene');
  1651. $scene_url = getProp($scene, 'url');
  1652. if (!empty($scene_name) && !empty($scene_url)) {
  1653. $scene_map[$scene_name] = $scene_url;
  1654. }
  1655. }
  1656. // 获取所有分镜信息
  1657. $segments = DB::table('mp_episode_segments')
  1658. ->where('anime_id', $anime_id)
  1659. ->where('episode_id', $episode_id)
  1660. ->whereNotIn('pic_task_status', ['已完成', '生成中'])
  1661. ->orderBy('segment_number')
  1662. ->get()
  1663. ->toArray();
  1664. if (empty($segments)) {
  1665. Utils::throwError('20003:所有分镜图片已完成或正在生成中');
  1666. }
  1667. // 保存图片比例
  1668. DB::table('mp_anime_episodes')->where('id', $episode_id)->update(['ratio' => $ratio, 'updated_at' => date('Y-m-d H:i:s')]);
  1669. $updated_segments = [];
  1670. $failed_segments = [];
  1671. // 批量为每个分镜生成图片任务
  1672. foreach ($segments as $segment) {
  1673. $segment_id = $segment->segment_id;
  1674. $segment_content = $segment->segment_content;
  1675. if (empty($segment_content)) {
  1676. $failed_segments[] = [
  1677. 'segment_id' => $segment_id,
  1678. 'error' => '分镜内容为空'
  1679. ];
  1680. continue;
  1681. }
  1682. try {
  1683. $dubTaskId = 0;
  1684. // 解析分镜内容,提取画面描述作为主要提示词
  1685. $prompt = $segment_content;
  1686. $ref_img_urls = [];
  1687. // 分镜场景
  1688. $scene = getProp($segment, 'scene');
  1689. $matched_scene = '';
  1690. if (isset($scene_map[$scene])) {
  1691. $img_index = count($ref_img_urls) + 1;
  1692. $prompt = "场景:$scene(图$img_index)\n$prompt";
  1693. $ref_img_urls[] = $scene_map[$scene];
  1694. $matched_scene = $scene;
  1695. }
  1696. // 分镜角色
  1697. $characters = getProp($segment, 'characters');
  1698. $characters = str_replace(['、', ',', ';'], ',', $characters);
  1699. $roles = explode(',', $characters);
  1700. // 从分镜内容中提取涉及的角色
  1701. $segment_characters = $this->extractCharactersFromSegment($segment_content, array_keys($role_map), $roles);
  1702. // 获取匹配角色的参考图
  1703. foreach ($segment_characters as $character) {
  1704. if (isset($role_map[$character])) {
  1705. // 将$prompt中出现的角色替换成角色(图1、2、3,序号是$ref_img_urls的个数加1)
  1706. $img_index = count($ref_img_urls) + 1;
  1707. $prompt = str_replace($character, $character . '(图' . $img_index . ')', $prompt);
  1708. $ref_img_urls[] = $role_map[$character];
  1709. }
  1710. }
  1711. // 如果没有找到匹配的角色参考图,不使用参考图
  1712. if (empty($ref_img_urls)) {
  1713. $ref_img_urls = [];
  1714. }
  1715. // 准备生成任务参数
  1716. $params = [
  1717. 'model' => $model,
  1718. 'alias_segment_id' => $segment_id,
  1719. 'prompt' => $prompt,
  1720. 'ref_img_urls' => $ref_img_urls,
  1721. 'width' => $width,
  1722. 'height' => $height,
  1723. ];
  1724. // 优化提示词(不要生成字幕)
  1725. $params['prompt'] = "前置要求:图片中不要带有任何对话台词或字幕信息\n".$params['prompt'];
  1726. // $task_id = mt_rand(100000, 999999);
  1727. // 调用AI图片生成服务
  1728. $task = $this->aiImageGenerationService->createImageGenerationTask($params);
  1729. $task_id = $task->id;
  1730. if (!$task_id) {
  1731. $failed_segments[] = [
  1732. 'segment_id' => $segment_id,
  1733. 'error' => '创建生成任务失败'
  1734. ];
  1735. continue;
  1736. }
  1737. $update_data = [
  1738. 'pic_task_id' => $task_id,
  1739. 'pic_task_status' => '生成中',
  1740. 'audio_url' => '',
  1741. 'updated_at' => date('Y-m-d H:i:s')
  1742. ];
  1743. // 如果有对话内容,创建视频配音合成任务
  1744. $dialogue = getProp($segment, 'dialogue');
  1745. if (!empty($dialogue)) {
  1746. $now = date('Y-m-d H:i:s');
  1747. $generate_json = [
  1748. 'text' => $dialogue,
  1749. 'role' => getProp($segment, 'voice_actor'),
  1750. 'voice_type' => getProp($segment, 'voice_type'),
  1751. 'voice_name' => getProp($segment, 'voice_name'),
  1752. 'emotion' => getProp($segment, 'emotion'),
  1753. 'emotion_type' => getProp($segment, 'emotion_type'),
  1754. 'gender' => getProp($segment, 'gender'),
  1755. 'speed_ratio' => getProp($segment, 'speed_ratio', 0),
  1756. 'loudness_ratio' => getProp($segment, 'loudness_ratio', 0),
  1757. 'emotion_scale' => getProp($segment, 'emotion_scale', 0),
  1758. 'pitch' => getProp($segment, 'pitch', 0),
  1759. ];
  1760. // 插入视频配音合成任务
  1761. $dubTaskId = DB::table('mp_dub_video_tasks')->insertGetId([
  1762. 'alias_segment_id' => $segment_id,
  1763. 'generate_status' => '执行中',
  1764. 'audio_url' => '',
  1765. 'generate_json' => json_encode($generate_json, 256),
  1766. 'created_at' => $now,
  1767. 'updated_at' => $now,
  1768. ]);
  1769. if (!$dubTaskId) {
  1770. dLog('anime')->error('火山生成音频失败', ['segment_id' => $segment_id, 'generate_json'=>$generate_json]);
  1771. logDB('anime', 'error', '火山生成音频失败', ['segment_id' => $segment_id, 'generate_json'=>$generate_json]);
  1772. // Utils::throwError('20003:创建配音任务失败!');
  1773. }
  1774. } else {
  1775. // dialogue为空时,直接写入默认音频信息到分镜表
  1776. $update_data['audio_url'] = 'https://zw-audiobook.tos-cn-beijing.volces.com/effects/ellipses_2s.mp3';
  1777. $update_data['audio_duration'] = 2.0;
  1778. $update_data['subtitle_info'] = json_encode(['duration' => 2.0, 'words' => []], 256);
  1779. }
  1780. // 更新分镜的任务信息
  1781. $update_result = DB::table('mp_episode_segments')
  1782. ->where('segment_id', $segment_id)
  1783. ->update($update_data);
  1784. // 如果是第一集的首帧图片,则存入待更新数组
  1785. if ($update_result && (int)getProp($segment, 'episode_number') === 1 && (int)getProp($segment, 'segment_number') === 1) {
  1786. Redis::sadd('anime_first_frame_urls', $segment_id);
  1787. }
  1788. if ($update_result) {
  1789. $updated_segments[] = [
  1790. 'segment_id' => $segment_id,
  1791. 'task_id' => $task_id,
  1792. 'status' => '生成中',
  1793. 'matched_scenes' => $matched_scene,
  1794. 'matched_roles' => $segment_characters,
  1795. 'ref_urls_count' => count($ref_img_urls)
  1796. ];
  1797. } else {
  1798. $failed_segments[] = [
  1799. 'segment_id' => $segment_id,
  1800. 'error' => '更新分镜任务状态失败'
  1801. ];
  1802. }
  1803. if ($dubTaskId) {
  1804. sleep(1);
  1805. // 请求远程服务器执行生成
  1806. $client = new Client(['timeout' => 300, 'verify' => false]);
  1807. $result = $client->get("http://122.9.129.83:5000/api/anime/genAudio?taskId={$dubTaskId}");
  1808. $response = $result->getBody()->getContents();
  1809. $response_arr = json_decode($response, true);
  1810. if (!isset($response_arr['code']) || (int)$response_arr['code'] !== 0) {
  1811. $error_msg = isset($response_arr['msg']) ? $response_arr['msg'] : '未知错误';
  1812. dLog('anime')->error('火山生成音频失败', ['error' => $error_msg, 'task_id' => $dubTaskId, 'segment_id' => $segment_id]);
  1813. logDB('anime', 'error', '火山生成音频失败', ['error' => $error_msg, 'task_id' => $dubTaskId, 'segment_id' => $segment_id]);
  1814. }
  1815. }
  1816. } catch (\Exception $e) {
  1817. $failed_segments[] = [
  1818. 'segment_id' => $segment_id,
  1819. 'error' => $e->getMessage()
  1820. ];
  1821. }
  1822. }
  1823. // 更新剧集生成状态
  1824. if (!empty($updated_segments)) {
  1825. DB::table('mp_anime_episodes')
  1826. ->where('id', $episode_id)
  1827. ->update([
  1828. 'is_generated' => 1,
  1829. 'updated_at' => date('Y-m-d H:i:s')
  1830. ]);
  1831. }
  1832. return [
  1833. 'success_count' => count($updated_segments),
  1834. 'failed_count' => count($failed_segments),
  1835. 'success_segments' => $updated_segments,
  1836. 'failed_segments' => $failed_segments,
  1837. 'total_segments' => count($segments)
  1838. ];
  1839. }
  1840. public function reGenerateSegment($data) {
  1841. $segment_id = getProp($data, 'segment_id');
  1842. $segment = DB::table('mp_episode_segments')->where('segment_id', $segment_id)->first();
  1843. $anime_id = getProp($segment, 'anime_id');
  1844. $episode_id = getProp($segment, 'episode_id');
  1845. $episode_number = getProp($segment, 'episode_number');
  1846. $segment_content = getProp($data, 'segment_content');
  1847. $ratio = getProp($data, 'ratio');
  1848. if (!$ratio) {
  1849. $ratio = DB::table('mp_anime_episodes')->where('id', $episode_id)->value('ratio');
  1850. if (!$ratio) $ratio = '9:16';
  1851. }
  1852. $dimensions = $this->getRatioDimensions($ratio);
  1853. $width = $dimensions['width'];
  1854. $height = $dimensions['height'];
  1855. if (!$anime_id || !$episode_id) {
  1856. Utils::throwError('1002:请选择分镜');
  1857. }
  1858. // 使用文生文模型重新解析segment_content
  1859. if (!empty($segment_content)) {
  1860. $segment_content = $this->parseSegmentContentWithAI($segment_content);
  1861. }
  1862. // 获取动漫的角色信息(包含参考图)
  1863. $anime = DB::table('mp_animes')
  1864. ->where('id', $anime_id)
  1865. ->select('roles', 'scenes')
  1866. ->first();
  1867. if (!$anime || !$anime->roles) {
  1868. Utils::throwError('20003:未找到角色信息');
  1869. }
  1870. $roles = json_decode($anime->roles, true);
  1871. if (!$roles) {
  1872. Utils::throwError('20003:角色信息格式错误');
  1873. }
  1874. // 构建角色名称到参考图的映射
  1875. $role_map = [];
  1876. foreach ($roles as $role) {
  1877. $role_name = getProp($role, 'role');
  1878. $role_url = getProp($role, 'url');
  1879. if (!empty($role_name) && !empty($role_url)) {
  1880. $role_map[$role_name] = $role_url;
  1881. }
  1882. }
  1883. $scenes = json_decode($anime->scenes, true);
  1884. if (!$scenes) {
  1885. Utils::throwError('20003:角色信息格式错误');
  1886. }
  1887. // 构建角色名称到参考图的映射
  1888. $scene_map = [];
  1889. foreach ($scenes as $scene) {
  1890. $scene_name = getProp($scene, 'scene');
  1891. $scene_url = getProp($scene, 'url');
  1892. if (!empty($scene_name) && !empty($scene_url)) {
  1893. $scene_map[$scene_name] = $scene_url;
  1894. }
  1895. }
  1896. $segment_id = $segment->segment_id;
  1897. $original_segment_content = $segment->segment_content;
  1898. // 如果传入了新的segment_content,使用新的内容,否则使用原有内容
  1899. $final_segment_content = !empty($segment_content) ? $segment_content : $original_segment_content;
  1900. if (empty($final_segment_content)) {
  1901. Utils::throwError('20003:分镜内容不存在,请填写内容后重试');
  1902. }
  1903. try {
  1904. $dubTaskId = 0;
  1905. // 分镜剧本数组
  1906. $update_data = [
  1907. 'segment_content' => $final_segment_content,
  1908. 'pic_task_status' => '生成中',
  1909. 'updated_at' => date('Y-m-d H:i:s')
  1910. ];
  1911. // 解析分镜内容,提取画面描述作为主要提示词
  1912. $prompt = $final_segment_content;
  1913. $ref_img_urls = [];
  1914. // 分镜场景
  1915. $scene = getProp($data, 'scene');
  1916. if ($scene) {
  1917. $matched_scene = '';
  1918. if (isset($scene_map[$scene])) {
  1919. $img_index = count($ref_img_urls) + 1;
  1920. $prompt = "场景:$scene(图$img_index)\n$prompt";
  1921. $ref_img_urls[] = $scene_map[$scene];
  1922. $matched_scene = $scene;
  1923. }
  1924. $update_data['scene'] = $scene;
  1925. }
  1926. // 分镜角色
  1927. $characters = getProp($data, 'characters');
  1928. if ($characters) {
  1929. $update_data['characters'] = $characters;
  1930. $characters = str_replace(['、', ',', ';'], ',', $characters);
  1931. $characters = explode(',', $characters);
  1932. // 从分镜内容中提取涉及的角色
  1933. $segment_characters = $this->extractCharactersFromSegment($final_segment_content, array_keys($role_map), $characters);
  1934. // 获取匹配角色的参考图
  1935. foreach ($segment_characters as $character) {
  1936. if (isset($role_map[$character])) {
  1937. // 将$prompt中出现的角色替换成角色(图1、2、3,序号是$ref_img_urls的个数加1)
  1938. $img_index = count($ref_img_urls) + 1;
  1939. $prompt = str_replace($character, $character . '(图' . $img_index . ')', $prompt);
  1940. $ref_img_urls[] = $role_map[$character];
  1941. }
  1942. }
  1943. }
  1944. // 如果没有找到匹配的角色参考图,不使用参考图
  1945. if (empty($ref_img_urls)) {
  1946. $ref_img_urls = [];
  1947. }
  1948. // 准备生成任务参数
  1949. $params = [
  1950. 'alias_segment_id' => $segment_id,
  1951. 'prompt' => $prompt,
  1952. 'ref_img_urls' => $ref_img_urls,
  1953. 'width' => $width,
  1954. 'height' => $height,
  1955. ];
  1956. // 优化提示词(不要生成字幕)
  1957. $params['prompt'] = "前置要求:图片中不要带有任何对话台词或字幕信息\n".$params['prompt'];
  1958. // 调用AI图片生成服务
  1959. $task = $this->aiImageGenerationService->createImageGenerationTask($params);
  1960. $task_id = $task->id;
  1961. if (!$task_id) {
  1962. Utils::throwError('20003:创建生成任务失败!');
  1963. }
  1964. $update_data['pic_task_id'] = $task_id;
  1965. // 更新分镜剧本信息
  1966. $this->handleSegmentContent($update_data);
  1967. // 如果有对话内容,创建视频配音合成任务(有更改分镜内容时创建)
  1968. if ($segment_content) {
  1969. $dialogue = getProp($update_data, 'dialogue');
  1970. if (!empty($dialogue)) {
  1971. $now = date('Y-m-d H:i:s');
  1972. $generate_json = [
  1973. 'text' => $dialogue,
  1974. 'role' => getProp($update_data, 'voice_actor'),
  1975. 'voice_type' => getProp($update_data, 'voice_type'),
  1976. 'voice_name' => getProp($update_data, 'voice_name'),
  1977. 'emotion' => getProp($update_data, 'emotion'),
  1978. 'emotion_type' => getProp($update_data, 'emotion_type'),
  1979. 'gender' => getProp($update_data, 'gender'),
  1980. 'speed_ratio' => getProp($update_data, 'speed_ratio', 0),
  1981. 'loudness_ratio' => getProp($update_data, 'loudness_ratio', 0),
  1982. 'emotion_scale' => getProp($update_data, 'emotion_scale', 0),
  1983. 'pitch' => getProp($update_data, 'pitch', 0),
  1984. ];
  1985. // 插入视频配音合成任务
  1986. $dubTaskId = DB::table('mp_dub_video_tasks')->insertGetId([
  1987. 'alias_segment_id' => $segment_id,
  1988. 'generate_status' => '执行中',
  1989. 'audio_url' => '',
  1990. 'generate_json' => json_encode($generate_json, 256),
  1991. 'created_at' => date('Y-m-d H:i:s'),
  1992. 'updated_at' => date('Y-m-d H:i:s'),
  1993. ]);
  1994. if (!$dubTaskId) {
  1995. Utils::throwError('20003:创建配音任务失败!');
  1996. }
  1997. $update_data['audio_url'] = '';
  1998. } else {
  1999. // dialogue为空时,直接写入默认音频信息
  2000. $update_data['audio_url'] = 'https://zw-audiobook.tos-cn-beijing.volces.com/effects/ellipses_2s.mp3';
  2001. $update_data['audio_duration'] = 2.0;
  2002. $update_data['subtitle_info'] = json_encode(['duration' => 2.0, 'words' => []], 256);
  2003. }
  2004. }
  2005. $boolen = DB::table('mp_episode_segments')
  2006. ->where('segment_id', $segment_id)
  2007. ->update($update_data);
  2008. // 如果是第一集的首帧图片,则存入待更新数组
  2009. if ($boolen && (int)getProp($segment, 'episode_number') === 1 && (int)getProp($segment, 'segment_number') === 1) {
  2010. Redis::sadd('anime_first_frame_urls', $segment_id);
  2011. }
  2012. if ($dubTaskId) {
  2013. // 请求远程服务器执行生成
  2014. $client = new Client(['timeout' => 300, 'verify' => false]);
  2015. $result = $client->get("http://122.9.129.83:5000/api/anime/genAudio?taskId={$dubTaskId}");
  2016. $response = $result->getBody()->getContents();
  2017. $response_arr = json_decode($response, true);
  2018. if (!isset($response_arr['code']) || (int)$response_arr['code'] !== 0) {
  2019. $error_msg = isset($response_arr['msg']) ? $response_arr['msg'] : '未知错误';
  2020. dLog('anime')->error('火山生成音频失败', ['error' => $error_msg, 'task_id' => $dubTaskId]);
  2021. logDB('anime', 'error', '火山生成音频失败', ['error' => $error_msg, 'task_id' => $dubTaskId]);
  2022. Utils::throwError('20003:火山生成音频失败');
  2023. }
  2024. }
  2025. } catch (\Exception $e) {
  2026. $failed_segments[] = [
  2027. 'segment_id' => $segment_id,
  2028. 'error' => $e->getMessage()
  2029. ];
  2030. }
  2031. // 创建任务之后先暂停10s等待异步任务完成
  2032. sleep(10);
  2033. $img_url = $this->loopGetPicTaskResult($task_id);
  2034. if (!$img_url) Utils::throwError('20003:图片生成中,请稍后刷新');
  2035. // 图片生成后新增对话记录
  2036. try {
  2037. $uid = Site::getUid();
  2038. $now = date('Y-m-d H:i:s');
  2039. // 使用AI反推图片提示词
  2040. $pic_prompt = $this->generateImagePromptFromUrl($img_url);
  2041. // 保存对话记录
  2042. $records = [
  2043. [
  2044. 'uid' => $uid,
  2045. 'anime_id' => $anime_id,
  2046. 'sequence' => $episode_number,
  2047. 'role' => 'user',
  2048. 'content' => '重新生成',
  2049. 'segment_id' => $segment_id,
  2050. 'image_url' => '',
  2051. 'created_at' => $now,
  2052. 'updated_at' => $now
  2053. ],
  2054. [
  2055. 'uid' => $uid,
  2056. 'anime_id' => $anime_id,
  2057. 'sequence' => $episode_number,
  2058. 'role' => 'assistant',
  2059. 'content' => $pic_prompt,
  2060. 'segment_id' => $segment_id,
  2061. 'image_url' => $img_url,
  2062. 'created_at' => $now,
  2063. 'updated_at' => $now
  2064. ]
  2065. ];
  2066. DB::table('mp_anime_records')->insert($records);
  2067. } catch (\Exception $e) {
  2068. // 记录日志但不影响主流程
  2069. dLog('anime')->error('保存对话记录失败: ' . $e->getMessage(), [
  2070. 'segment_id' => $segment_id,
  2071. 'img_url' => $img_url
  2072. ]);
  2073. }
  2074. return $img_url;
  2075. }
  2076. public function addSegment($data) {
  2077. $prev_segment_id = getProp($data, 'prev_segment_id');
  2078. $img_url = getProp($data, 'img_url');
  2079. $video_url = getProp($data, 'video_url');
  2080. $segment = DB::table('mp_episode_segments')->where('segment_id', $prev_segment_id)->first();
  2081. if (!$segment) Utils::throwError('20003:该分镜不存在');
  2082. $anime_id = getProp($segment, 'anime_id');
  2083. $episode_id = getProp($segment, 'episode_id');
  2084. $episode_number = getProp($segment, 'episode_number');
  2085. $segment_number = getProp($segment, 'segment_number');
  2086. $new_segment_number = $segment_number + 1;
  2087. $segment_id = date('YmdHis') . mt_rand(1000, 9999) . str_pad($new_segment_number, 3, "0", STR_PAD_LEFT);
  2088. // 分镜剧本数组
  2089. $insert_data = [
  2090. 'anime_id' => $anime_id,
  2091. 'episode_id' => $episode_id,
  2092. 'episode_number' => $episode_number,
  2093. 'act_number' => getProp($segment, 'act_number'),
  2094. 'act_title' => getProp($segment, 'act_title'),
  2095. 'segment_id' => $segment_id,
  2096. 'segment_number' => $new_segment_number,
  2097. 'segment_content' => '',
  2098. 'img_url' => '',
  2099. 'video_url' => '',
  2100. 'created_at' => date('Y-m-d H:i:s'),
  2101. 'updated_at' => date('Y-m-d H:i:s')
  2102. ];
  2103. if ($img_url) $insert_data['img_url'] = $img_url;
  2104. if ($video_url) {
  2105. $insert_data['origin_video_url'] = $video_url;
  2106. $insert_data['current_type'] = 2;
  2107. $compressed_video_url = compressVideo($video_url);
  2108. $insert_data['video_url'] = $compressed_video_url ?: $video_url;
  2109. }
  2110. try {
  2111. DB::beginTransaction();
  2112. // 先更新序号
  2113. DB::table('mp_episode_segments')->where('anime_id', $anime_id)->where('episode_id', $episode_id)->where('segment_number', '>', $segment_number)->increment('segment_number');
  2114. $id = DB::table('mp_episode_segments')->insertGetId($insert_data);
  2115. if (!$id) {
  2116. Utils::throwError('20003:新增分镜失败!');
  2117. }
  2118. }catch (\Exception $e) {
  2119. DB::rollBack();
  2120. Utils::throwError('20003:'.$e->getMessage());
  2121. }
  2122. DB::commit();
  2123. $segment = DB::table('mp_episode_segments')->where('id', $id)->first();
  2124. $segment = $segment ? (array)$segment : [];
  2125. return $segment;
  2126. // 以下代码暂弃用
  2127. $anime_id = getProp($segment, 'anime_id');
  2128. $episode_id = getProp($segment, 'episode_id');
  2129. $episode_number = getProp($segment, 'episode_number');
  2130. $segment_number = getProp($segment, 'segment_number');
  2131. $segment_content = getProp($data, 'segment_content');
  2132. $img_url = getProp($data, 'img_url');
  2133. $video_url = getProp($data, 'video_url');
  2134. $ratio = getProp($data, 'ratio');
  2135. $dimensions = $this->getRatioDimensions($ratio);
  2136. $width = $dimensions['width'];
  2137. $height = $dimensions['height'];
  2138. if (!$anime_id || !$episode_id) {
  2139. Utils::throwError('1002:请选择分镜');
  2140. }
  2141. // 使用文生文模型重新解析segment_content
  2142. if (!empty($segment_content)) {
  2143. $segment_content = $this->parseSegmentContentWithAI($segment_content);
  2144. }
  2145. // 获取动漫的角色信息(包含参考图)
  2146. $anime = DB::table('mp_animes')
  2147. ->where('id', $anime_id)
  2148. ->select('roles', 'scenes')
  2149. ->first();
  2150. if (!$anime || !$anime->roles) {
  2151. Utils::throwError('20003:未找到角色信息');
  2152. }
  2153. $roles = json_decode($anime->roles, true);
  2154. if (!$roles) {
  2155. Utils::throwError('20003:角色信息格式错误');
  2156. }
  2157. // 构建角色名称到参考图的映射
  2158. $role_map = [];
  2159. foreach ($roles as $role) {
  2160. $role_name = getProp($role, 'role');
  2161. $role_url = getProp($role, 'url');
  2162. if (!empty($role_name) && !empty($role_url)) {
  2163. $role_map[$role_name] = $role_url;
  2164. }
  2165. }
  2166. $scenes = json_decode($anime->scenes, true);
  2167. if (!$scenes) {
  2168. Utils::throwError('20003:角色信息格式错误');
  2169. }
  2170. // 构建角色名称到参考图的映射
  2171. $scene_map = [];
  2172. foreach ($scenes as $scene) {
  2173. $scene_name = getProp($scene, 'scene');
  2174. $scene_url = getProp($scene, 'url');
  2175. if (!empty($scene_name) && !empty($scene_url)) {
  2176. $scene_map[$scene_name] = $scene_url;
  2177. }
  2178. }
  2179. $segment_id = $segment->segment_id;
  2180. $original_segment_content = $segment->segment_content;
  2181. // 如果传入了新的segment_content,使用新的内容,否则使用原有内容
  2182. $final_segment_content = !empty($segment_content) ? $segment_content : $original_segment_content;
  2183. if (empty($final_segment_content)) {
  2184. Utils::throwError('20003:分镜内容不存在,请填写内容后重试');
  2185. }
  2186. try {
  2187. $dubTaskId = 0;
  2188. DB::beginTransaction();
  2189. $new_segment_number = $segment_number + 1;
  2190. $segment_id = date('YmdHis') . mt_rand(1000, 9999) . str_pad($new_segment_number, 3, "0", STR_PAD_LEFT);
  2191. // 分镜剧本数组
  2192. $insert_data = [
  2193. 'anime_id' => $anime_id,
  2194. 'episode_id' => $episode_id,
  2195. 'episode_number' => $episode_number,
  2196. 'act_number' => getProp($segment, 'act_number'),
  2197. 'act_title' => getProp($segment, 'act_title'),
  2198. 'segment_id' => $segment_id,
  2199. 'segment_number' => $new_segment_number,
  2200. 'segment_content' => $final_segment_content,
  2201. 'img_url' => $img_url,
  2202. 'video_url' => $video_url,
  2203. 'created_at' => date('Y-m-d H:i:s'),
  2204. 'updated_at' => date('Y-m-d H:i:s')
  2205. ];
  2206. // 更新分镜剧本信息
  2207. $this->handleSegmentContent($insert_data);
  2208. // 如果有对话内容,创建视频配音合成任务
  2209. $dialogue = getProp($insert_data, 'dialogue');
  2210. if (!empty($dialogue)) {
  2211. $now = date('Y-m-d H:i:s');
  2212. $generate_json = [
  2213. 'text' => $dialogue,
  2214. 'role' => getProp($insert_data, 'voice_actor'),
  2215. 'voice_type' => getProp($insert_data, 'voice_type'),
  2216. 'voice_name' => getProp($insert_data, 'voice_name'),
  2217. 'emotion' => getProp($insert_data, 'emotion'),
  2218. 'emotion_type' => getProp($insert_data, 'emotion_type'),
  2219. 'gender' => getProp($insert_data, 'gender'),
  2220. 'speed_ratio' => getProp($insert_data, 'speed_ratio', 0),
  2221. 'loudness_ratio' => getProp($insert_data, 'loudness_ratio', 0),
  2222. 'emotion_scale' => getProp($insert_data, 'emotion_scale', 0),
  2223. 'pitch' => getProp($insert_data, 'pitch', 0),
  2224. ];
  2225. // 插入视频配音合成任务
  2226. $dubTaskId = DB::table('mp_dub_video_tasks')->insertGetId([
  2227. 'alias_segment_id' => $segment_id,
  2228. 'generate_status' => '执行中',
  2229. 'audio_url' => '',
  2230. 'generate_json' => json_encode($generate_json, 256),
  2231. 'created_at' => $now,
  2232. 'updated_at' => $now,
  2233. ]);
  2234. if (!$dubTaskId) {
  2235. Utils::throwError('20003:创建配音任务失败!');
  2236. }
  2237. $insert_data['audio_url'] = '';
  2238. } else {
  2239. // dialogue为空时,直接写入默认音频信息
  2240. $insert_data['audio_url'] = 'https://zw-audiobook.tos-cn-beijing.volces.com/effects/ellipses_2s.mp3';
  2241. $insert_data['audio_duration'] = 2.0;
  2242. $insert_data['subtitle_info'] = json_encode(['duration' => 2.0, 'words' => []], 256);
  2243. }
  2244. // 如果没有上传图片则使用当前描述进行生成
  2245. if (!$img_url) {
  2246. // 解析分镜内容,提取画面描述作为主要提示词
  2247. $prompt = $final_segment_content;
  2248. $ref_img_urls = [];
  2249. // 分镜场景
  2250. $scene = getProp($insert_data, 'scene');
  2251. if ($scene) {
  2252. $matched_scene = '';
  2253. if (isset($scene_map[$scene])) {
  2254. $img_index = count($ref_img_urls) + 1;
  2255. $prompt = "场景:$scene(图$img_index)\n$prompt";
  2256. $ref_img_urls[] = $scene_map[$scene];
  2257. $matched_scene = $scene;
  2258. }
  2259. $update_data['scene'] = $scene;
  2260. }
  2261. // 分镜角色
  2262. $characters = getProp($insert_data, 'characters');
  2263. if ($characters) {
  2264. $update_data['characters'] = $characters;
  2265. $characters = str_replace(['、', ',', ';'], ',', $characters);
  2266. $characters = explode(',', $characters);
  2267. // 从分镜内容中提取涉及的角色
  2268. $segment_characters = $this->extractCharactersFromSegment($final_segment_content, array_keys($role_map), $characters);
  2269. // 获取匹配角色的参考图
  2270. foreach ($segment_characters as $character) {
  2271. if (isset($role_map[$character])) {
  2272. // 将$prompt中出现的角色替换成角色(图1、2、3,序号是$ref_img_urls的个数加1)
  2273. $img_index = count($ref_img_urls) + 1;
  2274. $prompt = str_replace($character, $character . '(图' . $img_index . ')', $prompt);
  2275. $ref_img_urls[] = $role_map[$character];
  2276. }
  2277. }
  2278. }
  2279. // 如果没有找到匹配的角色参考图,不使用参考图
  2280. if (empty($ref_img_urls)) {
  2281. $ref_img_urls = [];
  2282. }
  2283. // 准备生成任务参数
  2284. $params = [
  2285. 'alias_segment_id' => $segment_id,
  2286. 'prompt' => $prompt,
  2287. 'ref_img_urls' => $ref_img_urls,
  2288. 'width' => $width,
  2289. 'height' => $height,
  2290. ];
  2291. // 调用AI图片生成服务
  2292. $task = $this->aiImageGenerationService->createImageGenerationTask($params);
  2293. $task_id = $task->id;
  2294. // $task_id = 'whatever';
  2295. if (!$task_id) {
  2296. Utils::throwError('20003:创建生成任务失败!');
  2297. }
  2298. $insert_data['pic_task_status'] = '生成中';
  2299. $insert_data['pic_task_id'] = $task_id;
  2300. }
  2301. // 先更新序号
  2302. DB::table('mp_episode_segments')->where('anime_id', $anime_id)->where('episode_id', $episode_id)->where('segment_number', '>', $segment_number)->increment('segment_number');
  2303. $boolen = DB::table('mp_episode_segments')->insert($insert_data);
  2304. if (!$boolen) {
  2305. Utils::throwError('20003:新增分镜失败!');
  2306. }
  2307. // 如果是第一集的首帧图片,则存入待更新数组
  2308. if ($boolen && (int)$episode_number === 1 && (int)$new_segment_number === 1) {
  2309. Redis::sadd('anime_first_frame_urls', $segment_id);
  2310. }
  2311. if ($dubTaskId) {
  2312. // 请求远程服务器执行生成
  2313. $client = new Client(['timeout' => 300, 'verify' => false]);
  2314. $result = $client->get("http://122.9.129.83:5000/api/anime/genAudio?taskId={$dubTaskId}");
  2315. $response = $result->getBody()->getContents();
  2316. $response_arr = json_decode($response, true);
  2317. if (!isset($response_arr['code']) || (int)$response_arr['code'] !== 0) {
  2318. $error_msg = isset($response_arr['msg']) ? $response_arr['msg'] : '未知错误';
  2319. dLog('anime')->error('火山生成音频失败', ['error' => $error_msg, 'task_id' => $dubTaskId]);
  2320. Utils::throwError('20003:火山生成音频失败');
  2321. }
  2322. }
  2323. } catch (\Exception $e) {
  2324. DB::rollBack();
  2325. Utils::throwError('20003:'.$e->getMessage());
  2326. }
  2327. DB::commit();
  2328. // 创建任务之后先暂停10s等待异步任务完成
  2329. sleep(10);
  2330. if (isset($task_id)) $img_url = $this->loopGetPicTaskResult($task_id);
  2331. if (!$img_url) Utils::throwError('20003:图片生成中,请稍后刷新');
  2332. $segment = DB::table('mp_episode_segments')->where('segment_id', $segment_id)->first();
  2333. $segment = $segment ? (array)$segment : [];
  2334. return $segment;
  2335. }
  2336. public function copySegment($data) {
  2337. $segment_id = getProp($data, 'segment_id');
  2338. $segment = DB::table('mp_episode_segments')->where('segment_id', $segment_id)->first();
  2339. if (!$segment) Utils::throwError('20003:请选择分镜');
  2340. $anime_id = getProp($segment, 'anime_id');
  2341. $episode_id = getProp($segment, 'episode_id');
  2342. $episode_number = getProp($segment, 'episode_number');
  2343. $segment_number = getProp($segment, 'segment_number');
  2344. $new_segment_id = 0;
  2345. try {
  2346. DB::beginTransaction();
  2347. $segment = (array)$segment;
  2348. unset($segment['id']);
  2349. $segment['segment_number'] += 1;
  2350. $segment['segment_id'] = date('YmdHis') . mt_rand(1000, 9999) . str_pad($segment['segment_number'], 3, "0", STR_PAD_LEFT);
  2351. // $segment['pic_task_id'] = $segment['pic_task_status'] = $segment['video_task_id'] = $segment['video_task_status'] = '';
  2352. $segment['created_at'] = $segment['updated_at'] = date('Y-m-d H:i:s');
  2353. // 更新其他分镜序号
  2354. DB::table('mp_episode_segments')->where('anime_id', $anime_id)->where('episode_id', $episode_id)->where('segment_number', '>', $segment_number)->increment('segment_number');
  2355. // 复制分镜
  2356. $id = DB::table('mp_episode_segments')->insertGetId($segment);
  2357. if (!$id) {
  2358. Utils::throwError('20003:复制分镜失败');
  2359. }
  2360. }catch (\Exception $e) {
  2361. DB::rollBack();
  2362. Utils::throwError('20003:'.$e->getMessage());
  2363. }
  2364. DB::commit();
  2365. $segment = DB::table('mp_episode_segments')->where('id', $id)->first();
  2366. $segment = $segment ? (array)$segment : [];
  2367. return $segment;
  2368. }
  2369. public function moveSegment($data) {
  2370. $segment_id = getProp($data, 'segment_id');
  2371. $target_segment_id = getProp($data, 'target_segment_id');
  2372. // 获取源分镜信息
  2373. $source_segment = DB::table('mp_episode_segments')->where('segment_id', $segment_id)->first();
  2374. if (!$source_segment) Utils::throwError('20003:请选择分镜');
  2375. // 获取目标分镜信息
  2376. $target_segment = DB::table('mp_episode_segments')->where('segment_id', $target_segment_id)->first();
  2377. if (!$target_segment) Utils::throwError('20003:目标分镜不存在');
  2378. $anime_id = getProp($source_segment, 'anime_id');
  2379. $episode_id = getProp($source_segment, 'episode_id');
  2380. $episode_number = getProp($source_segment, 'episode_number');
  2381. $source_segment_number = getProp($source_segment, 'segment_number');
  2382. $target_segment_number = getProp($target_segment, 'segment_number');
  2383. // 验证源分镜和目标分镜必须属于同一个动漫的同一集
  2384. $target_anime_id = getProp($target_segment, 'anime_id');
  2385. $target_episode_number = getProp($target_segment, 'episode_number');
  2386. if ($anime_id != $target_anime_id || $episode_number != $target_episode_number) {
  2387. Utils::throwError('20003:只能在同一动漫的同一集内移动分镜');
  2388. }
  2389. // 如果源分镜和目标分镜相同,无需移动
  2390. if ($source_segment_number == $target_segment_number) {
  2391. return true;
  2392. }
  2393. try {
  2394. DB::beginTransaction();
  2395. if ($source_segment_number < $target_segment_number) {
  2396. // 向后移动:源分镜移动到目标分镜之后
  2397. // 1. 将源分镜和目标分镜之间的所有分镜序号减1
  2398. DB::table('mp_episode_segments')
  2399. ->where('anime_id', $anime_id)
  2400. ->where('episode_id', $episode_id)
  2401. ->where('segment_number', '>', $source_segment_number)
  2402. ->where('segment_number', '<=', $target_segment_number)
  2403. ->decrement('segment_number');
  2404. // 2. 将源分镜移动到目标分镜之后
  2405. $new_segment_number = $target_segment_number;
  2406. } else {
  2407. // 向前移动:源分镜移动到目标分镜之后
  2408. // 1. 将目标分镜之后到源分镜之前的所有分镜序号加1
  2409. DB::table('mp_episode_segments')
  2410. ->where('anime_id', $anime_id)
  2411. ->where('episode_id', $episode_id)
  2412. ->where('segment_number', '>', $target_segment_number)
  2413. ->where('segment_number', '<', $source_segment_number)
  2414. ->increment('segment_number');
  2415. // 2. 将源分镜移动到目标分镜之后
  2416. $new_segment_number = $target_segment_number + 1;
  2417. }
  2418. // 3. 更新源分镜的序号
  2419. $update_result = DB::table('mp_episode_segments')
  2420. ->where('segment_id', $segment_id)
  2421. ->update([
  2422. 'segment_number' => $new_segment_number,
  2423. 'updated_at' => date('Y-m-d H:i:s')
  2424. ]);
  2425. if (!$update_result) {
  2426. Utils::throwError('20003:更新分镜序号失败');
  2427. }
  2428. DB::commit();
  2429. return true;
  2430. } catch (\Exception $e) {
  2431. DB::rollBack();
  2432. Utils::throwError('20003:' . $e->getMessage());
  2433. }
  2434. }
  2435. public function delSegment($data) {
  2436. $segment_id = getProp($data, 'segment_id');
  2437. $segment = DB::table('mp_episode_segments')->where('segment_id', $segment_id)->first();
  2438. if (!$segment) Utils::throwError('20003:请选择分镜');
  2439. $anime_id = getProp($segment, 'anime_id');
  2440. $episode_id = getProp($segment, 'episode_id');
  2441. $episode_number = getProp($segment, 'episode_number');
  2442. $segment_number = getProp($segment, 'segment_number');
  2443. try {
  2444. DB::beginTransaction();
  2445. // 删除分镜
  2446. $boolen = DB::table('mp_episode_segments')->where('segment_id', $segment_id)->delete();
  2447. if (!$boolen) {
  2448. Utils::throwError('20003:删除分镜失败');
  2449. }
  2450. // 更新其他分镜序号
  2451. DB::table('mp_episode_segments')->where('anime_id', $anime_id)->where('episode_id', $episode_id)->where('segment_number', '>', $segment_number)->decrement('segment_number');
  2452. }catch (\Exception $e) {
  2453. DB::rollBack();
  2454. Utils::throwError('20003:'.$e->getMessage());
  2455. }
  2456. DB::commit();
  2457. return true;
  2458. }
  2459. public function applySegment($data) {
  2460. $segment_id = getProp($data, 'segment_id');
  2461. $url = getProp($data, 'url');
  2462. if (!$segment_id) Utils::throwError('20003:请选择分镜');
  2463. if (!$url) Utils::throwError('20003:URL不能为空');
  2464. // 获取URL的文件扩展名
  2465. $urlPath = parse_url($url, PHP_URL_PATH);
  2466. $extension = strtolower(pathinfo($urlPath, PATHINFO_EXTENSION));
  2467. // 定义图片和视频的扩展名
  2468. $imageExtensions = ['jpg', 'jpeg', 'png', 'gif', 'bmp', 'webp', 'svg'];
  2469. $videoExtensions = ['mp4', 'avi', 'mov', 'wmv', 'flv', 'mkv', 'webm', 'm4v'];
  2470. // 判断是图片还是视频
  2471. $updateData = ['updated_at' => date('Y-m-d H:i:s')];
  2472. if (in_array($extension, $imageExtensions)) {
  2473. // 图片类型
  2474. $updateData['img_url'] = $url;
  2475. $updateData['current_type'] = 1;
  2476. } elseif (in_array($extension, $videoExtensions)) {
  2477. // 视频类型
  2478. $updateData['video_url'] = $url;
  2479. $updateData['current_type'] = 2;
  2480. } else {
  2481. Utils::throwError('20003:不支持的文件类型');
  2482. }
  2483. // 更新分镜表
  2484. $result = DB::table('mp_episode_segments')
  2485. ->where('segment_id', $segment_id)
  2486. ->update($updateData);
  2487. if (!$result) {
  2488. Utils::throwError('20003:更新分镜失败');
  2489. }
  2490. return true;
  2491. }
  2492. public function segmentHistory($data) {
  2493. $segment_id = getProp($data, 'segment_id');
  2494. // 获取历史图片
  2495. $pics = [];
  2496. $pic_history = DB::table('mp_generate_pic_tasks')->where('alias_segment_id', $segment_id)->where('status', 'success')->orderBy('created_at', 'desc')->get();
  2497. foreach($pic_history as $task) {
  2498. $result_url = getProp($task, 'result_url');
  2499. if (is_json($result_url)) {
  2500. $pics = array_merge($pics, json_decode($result_url, true));
  2501. }else {
  2502. $pics[] = $result_url;
  2503. }
  2504. }
  2505. // 获取历史视频
  2506. $videos = [];
  2507. $video_history = DB::table('mp_generate_video_tasks')->where('alias_segment_id', $segment_id)->where('status', 'success')->orderBy('created_at', 'desc')->get();
  2508. foreach($video_history as $task) {
  2509. $result_url = getProp($task, 'result_url');
  2510. if (is_json($result_url)) {
  2511. $videos = array_merge($videos, json_decode($result_url, true));
  2512. }else {
  2513. $videos[] = $result_url;
  2514. }
  2515. }
  2516. return compact('pics', 'videos');
  2517. }
  2518. public function addAct($data) {
  2519. $prev_act_id = getProp($data, 'prev_act_id');
  2520. $act_title = getProp($data, 'act_title', '');
  2521. $act_content = getProp($data, 'act_content', '');
  2522. $act_duration = getProp($data, 'act_duration', 5);
  2523. $video_url = getProp($data, 'video_url');
  2524. // 根据prev_act_id获取记录
  2525. $prev_segment = DB::table('mp_episode_segments')->where('id', $prev_act_id)->first();
  2526. if (!$prev_segment) Utils::throwError('20003:该片段不存在');
  2527. $anime_id = getProp($prev_segment, 'anime_id');
  2528. $episode_id = getProp($prev_segment, 'episode_id');
  2529. $episode_number = getProp($prev_segment, 'episode_number');
  2530. $prev_act_number = getProp($prev_segment, 'act_number');
  2531. // 获取新的act_number
  2532. $new_act_number = $prev_act_number + 1;
  2533. try {
  2534. DB::beginTransaction();
  2535. // 更新后续所有act的act_number(全能模式下每个act只有一条记录)
  2536. DB::table('mp_episode_segments')
  2537. ->where('anime_id', $anime_id)
  2538. ->where('episode_id', $episode_id)
  2539. ->where('act_number', '>', $prev_act_number)
  2540. ->increment('act_number');
  2541. // 插入新片段记录
  2542. $insert_data = [
  2543. 'anime_id' => $anime_id,
  2544. 'episode_id' => $episode_id,
  2545. 'episode_number' => $episode_number,
  2546. 'act_number' => $new_act_number,
  2547. 'created_at' => date('Y-m-d H:i:s'),
  2548. 'updated_at' => date('Y-m-d H:i:s')
  2549. ];
  2550. if ($act_title) {
  2551. $insert_data['act_title'] = $act_title;
  2552. }
  2553. if ($act_content) {
  2554. $insert_data['act_content'] = $act_content;
  2555. }
  2556. if ($act_duration) {
  2557. $insert_data['act_duration'] = $act_duration;
  2558. }
  2559. if ($video_url) {
  2560. $insert_data['origin_video_url'] = $video_url;
  2561. $insert_data['current_type'] = 2;
  2562. $compressed_video_url = compressVideo($video_url);
  2563. $insert_data['video_url'] = $compressed_video_url ?: $video_url;
  2564. }
  2565. $id = DB::table('mp_episode_segments')->insertGetId($insert_data);
  2566. if (!$id) {
  2567. Utils::throwError('20003:新增片段失败!');
  2568. }
  2569. DB::commit();
  2570. }catch (\Exception $e) {
  2571. DB::rollBack();
  2572. Utils::throwError('20003:'.$e->getMessage());
  2573. }
  2574. $segment = DB::table('mp_episode_segments')->selectRaw("id as act_id,anime_id,episode_id,episode_number,act_number,act_title,act_duration,act_content,video_url,video_duration,video_time_point_start,video_time_point_end")->where('id', $id)->first();
  2575. $segment = $segment ? (array)$segment : [];
  2576. return $segment;
  2577. }
  2578. public function editAct($data) {
  2579. $act_id = getProp($data, 'act_id');
  2580. $act_content = getProp($data, 'act_content');
  2581. $act_duration = getProp($data, 'act_duration');
  2582. $act_title = getProp($data, 'act_title');
  2583. $image_url = getProp($data, 'image_url');
  2584. $video_url = getProp($data, 'video_url');
  2585. // 参数验证
  2586. if (!$act_id) Utils::throwError('20003:请提供片段ID');
  2587. // 验证片段是否存在(全能模式下每个act只有一条记录)
  2588. $segment = DB::table('mp_episode_segments')
  2589. ->where('id', $act_id)
  2590. ->first();
  2591. if (!$segment) Utils::throwError('20003:该片段不存在');
  2592. try {
  2593. DB::beginTransaction();
  2594. // 准备更新数据
  2595. $update_data = [
  2596. 'updated_at' => date('Y-m-d H:i:s')
  2597. ];
  2598. // 更新act相关字段
  2599. if (!empty($act_content)) {
  2600. $update_data['act_show_content'] = $act_content;
  2601. $update_data['act_content'] = str_replace(["@", "{", "}"], "", $act_content);
  2602. // 处理【镜头X】或【分镜X】重新编号为从1开始的连续整数【镜头X】
  2603. $shot_counter = 0;
  2604. $update_data['act_show_content'] = preg_replace_callback(
  2605. '/【(?:镜头|分镜)(\d+)】/u',
  2606. function($matches) use (&$shot_counter) {
  2607. $shot_counter++;
  2608. return '【镜头' . $shot_counter . '】';
  2609. },
  2610. $update_data['act_show_content']
  2611. );
  2612. }
  2613. if (!empty($act_duration)) {
  2614. $update_data['act_duration'] = $act_duration;
  2615. }
  2616. if (!empty($act_title)) {
  2617. $update_data['act_title'] = $act_title;
  2618. }
  2619. // 处理图片上传
  2620. if ($image_url) {
  2621. $update_data['img_url'] = $image_url;
  2622. $update_data['current_type'] = 1;
  2623. // 同时写入一个图片生成任务记录
  2624. if ($act_id) {
  2625. $pic_task = [
  2626. 'alias_act_id' => $act_id,
  2627. 'ref_img_url' => json_encode([]),
  2628. 'status' => 'success',
  2629. 'result_url' => json_encode([$image_url], 256),
  2630. 'model' => '',
  2631. 'created_at' => date('Y-m-d H:i:s'),
  2632. 'updated_at' => date('Y-m-d H:i:s'),
  2633. ];
  2634. DB::table('mp_generate_pic_tasks')->insert($pic_task);
  2635. }
  2636. }
  2637. // 处理视频上传
  2638. if ($video_url) {
  2639. $update_data['origin_video_url'] = $video_url;
  2640. $compressed_video_url = compressVideo($video_url);
  2641. $update_data['current_type'] = 2;
  2642. $update_data['video_url'] = $compressed_video_url ?: $video_url;
  2643. // 同时写入一个视频生成任务记录
  2644. if ($act_id) {
  2645. $video_task = [
  2646. 'alias_act_id' => $act_id,
  2647. 'status' => 'success',
  2648. 'result_url' => $update_data['origin_video_url'],
  2649. 'compressed_url' => $update_data['video_url'],
  2650. 'created_at' => date('Y-m-d H:i:s'),
  2651. 'updated_at' => date('Y-m-d H:i:s'),
  2652. ];
  2653. DB::table('mp_generate_video_tasks')->insert($video_task);
  2654. }
  2655. }
  2656. // 更新片段信息
  2657. $result = DB::table('mp_episode_segments')
  2658. ->where('id', $act_id)
  2659. ->update($update_data);
  2660. if ($result === false) {
  2661. Utils::throwError('20003:更新片段失败');
  2662. }
  2663. DB::commit();
  2664. // 返回新复制的记录
  2665. $new_segment = DB::table('mp_episode_segments')->selectRaw("id as act_id,anime_id,episode_id,episode_number,act_number,act_title,act_duration,act_content,act_show_content,video_url,video_duration,video_time_point_start,video_time_point_end")->where('id', $act_id)->first();
  2666. $new_segment = (array)$new_segment;
  2667. return $new_segment;
  2668. } catch (\Exception $e) {
  2669. DB::rollBack();
  2670. dLog('anime')->error('更新片段失败', [
  2671. 'act_id' => $act_id,
  2672. 'error' => $e->getMessage()
  2673. ]);
  2674. Utils::throwError('20003:更新片段失败 ' . $e->getMessage());
  2675. }
  2676. }
  2677. public function copyAct($data) {
  2678. $act_id = getProp($data, 'act_id');
  2679. // 根据act_id获取记录(全能模式下每个act只有一条记录)
  2680. $source_segment = DB::table('mp_episode_segments')->where('id', $act_id)->first();
  2681. if (!$source_segment) Utils::throwError('20003:请选择片段');
  2682. $anime_id = getProp($source_segment, 'anime_id');
  2683. $episode_id = getProp($source_segment, 'episode_id');
  2684. $episode_number = getProp($source_segment, 'episode_number');
  2685. $act_number = getProp($source_segment, 'act_number');
  2686. try {
  2687. DB::beginTransaction();
  2688. // 新act的编号
  2689. $new_act_number = $act_number + 1;
  2690. // 更新后续所有act的act_number
  2691. DB::table('mp_episode_segments')
  2692. ->where('anime_id', $anime_id)
  2693. ->where('episode_id', $episode_id)
  2694. ->where('act_number', '>', $act_number)
  2695. ->increment('act_number');
  2696. // 复制该片段记录
  2697. $segment_data = (array)$source_segment;
  2698. unset($segment_data['id']);
  2699. $segment_data['video_url'] = '';
  2700. $segment_data['video_task_id'] = '';
  2701. $segment_data['video_task_status'] = '';
  2702. $segment_data['act_number'] = $new_act_number;
  2703. $segment_data['created_at'] = $segment_data['updated_at'] = date('Y-m-d H:i:s');
  2704. $id = DB::table('mp_episode_segments')->insertGetId($segment_data);
  2705. if (!$id) {
  2706. Utils::throwError('20003:复制片段失败');
  2707. }
  2708. DB::commit();
  2709. }catch (\Exception $e) {
  2710. DB::rollBack();
  2711. Utils::throwError('20003:'.$e->getMessage());
  2712. }
  2713. // 返回新复制的记录
  2714. $new_segment = DB::table('mp_episode_segments')->selectRaw("id as act_id,anime_id,episode_id,episode_number,act_number,act_title,act_duration,act_content,act_show_content,video_url,video_duration,video_time_point_start,video_time_point_end")->where('id', $id)->first();
  2715. $new_segment = $new_segment ? (array)$new_segment : [];
  2716. $new_segment['act_id'] = $id;
  2717. return $new_segment;
  2718. }
  2719. public function moveAct($data) {
  2720. $act_id = getProp($data, 'act_id');
  2721. $target_act_id = getProp($data, 'target_act_id');
  2722. // 获取源片段信息
  2723. $source_segment = DB::table('mp_episode_segments')->where('id', $act_id)->first();
  2724. if (!$source_segment) Utils::throwError('20003:请选择片段');
  2725. // 获取目标片段信息
  2726. $target_segment = DB::table('mp_episode_segments')->where('id', $target_act_id)->first();
  2727. if (!$target_segment) Utils::throwError('20003:目标片段不存在');
  2728. $anime_id = getProp($source_segment, 'anime_id');
  2729. $episode_id = getProp($source_segment, 'episode_id');
  2730. $source_act_number = getProp($source_segment, 'act_number');
  2731. $target_act_number = getProp($target_segment, 'act_number');
  2732. // 验证源片段和目标片段必须属于同一个动漫的同一集
  2733. $target_anime_id = getProp($target_segment, 'anime_id');
  2734. $target_episode_id = getProp($target_segment, 'episode_id');
  2735. if ($anime_id != $target_anime_id || $episode_id != $target_episode_id) {
  2736. Utils::throwError('20003:只能在同一动漫的同一集内移动片段');
  2737. }
  2738. // 如果源片段和目标片段相同,无需移动
  2739. if ($source_act_number == $target_act_number) {
  2740. return true;
  2741. }
  2742. try {
  2743. DB::beginTransaction();
  2744. if ($source_act_number < $target_act_number) {
  2745. // 向后移动:源片段移动到目标片段之后
  2746. // 1. 将源片段和目标片段之间的所有片段编号减1
  2747. DB::table('mp_episode_segments')
  2748. ->where('anime_id', $anime_id)
  2749. ->where('episode_id', $episode_id)
  2750. ->where('act_number', '>', $source_act_number)
  2751. ->where('act_number', '<=', $target_act_number)
  2752. ->decrement('act_number');
  2753. // 2. 将源片段移动到目标片段之后
  2754. $new_act_number = $target_act_number;
  2755. } else {
  2756. // 向前移动:源片段移动到目标片段之后
  2757. // 1. 将目标片段之后到源片段之前的所有片段编号加1
  2758. DB::table('mp_episode_segments')
  2759. ->where('anime_id', $anime_id)
  2760. ->where('episode_id', $episode_id)
  2761. ->where('act_number', '>', $target_act_number)
  2762. ->where('act_number', '<', $source_act_number)
  2763. ->increment('act_number');
  2764. // 2. 将源片段移动到目标片段之后
  2765. $new_act_number = $target_act_number + 1;
  2766. }
  2767. // 3. 更新源片段的编号
  2768. $update_result = DB::table('mp_episode_segments')
  2769. ->where('id', $act_id)
  2770. ->update([
  2771. 'act_number' => $new_act_number,
  2772. 'updated_at' => date('Y-m-d H:i:s')
  2773. ]);
  2774. if (!$update_result) {
  2775. Utils::throwError('20003:更新片段编号失败');
  2776. }
  2777. DB::commit();
  2778. return true;
  2779. } catch (\Exception $e) {
  2780. DB::rollBack();
  2781. Utils::throwError('20003:' . $e->getMessage());
  2782. }
  2783. }
  2784. public function delAct($data) {
  2785. $act_id = getProp($data, 'act_id');
  2786. // 根据act_id获取记录(全能模式下每个act只有一条记录)
  2787. $segment = DB::table('mp_episode_segments')->where('id', $act_id)->first();
  2788. if (!$segment) Utils::throwError('20003:请选择片段');
  2789. $anime_id = getProp($segment, 'anime_id');
  2790. $episode_id = getProp($segment, 'episode_id');
  2791. $act_number = getProp($segment, 'act_number');
  2792. try {
  2793. DB::beginTransaction();
  2794. // 删除该片段记录
  2795. $deleted = DB::table('mp_episode_segments')->where('id', $act_id)->delete();
  2796. if (!$deleted) {
  2797. Utils::throwError('20003:删除片段失败');
  2798. }
  2799. // 更新后续act的编号
  2800. DB::table('mp_episode_segments')
  2801. ->where('anime_id', $anime_id)
  2802. ->where('episode_id', $episode_id)
  2803. ->where('act_number', '>', $act_number)
  2804. ->decrement('act_number');
  2805. DB::commit();
  2806. }catch (\Exception $e) {
  2807. DB::rollBack();
  2808. Utils::throwError('20003:'.$e->getMessage());
  2809. }
  2810. return true;
  2811. }
  2812. public function applyAct($data) {
  2813. $act_id = getProp($data, 'act_id');
  2814. $url = getProp($data, 'url');
  2815. if (!$act_id) Utils::throwError('20003:请选择片段');
  2816. if (!$url) Utils::throwError('20003:URL不能为空');
  2817. // 获取URL的文件扩展名
  2818. $urlPath = parse_url($url, PHP_URL_PATH);
  2819. $extension = strtolower(pathinfo($urlPath, PATHINFO_EXTENSION));
  2820. // 定义图片和视频的扩展名
  2821. $imageExtensions = ['jpg', 'jpeg', 'png', 'gif', 'bmp', 'webp', 'svg'];
  2822. $videoExtensions = ['mp4', 'avi', 'mov', 'wmv', 'flv', 'mkv', 'webm', 'm4v'];
  2823. // 判断是图片还是视频
  2824. $updateData = ['updated_at' => date('Y-m-d H:i:s')];
  2825. if (in_array($extension, $imageExtensions)) {
  2826. // 图片类型
  2827. $updateData['img_url'] = $url;
  2828. $updateData['current_type'] = 1;
  2829. } elseif (in_array($extension, $videoExtensions)) {
  2830. // 视频类型
  2831. $updateData['video_url'] = $url;
  2832. $updateData['current_type'] = 2;
  2833. } else {
  2834. Utils::throwError('20003:不支持的文件类型');
  2835. }
  2836. // 更新片段记录(全能模式下每个act只有一条记录)
  2837. $result = DB::table('mp_episode_segments')
  2838. ->where('id', $act_id)
  2839. ->update($updateData);
  2840. if (!$result) {
  2841. Utils::throwError('20003:更新片段失败');
  2842. }
  2843. return true;
  2844. }
  2845. public function actChatHistory($data) {
  2846. $act_id = getProp($data, 'act_id');
  2847. if (!$act_id) Utils::throwError('20003:请选择片段!');
  2848. $query = DB::table('mp_anime_records')->where('act_id', $act_id)->select('role', 'content', 'act_id', 'image_url', 'video_url', 'reference_images', 'created_at');
  2849. $chat = $query->orderBy('id')->get()->map(function ($value) {
  2850. $value = (array)$value;
  2851. $value['created_at'] = transDate($value['created_at']);
  2852. if ($value['reference_images']) $value['reference_images'] = json_decode($value['reference_images'], 256);
  2853. else $value['reference_images'] = [];
  2854. return $value;
  2855. })->toArray();
  2856. // 获取历史图片
  2857. $url = [];
  2858. $pic_history = DB::table('mp_generate_pic_tasks')->where('alias_act_id', $act_id)->where('status', 'success')->orderBy('created_at', 'desc')->get();
  2859. foreach($pic_history as $task) {
  2860. $result_url = getProp($task, 'result_url');
  2861. if (is_json($result_url)) {
  2862. $url = array_merge($url, json_decode($result_url, true));
  2863. }else {
  2864. $url[] = $result_url;
  2865. }
  2866. }
  2867. // 获取历史视频
  2868. $video_history = DB::table('mp_generate_video_tasks')->where('alias_act_id', $act_id)->where('status', 'success')->orderBy('created_at', 'desc')->get();
  2869. foreach($video_history as $task) {
  2870. $result_url = getProp($task, 'result_url');
  2871. if (is_json($result_url)) {
  2872. $url = array_merge($url, json_decode($result_url, true));
  2873. }else {
  2874. $url[] = $result_url;
  2875. }
  2876. }
  2877. // 获取资产库
  2878. $products = [];
  2879. // 通过act_id查询片段信息获取episode_id
  2880. $segment = DB::table('mp_episode_segments')->where('id', $act_id)->first();
  2881. if ($segment) {
  2882. $episode_id = getProp($segment, 'episode_id');
  2883. // 查询剧集信息获取roles、scenes和extra_products
  2884. $episode = DB::table('mp_anime_episodes')->where('id', $episode_id)->first();
  2885. if ($episode) {
  2886. $roles = json_decode(getProp($episode, 'roles', '[]'), true) ?: [];
  2887. $scenes = json_decode(getProp($episode, 'scenes', '[]'), true) ?: [];
  2888. $extra_products = json_decode(getProp($episode, 'extra_products', '[]'), true) ?: [];
  2889. // 先合并roles和scenes
  2890. // 处理角色数组
  2891. foreach ($roles as $role) {
  2892. $product = $role;
  2893. // 将role字段重命名为product_name
  2894. if (isset($product['role'])) {
  2895. $product['product_name'] = $product['role'];
  2896. unset($product['role']);
  2897. }
  2898. $product['product'] = 1; // 标记类型为角色
  2899. $products[$product['product_name']] = $product; // 使用product_name作为key便于后续覆盖
  2900. }
  2901. // 处理场景数组
  2902. foreach ($scenes as $scene) {
  2903. $product = $scene;
  2904. // 将scene字段重命名为product_name
  2905. if (isset($product['scene'])) {
  2906. $product['product_name'] = $product['scene'];
  2907. unset($product['scene']);
  2908. }
  2909. $product['product'] = 2; // 标记类型为场景
  2910. $products[$product['product_name']] = $product; // 使用product_name作为key便于后续覆盖
  2911. }
  2912. // extra_products优先级更高,直接覆盖同名的roles和scenes
  2913. foreach ($extra_products as $extra_product) {
  2914. $product_name = getProp($extra_product, 'product_name');
  2915. if ($product_name) {
  2916. $products[$product_name] = $extra_product; // 覆盖同名数据
  2917. }
  2918. }
  2919. // 重新索引数组(去除key)
  2920. $products = array_values($products);
  2921. }
  2922. }
  2923. // 获取执行中的任务
  2924. $tasks = DB::table('mp_generate_video_tasks')->where('alias_act_id', $act_id)->whereNotIn('status', ['success', 'failed'])->select('id as task_id', 'alias_act_id', 'prompt', 'ref_image_url', 'status')->orderBy('id')->get()->map(function($value) {
  2925. $value = (array)$value;
  2926. if ($value['ref_image_url']) $value['ref_image_url'] = json_decode($value['ref_image_url'], true);
  2927. else $value['ref_image_url'] = [];
  2928. $value['status'] = $value['status'] == 'pending' ? '视频待生成' : '视频生成中';
  2929. // 处理prompt:删除人物音色部分,保留【镜头】开始的内容,并去掉<图片X>标记
  2930. if (!empty($value['prompt'])) {
  2931. $prompt = $value['prompt'];
  2932. // 查找第一个【镜头】的位置
  2933. if (preg_match('/【镜头\d+】/u', $prompt, $matches, PREG_OFFSET_CAPTURE)) {
  2934. // 从【镜头】开始截取
  2935. $prompt = substr($prompt, $matches[0][1]);
  2936. }
  2937. // 去除所有<图片X>格式的标记(X可以是任意数字)
  2938. $prompt = preg_replace('/<图片\d+>/u', '', $prompt);
  2939. $value['prompt'] = $prompt;
  2940. }
  2941. return $value;
  2942. })->toArray();
  2943. return compact('chat', 'url', 'products', 'tasks');
  2944. }
  2945. public function applyAudioData($data) {
  2946. $segment_id = getProp($data, 'segment_id');
  2947. $global_data = getProp($data, 'global_data');
  2948. $segment_data = getProp($data, 'segment_data');
  2949. if (!$segment_id) Utils::throwError('20003:请选择分镜');
  2950. $global_data = is_array($global_data) ? $global_data : [];
  2951. $segment_data = is_array($segment_data) ? $segment_data : [];
  2952. // dialogue只能在segment_data中,如果在global_data中则移到segment_data
  2953. $dialogue_item = null;
  2954. foreach ($global_data as $key => $item) {
  2955. if (trim((string)getProp($item, 'name')) === 'dialogue') {
  2956. $dialogue_item = $item;
  2957. unset($global_data[$key]);
  2958. break;
  2959. }
  2960. }
  2961. if ($dialogue_item) {
  2962. $segment_data[] = $dialogue_item;
  2963. }
  2964. // 特殊参数: audio_url,audio_duration,subtitle_info
  2965. // 这些特殊参数必须同时存在才对当前分镜有效,直接保存但不创建音频任务
  2966. // 如果不是全部存在,则仍需创建音频任务
  2967. $special_fields = ['audio_url', 'audio_duration', 'subtitle_info'];
  2968. $special_update_data = [];
  2969. $has_all_special_params = false;
  2970. // 从segment_data中提取特殊参数
  2971. $filtered_segment_data = [];
  2972. foreach ($segment_data as $item) {
  2973. $field_name = trim((string)getProp($item, 'name'));
  2974. if (in_array($field_name, $special_fields)) {
  2975. $special_update_data[$field_name] = getProp($item, 'value');
  2976. } else {
  2977. // 非特殊参数保留,继续后续处理
  2978. $filtered_segment_data[] = $item;
  2979. }
  2980. }
  2981. // 检查是否三个特殊参数都存在
  2982. if (count($special_update_data) === 3 &&
  2983. isset($special_update_data['audio_url']) &&
  2984. isset($special_update_data['audio_duration']) &&
  2985. isset($special_update_data['subtitle_info'])) {
  2986. $has_all_special_params = true;
  2987. // 立即更新到当前分镜
  2988. $special_update_data['updated_at'] = date('Y-m-d H:i:s');
  2989. DB::table('mp_episode_segments')
  2990. ->where('segment_id', $segment_id)
  2991. ->update($special_update_data);
  2992. }
  2993. // 使用过滤后的segment_data继续处理其他参数
  2994. $segment_data = $filtered_segment_data;
  2995. $allow_fields = ['dialogue', 'voice_type', 'speed_ratio', 'loudness_ratio', 'emotion_scale', 'pitch'];
  2996. $global_update_data = [];
  2997. $segment_update_data = [];
  2998. $global_voice_type = '';
  2999. $target_segment = DB::table('mp_episode_segments')->where('segment_id', $segment_id)->first();
  3000. if (!$target_segment) Utils::throwError('20003:分镜不存在');
  3001. $episode_id = getProp($target_segment, 'episode_id');
  3002. $target_voice_actor = trim((string)getProp($target_segment, 'voice_actor'));
  3003. $episode = DB::table('mp_anime_episodes')->where('id', $episode_id)->first();
  3004. if (!$episode) Utils::throwError('20003:分集不存在');
  3005. foreach ($global_data as $item) {
  3006. $field_name = trim((string)getProp($item, 'name'));
  3007. if (!$field_name || !in_array($field_name, $allow_fields)) {
  3008. continue;
  3009. }
  3010. $global_update_data[$field_name] = getProp($item, 'value');
  3011. if ($field_name === 'voice_type') {
  3012. $global_voice_type = trim((string)getProp($item, 'value'));
  3013. }
  3014. }
  3015. foreach ($segment_data as $item) {
  3016. $field_name = trim((string)getProp($item, 'name'));
  3017. if (!$field_name || !in_array($field_name, $allow_fields)) {
  3018. continue;
  3019. }
  3020. $segment_update_data[$field_name] = getProp($item, 'value');
  3021. }
  3022. if ($global_voice_type) {
  3023. $timbre_info = DB::table('mp_timbres')
  3024. ->where('timbre_type', $global_voice_type)
  3025. ->select('audio_url', 'timbre_name')
  3026. ->first();
  3027. if ($timbre_info) {
  3028. $global_update_data['voice_audio_url'] = getProp($timbre_info, 'audio_url');
  3029. $global_update_data['voice_name'] = str_replace('(多情感)', '', getProp($timbre_info, 'timbre_name'));
  3030. }
  3031. }
  3032. try {
  3033. DB::beginTransaction();
  3034. // 收集需要创建音频合成任务的segment_id和对应的分镜数据
  3035. $segment_ids_to_create_task = [];
  3036. $segments_data = [];
  3037. // 如果有全局更新,获取该角色的所有分镜数据并检查是否有变化
  3038. if (!empty($global_update_data)) {
  3039. // 如果角色不存在,则只更新当前分镜
  3040. if (!$target_voice_actor) {
  3041. // 只处理当前分镜
  3042. $affected_segments = DB::table('mp_episode_segments')
  3043. ->where('segment_id', $segment_id)
  3044. ->select('segment_id', 'audio_url', 'voice_actor', 'dialogue', 'voice_type', 'voice_name', 'voice_audio_url', 'emotion', 'emotion_type', 'gender', 'speed_ratio', 'loudness_ratio', 'emotion_scale', 'pitch')
  3045. ->get();
  3046. } else {
  3047. // 获取该角色的所有分镜
  3048. $affected_segments = DB::table('mp_episode_segments')
  3049. ->where('episode_id', $episode_id)
  3050. ->where('voice_actor', $target_voice_actor)
  3051. ->select('segment_id', 'audio_url', 'voice_actor', 'dialogue', 'voice_type', 'voice_name', 'voice_audio_url', 'emotion', 'emotion_type', 'gender', 'speed_ratio', 'loudness_ratio', 'emotion_scale', 'pitch')
  3052. ->get();
  3053. }
  3054. foreach ($affected_segments as $seg) {
  3055. $seg = (array)$seg;
  3056. $sid = getProp($seg, 'segment_id');
  3057. // 检查参数是否发生变化
  3058. $has_changed = false;
  3059. foreach ($global_update_data as $field => $new_value) {
  3060. $old_value = getProp($seg, $field);
  3061. if ($old_value != $new_value) {
  3062. $has_changed = true;
  3063. break;
  3064. }
  3065. }
  3066. if ($has_changed) {
  3067. $segment_ids_to_create_task[] = $sid;
  3068. $segments_data[$sid] = $seg;
  3069. }
  3070. }
  3071. // 只有在有变化的分镜时才更新
  3072. if (!empty($segment_ids_to_create_task)) {
  3073. $global_segment_update_data = $global_update_data;
  3074. $global_segment_update_data['audio_url'] = ''; // 清空音频URL
  3075. $global_segment_update_data['updated_at'] = date('Y-m-d H:i:s');
  3076. DB::table('mp_episode_segments')
  3077. ->where('episode_id', $episode_id)
  3078. ->where('voice_actor', $target_voice_actor)
  3079. ->whereIn('segment_id', $segment_ids_to_create_task)
  3080. ->update($global_segment_update_data);
  3081. }
  3082. if ($global_voice_type) {
  3083. $episode_roles = json_decode((string)getProp($episode, 'roles'), true);
  3084. $episode_roles = is_array($episode_roles) ? $episode_roles : [];
  3085. $roles_updated = false;
  3086. foreach ($episode_roles as &$role) {
  3087. // 通过 role 字段匹配角色名,而不是 voice_name
  3088. if (trim((string)getProp($role, 'role')) !== $target_voice_actor) {
  3089. continue;
  3090. }
  3091. $role['voice_type'] = $global_voice_type;
  3092. $role['voice_audio_url'] = getProp($global_update_data, 'voice_audio_url');
  3093. $role['voice_name'] = getProp($global_update_data, 'voice_name');
  3094. $roles_updated = true;
  3095. }
  3096. unset($role);
  3097. if ($roles_updated) {
  3098. DB::table('mp_anime_episodes')->where('id', $episode_id)->update([
  3099. 'roles' => json_encode($episode_roles, 256),
  3100. 'updated_at' => date('Y-m-d H:i:s'),
  3101. ]);
  3102. }
  3103. }
  3104. }
  3105. // 如果有单个分镜更新,检查是否有变化
  3106. if (!empty($segment_update_data)) {
  3107. // 获取当前分镜数据
  3108. $current_segment = DB::table('mp_episode_segments')
  3109. ->where('segment_id', $segment_id)
  3110. ->select('segment_id', 'audio_url', 'voice_actor', 'dialogue', 'voice_type', 'voice_name', 'voice_audio_url', 'emotion', 'emotion_type', 'gender', 'speed_ratio', 'loudness_ratio', 'emotion_scale', 'pitch')
  3111. ->first();
  3112. if ($current_segment) {
  3113. $current_segment = (array)$current_segment;
  3114. // 检查参数是否发生变化
  3115. $has_changed = false;
  3116. foreach ($segment_update_data as $field => $new_value) {
  3117. $old_value = getProp($current_segment, $field);
  3118. if ($old_value != $new_value) {
  3119. $has_changed = true;
  3120. break;
  3121. }
  3122. }
  3123. if ($has_changed) {
  3124. // 如果该分镜还未在列表中,添加进去
  3125. if (!in_array($segment_id, $segment_ids_to_create_task)) {
  3126. $segment_ids_to_create_task[] = $segment_id;
  3127. $segments_data[$segment_id] = $current_segment;
  3128. }
  3129. // 更新分镜数据并清空音频URL
  3130. $segment_update_data['audio_url'] = '';
  3131. $segment_update_data['updated_at'] = date('Y-m-d H:i:s');
  3132. DB::table('mp_episode_segments')->where('segment_id', $segment_id)->update($segment_update_data);
  3133. }
  3134. }
  3135. }
  3136. // 为所有有变化的分镜创建音频合成任务
  3137. // 但如果当前分镜同时设置了全部三个特殊参数(audio_url, audio_duration, subtitle_info),则跳过该分镜
  3138. if (!empty($segment_ids_to_create_task)) {
  3139. foreach ($segment_ids_to_create_task as $sid) {
  3140. // 如果当前分镜同时设置了全部三个特殊参数,则跳过音频任务创建
  3141. if ($sid === $segment_id && $has_all_special_params) {
  3142. continue;
  3143. }
  3144. // 重新获取更新后的分镜数据
  3145. $updated_segment = DB::table('mp_episode_segments')
  3146. ->where('segment_id', $sid)
  3147. ->select('voice_actor', 'dialogue', 'voice_type', 'voice_name', 'emotion', 'emotion_type', 'gender', 'speed_ratio', 'loudness_ratio', 'emotion_scale', 'pitch')
  3148. ->first();
  3149. if (!$updated_segment) continue;
  3150. $updated_segment = (array)$updated_segment;
  3151. // 检查dialogue是否为空
  3152. $dialogue = getProp($updated_segment, 'dialogue');
  3153. if (empty($dialogue)) {
  3154. // dialogue为空时,直接写入默认音频信息
  3155. DB::table('mp_episode_segments')->where('segment_id', $sid)->update([
  3156. 'audio_url' => 'https://zw-audiobook.tos-cn-beijing.volces.com/effects/ellipses_2s.mp3',
  3157. 'audio_duration' => 2.0,
  3158. 'subtitle_info' => json_encode(['duration' => 2.0, 'words' => []], 256),
  3159. 'updated_at' => date('Y-m-d H:i:s')
  3160. ]);
  3161. continue;
  3162. }
  3163. $generate_json = [
  3164. 'text' => $dialogue,
  3165. 'role' => getProp($updated_segment, 'voice_actor'),
  3166. 'voice_type' => getProp($updated_segment, 'voice_type'),
  3167. 'voice_name' => getProp($updated_segment, 'voice_name'),
  3168. 'emotion' => getProp($updated_segment, 'emotion'),
  3169. 'emotion_type' => getProp($updated_segment, 'emotion_type'),
  3170. 'gender' => getProp($updated_segment, 'gender'),
  3171. 'speed_ratio' => getProp($updated_segment, 'speed_ratio', 0),
  3172. 'loudness_ratio' => getProp($updated_segment, 'loudness_ratio', 0),
  3173. 'emotion_scale' => getProp($updated_segment, 'emotion_scale', 0),
  3174. 'pitch' => getProp($updated_segment, 'pitch', 0),
  3175. ];
  3176. // 插入视频配音合成任务
  3177. $dubTaskId = DB::table('mp_dub_video_tasks')->insertGetId([
  3178. 'alias_segment_id' => $sid,
  3179. 'generate_status' => '执行中',
  3180. 'audio_url' => '',
  3181. 'generate_json' => json_encode($generate_json, 256),
  3182. 'created_at' => date('Y-m-d H:i:s'),
  3183. 'updated_at' => date('Y-m-d H:i:s'),
  3184. ]);
  3185. if (!$dubTaskId) {
  3186. dLog('anime')->error('创建配音任务失败', ['segment_id' => $sid]);
  3187. continue;
  3188. }
  3189. // 将任务ID添加到Redis列表中
  3190. Redis::lpush('dub_video_task_queue', $dubTaskId);
  3191. // 请求远程服务器执行生成
  3192. try {
  3193. sleep(1);
  3194. $client = new Client(['timeout' => 300, 'verify' => false]);
  3195. $result = $client->get("http://122.9.129.83:5000/api/anime/genAudio?taskId={$dubTaskId}");
  3196. $response = $result->getBody()->getContents();
  3197. $response_arr = json_decode($response, true);
  3198. if (!isset($response_arr['code']) || (int)$response_arr['code'] !== 0) {
  3199. $error_msg = isset($response_arr['msg']) ? $response_arr['msg'] : '未知错误';
  3200. dLog('anime')->error('火山生成音频失败', ['error' => $error_msg, 'task_id' => $dubTaskId, 'segment_id' => $sid]);
  3201. logDB('anime', 'error', '火山生成音频失败', ['error' => $error_msg, 'task_id' => $dubTaskId, 'segment_id' => $sid]);
  3202. }
  3203. } catch (\Exception $e) {
  3204. dLog('anime')->error('调用音频生成API失败', ['error' => $e->getMessage(), 'task_id' => $dubTaskId, 'segment_id' => $sid]);
  3205. logDB('anime', 'error', '调用音频生成API失败', ['error' => $e->getMessage(), 'task_id' => $dubTaskId, 'segment_id' => $sid]);
  3206. }
  3207. }
  3208. }
  3209. DB::commit();
  3210. } catch (\Exception $e) {
  3211. DB::rollBack();
  3212. Utils::throwError('20003:'.$e->getMessage());
  3213. }
  3214. return true;
  3215. }
  3216. public function episodePicsInfo($data) {
  3217. $anime_id = getProp($data, 'anime_id');
  3218. $episode_id = getProp($data, 'episode_id');
  3219. // 参数验证
  3220. if (!$anime_id && !$episode_id) {
  3221. Utils::throwError('20003:请提供动漫ID或分集ID');
  3222. }
  3223. // 根据参数获取数据源
  3224. if ($episode_id) {
  3225. // 从剧集表获取
  3226. $source = DB::table('mp_anime_episodes')->where('id', $episode_id)->first();
  3227. if (!$source) Utils::throwError('20003:该剧集不存在');
  3228. $table_name = 'mp_anime_episodes';
  3229. $id_field = 'id';
  3230. $id_value = $episode_id;
  3231. // 获取剧集的anime_id用于继承全局数据
  3232. $anime_id = getProp($source, 'anime_id');
  3233. } else {
  3234. // 从动漫表获取
  3235. $source = DB::table('mp_animes')->where('id', $anime_id)->where('is_deleted', 0)->first();
  3236. if (!$source) Utils::throwError('20003:该动漫不存在');
  3237. $table_name = 'mp_animes';
  3238. $id_field = 'id';
  3239. $id_value = $anime_id;
  3240. }
  3241. $source = (array)$source;
  3242. $roles = json_decode(getProp($source, 'roles', '[]'), true) ?: [];
  3243. $scenes = json_decode(getProp($source, 'scenes', '[]'), true) ?: [];
  3244. $props = json_decode(getProp($source, 'props', '[]'), true) ?: [];
  3245. // 如果是分集数据,需要处理继承和任务创建逻辑
  3246. if ($episode_id) {
  3247. $this->processEpisodeRolesAndScenes($episode_id, $anime_id, $roles, $scenes, $source);
  3248. }
  3249. // 返回生成器函数,用于 SSE 流式输出
  3250. return function() use ($roles, $scenes, $props, $table_name, $id_field, $id_value) {
  3251. $startTime = time();
  3252. $maxDuration = 600; // 10分钟超时
  3253. $checkInterval = 3; // 每3秒检查一次
  3254. // Redis 缓存键
  3255. $cacheKey = "anime:pics_info:{$table_name}:{$id_value}";
  3256. // 生成当前数据的哈希值用于比较
  3257. $generateHash = function($roles, $scenes, $props) {
  3258. return md5(json_encode(['roles' => $roles, 'scenes' => $scenes, 'props' => $props], JSON_UNESCAPED_UNICODE));
  3259. };
  3260. // 发送初始数据
  3261. $currentHash = $generateHash($roles, $scenes, $props);
  3262. Redis::setex($cacheKey, 600, $currentHash); // 缓存10分钟
  3263. echo "data: " . json_encode([
  3264. 'type' => 'init',
  3265. 'data' => [
  3266. 'roles' => $roles,
  3267. 'scenes' => $scenes,
  3268. 'props' => $props,
  3269. 'start_time' => $startTime
  3270. ]
  3271. ], JSON_UNESCAPED_UNICODE) . "\n\n";
  3272. if (ob_get_level() > 0) {
  3273. ob_flush();
  3274. }
  3275. flush();
  3276. // 持续轮询任务状态
  3277. while (time() - $startTime < $maxDuration) {
  3278. $hasProcessing = false;
  3279. $updated = false;
  3280. // 检查角色任务状态
  3281. foreach ($roles as $index => &$role) {
  3282. $task_id = getProp($role, 'task_id');
  3283. $task_status = getProp($role, 'task_status');
  3284. $existing_url = getProp($role, 'url');
  3285. // 只处理有任务ID且状态为processing的角色,或者状态为processing但没有URL的角色
  3286. if ($task_id && ($task_status === 'processing' || (in_array($task_status, ['success', 'completed']) && empty($existing_url)))) {
  3287. $hasProcessing = ($task_status === 'processing');
  3288. // 查询任务状态
  3289. $task = DB::table('mp_generate_pic_tasks')
  3290. ->where('id', $task_id)
  3291. ->select('id', 'status', 'result_url', 'error_message')
  3292. ->first();
  3293. if ($task) {
  3294. $task = (array)$task;
  3295. $status = getProp($task, 'status');
  3296. // 如果任务完成或失败
  3297. if (in_array($status, ['success', 'failed'])) {
  3298. $role['task_status'] = $status;
  3299. if ($status === 'success') {
  3300. $result_url = getProp($task, 'result_url');
  3301. if ($result_url) {
  3302. $result_urls = is_json($result_url) ? json_decode($result_url, true) : [$result_url];
  3303. if (is_array($result_urls) && !empty($result_urls[0])) {
  3304. $role['url'] = $result_urls[0];
  3305. }
  3306. }
  3307. }
  3308. $updated = true;
  3309. } else if ($status === 'processing') {
  3310. $hasProcessing = true;
  3311. }
  3312. }
  3313. }
  3314. }
  3315. // 检查场景任务状态
  3316. foreach ($scenes as $index => &$scene) {
  3317. $task_id = getProp($scene, 'task_id');
  3318. $task_status = getProp($scene, 'task_status');
  3319. $existing_url = getProp($scene, 'url');
  3320. // 只处理有任务ID且状态为processing的场景,或者状态为success但没有URL的场景
  3321. if ($task_id && ($task_status === 'processing' || (in_array($task_status, ['success', 'completed']) && empty($existing_url)))) {
  3322. $hasProcessing = ($task_status === 'processing');
  3323. // 查询任务状态
  3324. $task = DB::table('mp_generate_pic_tasks')
  3325. ->where('id', $task_id)
  3326. ->select('id', 'status', 'result_url', 'error_message')
  3327. ->first();
  3328. if ($task) {
  3329. $task = (array)$task;
  3330. $status = getProp($task, 'status');
  3331. // 如果任务完成或失败
  3332. if (in_array($status, ['success', 'failed'])) {
  3333. $scene['task_status'] = $status;
  3334. if ($status === 'success') {
  3335. $result_url = getProp($task, 'result_url');
  3336. if ($result_url) {
  3337. $result_urls = is_json($result_url) ? json_decode($result_url, true) : [$result_url];
  3338. if (is_array($result_urls) && !empty($result_urls[0])) {
  3339. $scene['url'] = $result_urls[0];
  3340. }
  3341. }
  3342. }
  3343. $updated = true;
  3344. } else if ($status === 'processing') {
  3345. $hasProcessing = true;
  3346. }
  3347. }
  3348. }
  3349. }
  3350. // 检查道具任务状态
  3351. foreach ($props as $index => &$prop) {
  3352. $task_id = getProp($prop, 'task_id');
  3353. $task_status = getProp($prop, 'task_status');
  3354. $existing_url = getProp($prop, 'url');
  3355. // 只处理有任务ID且状态为processing的道具,或者状态为success但没有URL的道具
  3356. if ($task_id && ($task_status === 'processing' || (in_array($task_status, ['success', 'completed']) && empty($existing_url)))) {
  3357. $hasProcessing = ($task_status === 'processing');
  3358. // 查询任务状态
  3359. $task = DB::table('mp_generate_pic_tasks')
  3360. ->where('id', $task_id)
  3361. ->select('id', 'status', 'result_url', 'error_message')
  3362. ->first();
  3363. if ($task) {
  3364. $task = (array)$task;
  3365. $status = getProp($task, 'status');
  3366. // 如果任务完成或失败
  3367. if (in_array($status, ['success', 'failed'])) {
  3368. $prop['task_status'] = $status;
  3369. if ($status === 'success') {
  3370. $result_url = getProp($task, 'result_url');
  3371. if ($result_url) {
  3372. $result_urls = is_json($result_url) ? json_decode($result_url, true) : [$result_url];
  3373. if (is_array($result_urls) && !empty($result_urls[0])) {
  3374. $prop['url'] = $result_urls[0];
  3375. }
  3376. }
  3377. }
  3378. $updated = true;
  3379. } else if ($status === 'processing') {
  3380. $hasProcessing = true;
  3381. }
  3382. }
  3383. }
  3384. }
  3385. // 如果有更新,检查数据是否真的变化了(通过哈希对比)
  3386. if ($updated) {
  3387. $newHash = $generateHash($roles, $scenes, $props);
  3388. $cachedHash = Redis::get($cacheKey);
  3389. // 只有当数据真正变化时才更新数据库和发送事件
  3390. if ($newHash !== $cachedHash) {
  3391. try {
  3392. // 更新数据库
  3393. DB::table($table_name)->where($id_field, $id_value)->update([
  3394. 'roles' => json_encode($roles, JSON_UNESCAPED_UNICODE),
  3395. 'scenes' => json_encode($scenes, JSON_UNESCAPED_UNICODE),
  3396. 'props' => json_encode($props, JSON_UNESCAPED_UNICODE),
  3397. 'updated_at' => date('Y-m-d H:i:s')
  3398. ]);
  3399. // 更新缓存
  3400. Redis::setex($cacheKey, 600, $newHash);
  3401. // 发送更新事件
  3402. echo "data: " . json_encode([
  3403. 'type' => 'update',
  3404. 'data' => [
  3405. 'roles' => $roles,
  3406. 'scenes' => $scenes,
  3407. 'props' => $props,
  3408. 'elapsed_time' => time() - $startTime
  3409. ]
  3410. ], JSON_UNESCAPED_UNICODE) . "\n\n";
  3411. if (ob_get_level() > 0) {
  3412. ob_flush();
  3413. }
  3414. flush();
  3415. } catch (\Exception $e) {
  3416. dLog('anime')->error('更新角色/场景/道具信息失败: ' . $e->getMessage());
  3417. }
  3418. } else {
  3419. // 即使哈希相同,如果有URL更新也要发送事件
  3420. $hasUrlUpdate = false;
  3421. foreach ($roles as $role) {
  3422. if (!empty(getProp($role, 'url')) && getProp($role, 'task_status') === 'success') {
  3423. $hasUrlUpdate = true;
  3424. break;
  3425. }
  3426. }
  3427. if (!$hasUrlUpdate) {
  3428. foreach ($scenes as $scene) {
  3429. if (!empty(getProp($scene, 'url')) && getProp($scene, 'task_status') === 'success') {
  3430. $hasUrlUpdate = true;
  3431. break;
  3432. }
  3433. }
  3434. }
  3435. if (!$hasUrlUpdate) {
  3436. foreach ($props as $prop) {
  3437. if (!empty(getProp($prop, 'url')) && getProp($prop, 'task_status') === 'success') {
  3438. $hasUrlUpdate = true;
  3439. break;
  3440. }
  3441. }
  3442. }
  3443. if ($hasUrlUpdate) {
  3444. // 强制更新数据库和发送事件
  3445. try {
  3446. DB::table($table_name)->where($id_field, $id_value)->update([
  3447. 'roles' => json_encode($roles, JSON_UNESCAPED_UNICODE),
  3448. 'scenes' => json_encode($scenes, JSON_UNESCAPED_UNICODE),
  3449. 'props' => json_encode($props, JSON_UNESCAPED_UNICODE),
  3450. 'updated_at' => date('Y-m-d H:i:s')
  3451. ]);
  3452. // 更新缓存
  3453. Redis::setex($cacheKey, 600, $newHash);
  3454. // 发送更新事件
  3455. echo "data: " . json_encode([
  3456. 'type' => 'update',
  3457. 'data' => [
  3458. 'roles' => $roles,
  3459. 'scenes' => $scenes,
  3460. 'props' => $props,
  3461. 'elapsed_time' => time() - $startTime
  3462. ]
  3463. ], JSON_UNESCAPED_UNICODE) . "\n\n";
  3464. if (ob_get_level() > 0) {
  3465. ob_flush();
  3466. }
  3467. flush();
  3468. } catch (\Exception $e) {
  3469. dLog('anime')->error('强制更新角色/场景/道具信息失败: ' . $e->getMessage());
  3470. }
  3471. }
  3472. }
  3473. }
  3474. // 如果所有任务都已完成,发送完成事件并退出
  3475. if (!$hasProcessing) {
  3476. // 查询数据库中的最终数据,确保返回最新的完整数据
  3477. try {
  3478. $finalSource = DB::table($table_name)->where($id_field, $id_value)->first();
  3479. if ($finalSource) {
  3480. $finalSource = (array)$finalSource;
  3481. $finalRoles = json_decode(getProp($finalSource, 'roles', '[]'), true) ?: [];
  3482. $finalScenes = json_decode(getProp($finalSource, 'scenes', '[]'), true) ?: [];
  3483. $finalProps = json_decode(getProp($finalSource, 'props', '[]'), true) ?: [];
  3484. // 使用数据库中的最终数据
  3485. $roles = $finalRoles;
  3486. $scenes = $finalScenes;
  3487. $props = $finalProps;
  3488. }
  3489. } catch (\Exception $e) {
  3490. dLog('anime')->error('查询最终数据失败: ' . $e->getMessage());
  3491. // 如果查询失败,继续使用内存中的数据
  3492. }
  3493. // 清理缓存
  3494. Redis::del($cacheKey);
  3495. echo "data: " . json_encode([
  3496. 'type' => 'completed',
  3497. 'data' => [
  3498. 'roles' => $roles,
  3499. 'scenes' => $scenes,
  3500. 'props' => $props,
  3501. 'total_time' => time() - $startTime
  3502. ]
  3503. ], JSON_UNESCAPED_UNICODE) . "\n\n";
  3504. if (ob_get_level() > 0) {
  3505. ob_flush();
  3506. }
  3507. flush();
  3508. break;
  3509. }
  3510. // 等待下次检查
  3511. sleep($checkInterval);
  3512. }
  3513. // 超时处理
  3514. if (time() - $startTime >= $maxDuration) {
  3515. // 查询数据库中的最终数据,即使超时也要返回最新数据
  3516. try {
  3517. $finalSource = DB::table($table_name)->where($id_field, $id_value)->first();
  3518. if ($finalSource) {
  3519. $finalSource = (array)$finalSource;
  3520. $finalRoles = json_decode(getProp($finalSource, 'roles', '[]'), true) ?: [];
  3521. $finalScenes = json_decode(getProp($finalSource, 'scenes', '[]'), true) ?: [];
  3522. $finalProps = json_decode(getProp($finalSource, 'props', '[]'), true) ?: [];
  3523. // 使用数据库中的最终数据
  3524. $roles = $finalRoles;
  3525. $scenes = $finalScenes;
  3526. $props = $finalProps;
  3527. }
  3528. } catch (\Exception $e) {
  3529. dLog('anime')->error('超时时查询最终数据失败: ' . $e->getMessage());
  3530. // 如果查询失败,继续使用内存中的数据
  3531. }
  3532. // 清理缓存
  3533. Redis::del($cacheKey);
  3534. echo "data: " . json_encode([
  3535. 'type' => 'timeout',
  3536. 'message' => '轮询超时,请刷新页面查看最新状态',
  3537. 'data' => [
  3538. 'roles' => $roles,
  3539. 'scenes' => $scenes,
  3540. 'props' => $props
  3541. ]
  3542. ], JSON_UNESCAPED_UNICODE) . "\n\n";
  3543. if (ob_get_level() > 0) {
  3544. ob_flush();
  3545. }
  3546. flush();
  3547. }
  3548. };
  3549. }
  3550. public function clipSegmentVideo($data) {
  3551. $segment_id = getProp($data, 'segment_id');
  3552. $video_time_point_start = getProp($data, 'video_time_point_start');
  3553. $video_time_point_end = getProp($data, 'video_time_point_end');
  3554. if (!$segment_id || !$video_time_point_start || !$video_time_point_end) {
  3555. Utils::throwError('20003:参数异常');
  3556. }
  3557. if (!DB::table('mp_episode_segments')->where('segment_id', $segment_id)->value('video_url')) {
  3558. Utils::throwError('20003:该分镜没有视频,无法裁剪');
  3559. }
  3560. $video_duration = $video_time_point_end - $video_time_point_start;
  3561. if (!$video_duration < 0) Utils::throwError('20003:参数异常');
  3562. return DB::table('mp_episode_segments')->where('segment_id', $segment_id)->update([
  3563. 'video_duration' => $video_duration,
  3564. 'video_time_point_start' => $video_time_point_start,
  3565. 'video_time_point_end' => $video_time_point_end,
  3566. 'updated_at' => date('Y-m-d H:i:s')
  3567. ]);
  3568. }
  3569. // 轮训获取图片任务结果
  3570. private function loopGetPicTaskResult($task_id) {
  3571. $task = MpGeneratePicTask::where('id', $task_id)->first();
  3572. if (!$task) {
  3573. return '';
  3574. }
  3575. // 检查任务模型类型(火山模型和GPT模型都支持直接检查任务状态)
  3576. $model = getProp($task, 'model');
  3577. $isVolcModel = in_array($model, \App\Consts\BaseConst::VOLC_PIC_MODELS);
  3578. $isGptModel = in_array($model, \App\Consts\BaseConst::GPT_IMAGE2_MODELS);
  3579. $isSyncModel = $isVolcModel || $isGptModel;
  3580. // 轮询查询任务状态(火山API和即梦AI都需要轮询)
  3581. $start_count = 0;
  3582. $img_url = '';
  3583. while ($start_count <= 60) { // 循环20次请求,每3s一次
  3584. sleep(3);
  3585. $task = MpGeneratePicTask::where('id', $task_id)->first();
  3586. // 如果任务已经完成,直接返回结果
  3587. if ($task->status === 'success' && $task->result_url) {
  3588. $result_urls = is_array($task->result_url) ? $task->result_url : json_decode($task->result_url, true);
  3589. return is_array($result_urls) ? $result_urls[0] : $task->result_url;
  3590. }
  3591. // 如果任务已失败,返回空
  3592. if ($task->status === 'failed') {
  3593. return '';
  3594. }
  3595. if ($isSyncModel) continue;
  3596. // 查询任务状态
  3597. $statusInfo = $this->aiImageGenerationService->queryTaskStatus($task);
  3598. if ($statusInfo['status'] === 'success') {
  3599. $task->updateStatus('success', [
  3600. 'result_url' => $statusInfo['result_url'],
  3601. 'result_json' => $statusInfo['result_json'] ?? []
  3602. ]);
  3603. // 同步调整分镜图片状态和结果
  3604. if (getProp($task, 'alias_segment_id')) {
  3605. DB::table('mp_episode_segments')->where('segment_id', getProp($task, 'alias_segment_id'))->update([
  3606. 'img_url' => $statusInfo['result_url'][0],
  3607. 'pic_task_status' => '已完成',
  3608. ]);
  3609. }
  3610. $img_url = $statusInfo['result_url'][0];
  3611. break;
  3612. } elseif ($statusInfo['status'] === 'failed') {
  3613. $task->updateStatus('failed', [
  3614. 'error_message' => $statusInfo['error_message'],
  3615. 'result_json' => $statusInfo['result_json'] ?? []
  3616. ]);
  3617. if (getProp($task, 'alias_segment_id')) {
  3618. DB::table('mp_episode_segments')->where('segment_id', getProp($task, 'alias_segment_id'))->update([
  3619. 'pic_task_status' => '失败',
  3620. ]);
  3621. }
  3622. break;
  3623. }
  3624. $start_count++;
  3625. }
  3626. return $img_url;
  3627. }
  3628. /**
  3629. * 从分镜内容中提取涉及的角色
  3630. */
  3631. private function extractCharactersFromSegment($segment_content, $available_characters, $roles) {
  3632. $found_characters = [];
  3633. foreach ($available_characters as $character) {
  3634. // 检查角色名称是否在分镜内容中出现
  3635. if (strpos($segment_content, $character) !== false) {
  3636. $found_characters[] = $character;
  3637. }
  3638. }
  3639. if (!$found_characters) {
  3640. foreach ($roles as $character) {
  3641. // 检查角色名称是否在分镜内容中出现
  3642. if (strpos($segment_content, $character) !== false) {
  3643. $found_characters[] = $character;
  3644. }
  3645. }
  3646. }
  3647. return array_unique($found_characters);
  3648. }
  3649. // 从分镜剧本中提取关键字段
  3650. private function handleSegmentContent(&$data) {
  3651. $segmentContent = getProp($data, 'segment_content');
  3652. // 解析分镜详细信息 - 与 Helpers.php 中 handleEpisodeContent 的 segmentData 结构保持一致
  3653. $segmentData = [
  3654. 'description' => '',
  3655. 'composition' => '',
  3656. 'camera_movement' => '',
  3657. 'voice_actor' => '',
  3658. 'dialogue' => '',
  3659. 'frame_type' => '',
  3660. 'scene' => '', // 场景
  3661. 'characters' => '', // 出镜角色
  3662. 'tail_frame' => '', // 尾帧描述
  3663. 'emotion' => '中性', // 情感
  3664. 'gender' => '0', // 性别(0未知,1男,2女)
  3665. 'speed_ratio' => 0, // 语速
  3666. 'loudness_ratio' => 0, // 音量
  3667. 'emotion_scale' => 4, // 情感强度
  3668. 'pitch' => 0, // 音调
  3669. ];
  3670. // 用于存储需要从 segment_content 中移除的匹配项
  3671. $replaceEmptyArr = [];
  3672. // 提取各个字段 - 兼容中文冒号和英文冒号,支持多种表达方式
  3673. if (preg_match('/(?:画面描述|镜头描述|场景描述)[::]\s*([^\n]+)/u', $segmentContent, $descMatch)) {
  3674. $segmentData['description'] = trim($descMatch[1]);
  3675. $data['description'] = trim($descMatch[1]);
  3676. }
  3677. if (preg_match('/(?:构图设计|构图|镜头构图)[::]\s*([^\n]+)/u', $segmentContent, $compMatch)) {
  3678. $segmentData['composition'] = trim($compMatch[1]);
  3679. $data['composition'] = trim($compMatch[1]);
  3680. }
  3681. if (preg_match('/(?:运镜调度|运镜|镜头运动|摄影机运动)[::]\s*([^\n]+)/u', $segmentContent, $cameraMatch)) {
  3682. $segmentData['camera_movement'] = trim($cameraMatch[1]);
  3683. $data['camera_movement'] = trim($cameraMatch[1]);
  3684. }
  3685. if (preg_match('/(?:配音角色|配音|角色|声优)[::]\s*([^\n]+)/u', $segmentContent, $voiceMatch)) {
  3686. $segmentData['voice_actor'] = trim($voiceMatch[1]);
  3687. $data['voice_actor'] = trim($voiceMatch[1]);
  3688. }
  3689. if (preg_match('/(?:台词内容|台词|对白|对话)[::]\s*([^\n]+)/u', $segmentContent, $dialogueMatch)) {
  3690. $segmentData['dialogue'] = trim($dialogueMatch[1]);
  3691. $data['dialogue'] = trim($dialogueMatch[1]);
  3692. }
  3693. if (preg_match('/(?:画面类型|镜头类型|类型)[::]\s*([^\n]+)/u', $segmentContent, $frameMatch)) {
  3694. $segmentData['frame_type'] = trim($frameMatch[1]);
  3695. $data['frame_type'] = trim($frameMatch[1]);
  3696. }
  3697. // 场景字段
  3698. if (preg_match('/(?:场景|拍摄场景|背景场景|环境)[::]\s*([^\n]+)/u', $segmentContent, $sceneMatch)) {
  3699. $segmentData['scene'] = trim($sceneMatch[1]);
  3700. $data['scene'] = trim($sceneMatch[1]);
  3701. }
  3702. // 出镜角色字段
  3703. if (preg_match('/(?:出镜角色|角色出镜|登场角色|人物)[::]\s*([^\n]+)/u', $segmentContent, $charactersMatch)) {
  3704. $segmentData['characters'] = trim($charactersMatch[1]);
  3705. $data['characters'] = trim($charactersMatch[1]);
  3706. }
  3707. // 尾帧描述字段
  3708. if (preg_match('/(?:尾帧描述|尾帧|结束帧|最后一帧|结尾画面|结束画面)[::]\s*([^\n]+)/u', $segmentContent, $tailFrameMatch)) {
  3709. $segmentData['tail_frame'] = trim($tailFrameMatch[1]);
  3710. $data['tail_frame'] = trim($tailFrameMatch[1]);
  3711. }
  3712. // 情感字段
  3713. if (preg_match('/(?:情感|情绪|感情)[::]\s*([^\n]+)/u', $segmentContent, $emotionMatch)) {
  3714. $replaceEmptyArr[] = trim($emotionMatch[0]);
  3715. $segmentData['emotion'] = trim($emotionMatch[1]);
  3716. $data['emotion'] = trim($emotionMatch[1]);
  3717. }
  3718. // 性别字段
  3719. if (preg_match('/(?:性别)[::]\s*([^\n]+)/u', $segmentContent, $genderMatch)) {
  3720. $replaceEmptyArr[] = trim($genderMatch[0]);
  3721. $genderStr = trim($genderMatch[1]);
  3722. if (strpos($genderStr, '男') !== false || $genderStr === '1') {
  3723. $segmentData['gender'] = '1';
  3724. $data['gender'] = '1';
  3725. } elseif (strpos($genderStr, '女') !== false || $genderStr === '2') {
  3726. $segmentData['gender'] = '2';
  3727. $data['gender'] = '2';
  3728. } else {
  3729. $segmentData['gender'] = '0';
  3730. $data['gender'] = '0';
  3731. }
  3732. }
  3733. // 语速字段
  3734. if (preg_match('/(?:语速|说话速度)[::]\s*([-+]?[0-9]*\.?[0-9]+)/u', $segmentContent, $speedMatch)) {
  3735. $replaceEmptyArr[] = trim($speedMatch[0]);
  3736. $segmentData['speed_ratio'] = (float)trim($speedMatch[1]);
  3737. $data['speed_ratio'] = (float)trim($speedMatch[1]);
  3738. }
  3739. // 音量字段
  3740. if (preg_match('/(?:音量|声音大小)[::]\s*([-+]?[0-9]*\.?[0-9]+)/u', $segmentContent, $loudnessMatch)) {
  3741. $replaceEmptyArr[] = trim($loudnessMatch[0]);
  3742. $segmentData['loudness_ratio'] = (float)trim($loudnessMatch[1]);
  3743. $data['loudness_ratio'] = (float)trim($loudnessMatch[1]);
  3744. }
  3745. // 情感强度字段
  3746. if (preg_match('/(?:情感强度|情绪强度)[::]\s*([0-9]+)/u', $segmentContent, $scaleMatch)) {
  3747. $replaceEmptyArr[] = trim($scaleMatch[0]);
  3748. $segmentData['emotion_scale'] = (int)trim($scaleMatch[1]);
  3749. $data['emotion_scale'] = (int)trim($scaleMatch[1]);
  3750. }
  3751. // 音调字段
  3752. if (preg_match('/(?:音调|音高)[::]\s*([-+]?[0-9]+)/u', $segmentContent, $pitchMatch)) {
  3753. $replaceEmptyArr[] = trim($pitchMatch[0]);
  3754. $segmentData['pitch'] = (int)trim($pitchMatch[1]);
  3755. $data['pitch'] = (int)trim($pitchMatch[1]);
  3756. }
  3757. // 从 segment_content 中移除已提取的配音参数字段
  3758. if (!empty($replaceEmptyArr)) {
  3759. $data['segment_content'] = str_replace($replaceEmptyArr, '', $segmentContent);
  3760. }
  3761. // 如果有配音角色,查询音色信息并验证情感
  3762. $voice_actor = $segmentData['voice_actor'];
  3763. if (!empty($voice_actor) && $voice_actor !== '旁白') {
  3764. // 从当前分镜所属的剧集或动漫中查找角色音色信息
  3765. $anime_id = getProp($data, 'anime_id');
  3766. $episode_id = getProp($data, 'episode_id');
  3767. // 优先从剧集的角色列表中查找
  3768. $roles = [];
  3769. if ($episode_id) {
  3770. $episode = DB::table('mp_anime_episodes')->where('id', $episode_id)->first();
  3771. if ($episode && getProp($episode, 'roles')) {
  3772. $roles = json_decode(getProp($episode, 'roles'), true) ?: [];
  3773. }
  3774. }
  3775. // 如果剧集中没有,从动漫的角色列表中查找
  3776. if (empty($roles) && $anime_id) {
  3777. $anime = DB::table('mp_animes')->where('id', $anime_id)->first();
  3778. if ($anime && getProp($anime, 'roles')) {
  3779. $roles = json_decode(getProp($anime, 'roles'), true) ?: [];
  3780. }
  3781. }
  3782. // 查找匹配的角色音色信息
  3783. $timbre_info = null;
  3784. foreach ($roles as $role) {
  3785. if (getProp($role, 'role') === $voice_actor) {
  3786. $timbre_info = $role;
  3787. break;
  3788. }
  3789. }
  3790. // 如果找到音色信息,添加到数据中
  3791. if ($timbre_info) {
  3792. $voice_type = getProp($timbre_info, 'voice_type');
  3793. $voice_name = getProp($timbre_info, 'voice_name');
  3794. $voice_audio_url = getProp($timbre_info, 'voice_audio_url');
  3795. if ($voice_type) {
  3796. $data['voice_type'] = $voice_type;
  3797. $segmentData['voice_type'] = $voice_type;
  3798. }
  3799. if ($voice_name) {
  3800. $data['voice_name'] = $voice_name;
  3801. $segmentData['voice_name'] = $voice_name;
  3802. }
  3803. if ($voice_audio_url) {
  3804. $data['voice_audio_url'] = $voice_audio_url;
  3805. $segmentData['voice_audio_url'] = $voice_audio_url;
  3806. }
  3807. // 验证情感是否在音色支持的情感列表中
  3808. if ($voice_type) {
  3809. $timbre_emotion = DB::table('mp_timbres')->where('timbre_type', $voice_type)->value('emotion');
  3810. if ($timbre_emotion) {
  3811. $timbre_emotion = explode(',', $timbre_emotion);
  3812. } else {
  3813. $timbre_emotion = [];
  3814. }
  3815. $emotion = getProp($segmentData, 'emotion', '中性');
  3816. if (!in_array($emotion, $timbre_emotion)) {
  3817. $emotion = '中性';
  3818. }
  3819. $emotion_list = DB::table('mp_emotion_list')->where('is_enabled', 1)->pluck('emotion_name', 'emotion_code')->toArray();
  3820. $emotion_list = array_flip($emotion_list);
  3821. $emotion_type = isset($emotion_list[$emotion]) ? $emotion_list[$emotion] : 'neutral';
  3822. $data['emotion_type'] = $emotion_type;
  3823. $segmentData['emotion_type'] = $emotion_type;
  3824. }
  3825. }
  3826. }
  3827. return $segmentData;
  3828. }
  3829. public function createSegmentVideoTask($data) {
  3830. $segment_id = getProp($data, 'segment_id');
  3831. $tail_frame = getProp($data, 'tail_frame');
  3832. $first_frame_url = getProp($data, 'first_frame_url');
  3833. $tail_frame_url = getProp($data, 'tail_frame_url');
  3834. $generate_audio = getProp($data, 'generate_audio', 0);
  3835. if (!$segment_id) {
  3836. Utils::throwError('1002:分镜ID不能为空');
  3837. }
  3838. // 获取分镜信息
  3839. $segment = DB::table('mp_episode_segments')->where('segment_id', $segment_id)->first();
  3840. if (!$segment) {
  3841. Utils::throwError('20003:分镜不存在');
  3842. }
  3843. $segment = (array)$segment;
  3844. $episode_id = getProp($segment, 'episode_id');
  3845. $ratio = DB::table('mp_anime_episodes')->where('id', $episode_id)->value('ratio');
  3846. if (!$ratio) $ratio = '9:16';
  3847. // 获取分镜内容
  3848. $segmentContent = getProp($segment, 'segment_content', '');
  3849. // 检查 $segmentContent 中是否已有尾帧描述
  3850. $contentHasTailFrame = preg_match('/(?:尾帧描述|尾帧)[::]\s*([^\n]+)/u', $segmentContent, $contentTailFrameMatch);
  3851. // 确定最终使用的尾帧描述(优先级:用户输入 > segmentContent自带 > 分镜表字段)
  3852. $finalTailFrame = '';
  3853. if ($tail_frame) {
  3854. // 用户输入了尾帧描述,优先使用
  3855. $finalTailFrame = $tail_frame;
  3856. // 如果 segmentContent 中已有尾帧描述,需要替换
  3857. if ($contentHasTailFrame) {
  3858. $segmentContent = preg_replace('/(?:尾帧描述|尾帧)[::]\s*[^\n]+/u', "尾帧描述:$tail_frame", $segmentContent);
  3859. }
  3860. } elseif ($contentHasTailFrame) {
  3861. // segmentContent 中有尾帧描述,使用它
  3862. $finalTailFrame = trim($contentTailFrameMatch[1]);
  3863. } else {
  3864. // 两者都没有,使用分镜表中的尾帧描述
  3865. $finalTailFrame = getProp($segment, 'tail_frame', '');
  3866. }
  3867. // 判断 $segmentContent 是否有台词内容,如果有则确保使用中文左右双引号
  3868. $hasDialogue = false;
  3869. if (preg_match('/(?:台词内容|台词|对白|对话)[::]\s*([^\n]+)/u', $segmentContent, $dialogueMatch)) {
  3870. $dialogue = trim($dialogueMatch[1]);
  3871. // 如果台词不为空且不是"无"
  3872. if (!empty($dialogue) && $dialogue !== '无') {
  3873. // 过滤掉所有符号(引号、标点、空格等),只保留文字内容来判断是否有实际台词
  3874. $dialogueFiltered = preg_replace('/[""\'\',。!?、;:…—\-\s\p{P}\p{S}]/u', '', $dialogue);
  3875. if (!empty($dialogueFiltered) && $dialogueFiltered !== '无') {
  3876. $hasDialogue = true;
  3877. }
  3878. $dialogue = preg_replace('/^["”]/u', '“', $dialogue); // 替换句首英文双引号或中文右双引号
  3879. $dialogue = preg_replace('/["“]$/u', '”', $dialogue); // 替换句尾英文双引号或中文左双引号
  3880. // 句首或句尾没有中文双引号,则分别添加中文左右双引号
  3881. if (!preg_match('/^[“]/', $dialogue)) {
  3882. $dialogue = '“' . $dialogue;
  3883. }
  3884. if (!preg_match('/[”]$/', $dialogue)) {
  3885. $dialogue .= '”';
  3886. }
  3887. // 将修改后的台词替换回 $segmentContent
  3888. $originalDialogue = $dialogueMatch[1];
  3889. $segmentContent = str_replace($originalDialogue, $dialogue, $segmentContent);
  3890. }
  3891. }
  3892. // 构建完整的提示词
  3893. $fullPrompt = $segmentContent;
  3894. if ($finalTailFrame && !$contentHasTailFrame) {
  3895. // 只有当 segmentContent 中没有尾帧描述时才追加
  3896. $fullPrompt .= "\n尾帧描述:$finalTailFrame";
  3897. }
  3898. // 去除多余的换行符(将连续多个换行符替换为单个换行符)
  3899. $fullPrompt = preg_replace('/\n{2,}/', "\n", $fullPrompt);
  3900. $fullPrompt = trim($fullPrompt);
  3901. // 当前是否启用音效同出(没台词强制关闭音效同出,节省资源收费)
  3902. $current_generate_audio = $hasDialogue ? $generate_audio : 0;
  3903. // 智能选择视频时长
  3904. // $videoDuration = $this->calculateOptimalVideoDuration($segmentContent, $tail_frame);
  3905. $videoDuration = -1;
  3906. // 处理视频模型
  3907. $model = getProp($data, 'model');
  3908. if (!$model) {
  3909. // 用户没有输入,从episode表获取
  3910. $episode = DB::table('mp_anime_episodes')->where('id', getProp($segment, 'episode_id'))->first();
  3911. $model = getProp($episode, 'video_model');
  3912. if (!$model) {
  3913. // episode表也没有,使用默认值
  3914. $model = 'doubao-seedance-1-5-pro-251215';
  3915. }
  3916. }
  3917. // 验证模型是否在可用模型表中
  3918. if (!DB::table('mp_video_models')->where('model', $model)->where('is_enabled', 1)->exists()) {
  3919. $model = 'doubao-seedance-1-5-pro-251215';
  3920. }
  3921. // 保存到episode表
  3922. $episode_id = getProp($segment, 'episode_id');
  3923. DB::table('mp_anime_episodes')->where('id', $episode_id)->update([
  3924. 'video_model' => $model,
  3925. 'updated_at' => date('Y-m-d H:i:s')
  3926. ]);
  3927. // 构建视频生成参数
  3928. $videoParams = [
  3929. 'model' => $model,
  3930. 'alias_segment_id' => $segment_id,
  3931. 'prompt' => trim($fullPrompt),
  3932. 'video_duration' => $videoDuration,
  3933. 'video_resolution' => '720P',
  3934. 'seed' => -1,
  3935. 'ratio' => $ratio,
  3936. 'generate_audio' => (int)$current_generate_audio === 0 ? false : true,
  3937. 'draft' => false,
  3938. 'watermark' => false,
  3939. 'camera_fixed' => false,
  3940. // 'callback_url' => 'http://mpaudio.yqsd.cn/api/video/seedanceCallback'
  3941. ];
  3942. // 如果分镜有图片,作为首帧
  3943. $hasImage = !empty(getProp($segment, 'img_url')) || $first_frame_url;
  3944. $hasVideo = !empty(getProp($segment, 'video_url'));
  3945. if ($hasImage) {
  3946. if ($first_frame_url) {
  3947. $videoParams['first_frame_url'] = $first_frame_url;
  3948. }else {
  3949. $videoParams['first_frame_url'] = getProp($segment, 'img_url');
  3950. }
  3951. if ($tail_frame_url) $videoParams['tail_frame_url'] = $tail_frame_url;
  3952. }
  3953. // 构建content数组
  3954. $videoParams['content'] = [
  3955. [
  3956. 'type' => 'text',
  3957. 'text' => $videoParams['prompt'],
  3958. ]
  3959. ];
  3960. // 如果有首帧图片,添加到content中
  3961. if ($hasImage) {
  3962. if (in_array($model, ['doubao-seedance-2-0-260128', 'doubao-seedance-2-0-fast-260128'])) {
  3963. $videoParams['content'][] = [
  3964. 'type' => 'image_url',
  3965. 'image_url' => [
  3966. 'url' => $videoParams['first_frame_url'],
  3967. ],
  3968. 'role' => 'reference_image',
  3969. ];
  3970. if (isset($videoParams['tail_frame_url'])) {
  3971. $videoParams['content'][] = [
  3972. 'type' => 'image_url',
  3973. 'image_url' => [
  3974. 'url' => $videoParams['tail_frame_url'],
  3975. ],
  3976. 'role' => 'reference_image',
  3977. ];
  3978. }
  3979. }else {
  3980. $videoParams['content'][] = [
  3981. 'type' => 'image_url',
  3982. 'image_url' => [
  3983. 'url' => $videoParams['first_frame_url'],
  3984. ],
  3985. 'role' => 'first_frame',
  3986. ];
  3987. if (isset($videoParams['tail_frame_url'])) {
  3988. $videoParams['content'][] = [
  3989. 'type' => 'image_url',
  3990. 'image_url' => [
  3991. 'url' => $videoParams['tail_frame_url'],
  3992. ],
  3993. 'role' => 'last_frame',
  3994. ];
  3995. }
  3996. }
  3997. }
  3998. // 获取配音音频URL
  3999. $audioUrl = getProp($segment, 'audio_url');
  4000. $audioDuration = getProp($segment, 'audio_duration');
  4001. // 音频传入的前提:必须有至少一张图片或一个视频
  4002. $canUseAudio = ($hasImage || $hasVideo) && !empty($audioUrl);
  4003. // dd($videoParams);
  4004. // 根据模型选择不同的视频生成方法
  4005. if (strpos($model, 'jimeng') !== false) {
  4006. // 即梦模型参数调整
  4007. $videoParams['video_duration'] = $audioDuration > 5 ? 10 : 5; // 即梦只支持5s或10s
  4008. unset($videoParams['content']); // 即梦不使用content格式
  4009. $task = $this->aiVideoGenerationService->createJimengTask($videoParams);
  4010. } elseif (strpos($model, 'kling') !== false) {
  4011. // Keling模型参数调整
  4012. $videoParams['video_duration'] = max(3, min(15, ceil($audioDuration))); // Keling支持3-15秒
  4013. $videoParams['aspect_ratio'] = $videoParams['ratio']; // Keling使用aspect_ratio
  4014. unset($videoParams['ratio']);
  4015. unset($videoParams['content']); // Keling不使用content格式
  4016. $task = $this->aiVideoGenerationService->createKelingOmniTask($videoParams);
  4017. } elseif (strpos($model, 'zhizhen') !== false) {
  4018. // 智帧20等新模型使用统一API
  4019. // 构建统一API参数
  4020. $unifiedParams = [
  4021. 'model_code' => $model,
  4022. 'alias_segment_id' => $segment_id,
  4023. 'prompt' => trim($fullPrompt),
  4024. 'video_duration' => $audioDuration > 0 ? max(5, min(15, ceil($audioDuration))) : 5,
  4025. 'video_resolution' => strtolower($videoParams['video_resolution']),
  4026. 'video_ratio' => $ratio,
  4027. 'seed' => -1,
  4028. ];
  4029. // 构建parameters参数
  4030. $parameters = [
  4031. 'seconds' => $unifiedParams['video_duration'],
  4032. 'resolution' => $unifiedParams['video_resolution'],
  4033. 'ratio' => $ratio,
  4034. // 'video_mode' => 'multi_image',
  4035. // 'mode' => 'multi_image',
  4036. 'generate_audio' => (int)$current_generate_audio === 1 ? true : false,
  4037. ];
  4038. $hasImage = false;
  4039. // 处理首帧和尾帧(智帧20模型必须要有首帧图片)
  4040. if ($hasImage) {
  4041. $parameters['first_frame_url'] = $videoParams['first_frame_url'];
  4042. if (isset($videoParams['tail_frame_url'])) {
  4043. $parameters['last_frame_url'] = $videoParams['tail_frame_url'];
  4044. }
  4045. // 只有在有图片的情况下才能添加参考音频
  4046. if ($audioUrl) {
  4047. // $parameters['reference_audios'] = [$audioUrl];
  4048. }
  4049. } else {
  4050. // 没有图片时,记录错误日志
  4051. logDB('anime', 'error', '智帧20模型缺少首帧图片', [
  4052. 'segment_id' => $segment_id,
  4053. 'model' => $model
  4054. ]);
  4055. }
  4056. $unifiedParams['parameters'] = $parameters;
  4057. // 调用统一API创建任务
  4058. $task = $this->aiVideoGenerationService->createUnifiedApiTask($unifiedParams);
  4059. } else {
  4060. // Seedance模型(默认)
  4061. // 检查是否为 Seedance 2.0 模型,如果是则需要处理配音音频
  4062. if ($canUseAudio && in_array($model, ['doubao-seedance-2-0-260128', 'doubao-seedance-2-0-fast-260128'])) {
  4063. // 添加配音音频到content中
  4064. $videoParams['content'][] = [
  4065. 'type' => 'audio_url',
  4066. 'audio_url' => [
  4067. 'url' => $audioUrl,
  4068. ],
  4069. 'role' => 'reference_audio',
  4070. ];
  4071. // 优化提示词,增加音频相关描述
  4072. $audioPrompt = "全程使用音频1作为视频配音。" . $fullPrompt;
  4073. $videoParams['prompt'] = $audioPrompt;
  4074. $videoParams['content'][0]['text'] = $audioPrompt;
  4075. } else if ($audioDuration) { // 有音频时长则需将视频时长设置为比音频时长更长的整数
  4076. $videoParams['video_duration'] = max(4, min(12, ceil($audioDuration))); // seedance支持2-12s
  4077. }
  4078. $task = $this->aiVideoGenerationService->createSeedanceTask($videoParams);
  4079. }
  4080. // 更新分镜表的视频任务信息
  4081. DB::table('mp_episode_segments')->where('segment_id', $segment_id)->update([
  4082. 'video_task_id' => $task->id,
  4083. 'video_task_status' => '生成中',
  4084. 'generate_audio' => $generate_audio,
  4085. 'updated_at' => date('Y-m-d H:i:s')
  4086. ]);
  4087. return [
  4088. 'task_id' => $task->id,
  4089. 'status' => $task->status,
  4090. 'segment_id' => $segment_id,
  4091. 'video_duration' => $videoDuration
  4092. ];
  4093. }
  4094. public function createActVideoTask($data) {
  4095. $act_id = getProp($data, 'act_id');
  4096. $first_frame_url = getProp($data, 'first_frame_url');
  4097. $tail_frame_url = getProp($data, 'tail_frame_url');
  4098. $generate_audio = getProp($data, 'generate_audio', 1);
  4099. $video_duration = getProp($data, 'video_duration');
  4100. $video_resolution = getProp($data, 'video_resolution');
  4101. $ratio = getProp($data, 'ratio');
  4102. $products = getProp($data, 'products', []);
  4103. $reference_images = array_unique(getProp($data, 'reference_images', []));
  4104. if (!is_array($reference_images) || !is_array($products)) {
  4105. Utils::throwError('20003:传入的参考图或资产格式不正确');
  4106. }
  4107. if (!$act_id) {
  4108. Utils::throwError('1002:片段ID不能为空');
  4109. }
  4110. // 获取片段信息
  4111. $act = DB::table('mp_episode_segments')->where('id', $act_id)->first();
  4112. if (!$act) {
  4113. Utils::throwError('20003:片段不存在');
  4114. }
  4115. $act = (array)$act;
  4116. $anime_id = getProp($act, 'anime_id');
  4117. $episode_id = getProp($act, 'episode_id');
  4118. $anime = DB::table('mp_animes')->where('id', $anime_id)->first();
  4119. $ace_mode = getProp($anime, 'ace_mode');
  4120. $art_style_type = getProp($anime, 'art_style_type');
  4121. $art_style = getProp($anime, 'art_style');
  4122. $episode = DB::table('mp_anime_episodes')->where('id', $episode_id)->first();
  4123. if (!$ratio) $ratio = getProp($episode, 'ratio', '9:16');
  4124. if (!$video_resolution) $video_resolution = getProp($episode, 'video_resolution', '720p');
  4125. // 将资产中新出现的资产放到extra_products中
  4126. // 满足以下要求: 遍历传入的$products,将product_name与$episode中的roles、scenes和props做比对,如果不在其中,则与$episode中的extra_products做比对,如果有同名的则覆盖,没有则新增后存入$episode中的extra_products字段中
  4127. if (!empty($products) && $episode) {
  4128. // 获取剧集中的角色、场景和道具列表
  4129. $roles = json_decode(getProp($episode, 'roles', '[]'), true) ?: [];
  4130. $scenes = json_decode(getProp($episode, 'scenes', '[]'), true) ?: [];
  4131. $props = json_decode(getProp($episode, 'props', '[]'), true) ?: [];
  4132. $extra_products = json_decode(getProp($episode, 'extra_products', '[]'), true) ?: [];
  4133. // 构建角色名称列表
  4134. $role_names = array_column($roles, 'role');
  4135. // 构建场景名称列表
  4136. $scene_names = array_column($scenes, 'scene');
  4137. // 构建道具名称列表
  4138. $prop_names = array_column($props, 'prop');
  4139. // 遍历传入的products
  4140. foreach ($products as $product) {
  4141. $product_name = getProp($product, 'product_name');
  4142. // 如果product_name不在roles、scenes和props中
  4143. if (!in_array($product_name, $role_names) && !in_array($product_name, $scene_names) && !in_array($product_name, $prop_names)) {
  4144. // 查找是否在extra_products中存在同名的
  4145. $found = false;
  4146. foreach ($extra_products as $key => $extra_product) {
  4147. if (getProp($extra_product, 'product_name') === $product_name) {
  4148. // 有同名的则覆盖
  4149. $extra_products[$key] = $product;
  4150. $found = true;
  4151. break;
  4152. }
  4153. }
  4154. // 没有则新增
  4155. if (!$found) {
  4156. $extra_products[] = $product;
  4157. }
  4158. }
  4159. }
  4160. if ($extra_products) {
  4161. // 保存到数据库
  4162. DB::table('mp_anime_episodes')
  4163. ->where('id', $episode_id)
  4164. ->update([
  4165. 'extra_products' => json_encode($extra_products, 256),
  4166. 'updated_at' => date('Y-m-d H:i:s')
  4167. ]);
  4168. }
  4169. }
  4170. // 获取分镜内容
  4171. $actContent = getProp($act, 'act_show_content', '');
  4172. // 音效同出(默认使用)
  4173. $current_generate_audio = $generate_audio ? 1 : 0;
  4174. // 构建完整的提示词
  4175. $processResult = $this->processActContentWithProducts($actContent, $products);
  4176. $fullPrompt = $processResult['content'];
  4177. // if ($art_style_type == '3D真人风格') $fullPrompt = "美术风格: $art_style\n\n".$fullPrompt;
  4178. $reference_images = array_merge($processResult['reference_images'], $reference_images);
  4179. $videoDuration = $video_duration ? $video_duration : getProp($act, 'act_duration');
  4180. // 处理视频模型
  4181. $model = getProp($data, 'model');
  4182. if (!$model) {
  4183. $model = getProp($episode, 'video_model');
  4184. if (!$model) {
  4185. // episode表也没有,使用默认值
  4186. $model = 'zhizhen-20';
  4187. }
  4188. }
  4189. // 验证模型是否在可用模型表中
  4190. if (!DB::table('mp_video_models')->where('model', $model)->where('is_enabled', 1)->exists()) {
  4191. $model = 'zhizhen-20';
  4192. }
  4193. // 保存到episode表
  4194. DB::table('mp_anime_episodes')->where('id', $episode_id)->update([
  4195. 'video_model' => $model,
  4196. 'updated_at' => date('Y-m-d H:i:s')
  4197. ]);
  4198. // 构建视频生成参数
  4199. $videoParams = [
  4200. 'model' => $model,
  4201. 'alias_act_id' => $act_id,
  4202. 'prompt' => trim($fullPrompt),
  4203. 'video_duration' => $videoDuration,
  4204. 'video_resolution' => $video_resolution,
  4205. 'seed' => -1,
  4206. 'ratio' => $ratio,
  4207. 'generate_audio' => (int)$current_generate_audio === 0 ? false : true,
  4208. 'draft' => false,
  4209. 'watermark' => false,
  4210. 'camera_fixed' => false,
  4211. // 'callback_url' => 'http://mpaudio.yqsd.cn/api/video/seedanceCallback'
  4212. ];
  4213. // 如果分镜有图片,作为首帧
  4214. $hasImage = !empty(getProp($act, 'img_url')) || $first_frame_url;
  4215. $hasVideo = !empty(getProp($act, 'video_url'));
  4216. if ($hasImage) {
  4217. if ($first_frame_url) {
  4218. $videoParams['first_frame_url'] = $first_frame_url;
  4219. }else {
  4220. $videoParams['first_frame_url'] = getProp($act, 'img_url');
  4221. }
  4222. if ($tail_frame_url) $videoParams['tail_frame_url'] = $tail_frame_url;
  4223. }
  4224. // 构建content数组
  4225. $videoParams['content'] = [
  4226. [
  4227. 'type' => 'text',
  4228. 'text' => $videoParams['prompt'],
  4229. ]
  4230. ];
  4231. // 如果有首帧图片,添加到content中
  4232. if ($hasImage) {
  4233. if (in_array($model, ['doubao-seedance-2-0-260128', 'doubao-seedance-2-0-fast-260128', 'doubao-seedance-2.0'])) {
  4234. $videoParams['content'][] = [
  4235. 'type' => 'image_url',
  4236. 'image_url' => [
  4237. 'url' => $videoParams['first_frame_url'],
  4238. ],
  4239. 'role' => 'reference_image',
  4240. ];
  4241. if (isset($videoParams['tail_frame_url'])) {
  4242. $videoParams['content'][] = [
  4243. 'type' => 'image_url',
  4244. 'image_url' => [
  4245. 'url' => $videoParams['tail_frame_url'],
  4246. ],
  4247. 'role' => 'reference_image',
  4248. ];
  4249. }
  4250. }else {
  4251. $videoParams['content'][] = [
  4252. 'type' => 'image_url',
  4253. 'image_url' => [
  4254. 'url' => $videoParams['first_frame_url'],
  4255. ],
  4256. 'role' => 'first_frame',
  4257. ];
  4258. if (isset($videoParams['tail_frame_url'])) {
  4259. $videoParams['content'][] = [
  4260. 'type' => 'image_url',
  4261. 'image_url' => [
  4262. 'url' => $videoParams['tail_frame_url'],
  4263. ],
  4264. 'role' => 'last_frame',
  4265. ];
  4266. }
  4267. }
  4268. }
  4269. // dd($videoParams);
  4270. // 根据模型选择不同的视频生成方法
  4271. if (strpos($model, 'jimeng') !== false) {
  4272. // 即梦模型参数调整
  4273. unset($videoParams['content']); // 即梦不使用content格式
  4274. $task = $this->aiVideoGenerationService->createJimengTask($videoParams);
  4275. } elseif (strpos($model, 'kling') !== false) {
  4276. // Keling模型参数调整
  4277. $videoParams['aspect_ratio'] = $videoParams['ratio']; // Keling使用aspect_ratio
  4278. unset($videoParams['ratio']);
  4279. unset($videoParams['content']); // Keling不使用content格式
  4280. $task = $this->aiVideoGenerationService->createKelingOmniTask($videoParams);
  4281. } elseif (strpos($model, 'zhizhen') !== false) {
  4282. // 智帧20等新模型使用统一API
  4283. // 构建统一API参数
  4284. $unifiedParams = [
  4285. 'model_code' => $model,
  4286. 'alias_act_id' => $act_id,
  4287. 'prompt' => trim($fullPrompt),
  4288. 'video_duration' => $videoDuration,
  4289. 'video_resolution' => strtolower($videoParams['video_resolution']),
  4290. 'video_ratio' => $ratio,
  4291. 'seed' => -1,
  4292. ];
  4293. // 构建parameters参数
  4294. $parameters = [
  4295. 'seconds' => $unifiedParams['video_duration'],
  4296. 'resolution' => $unifiedParams['video_resolution'],
  4297. 'ratio' => $ratio,
  4298. // 'video_mode' => 'multi_image',
  4299. // 'mode' => 'multi_image',
  4300. 'generate_audio' => (int)$current_generate_audio === 1 ? true : false,
  4301. ];
  4302. $hasImage = false;
  4303. // 处理首帧和尾帧(智帧20模型必须要有首帧图片)
  4304. if ($hasImage) {
  4305. $parameters['first_frame_url'] = $videoParams['first_frame_url'];
  4306. if (isset($videoParams['tail_frame_url'])) {
  4307. $parameters['last_frame_url'] = $videoParams['tail_frame_url'];
  4308. }
  4309. } else {
  4310. // 没有图片时,记录错误日志
  4311. logDB('anime', 'error', '智帧20模型缺少首帧图片', [
  4312. 'act_id' => $act_id,
  4313. 'model' => $model
  4314. ]);
  4315. }
  4316. if ($reference_images) {
  4317. // 限制只传入9张参考图
  4318. $reference_images = array_slice($reference_images, 0, 9);
  4319. // 在处理之前先保存原始reference_images到任务参数中
  4320. $unifiedParams['ref_image_url'] = json_encode($reference_images, 256);
  4321. $reference_images = $this->aiImageGenerationService->processReferenceImagesToAssets($reference_images, $unifiedParams['prompt']);
  4322. $parameters['reference_images'] = $reference_images;
  4323. $parameters['video_mode'] = 'multi_image';
  4324. $parameters['mode'] = 'multi_image';
  4325. }
  4326. $unifiedParams['parameters'] = $parameters;
  4327. // 调用统一API创建任务
  4328. $task = $this->aiVideoGenerationService->createUnifiedApiTask($unifiedParams);
  4329. } elseif (strpos($model, 'doubao-seedance-2.0') !== false) {
  4330. // 豆包Seedance 2.0(百度AI网关):图片需要先上传为素材
  4331. // 保存原始参考图用于任务记录
  4332. $videoParams['reference_images'] = $reference_images;
  4333. if ($reference_images) {
  4334. // 限制只传入9张参考图
  4335. $reference_images = array_slice($reference_images, 0, 9);
  4336. // 参考图上传为百度网关素材,上传失败时同步清理提示词中的<图片N>标记
  4337. $reference_image_assets = $this->aiVideoGenerationService->processReferenceImagesToSeedance20Assets($reference_images, $fullPrompt);
  4338. // 素材上传失败后提示词可能被清理,同步更新视频参数中的提示词
  4339. $videoParams['prompt'] = trim($fullPrompt);
  4340. $videoParams['content'][0]['text'] = trim($fullPrompt);
  4341. $videoParams['reference_image_assets'] = $reference_image_assets;
  4342. }
  4343. $task = $this->aiVideoGenerationService->createSeedance20Task($videoParams);
  4344. } else {
  4345. $task = $this->aiVideoGenerationService->createSeedanceTask($videoParams);
  4346. }
  4347. // 更新分镜表的视频任务信息
  4348. DB::table('mp_episode_segments')->where('id', $act_id)->update([
  4349. 'video_task_id' => $task->id,
  4350. 'video_task_status' => '生成中',
  4351. 'generate_audio' => $generate_audio,
  4352. 'updated_at' => date('Y-m-d H:i:s')
  4353. ]);
  4354. // 如果是全能模式,并且是第一集的第一个片段,将act_id存入Redis
  4355. $episode_number = getProp($act, 'episode_number');
  4356. $act_number = getProp($act, 'act_number');
  4357. if ((int)$ace_mode === 1 && (int)$episode_number === 1 && (int)$act_number === 1) {
  4358. Redis::sadd('anime_act_first_frame_urls', $act_id);
  4359. }
  4360. return [
  4361. 'task_id' => $task->id,
  4362. 'status' => $task->status,
  4363. 'act_id' => $act_id,
  4364. 'video_duration' => $videoDuration
  4365. ];
  4366. }
  4367. /**
  4368. * 根据提示词内容智能计算最优视频时长
  4369. *
  4370. * @param string $segmentContent 分镜内容
  4371. * @param string $tailFrame 尾帧描述
  4372. * @return int 视频时长(2-12秒)
  4373. */
  4374. public function calculateOptimalVideoDuration($segmentContent, $tailFrame = '') {
  4375. // 合并所有文本内容
  4376. $fullText = trim($segmentContent . ' ' . $tailFrame);
  4377. // 如果没有内容,返回默认时长
  4378. if (empty($fullText)) {
  4379. return 5;
  4380. }
  4381. // 计算文本长度(中文字符按2个字符计算)
  4382. $textLength = mb_strlen($fullText, 'UTF-8');
  4383. $chineseCharCount = preg_match_all('/[\x{4e00}-\x{9fff}]/u', $fullText);
  4384. $adjustedLength = $textLength + $chineseCharCount; // 中文字符权重更高
  4385. // 分析内容复杂度
  4386. $complexityScore = $this->analyzeContentComplexity($fullText);
  4387. // 基础时长计算(根据文本长度)
  4388. $baseDuration = 3; // 默认2秒
  4389. // if ($adjustedLength <= 20) {
  4390. // $baseDuration = 3;
  4391. // } elseif ($adjustedLength <= 40) {
  4392. // $baseDuration = 4;
  4393. // } elseif ($adjustedLength <= 60) {
  4394. // $baseDuration = 5;
  4395. // } elseif ($adjustedLength <= 80) {
  4396. // $baseDuration = 6;
  4397. // } elseif ($adjustedLength <= 100) {
  4398. // $baseDuration = 7;
  4399. // } elseif ($adjustedLength <= 120) {
  4400. // $baseDuration = 8;
  4401. // } else {
  4402. // $baseDuration = 9;
  4403. // }
  4404. // 根据内容复杂度调整时长
  4405. $finalDuration = $baseDuration + $complexityScore;
  4406. // 确保时长在2-12秒范围内
  4407. return max(4, min(12, $finalDuration));
  4408. }
  4409. /**
  4410. * 分析内容复杂度,返回时长调整值
  4411. *
  4412. * @param string $text 文本内容
  4413. * @return int 调整值(-2到+3)
  4414. */
  4415. private function analyzeContentComplexity($text) {
  4416. $score = 0;
  4417. // 动作关键词(需要更长时间展现)
  4418. $actionKeywords = [
  4419. '跑步', '奔跑', '飞行', '跳跃', '战斗', '打斗', '追逐', '逃跑', '舞蹈', '表演',
  4420. '变化', '变身', '爆炸', '崩塌', '建造', '制作', '烹饪', '绘画', '写字',
  4421. '移动', '旋转', '翻滚', '攀爬', '游泳', '潜水', '滑行', '飞翔'
  4422. ];
  4423. // 静态关键词(可以用较短时间)
  4424. $staticKeywords = [
  4425. '站立', '坐着', '躺着', '静止', '凝视', '思考', '沉思', '观察', '等待',
  4426. '睡觉', '休息', '静坐', '冥想', '阅读', '听音乐'
  4427. ];
  4428. // 复杂场景关键词(需要更长时间)
  4429. $complexSceneKeywords = [
  4430. '人群', '聚会', '会议', '战争', '庆典', '仪式', '表演', '比赛', '竞技',
  4431. '多人', '群体', '团队', '合作', '互动', '对话', '争论', '讨论'
  4432. ];
  4433. // 情感关键词(需要适中时间表现)
  4434. $emotionKeywords = [
  4435. '哭泣', '笑容', '愤怒', '惊讶', '恐惧', '悲伤', '喜悦', '兴奋', '紧张',
  4436. '感动', '震惊', '困惑', '失望', '希望', '绝望', '温柔', '严肃'
  4437. ];
  4438. // 检查动作关键词
  4439. foreach ($actionKeywords as $keyword) {
  4440. if (strpos($text, $keyword) !== false) {
  4441. $score += 1;
  4442. break; // 避免重复加分
  4443. }
  4444. }
  4445. // 检查静态关键词
  4446. foreach ($staticKeywords as $keyword) {
  4447. if (strpos($text, $keyword) !== false) {
  4448. $score -= 1;
  4449. break;
  4450. }
  4451. }
  4452. // 检查复杂场景关键词
  4453. foreach ($complexSceneKeywords as $keyword) {
  4454. if (strpos($text, $keyword) !== false) {
  4455. $score += 1;
  4456. break;
  4457. }
  4458. }
  4459. // 检查情感关键词
  4460. foreach ($emotionKeywords as $keyword) {
  4461. if (strpos($text, $keyword) !== false) {
  4462. $score += 1;
  4463. break;
  4464. }
  4465. }
  4466. // 检查时间相关词汇
  4467. if (preg_match('/缓慢|慢慢|渐渐|逐渐|慢动作/', $text)) {
  4468. $score += 1;
  4469. }
  4470. if (preg_match('/快速|迅速|急速|瞬间|立刻|马上/', $text)) {
  4471. $score -= 1;
  4472. }
  4473. // 检查转场词汇
  4474. if (preg_match('/然后|接着|随后|紧接着|同时|与此同时/', $text)) {
  4475. $score += 1;
  4476. }
  4477. // 检查环境描述(复杂环境需要更多时间)
  4478. if (preg_match('/风景|景色|环境|背景|氛围|光线|阴影|色彩|细节/', $text)) {
  4479. $score += 1;
  4480. }
  4481. // 检查对话内容(对话需要更多时间)
  4482. if (preg_match('/说|讲|告诉|回答|询问|问|对话|交谈/', $text)) {
  4483. $score += 1;
  4484. }
  4485. // 限制调整范围
  4486. return max(-1, min(4, $score));
  4487. }
  4488. /**
  4489. * 创建完整视频合成任务
  4490. *
  4491. * @param array $data
  4492. * @return array
  4493. */
  4494. public function createCompleteVideoTask($data)
  4495. {
  4496. $animeId = getProp($data, 'anime_id');
  4497. $episodeId = getProp($data, 'episode_id');
  4498. // 验证参数
  4499. if (!$animeId || !$episodeId) {
  4500. Utils::throwError('20003:anime_id 和 episode_id 不能为空');
  4501. }
  4502. // 检查是否已存在处理中的任务
  4503. $existingTask = DB::table('mp_complete_video_tasks')
  4504. ->where('anime_id', $animeId)
  4505. ->where('episode_id', $episodeId)
  4506. ->whereIn('generate_status', ['执行中'])
  4507. ->first();
  4508. if ($existingTask) {
  4509. Utils::throwError('20003:该剧集已有正在处理的视频合成任务');
  4510. }
  4511. // 获取全能模式状态
  4512. $ace_mode = DB::table('mp_animes')->where('id', $animeId)->value('ace_mode');
  4513. if ((int)$ace_mode === 1) {
  4514. // 获取所有片段的配音视频,按 act_number 排序
  4515. $segments = DB::table('mp_episode_segments')
  4516. ->where('anime_id', $animeId)
  4517. ->where('episode_id', $episodeId)
  4518. ->orderBy('segment_number')
  4519. ->select('id as act_id', 'act_number', 'video_url', 'audio_url', 'video_time_point_start', 'video_time_point_end')
  4520. ->get();
  4521. // 检查是否所有片段都有视频
  4522. $missingVideos = $segments->filter(function($segment) {
  4523. return empty($segment->video_url);
  4524. });
  4525. if ($missingVideos->isNotEmpty()) {
  4526. Utils::throwError('20003:存在未完成视频的片段,请确保所有片段都已完成配音');
  4527. }
  4528. }else {
  4529. // 获取所有分镜的配音视频,按 segment_number 排序
  4530. $segments = DB::table('mp_episode_segments')
  4531. ->where('anime_id', $animeId)
  4532. ->where('episode_id', $episodeId)
  4533. ->orderBy('segment_number')
  4534. ->select('segment_id', 'segment_number', 'video_url', 'audio_url', 'video_time_point_start', 'video_time_point_end')
  4535. ->get();
  4536. // 检查是否所有分镜都有配音和视频
  4537. $missingVideos = $segments->filter(function($segment) {
  4538. return empty($segment->audio_url) || empty($segment->video_url);
  4539. });
  4540. if ($missingVideos->isNotEmpty()) {
  4541. Utils::throwError('20003:存在未完成配音或视频的分镜,请确保所有分镜都已完成配音或视频');
  4542. }
  4543. }
  4544. if ($segments->isEmpty()) {
  4545. Utils::throwError('20003:未找到该剧集的分镜数据');
  4546. }
  4547. // 获取当前完整视频url
  4548. $completeVideoUrl = DB::table('mp_anime_episodes')
  4549. ->where('anime_id', $animeId)
  4550. ->where('id', $episodeId)
  4551. ->value('complete_video_url');
  4552. // 构建 generate_json
  4553. $generateJson = [];
  4554. $sequence = 1;
  4555. foreach ($segments as $segment) {
  4556. if ((int)$ace_mode === 1) {
  4557. $generateJson[] = [
  4558. 'sequence' => $sequence++,
  4559. 'video_url' => $segment->video_url,
  4560. 'video_time_point_start' => $segment->video_time_point_start,
  4561. 'video_time_point_end' => $segment->video_time_point_end
  4562. ];
  4563. }else {
  4564. $generateJson[] = [
  4565. 'sequence' => $sequence++,
  4566. 'video_url' => $segment->video_url,
  4567. 'audio_url' => $segment->audio_url,
  4568. 'video_time_point_start' => $segment->video_time_point_start,
  4569. 'video_time_point_end' => $segment->video_time_point_end
  4570. ];
  4571. }
  4572. }
  4573. // 创建任务
  4574. $now = date('Y-m-d H:i:s');
  4575. $taskId = DB::table('mp_complete_video_tasks')->insertGetId([
  4576. 'anime_id' => $animeId,
  4577. 'episode_id' => $episodeId,
  4578. 'generate_json' => json_encode($generateJson, 256),
  4579. 'generate_status' => '执行中',
  4580. 'complete_video_url' => '',
  4581. 'created_at' => $now,
  4582. 'updated_at' => $now
  4583. ]);
  4584. if (!$taskId) {
  4585. Utils::throwError('20003:创建任务失败');
  4586. }
  4587. // 更新剧集表的任务ID和状态
  4588. $boolen = DB::table('mp_anime_episodes')
  4589. ->where('anime_id', $animeId)
  4590. ->where('id', $episodeId)
  4591. ->update([
  4592. 'complete_video_task_id' => $taskId,
  4593. 'complete_video_task_status' => '执行中',
  4594. 'updated_at' => $now
  4595. ]);
  4596. if (!$boolen) {
  4597. Utils::throwError('20003:更新剧集表失败');
  4598. }
  4599. dLog('anime')->info('创建完整视频合成任务', [
  4600. 'task_id' => $taskId,
  4601. 'anime_id' => $animeId,
  4602. 'episode_id' => $episodeId,
  4603. 'segment_count' => count($generateJson)
  4604. ]);
  4605. // 请求远程服务器执行生成
  4606. $client = new Client(['timeout' => 600, 'verify' => false]);
  4607. try {
  4608. $result = $client->get("http://122.9.129.83:5000/api/anime/genVideo?taskId={$taskId}");
  4609. $response = $result->getBody()->getContents();
  4610. $response_arr = json_decode($response, true);
  4611. if (!isset($response_arr['code']) || (int)$response_arr['code'] !== 0) {
  4612. $error_msg = isset($response_arr['msg']) ? $response_arr['msg'] : '未知错误';
  4613. dLog('anime')->error('火山合成完整视频失败', ['error' => $error_msg, 'task_id' => $taskId]);
  4614. // // 更新任务状态为失败
  4615. // DB::table('mp_complete_video_tasks')
  4616. // ->where('id', $taskId)
  4617. // ->update([
  4618. // 'generate_status' => '执行失败',
  4619. // 'error_message' => $error_msg,
  4620. // 'updated_at' => date('Y-m-d H:i:s')
  4621. // ]);
  4622. // // 同步更新剧集表状态
  4623. // DB::table('mp_anime_episodes')
  4624. // ->where('complete_video_task_id', $taskId)
  4625. // ->update([
  4626. // 'complete_video_task_status' => '执行失败',
  4627. // 'updated_at' => date('Y-m-d H:i:s')
  4628. // ]);
  4629. Utils::throwError('20003:火山合成完整视频失败: ' . $error_msg);
  4630. }
  4631. } catch (\Exception $e) {
  4632. dLog('anime')->error('调用远程服务器失败', ['error' => $e->getMessage(), 'task_id' => $taskId]);
  4633. // 更新任务状态为失败
  4634. DB::table('mp_complete_video_tasks')
  4635. ->where('id', $taskId)
  4636. ->update([
  4637. 'generate_status' => '执行失败',
  4638. 'error_message' => $e->getMessage(),
  4639. 'updated_at' => date('Y-m-d H:i:s')
  4640. ]);
  4641. // 同步更新剧集表状态
  4642. DB::table('mp_anime_episodes')
  4643. ->where('complete_video_task_id', $taskId)
  4644. ->update([
  4645. 'complete_video_task_status' => '执行失败',
  4646. 'updated_at' => date('Y-m-d H:i:s')
  4647. ]);
  4648. Utils::throwError('20003:调用远程服务器失败: ' . $e->getMessage());
  4649. }
  4650. // 开始轮询任务状态
  4651. $maxAttempts = 60; // 5分钟 = 60次 * 5秒
  4652. $pollInterval = 5; // 每5秒轮询一次
  4653. $attempt = 0;
  4654. dLog('anime')->info('开始轮询任务状态', ['task_id' => $taskId]);
  4655. while ($attempt < $maxAttempts) {
  4656. sleep($pollInterval);
  4657. $attempt++;
  4658. // 查询任务状态
  4659. $task = DB::table('mp_complete_video_tasks')
  4660. ->where('id', $taskId)
  4661. ->first();
  4662. if (!$task) {
  4663. dLog('anime')->error('任务不存在', ['task_id' => $taskId]);
  4664. Utils::throwError('20003:任务不存在');
  4665. }
  4666. dLog('anime')->info('轮询任务状态', [
  4667. 'task_id' => $taskId,
  4668. 'attempt' => $attempt,
  4669. 'status' => $task->generate_status
  4670. ]);
  4671. // 检查任务是否完成
  4672. if ($task->generate_status === '执行成功') {
  4673. // 同步更新剧集表状态
  4674. $boolen3 = DB::table('mp_anime_episodes')
  4675. ->where('anime_id', $animeId)
  4676. ->where('id', $episodeId)
  4677. ->update([
  4678. 'complete_video_url' => $task->complete_video_url,
  4679. 'complete_video_task_status' => '执行成功',
  4680. 'updated_at' => date('Y-m-d H:i:s')
  4681. ]);
  4682. dLog('anime')->info('视频合成任务完成', [
  4683. 'task_id' => $taskId,
  4684. 'video_url' => $task->complete_video_url,
  4685. 'attempts' => $attempt
  4686. ]);
  4687. // 如果更新成功则远程删除之前的文件
  4688. if ($boolen3 && $completeVideoUrl) {
  4689. $encode_url = urlencode($completeVideoUrl);
  4690. $client = new Client(['timeout' => 300, 'verify' => false]);
  4691. // 根据ID通过API通知合成音频
  4692. // $result = $client->get("http://47.240.171.155:5000/api/fileDelete?url={$encode_url}");
  4693. $result = $client->get("http://122.9.129.83:5000/api/fileDelete?url={$encode_url}");
  4694. $response = $result->getBody()->getContents();
  4695. $response_arr = json_decode($response, true);
  4696. Log::info('火山删除音频返回: '.$response);
  4697. if (!isset($response_arr['status']) || (int)$response_arr['status'] !== 0) {
  4698. $error_msg = isset($response_arr['msg']) ? $response_arr['msg'] : '未知错误';
  4699. Log::info('火山删除音频失败: '.$error_msg);
  4700. // Utils::throwError('20003:火山删除音频失败');
  4701. }
  4702. }
  4703. return [
  4704. 'task_id' => $taskId,
  4705. 'anime_id' => $animeId,
  4706. 'episode_id' => $episodeId,
  4707. 'segment_count' => count($generateJson),
  4708. 'generate_status' => '执行成功',
  4709. 'complete_video_url' => $task->complete_video_url,
  4710. ];
  4711. }
  4712. // 检查任务是否失败
  4713. if ($task->generate_status === '执行失败') {
  4714. // 同步更新剧集表状态
  4715. DB::table('mp_anime_episodes')
  4716. ->where('anime_id', $animeId)
  4717. ->where('id', $episodeId)
  4718. ->update([
  4719. 'complete_video_task_status' => '执行失败',
  4720. 'updated_at' => date('Y-m-d H:i:s')
  4721. ]);
  4722. $errorMessage = $task->error_message ?? '未知错误';
  4723. dLog('anime')->error('视频合成任务失败', [
  4724. 'task_id' => $taskId,
  4725. 'error' => $errorMessage,
  4726. 'attempts' => $attempt
  4727. ]);
  4728. return [
  4729. 'task_id' => $taskId,
  4730. 'anime_id' => $animeId,
  4731. 'episode_id' => $episodeId,
  4732. 'segment_count' => count($generateJson),
  4733. 'generate_status' => '执行失败',
  4734. 'error_message' => $errorMessage
  4735. ];
  4736. }
  4737. }
  4738. // 超时处理
  4739. dLog('anime')->warning('视频合成任务超时', [
  4740. 'task_id' => $taskId,
  4741. 'max_attempts' => $maxAttempts,
  4742. 'timeout_seconds' => $maxAttempts * $pollInterval
  4743. ]);
  4744. // 更新任务状态为超时
  4745. DB::table('mp_complete_video_tasks')
  4746. ->where('id', $taskId)
  4747. ->update([
  4748. 'generate_status' => '超时',
  4749. 'error_message' => '任务执行超时(5分钟)',
  4750. 'updated_at' => date('Y-m-d H:i:s')
  4751. ]);
  4752. return [
  4753. 'task_id' => $taskId,
  4754. 'anime_id' => $animeId,
  4755. 'episode_id' => $episodeId,
  4756. 'segment_count' => count($generateJson),
  4757. 'generate_status' => '超时',
  4758. 'error_message' => '任务执行超时,请稍后查询任务状态'
  4759. ];
  4760. }
  4761. /**
  4762. * 根据 inner_prompt_type 附加内置提示词
  4763. *
  4764. * @param string $prompt 用户提示词
  4765. * @param int $innerPromptType 内置提示词类型(1=三视图, 2=九宫格)
  4766. * @return string 合并后的提示词
  4767. */
  4768. public static function appendInnerPrompt($prompt, $innerPromptType = 0)
  4769. {
  4770. $innerPromptMap = [
  4771. 1 => '基于参考图生成主体的标准正面、侧面、后面三视图,主体完整。在最左侧添加主体正视图的特写,主体清晰完整。背景修改成纯白色,整体保持与参考图一致的美术风格和色彩搭配。画面无说明文字',
  4772. 2 => '基于参考图及提示词内容,生成9张连贯的系列图片:9张图片围绕同一主体展开,保持角色形象、美术风格和色彩搭配完全一致,画面内容依次衔接、情节连贯,整体构成一组完整的系列图。每张图片主体完整清晰,构图合理,画面干净,无文字、无水印、无字幕。',
  4773. ];
  4774. if (!isset($innerPromptMap[$innerPromptType])) {
  4775. return $prompt;
  4776. }
  4777. return trim((string)$prompt) . "\n" . $innerPromptMap[$innerPromptType];
  4778. }
  4779. /**
  4780. * 根据 inner_prompt_type 获取生成图片数量
  4781. *
  4782. * @param int $innerPromptType 内置提示词类型
  4783. * @return int 图片数量
  4784. */
  4785. public static function getInnerImageNum($innerPromptType = 0)
  4786. {
  4787. return (int)$innerPromptType === 2 ? 9 : 1;
  4788. }
  4789. /**
  4790. * 提取图片生成结果URL
  4791. *
  4792. * @param mixed $resultUrl 任务结果URL(数组、JSON字符串或普通字符串)
  4793. * @param int $innerPromptType 内置提示词类型
  4794. * @return mixed 类型2返回全部URL数组,其它类型返回首个URL
  4795. */
  4796. public static function extractResultUrls($resultUrl, $innerPromptType = 0)
  4797. {
  4798. $resultUrls = is_array($resultUrl) ? $resultUrl : json_decode((string)$resultUrl, true);
  4799. if (is_array($resultUrls) && !empty($resultUrls)) {
  4800. $resultUrls = array_values($resultUrls);
  4801. return (int)$innerPromptType === 2 ? $resultUrls : $resultUrls[0];
  4802. }
  4803. if (!empty($resultUrl)) {
  4804. return (int)$innerPromptType === 2 ? [$resultUrl] : $resultUrl;
  4805. }
  4806. return (int)$innerPromptType === 2 ? [] : '';
  4807. }
  4808. public function generateImg($data) {
  4809. $prompt = getProp($data, 'prompt');
  4810. $episode_id = getProp($data, 'episode_id');
  4811. $ref_img_urls = getProp($data, 'ref_img_urls');
  4812. $ratio = getProp($data, 'ratio', '9:16');
  4813. $resolution = getProp($data, 'resolution', '2k');
  4814. $inner_prompt_type = getProp($data, 'inner_prompt_type', 0);
  4815. // 定义分辨率和宽高比对应的尺寸映射表
  4816. $sizeMap = [
  4817. '2k' => [
  4818. '1:1' => ['width' => 2048, 'height' => 2048],
  4819. '4:3' => ['width' => 2304, 'height' => 1728],
  4820. '3:4' => ['width' => 1728, 'height' => 2304],
  4821. '16:9' => ['width' => 2848, 'height' => 1600],
  4822. '9:16' => ['width' => 1600, 'height' => 2848],
  4823. '3:2' => ['width' => 2496, 'height' => 1664],
  4824. '2:3' => ['width' => 1664, 'height' => 2496],
  4825. '21:9' => ['width' => 3136, 'height' => 1344],
  4826. ],
  4827. '3k' => [
  4828. '1:1' => ['width' => 3072, 'height' => 3072],
  4829. '4:3' => ['width' => 3456, 'height' => 2592],
  4830. '3:4' => ['width' => 2592, 'height' => 3456],
  4831. '16:9' => ['width' => 4096, 'height' => 2304],
  4832. '9:16' => ['width' => 2304, 'height' => 4096],
  4833. '2:3' => ['width' => 2496, 'height' => 3744],
  4834. '3:2' => ['width' => 3744, 'height' => 2496],
  4835. '21:9' => ['width' => 4704, 'height' => 2016],
  4836. ],
  4837. '4k' => [
  4838. '1:1' => ['width' => 4096, 'height' => 4096],
  4839. '3:4' => ['width' => 3520, 'height' => 4704],
  4840. '4:3' => ['width' => 4704, 'height' => 3520],
  4841. '16:9' => ['width' => 5504, 'height' => 3040],
  4842. '9:16' => ['width' => 3040, 'height' => 5504],
  4843. '2:3' => ['width' => 3328, 'height' => 4992],
  4844. '3:2' => ['width' => 4992, 'height' => 3328],
  4845. '21:9' => ['width' => 6240, 'height' => 2656],
  4846. ],
  4847. ];
  4848. // 参数验证
  4849. $resolution = strtolower($resolution);
  4850. if (!isset($sizeMap[$resolution])) {
  4851. Utils::throwError('20003:分辨率参数错误,仅支持 2k、3k、4k');
  4852. }
  4853. if (!isset($sizeMap[$resolution][$ratio])) {
  4854. Utils::throwError('20003:宽高比参数错误,该分辨率下不支持 ' . $ratio . ' 比例');
  4855. }
  4856. // 根据 ratio 和 resolution 确定宽高
  4857. $width = $sizeMap[$resolution][$ratio]['width'];
  4858. $height = $sizeMap[$resolution][$ratio]['height'];
  4859. if (!is_array($ref_img_urls) && !empty($ref_img_urls)) {
  4860. if (is_json($ref_img_urls)) {
  4861. $ref_img_urls = json_decode($ref_img_urls, true);
  4862. }else {
  4863. $ref_img_urls = explode(',', $ref_img_urls);
  4864. }
  4865. }
  4866. // 处理图片模型
  4867. $model = getProp($data, 'model');
  4868. if (!$model) {
  4869. // 用户没有输入,从episode表获取
  4870. if ($episode_id) {
  4871. $episode = DB::table('mp_anime_episodes')->where('id', $episode_id)->first();
  4872. $model = getProp($episode, 'image_model');
  4873. }
  4874. if (!$model) {
  4875. // episode表也没有,使用默认值
  4876. $model = 'doubao-seedream-5-0-lite-260128';
  4877. }
  4878. }
  4879. // 验证模型是否在可用模型表中
  4880. if (!DB::table('mp_image_models')->where('model', $model)->where('is_enabled', 1)->exists()) {
  4881. // $model = 'doubao-seedream-5-0-lite-260128';
  4882. Utils::throwError('20003:该模型已不可用,请更换!');
  4883. }
  4884. // 保存到episode表
  4885. if ($episode_id) {
  4886. DB::table('mp_anime_episodes')->where('id', $episode_id)->update([
  4887. 'image_model' => $model,
  4888. 'updated_at' => date('Y-m-d H:i:s')
  4889. ]);
  4890. }
  4891. // 参数验证
  4892. if (!$prompt) Utils::throwError('20003:请提供提示词');
  4893. // 根据 inner_prompt_type 附加内置提示词并确定生成图片数量
  4894. $prompt = self::appendInnerPrompt($prompt, $inner_prompt_type);
  4895. $imageNum = self::getInnerImageNum($inner_prompt_type);
  4896. try {
  4897. // 创建图片生成任务
  4898. $params = [
  4899. 'prompt' => $prompt,
  4900. 'model' => $model,
  4901. 'ref_img_urls' => '',
  4902. 'width' => $width,
  4903. 'height' => $height,
  4904. 'image_num' => $imageNum
  4905. ];
  4906. if ($ref_img_urls) $params['ref_img_urls'] = is_array($ref_img_urls) ? $ref_img_urls : [$ref_img_urls];
  4907. $task = $this->aiImageGenerationService->createImageGenerationTask($params);
  4908. $task_id = $task->id;
  4909. if (!$task_id) {
  4910. Utils::throwError('20003:创建图片生成任务失败');
  4911. }
  4912. // 检查任务模型类型(火山模型和GPT模型都支持直接检查任务状态)
  4913. $model = getProp($task, 'model');
  4914. $isVolcModel = in_array($model, \App\Consts\BaseConst::VOLC_PIC_MODELS);
  4915. $isGptModel = in_array($model, \App\Consts\BaseConst::GPT_IMAGE2_MODELS);
  4916. $isSyncModel = $isVolcModel || $isGptModel;
  4917. // 即梦AI需要轮询获取结果(5分钟超时,每3秒查询一次)
  4918. $start_time = time();
  4919. $timeout = 300; // 5分钟
  4920. $img_url = '';
  4921. while (time() - $start_time < $timeout) {
  4922. sleep(3);
  4923. // 火山API和GPT-Image2 API是同步返回结果的,直接检查任务状态
  4924. if ($isSyncModel) {
  4925. // 刷新任务状态
  4926. $task = MpGeneratePicTask::where('id', $task_id)->first();
  4927. if ($task->status === 'success' && $task->result_url) {
  4928. $img_url = self::extractResultUrls($task->result_url, $inner_prompt_type);
  4929. break;
  4930. } elseif ($task->status === 'failed') {
  4931. $errorMsg = mapErrorMessage($task->error_message ?? '');
  4932. Utils::throwError('20003:图片生成失败,' . $errorMsg);
  4933. }
  4934. // // 如果还在处理中,提示用户稍后查看
  4935. // Utils::throwError('20003:图片生成中,请稍后刷新查看结果');
  4936. }else {
  4937. $task = MpGeneratePicTask::where('id', $task_id)->first();
  4938. $statusInfo = $this->aiImageGenerationService->queryTaskStatus($task);
  4939. if ($statusInfo['status'] === 'success') {
  4940. $task->updateStatus('success', [
  4941. 'result_url' => $statusInfo['result_url'],
  4942. 'result_json' => $statusInfo['result_json'] ?? []
  4943. ]);
  4944. $img_url = self::extractResultUrls($statusInfo['result_url'], $inner_prompt_type);
  4945. break;
  4946. } elseif ($statusInfo['status'] === 'failed') {
  4947. $task->updateStatus('failed', [
  4948. 'error_message' => $statusInfo['error_message'],
  4949. 'result_json' => $statusInfo['result_json'] ?? []
  4950. ]);
  4951. dLog('anime')->error('图片生成失败,', [
  4952. 'error' => $statusInfo['error_message'] ?? '未知错误'
  4953. ]);
  4954. $errorMsg = mapErrorMessage($statusInfo['error_message'] ?? '');
  4955. Utils::throwError('20003:图片生成失败,' . $errorMsg);
  4956. }
  4957. }
  4958. }
  4959. if (empty($img_url)) {
  4960. Utils::throwError('20003:图片生成超时,请稍后重试');
  4961. }
  4962. return $img_url;
  4963. } catch (\Exception $e) {
  4964. dLog('anime')->error('更新角色或场景失败', [
  4965. 'error' => $e->getMessage()
  4966. ]);
  4967. logDB('anime', 'error', '更新角色或场景失败', ['error' => $e->getMessage()]);
  4968. Utils::throwError('20003:' . $e->getMessage());
  4969. }
  4970. }
  4971. /**
  4972. * 使用文生文模型解析分镜内容
  4973. */
  4974. private function parseSegmentContentWithAI($segment_content) {
  4975. try {
  4976. // 使用DeepSeek服务的公开方法解析分镜内容
  4977. return $this->DeepSeekService->parseSegmentContent($segment_content);
  4978. } catch (\Exception $e) {
  4979. // 如果AI解析失败,记录日志并返回原内容
  4980. dLog('anime')->error('AI解析分镜内容失败: ' . $e->getMessage());
  4981. return $segment_content;
  4982. }
  4983. }
  4984. /**
  4985. * 处理分集的角色和场景数据(继承全局数据或创建新任务)
  4986. *
  4987. * @param int $episode_id 分集ID
  4988. * @param int $anime_id 动漫ID
  4989. * @param array $roles 分集角色数组(引用传递)
  4990. * @param array $scenes 分集场景数组(引用传递)
  4991. * @param array $episode 分集数据
  4992. */
  4993. private function processEpisodeRolesAndScenes($episode_id, $anime_id, &$roles, &$scenes, $episode) {
  4994. // 获取全局动漫的角色和场景数据
  4995. $anime = DB::table('mp_animes')->where('id', $anime_id)->first();
  4996. if (!$anime) return;
  4997. $art_style_type = getProp($anime, 'art_style_type');
  4998. $character_prefix = '';
  4999. $scene_prefix = '';
  5000. if ($art_style_type) {
  5001. $art_style_arr = $this->DeepSeekService->getArtStyleShortPromptByInput($art_style_type);
  5002. $character_prefix = isset($art_style_arr['character_prefix']) ? $art_style_arr['character_prefix'] : '';
  5003. $scene_prefix = isset($art_style_arr['scene_prefix']) ? $art_style_arr['scene_prefix'] : '';
  5004. }
  5005. $global_roles = json_decode(getProp($anime, 'roles'), true) ?: [];
  5006. $global_scenes = json_decode(getProp($anime, 'scenes'), true) ?: [];
  5007. $roles_updated = false;
  5008. $scenes_updated = false;
  5009. // 处理角色
  5010. foreach ($roles as &$role) {
  5011. $role_name = getProp($role, 'role');
  5012. $role_description = getProp($role, 'description');
  5013. $role_pic_prompt = getProp($role, 'pic_prompt');
  5014. $role_url = getProp($role, 'url');
  5015. $role_task_id = getProp($role, 'task_id');
  5016. // 如果已有URL或已有任务ID,跳过
  5017. if (!empty($role_url) || !empty($role_task_id) || $role_name === '旁白') {
  5018. continue;
  5019. }
  5020. $url_inherited = false;
  5021. // 尝试从全局数据中继承
  5022. foreach ($global_roles as $global_role) {
  5023. $global_role_name = getProp($global_role, 'role');
  5024. $global_role_description = getProp($global_role, 'description');
  5025. $global_role_pic_prompt = getProp($global_role, 'pic_prompt');
  5026. $global_role_url = getProp($global_role, 'url');
  5027. $global_role_task_id = getProp($global_role, 'task_id');
  5028. $global_role_task_status = getProp($global_role, 'task_status');
  5029. // 满足条件:角色名相同、描述相同、pic_prompt相同、全局有URL
  5030. if ($role_name === $global_role_name
  5031. && $role_description === $global_role_description
  5032. && $role_pic_prompt === $global_role_pic_prompt
  5033. && !empty($global_role_url)) {
  5034. // 继承 task_id、task_status 和 url
  5035. $role['task_id'] = $global_role_task_id;
  5036. $role['task_status'] = $global_role_task_status;
  5037. $role['url'] = $global_role_url;
  5038. $roles_updated = true;
  5039. $url_inherited = true;
  5040. dLog('anime')->info("分集ID:{$episode_id} 角色:{$role_name} 继承全局数据");
  5041. break;
  5042. }
  5043. }
  5044. // 如果无法继承且没有任务ID,创建新任务
  5045. if (!$url_inherited && empty($role_task_id)) {
  5046. try {
  5047. $art_style = getProp($episode, 'art_style');
  5048. // 优先使用 pic_prompt,如果没有则使用 description
  5049. $description = !empty($role_pic_prompt) ? trim((string)$role_pic_prompt) : $role_description;
  5050. // if ($art_style) {
  5051. // // $description = "美术风格:\n{$art_style}\n主体描述:{$description}\n图片要求:图片侧重点是人物,不要出现场景或背景,并且只能生成一个人物";
  5052. // $description = "主体描述:{$description}\n图片要求:图片侧重点是人物,不要出现场景或背景,并且只能生成一个人物";
  5053. // }
  5054. $description = "{$character_prefix}。\n主体描述:{$description}\n超高清,高细节,主体突出,构图合理,画面干净,无场景或背景,单人物,无文字,无水印,无字幕,电影级光影,视觉焦点明确";
  5055. $params = [
  5056. 'prompt' => $description,
  5057. 'ref_img_urls' => []
  5058. ];
  5059. $task = $this->aiImageGenerationService->createImageGenerationTask($params);
  5060. $task_id = $task->id;
  5061. if ($task_id) {
  5062. $role['task_id'] = $task_id;
  5063. $role['task_status'] = 'processing';
  5064. $roles_updated = true;
  5065. dLog('anime')->info("分集ID:{$episode_id} 角色:{$role_name} 创建图片生成任务,任务ID:{$task_id}");
  5066. }
  5067. } catch (\Exception $e) {
  5068. dLog('anime')->error("分集ID:{$episode_id} 角色:{$role_name} 创建图片生成任务失败: " . $e->getMessage());
  5069. }
  5070. }
  5071. }
  5072. // 处理场景
  5073. foreach ($scenes as &$scene) {
  5074. $scene_name = getProp($scene, 'scene');
  5075. $scene_description = getProp($scene, 'description');
  5076. $scene_pic_prompt = getProp($scene, 'pic_prompt');
  5077. $scene_url = getProp($scene, 'url');
  5078. $scene_task_id = getProp($scene, 'task_id');
  5079. // 如果已有URL或已有任务ID,跳过
  5080. if (!empty($scene_url) || !empty($scene_task_id)) {
  5081. continue;
  5082. }
  5083. $url_inherited = false;
  5084. // 尝试从全局数据中继承
  5085. foreach ($global_scenes as $global_scene) {
  5086. $global_scene_name = getProp($global_scene, 'scene');
  5087. $global_scene_description = getProp($global_scene, 'description');
  5088. $global_scene_pic_prompt = getProp($global_scene, 'pic_prompt');
  5089. $global_scene_url = getProp($global_scene, 'url');
  5090. $global_scene_task_id = getProp($global_scene, 'task_id');
  5091. $global_scene_task_status = getProp($global_scene, 'task_status');
  5092. // 满足条件:场景名相同、描述相同、pic_prompt相同、全局有URL
  5093. if ($scene_name === $global_scene_name
  5094. && $scene_description === $global_scene_description
  5095. && $scene_pic_prompt === $global_scene_pic_prompt
  5096. && !empty($global_scene_url)) {
  5097. // 继承 task_id、task_status 和 url
  5098. $scene['task_id'] = $global_scene_task_id;
  5099. $scene['task_status'] = $global_scene_task_status;
  5100. $scene['url'] = $global_scene_url;
  5101. $scenes_updated = true;
  5102. $url_inherited = true;
  5103. dLog('anime')->info("分集ID:{$episode_id} 场景:{$scene_name} 继承全局数据");
  5104. break;
  5105. }
  5106. }
  5107. // 如果无法继承且没有任务ID,创建新任务
  5108. if (!$url_inherited && empty($scene_task_id)) {
  5109. try {
  5110. $art_style = getProp($episode, 'art_style');
  5111. // 优先使用 pic_prompt,如果没有则使用 description
  5112. $description = !empty($scene_pic_prompt) ? trim((string)$scene_pic_prompt) : $scene_description;
  5113. // if ($art_style) {
  5114. // // $description = "美术风格:\n{$art_style}\n场景描述:{$description}\n图片要求: 图片侧重点是场景,生成的是场景环境图片,不要出现人物(此为第一优先要求)";
  5115. // $description = "场景描述:{$description}\n图片要求: 图片侧重点是场景,生成的是场景环境图片,不要出现人物(此为第一优先要求)";
  5116. // }
  5117. $description = "{$scene_prefix}。\n场景描述:{$description}\n无人物,超高清,高细节,主体突出,构图合理,画面干净,无文字,无水印,无字幕,电影级光影,视觉焦点明确";
  5118. $params = [
  5119. 'prompt' => $description,
  5120. 'ref_img_urls' => []
  5121. ];
  5122. $task = $this->aiImageGenerationService->createImageGenerationTask($params);
  5123. $task_id = $task->id;
  5124. if ($task_id) {
  5125. $scene['task_id'] = $task_id;
  5126. $scene['task_status'] = 'processing';
  5127. $scenes_updated = true;
  5128. dLog('anime')->info("分集ID:{$episode_id} 场景:{$scene_name} 创建图片生成任务,任务ID:{$task_id}");
  5129. }
  5130. } catch (\Exception $e) {
  5131. dLog('anime')->error("分集ID:{$episode_id} 场景:{$scene_name} 创建图片生成任务失败: " . $e->getMessage());
  5132. }
  5133. }
  5134. }
  5135. // 如果有更新,保存到数据库
  5136. if ($roles_updated || $scenes_updated) {
  5137. $update_data = ['updated_at' => date('Y-m-d H:i:s')];
  5138. if ($roles_updated) {
  5139. $update_data['roles'] = json_encode($roles, JSON_UNESCAPED_UNICODE);
  5140. }
  5141. if ($scenes_updated) {
  5142. $update_data['scenes'] = json_encode($scenes, JSON_UNESCAPED_UNICODE);
  5143. }
  5144. DB::table('mp_anime_episodes')->where('id', $episode_id)->update($update_data);
  5145. dLog('anime')->info("分集ID:{$episode_id} 角色和场景数据已更新");
  5146. }
  5147. }
  5148. /**
  5149. * 根据图片URL使用AI反推图片提示词
  5150. *
  5151. * @param string $img_url 图片URL
  5152. * @return string 反推的提示词
  5153. */
  5154. private function generateImagePromptFromUrl($img_url) {
  5155. try {
  5156. // 获取默认模型
  5157. $model = 'doubao-seed-2-0-mini-260215';
  5158. // 构建messages参数
  5159. $messages = [
  5160. [
  5161. 'role' => 'user',
  5162. 'content' => [
  5163. [
  5164. 'type' => 'text',
  5165. 'text' => '请解析这张参考图,并直接输出一段专业中文反推提示词。提示词用于短剧分镜图片生成,必须聚焦角色和场景本身,可包含姿态、镜头视角、构图、画风、色彩氛围、光线、景深或光圈质感等要素。不要输出解释、标题、列表或无关背景,只输出可直接用于文生图的分镜图片提示词'
  5166. ],
  5167. [
  5168. 'type' => 'image_url',
  5169. 'image_url' => [
  5170. 'url' => $img_url
  5171. ]
  5172. ]
  5173. ]
  5174. ]
  5175. ];
  5176. // 构建请求参数
  5177. $params = [
  5178. 'model' => $model,
  5179. 'messages' => $messages,
  5180. 'stream' => false,
  5181. 'thinking' => ['type' => 'disabled'] // 不使用思考模式
  5182. ];
  5183. // 调用DeepSeek服务的volcEngineChatCompletion方法(非流式)
  5184. $result = $this->DeepSeekService->volcEngineChatCompletion($params);
  5185. // 返回生成的内容
  5186. return getProp($result, 'fullContent', '图片描述生成失败');
  5187. } catch (\Exception $e) {
  5188. dLog('anime')->error('AI反推图片提示词失败: ' . $e->getMessage(), [
  5189. 'img_url' => $img_url
  5190. ]);
  5191. logDB('anime', 'error', 'AI反推图片提示词失败', [
  5192. 'error' => $e->getMessage(),
  5193. 'img_url' => $img_url
  5194. ]);
  5195. return '图片描述生成失败: ' . $e->getMessage();
  5196. }
  5197. }
  5198. /**
  5199. * 音频试听接口
  5200. * 创建音频任务并轮询获取结果
  5201. *
  5202. * @param array $data 参数数组
  5203. * @return array 返回音频URL或错误信息
  5204. */
  5205. public function previewAudio($data) {
  5206. $dialogue = getProp($data, 'dialogue');
  5207. // 必填参数验证
  5208. if (!$dialogue) Utils::throwError('20003:dialogue不能为空');
  5209. // 获取参数,优先使用传入的参数,否则使用分镜中的参数
  5210. $voice_type = getProp($data, 'voice_type');
  5211. $voice_name = getProp($data, 'voice_name');
  5212. $voice_actor = getProp($data, 'voice_actor');
  5213. $emotion_type = getProp($data, 'emotion_type');
  5214. $gender = getProp($data, 'gender', 0);
  5215. $emotion = getProp($data, 'emotion');
  5216. $speed_ratio = getProp($data, 'speed_ratio', 0);
  5217. $loudness_ratio = getProp($data, 'loudness_ratio', 0);
  5218. $emotion_scale = getProp($data, 'emotion_scale', 0);
  5219. $pitch = getProp($data, 'pitch', 0);
  5220. try {
  5221. $now = date('Y-m-d H:i:s');
  5222. // 构建生成参数
  5223. $generate_json = json_encode([
  5224. 'text' => $dialogue,
  5225. 'role' => $voice_actor,
  5226. 'voice_type' => $voice_type,
  5227. 'voice_name' => $voice_name,
  5228. 'emotion' => $emotion,
  5229. 'emotion_type' => $emotion_type,
  5230. 'gender' => $gender,
  5231. 'speed_ratio' => $speed_ratio,
  5232. 'loudness_ratio' => $loudness_ratio,
  5233. 'emotion_scale' => $emotion_scale,
  5234. 'pitch' => $pitch,
  5235. ], 256);
  5236. // 请求远程服务器执行生成
  5237. $client = new Client(['timeout' => 600, 'verify' => false]);
  5238. $result = $client->get("http://122.9.129.83:5000/api/anime/audioPreview?generateJson={$generate_json}");
  5239. $response = $result->getBody()->getContents();
  5240. $response_arr = json_decode($response, true);
  5241. if (!isset($response_arr['code']) || (int)$response_arr['code'] !== 0) {
  5242. $error_msg = isset($response_arr['msg']) ? $response_arr['msg'] : '未知错误';
  5243. dLog('anime')->error('音频试听任务创建失败', ['error' => $error_msg, 'response_arr' => $response_arr]);
  5244. Utils::throwError('20003:音频试听任务创建失败: ' . $error_msg);
  5245. }
  5246. $arr = $response_arr['data'];
  5247. $subtitle_info = $arr['subtitle_info'];
  5248. $audio_duration = json_decode($subtitle_info, true)['duration'];
  5249. if (!isset($arr['url']) || !$audio_duration || !$subtitle_info) Utils::throwError('20003:音频参数生成异常');
  5250. return [
  5251. 'audio_url' => $arr['url'],
  5252. 'subtitle_info' => $subtitle_info,
  5253. 'audio_duration' => round($audio_duration, 2)
  5254. ];
  5255. } catch (\Exception $e) {
  5256. dLog('anime')->error('音频试听失败', ['error' => $e->getMessage()]);
  5257. Utils::throwError('20003:' . $e->getMessage());
  5258. }
  5259. }
  5260. /**
  5261. * 获取角色库列表(支持文件夹递归查询)
  5262. * @param array $data 包含 parent_id(父文件夹ID,默认0表示最外层)、role(搜索关键词)、is_public(筛选类型)
  5263. * @return array 返回当前目录下的所有子目录和角色列表(递归)
  5264. */
  5265. public function globalProducts($data) {
  5266. $uid = Site::getUid();
  5267. $cpid = Site::getCpid();
  5268. $role = Site::getRole();
  5269. $id = getProp($data, 'id', 0);
  5270. $parent_id = getProp($data, 'parent_id', 0);
  5271. $product_name = getProp($data, 'product_name');
  5272. $product = getProp($data, 'product'); // 1.角色 2.场景 3.道具
  5273. $is_public = getProp($data, 'public_type', 2); // 0=仅个人库 1=仅公共库 2=个人库+公共库
  5274. if (!$product) {
  5275. Utils::throwError('20003:请选择产品类型');
  5276. }
  5277. // 根据角色和is_public参数确定查询范围
  5278. // admin角色:获取所有个人库+公共库(忽略is_public参数)
  5279. // user角色:根据is_public参数筛选
  5280. $query_user_ids = [];
  5281. if ($role === 'admin') {
  5282. // admin获取所有个人库和公共库
  5283. $query_user_ids = [$uid, 0];
  5284. } else {
  5285. // user角色根据is_public参数筛选
  5286. if ($is_public == 2) {
  5287. // 个人库+公共库
  5288. $query_user_ids = [$uid, 0];
  5289. } elseif ($is_public == 0) {
  5290. // 仅个人库
  5291. $query_user_ids = [$uid];
  5292. } elseif ($is_public == 1) {
  5293. // 仅公共库
  5294. $query_user_ids = [0];
  5295. }
  5296. }
  5297. // 如果有搜索条件(product_name 或 id),按条件搜索文件夹和产品
  5298. if ($id || $product_name) {
  5299. $query = DB::table('mp_products')
  5300. ->where('cpid', $cpid)
  5301. ->whereIn('user_id', $query_user_ids)
  5302. ->where('is_deleted', 0);
  5303. // 如果指定了 id,按 id 精确查询
  5304. if ($id) {
  5305. $query->where('id', $id);
  5306. }
  5307. // 如果指定了 product_name,按名称模糊查询
  5308. if ($product_name) {
  5309. $query->where('product_name', 'like', "%{$product_name}%");
  5310. }
  5311. // 如果指定了 product,添加筛选条件
  5312. if ($product) {
  5313. $query->where('product', $product);
  5314. }
  5315. $result = $query->select('id', 'type', 'parent_id', 'level', 'product_name', 'url', 'pic_prompt', 'three_view_image_url', 'versions', 'product', 'user_id', 'created_at')
  5316. ->orderByRaw('type DESC, CASE WHEN user_id = '.$uid.' THEN 0 ELSE 1 END ASC, sort_order DESC, created_at DESC')
  5317. ->get()
  5318. ->map(function($value) {
  5319. $value = (array)$value;
  5320. $value['created_at'] = transDate($value['created_at'], 'Y-m-d');
  5321. $value['type'] = (int)$value['type'];
  5322. $value['parent_id'] = (int)$value['parent_id'];
  5323. $value['level'] = (int)$value['level'];
  5324. $value['product'] = (int)($value['product'] ?? 1);
  5325. $value['is_public'] = (int)$value['user_id'] === 0 ? 1 : 0;
  5326. $value['versions'] = json_decode($value['versions'], true) ?: [];
  5327. unset($value['user_id']);
  5328. return $value;
  5329. })
  5330. ->toArray();
  5331. return $result;
  5332. }
  5333. // 递归获取所有子目录和角色
  5334. return $this->getChildrenRecursive($cpid, $parent_id, $product, $query_user_ids, $uid);
  5335. }
  5336. /**
  5337. * 递归获取指定目录下的所有子目录和角色
  5338. * @param int $cpid 公司ID
  5339. * @param int $parent_id 父目录ID
  5340. * @param int|null $product 产品类型筛选 1.角色 2.场景 3.道具
  5341. * @param array $query_user_ids 用户ID数组(支持多个)
  5342. * @param int $current_uid 当前用户ID(用于排序)
  5343. * @return array
  5344. */
  5345. private function getChildrenRecursive($cpid, $parent_id, $product = null, $query_user_ids = [], $current_uid = 0) {
  5346. // 查询当前层级的所有项(文件夹和角色)
  5347. $query = DB::table('mp_products')
  5348. ->where('cpid', $cpid)
  5349. ->where('is_deleted', 0)
  5350. ->where('parent_id', $parent_id);
  5351. // 添加用户ID验证(支持多个user_id)
  5352. if (!empty($query_user_ids)) {
  5353. $query->whereIn('user_id', $query_user_ids);
  5354. }
  5355. // 如果指定了 product,添加筛选条件(文件夹和角色都需要筛选)
  5356. if ($product) {
  5357. $query->where('product', $product);
  5358. }
  5359. // 排序规则:
  5360. // 1. 文件夹在前(type DESC)
  5361. // 2. 个人库在前,公共库在后(CASE WHEN user_id = current_uid)
  5362. // 3. 其他排序规则
  5363. $items = $query->select('id', 'type', 'parent_id', 'level', 'product_name', 'url', 'pic_prompt', 'three_view_image_url', 'versions', 'product', 'user_id', 'created_at')
  5364. ->orderByRaw('type DESC, CASE WHEN user_id = '.$current_uid.' THEN 0 ELSE 1 END ASC, sort_order DESC, created_at DESC')
  5365. ->get();
  5366. $result = [];
  5367. foreach ($items as $item) {
  5368. $itemArray = [
  5369. 'id' => $item->id,
  5370. 'type' => (int)$item->type,
  5371. 'parent_id' => (int)$item->parent_id,
  5372. 'level' => (int)$item->level,
  5373. 'product_name' => $item->product_name,
  5374. 'url' => $item->url,
  5375. 'pic_prompt' => $item->pic_prompt ?? '',
  5376. 'three_view_image_url' => $item->three_view_image_url,
  5377. 'product' => (int)($item->product ?? 1),
  5378. 'is_public' => (int)$item->user_id === 0 ? 1 : 0,
  5379. 'created_at' => transDate($item->created_at, 'Y-m-d')
  5380. ];
  5381. $itemArray['versions'] = json_decode($item->versions, true) ?: [];
  5382. // 如果是文件夹,递归获取其子项
  5383. if ($item->type == 2) {
  5384. $children = $this->getChildrenRecursive($cpid, $item->id, $product, $query_user_ids, $current_uid);
  5385. if (!empty($children)) {
  5386. $itemArray['children'] = $children;
  5387. }
  5388. }
  5389. $result[] = $itemArray;
  5390. }
  5391. return $result;
  5392. }
  5393. /**
  5394. * 创建文件夹
  5395. * @param array $data 包含 parent_id(父文件夹ID)、product_name(文件夹名称)、product(产品类型)
  5396. * @return int 返回新建文件夹ID
  5397. */
  5398. public function createFolder($data) {
  5399. $uid = Site::getUid();
  5400. $cpid = Site::getCpid();
  5401. $role = Site::getRole();
  5402. $parent_id = getProp($data, 'parent_id', 0);
  5403. $folder_name = getProp($data, 'product_name', '新建文件夹');
  5404. $is_public = getProp($data, 'is_public', 0); // 0=个人资产库 1=公共资产库
  5405. // 如果是公共库操作,需要admin权限
  5406. if ($is_public && $role !== 'admin') {
  5407. Utils::throwError('20003:只有管理员才能操作公共资产库');
  5408. }
  5409. // 根据is_public参数确定存储的user_id(公共库user_id=0,cpid保持不变)
  5410. $store_uid = $is_public ? 0 : $uid;
  5411. // 获取 product 字段:1.角色 2.场景 3.道具,默认为1
  5412. $product = getProp($data, 'product');
  5413. if (!in_array($product, [1, 2, 3])) {
  5414. // Utils::throwError('20003:product 参数错误,只能是 1(角色)、2(场景) 或 3(道具)');
  5415. }
  5416. // 验证父文件夹
  5417. $parent_level = 0;
  5418. if ($parent_id > 0) {
  5419. $parent = DB::table('mp_products')
  5420. ->where('id', $parent_id)
  5421. ->where('cpid', $cpid)
  5422. ->where('user_id', $store_uid)
  5423. ->where('type', 2)
  5424. ->where('is_deleted', 0)
  5425. ->first();
  5426. if (!$parent) {
  5427. Utils::throwError('20003:父文件夹不存在');
  5428. }
  5429. // 检查父文件夹的 product 类型是否一致
  5430. if ($parent->product != $product) {
  5431. Utils::throwError('20003:文件夹类型必须与父文件夹一致');
  5432. }
  5433. $parent_level = $parent->level;
  5434. // 检查层级限制(最多3层)
  5435. if ($parent_level >= 3) {
  5436. Utils::throwError('20003:文件夹层级不能超过3层');
  5437. }
  5438. }
  5439. // 检查当前目录下是否已存在空白文件夹
  5440. $empty_folder_exists = DB::table('mp_products')
  5441. ->where('parent_id', $parent_id)
  5442. ->where('cpid', $cpid)
  5443. ->where('user_id', $store_uid)
  5444. ->where('type', 2)
  5445. ->where('product', $product)
  5446. ->where('product_name', '新建文件夹')
  5447. ->where('is_deleted', 0)
  5448. ->exists();
  5449. if ($empty_folder_exists && $folder_name == '新建文件夹') {
  5450. Utils::throwError('20003:不允许创建多个空白文件夹,请先重命名现有文件夹');
  5451. }
  5452. // 创建文件夹
  5453. $folder_id = DB::table('mp_products')->insertGetId([
  5454. 'user_id' => $store_uid,
  5455. 'cpid' => $cpid,
  5456. 'type' => 2,
  5457. 'parent_id' => $parent_id,
  5458. 'level' => $parent_level + 1,
  5459. 'product_name' => $folder_name,
  5460. 'product' => $product,
  5461. 'sort_order' => time(), // 使用时间戳作为排序权重
  5462. 'is_deleted' => 0,
  5463. 'created_at' => date('Y-m-d H:i:s'),
  5464. 'updated_at' => date('Y-m-d H:i:s')
  5465. ]);
  5466. return [
  5467. 'id' => $folder_id,
  5468. 'type' => 2,
  5469. 'parent_id' => $parent_id,
  5470. 'level' => $parent_level + 1,
  5471. 'product_name' => $folder_name,
  5472. 'product' => $product,
  5473. ];
  5474. }
  5475. /**
  5476. * 重命名文件夹或角色
  5477. * @param array $data 包含 id、product_name(新名称)
  5478. * @return bool
  5479. */
  5480. public function renameFolder($data) {
  5481. $uid = Site::getUid();
  5482. $cpid = Site::getCpid();
  5483. $role = Site::getRole();
  5484. $id = getProp($data, 'id');
  5485. $new_name = getProp($data, 'product_name');
  5486. $is_public = getProp($data, 'is_public', 0); // 0=个人资产库 1=公共资产库
  5487. if (!$id || !$new_name) {
  5488. Utils::throwError('20003:参数不完整');
  5489. }
  5490. // 根据is_public参数确定查询的user_id(公共库user_id=0,cpid保持不变)
  5491. $query_uid = $is_public ? 0 : $uid;
  5492. // 如果是公共库操作,需要admin权限
  5493. if ($is_public && $role !== 'admin') {
  5494. Utils::throwError('20003:只有管理员才能操作公共资产库');
  5495. }
  5496. // 检查是否存在
  5497. $item = DB::table('mp_products')
  5498. ->where('id', $id)
  5499. ->where('cpid', $cpid)
  5500. ->where('user_id', $query_uid)
  5501. ->where('is_deleted', 0)
  5502. ->first();
  5503. if (!$item) {
  5504. Utils::throwError('20003:项目不存在');
  5505. }
  5506. return DB::table('mp_products')
  5507. ->where('id', $id)
  5508. ->where('cpid', $cpid)
  5509. ->where('user_id', $query_uid)
  5510. ->update([
  5511. 'product_name' => $new_name,
  5512. 'updated_at' => date('Y-m-d H:i:s')
  5513. ]);
  5514. }
  5515. /**
  5516. * 移动角色或文件夹到指定文件夹
  5517. * @param array $data 包含 id(要移动的项目ID)、target_parent_id(目标父文件夹ID)
  5518. * @return bool
  5519. */
  5520. public function moveProductOrFolder($data) {
  5521. $uid = Site::getUid();
  5522. $cpid = Site::getCpid();
  5523. $role = Site::getRole();
  5524. $id = getProp($data, 'id');
  5525. $target_parent_id = getProp($data, 'target_parent_id', 0);
  5526. $is_public = getProp($data, 'is_public', 0); // 0=个人资产库 1=公共资产库
  5527. if (!$id) {
  5528. Utils::throwError('20003:请选择要移动的项目');
  5529. }
  5530. // 根据is_public参数确定查询的user_id(公共库user_id=0,cpid保持不变)
  5531. $query_uid = $is_public ? 0 : $uid;
  5532. // 如果是公共库操作,需要admin权限
  5533. if ($is_public && $role !== 'admin') {
  5534. Utils::throwError('20003:只有管理员才能操作公共资产库');
  5535. }
  5536. // 检查要移动的项目
  5537. $item = DB::table('mp_products')
  5538. ->where('id', $id)
  5539. ->where('cpid', $cpid)
  5540. ->where('user_id', $query_uid)
  5541. ->where('is_deleted', 0)
  5542. ->first();
  5543. if (!$item) {
  5544. Utils::throwError('20003:项目不存在');
  5545. }
  5546. // 验证目标文件夹
  5547. $target_level = 0;
  5548. $target_product = $item->product; // 默认使用当前项目的 product
  5549. if ($target_parent_id > 0) {
  5550. $target_parent = DB::table('mp_products')
  5551. ->where('id', $target_parent_id)
  5552. ->where('cpid', $cpid)
  5553. ->where('user_id', $query_uid)
  5554. ->where('type', 2)
  5555. ->where('is_deleted', 0)
  5556. ->first();
  5557. if (!$target_parent) {
  5558. Utils::throwError('20003:目标文件夹不存在');
  5559. }
  5560. // 检查 product 类型是否一致
  5561. if ($target_parent->product != $item->product) {
  5562. Utils::throwError('20003:不能移动到不同类型的文件夹下');
  5563. }
  5564. $target_level = $target_parent->level;
  5565. $target_product = $target_parent->product;
  5566. // 如果移动的是文件夹,需要检查层级
  5567. if ($item->type == 2) {
  5568. // 计算移动后的最大层级
  5569. $max_child_level = $this->getMaxChildLevel($id);
  5570. $depth = $max_child_level - $item->level;
  5571. if ($target_level + 1 + $depth > 3) {
  5572. Utils::throwError('20003:移动后文件夹层级将超过3层限制');
  5573. }
  5574. // 不能移动到自己或自己的子文件夹下
  5575. if ($this->isDescendant($target_parent_id, $id)) {
  5576. Utils::throwError('20003:不能移动到自己或子文件夹下');
  5577. }
  5578. }
  5579. }
  5580. // 更新父文件夹和层级
  5581. $new_level = $target_level + 1;
  5582. DB::table('mp_products')
  5583. ->where('id', $id)
  5584. ->update([
  5585. 'parent_id' => $target_parent_id,
  5586. 'level' => $new_level,
  5587. 'updated_at' => date('Y-m-d H:i:s')
  5588. ]);
  5589. // 如果是文件夹,需要递归更新所有子项的层级
  5590. if ($item->type == 2) {
  5591. $this->updateChildrenLevel($id, $new_level);
  5592. }
  5593. return true;
  5594. }
  5595. /**
  5596. * 获取文件夹下最大子层级
  5597. * @param int $folder_id
  5598. * @return int
  5599. */
  5600. private function getMaxChildLevel($folder_id) {
  5601. $max_level = DB::table('mp_products')
  5602. ->where('parent_id', $folder_id)
  5603. ->where('is_deleted', 0)
  5604. ->max('level');
  5605. if (!$max_level) {
  5606. return DB::table('mp_products')->where('id', $folder_id)->value('level');
  5607. }
  5608. // 递归查找子文件夹
  5609. $children = DB::table('mp_products')
  5610. ->where('parent_id', $folder_id)
  5611. ->where('type', 2)
  5612. ->where('is_deleted', 0)
  5613. ->pluck('id');
  5614. foreach ($children as $child_id) {
  5615. $child_max = $this->getMaxChildLevel($child_id);
  5616. if ($child_max > $max_level) {
  5617. $max_level = $child_max;
  5618. }
  5619. }
  5620. return $max_level;
  5621. }
  5622. /**
  5623. * 检查 target_id 是否是 folder_id 的后代
  5624. * @param int $target_id
  5625. * @param int $folder_id
  5626. * @return bool
  5627. */
  5628. private function isDescendant($target_id, $folder_id) {
  5629. if ($target_id == $folder_id) {
  5630. return true;
  5631. }
  5632. $parent = DB::table('mp_products')
  5633. ->where('id', $target_id)
  5634. ->where('is_deleted', 0)
  5635. ->first();
  5636. if (!$parent || $parent->parent_id == 0) {
  5637. return false;
  5638. }
  5639. return $this->isDescendant($parent->parent_id, $folder_id);
  5640. }
  5641. /**
  5642. * 递归更新子项层级
  5643. * @param int $parent_id
  5644. * @param int $parent_level
  5645. */
  5646. private function updateChildrenLevel($parent_id, $parent_level) {
  5647. $children = DB::table('mp_products')
  5648. ->where('parent_id', $parent_id)
  5649. ->where('is_deleted', 0)
  5650. ->get();
  5651. foreach ($children as $child) {
  5652. $new_level = $parent_level + 1;
  5653. DB::table('mp_products')
  5654. ->where('id', $child->id)
  5655. ->update([
  5656. 'level' => $new_level,
  5657. 'updated_at' => date('Y-m-d H:i:s')
  5658. ]);
  5659. // 如果是文件夹,继续递归
  5660. if ($child->type == 2) {
  5661. $this->updateChildrenLevel($child->id, $new_level);
  5662. }
  5663. }
  5664. }
  5665. /**
  5666. * 获取文件夹路径(面包屑导航)
  5667. * @param array $data 包含 folder_id
  5668. * @return array 返回路径数组
  5669. */
  5670. public function getFolderPath($data) {
  5671. $uid = Site::getUid();
  5672. $cpid = Site::getCpid();
  5673. $folder_id = getProp($data, 'id', 0);
  5674. $is_public = getProp($data, 'is_public', 0); // 0=个人资产库 1=公共资产库
  5675. if ($folder_id == 0) {
  5676. return [
  5677. ['id' => 0, 'name' => '根目录']
  5678. ];
  5679. }
  5680. // 根据is_public参数确定查询的user_id(公共库user_id=0,cpid保持不变)
  5681. $query_uid = $is_public ? 0 : $uid;
  5682. $path = [];
  5683. $current_id = $folder_id;
  5684. while ($current_id > 0) {
  5685. $folder = DB::table('mp_products')
  5686. ->where('id', $current_id)
  5687. ->where('cpid', $cpid)
  5688. ->where('user_id', $query_uid)
  5689. ->where('type', 2)
  5690. ->where('is_deleted', 0)
  5691. ->first();
  5692. if (!$folder) {
  5693. break;
  5694. }
  5695. array_unshift($path, [
  5696. 'id' => $folder->id,
  5697. 'name' => $folder->product_name
  5698. ]);
  5699. $current_id = $folder->parent_id;
  5700. }
  5701. // 添加根目录
  5702. array_unshift($path, ['id' => 0, 'name' => '根目录']);
  5703. return $path;
  5704. }
  5705. public function createProduct($data) {
  5706. $uid = Site::getUid();
  5707. $cpid = Site::getCpid();
  5708. $role = Site::getRole();
  5709. $is_public = getProp($data, 'is_public', 0); // 0=个人资产库 1=公共资产库
  5710. // 如果是公共库操作,需要admin权限
  5711. if ($is_public && $role !== 'admin') {
  5712. Utils::throwError('20003:只有管理员才能操作公共资产库');
  5713. }
  5714. // 根据is_public参数确定存储的user_id(公共库user_id=0,cpid保持不变)
  5715. $store_uid = $is_public ? 0 : $uid;
  5716. $product_name = trim(getProp($data, 'product_name'));
  5717. if (!$product_name) Utils::throwError('20003:名称不能为空');
  5718. $product_name = preg_replace('/^[\s*\[\]【】[]{}{}\x{3000}]+|[\s*\[\]【】[]{}{}\x{3000}]+$/u', '', $product_name);
  5719. // $exists_id = DB::table('mp_products')->where('cpid', $cpid)->where('type', 1)->where('product_name', $product_name)->where('is_deleted', 0)->value('id');
  5720. // if ($exists_id) Utils::throwError('20003:名称不能重复,请修改');
  5721. $url = trim(getProp($data, 'url'));
  5722. if (!$url) Utils::throwError('20003:图片地址不能为空');
  5723. $versions = getProp($data, 'versions');
  5724. // 检查是否是正确的图片格式
  5725. $allowedExtensions = ['jpg', 'jpeg', 'png', 'gif', 'webp', 'bmp'];
  5726. $urlPath = parse_url($url, PHP_URL_PATH);
  5727. $extension = strtolower(pathinfo($urlPath, PATHINFO_EXTENSION));
  5728. if (!in_array($extension, $allowedExtensions)) {
  5729. Utils::throwError('20003:图片格式不正确,仅支持 jpg、jpeg、png、gif、webp、bmp 格式');
  5730. }
  5731. $pic_prompt = trim(getProp($data, 'pic_prompt'));
  5732. if (!$pic_prompt) Utils::throwError('20003:提示词不能为空');
  5733. // 获取 product 字段:1.角色 2.场景 3.道具,默认为1
  5734. $product = getProp($data, 'product');
  5735. if (!in_array($product, [1, 2, 3])) {
  5736. // Utils::throwError('20003:产品类型只能是 1(角色)、2(场景) 或 3(道具)');
  5737. }
  5738. // 获取父文件夹ID和层级
  5739. $parent_id = getProp($data, 'parent_id', 0);
  5740. $parent_level = 0;
  5741. if ($parent_id > 0) {
  5742. $parent = DB::table('mp_products')
  5743. ->where('id', $parent_id)
  5744. ->where('cpid', $cpid)
  5745. ->where('user_id', $store_uid)
  5746. ->where('type', 2)
  5747. ->where('is_deleted', 0)
  5748. ->first();
  5749. if (!$parent) {
  5750. Utils::throwError('20003:父文件夹不存在');
  5751. }
  5752. $parent_level = $parent->level;
  5753. }
  5754. $id = DB::table('mp_products')->insertGetId([
  5755. 'user_id' => $store_uid,
  5756. 'cpid' => $cpid,
  5757. 'type' => 1, // 1=角色图片
  5758. 'parent_id' => $parent_id,
  5759. 'level' => $parent_level + 1,
  5760. 'product_name' => $product_name,
  5761. 'url' => $url,
  5762. 'pic_prompt' => $pic_prompt,
  5763. 'product' => $product,
  5764. 'versions' => json_encode($versions, 256),
  5765. 'sort_order' => time(), // 使用时间戳作为排序权重
  5766. 'created_at' => date('Y-m-d H:i:s'),
  5767. 'updated_at' => date('Y-m-d H:i:s')
  5768. ]);
  5769. if (!$id) Utils::throwError('20003:创建失败');
  5770. return [
  5771. 'id' => $id,
  5772. 'type' => 1,
  5773. 'parent_id' => $parent_id,
  5774. 'level' => $parent_level + 1,
  5775. 'product_name' => $product_name,
  5776. 'url' => $url,
  5777. 'pic_prompt' => $pic_prompt,
  5778. 'product' => $product,
  5779. 'versions' => $versions
  5780. ];
  5781. }
  5782. public function editProduct($data) {
  5783. $uid = Site::getUid();
  5784. $cpid = Site::getCpid();
  5785. $role = Site::getRole();
  5786. $id = getProp($data, 'id');
  5787. if (!$id) Utils::throwError('20003:ID不能为空');
  5788. $versions = getProp($data, 'versions');
  5789. $is_public = getProp($data, 'is_public', 0); // 0=个人资产库 1=公共资产库
  5790. // 根据is_public参数确定查询的user_id(公共库user_id=0,cpid保持不变)
  5791. $query_uid = $is_public ? 0 : $uid;
  5792. // 如果是公共库操作,需要admin权限
  5793. if ($is_public && $role !== 'admin') {
  5794. Utils::throwError('20003:只有管理员才能操作公共资产库');
  5795. }
  5796. // 检查是否存在且属于当前用户或公共库
  5797. $role = DB::table('mp_products')
  5798. ->where('id', $id)
  5799. ->where('cpid', $cpid)
  5800. ->where('user_id', $query_uid)
  5801. ->where('type', 1)->first();
  5802. if (!$role) Utils::throwError('20003:记录不存在');
  5803. $updateData = [];
  5804. // $needVersionRecord = false; // 是否需要记录版本
  5805. // 名称
  5806. $product_name = trim(getProp($data, 'product_name'));
  5807. if ($product_name) {
  5808. $product_name = preg_replace('/^[\s*\[\]【】[]{}{}\x{3000}]+|[\s*\[\]【】[]{}{}\x{3000}]+$/u', '', $product_name);
  5809. $updateData['product_name'] = $product_name;
  5810. }
  5811. // $exists_id = DB::table('mp_products')->where('cpid', $cpid)->where('type', 1)->where('product_name', $product_name)->where('is_deleted', 0)->value('id');
  5812. // if ($exists_id && $exists_id != $id) Utils::throwError('20003:名称不能重复,请修改');
  5813. // 图片地址
  5814. $url = trim(getProp($data, 'url'));
  5815. if ($url) {
  5816. // 检查是否是正确的图片格式
  5817. $allowedExtensions = ['jpg', 'jpeg', 'png', 'gif', 'webp', 'bmp'];
  5818. $urlPath = parse_url($url, PHP_URL_PATH);
  5819. $extension = strtolower(pathinfo($urlPath, PATHINFO_EXTENSION));
  5820. if (!in_array($extension, $allowedExtensions)) {
  5821. Utils::throwError('20003:图片格式不正确,仅支持 jpg、jpeg、png、gif、webp、bmp 格式');
  5822. }
  5823. // // 如果 url 有变更,记录版本
  5824. // if ($url !== $role->url) {
  5825. // $needVersionRecord = true;
  5826. // }
  5827. $updateData['url'] = $url;
  5828. }
  5829. // 提示词
  5830. $pic_prompt = trim(getProp($data, 'pic_prompt'));
  5831. if ($pic_prompt) {
  5832. // // 如果 pic_prompt 有变更,记录版本
  5833. // if ($pic_prompt !== $role->pic_prompt) {
  5834. // $needVersionRecord = true;
  5835. // }
  5836. $updateData['pic_prompt'] = $pic_prompt;
  5837. }
  5838. if (empty($updateData)) {
  5839. Utils::throwError('20003:没有需要更新的数据');
  5840. }
  5841. // // 如果需要记录版本,将数据添加到 versions 数组
  5842. // if ($needVersionRecord) {
  5843. // // 获取现有的 versions 数据
  5844. // $versions = json_decode($role->versions, true) ?: [];
  5845. // $isFirstVersion = empty($versions); // 判断是否是第一次记录版本
  5846. // // 如果是第一次记录版本,先添加旧版本(变更前)
  5847. // if ($isFirstVersion) {
  5848. // $oldVersion = [
  5849. // 'url' => $role->url,
  5850. // 'description' => $role->pic_prompt,
  5851. // ];
  5852. // // 旧版本添加到数组末尾
  5853. // $versions[] = $oldVersion;
  5854. // }
  5855. // // 构建新版本(变更后)
  5856. // $newVersion = [
  5857. // 'url' => isset($updateData['url']) ? $updateData['url'] : $role->url,
  5858. // 'description' => isset($updateData['pic_prompt']) ? $updateData['pic_prompt'] : $role->pic_prompt,
  5859. // ];
  5860. // // 检查新版本是否已存在于历史版本中
  5861. // $existingIndex = -1;
  5862. // foreach ($versions as $index => $version) {
  5863. // if ($version['url'] === $newVersion['url'] && $version['description'] === $newVersion['description']) {
  5864. // $existingIndex = $index;
  5865. // break;
  5866. // }
  5867. // }
  5868. // if ($existingIndex !== -1) {
  5869. // // 如果已存在,移除旧的位置
  5870. // array_splice($versions, $existingIndex, 1);
  5871. // }
  5872. // // 新版本添加到数组开头(最新的在前)
  5873. // array_unshift($versions, $newVersion);
  5874. // // // 限制版本数量(可选,例如只保留最近10个版本)
  5875. // // if (count($versions) > 10) {
  5876. // // $versions = array_slice($versions, 0, 10);
  5877. // // }
  5878. // $updateData['versions'] = json_encode($versions, 256);
  5879. // }
  5880. if ($versions) {
  5881. $updateData['versions'] = json_encode($versions, 256);
  5882. }
  5883. $updateData['updated_at'] = date('Y-m-d H:i:s');
  5884. return DB::table('mp_products')
  5885. ->where('cpid', $cpid)
  5886. ->where('id', $id)->update($updateData);
  5887. }
  5888. /**
  5889. * 获取角色版本历史
  5890. * @param array $data 包含 id(角色ID)
  5891. * @return array 返回版本历史列表
  5892. */
  5893. public function getProductVersions($data) {
  5894. $cpid = Site::getCpid();
  5895. $id = getProp($data, 'id');
  5896. if (!$id) Utils::throwError('20003:角色ID不能为空');
  5897. $role = DB::table('mp_products')
  5898. ->where('id', $id)
  5899. ->where('cpid', $cpid)
  5900. ->where('type', 1)
  5901. ->first();
  5902. if (!$role) Utils::throwError('20003:角色不存在');
  5903. // 获取版本历史
  5904. $versions = json_decode($role->versions, true) ?: [];
  5905. // 添加当前版本作为最新版本
  5906. $currentVersion = [
  5907. 'version' => 0, // 0 表示当前版本
  5908. 'url' => $role->url,
  5909. 'pic_prompt' => $role->pic_prompt,
  5910. 'updated_at' => $role->updated_at,
  5911. 'is_current' => true
  5912. ];
  5913. array_unshift($versions, $currentVersion);
  5914. return $versions;
  5915. }
  5916. /**
  5917. * 恢复到指定版本
  5918. * @param array $data 包含 id(角色ID)、version(版本号)
  5919. * @return bool
  5920. */
  5921. public function restoreProductVersion($data) {
  5922. $uid = Site::getUid();
  5923. $cpid = Site::getCpid();
  5924. $id = getProp($data, 'id');
  5925. $version = getProp($data, 'version');
  5926. if (!$id) Utils::throwError('20003:角色ID不能为空');
  5927. if (!$version) Utils::throwError('20003:版本号不能为空');
  5928. $role = DB::table('mp_products')
  5929. ->where('id', $id)
  5930. ->where('cpid', $cpid)
  5931. ->where('type', 1)
  5932. ->first();
  5933. if (!$role) Utils::throwError('20003:角色不存在');
  5934. // 获取版本历史
  5935. $versions = json_decode($role->versions, true) ?: [];
  5936. // 查找指定版本
  5937. $targetVersion = null;
  5938. foreach ($versions as $v) {
  5939. if ($v['version'] == $version) {
  5940. $targetVersion = $v;
  5941. break;
  5942. }
  5943. }
  5944. if (!$targetVersion) Utils::throwError('20003:版本不存在');
  5945. // 先将当前版本保存到历史
  5946. $newVersion = [
  5947. 'version' => count($versions) + 1,
  5948. 'url' => $role->url,
  5949. 'pic_prompt' => $role->pic_prompt,
  5950. 'updated_at' => date('Y-m-d H:i:s'),
  5951. 'updated_by' => $uid
  5952. ];
  5953. array_unshift($versions, $newVersion);
  5954. // 限制版本数量
  5955. if (count($versions) > 10) {
  5956. $versions = array_slice($versions, 0, 10);
  5957. }
  5958. // 恢复到指定版本
  5959. return DB::table('mp_products')
  5960. ->where('id', $id)
  5961. ->where('cpid', $cpid)
  5962. ->update([
  5963. 'url' => $targetVersion['url'],
  5964. 'pic_prompt' => $targetVersion['pic_prompt'],
  5965. 'versions' => json_encode($versions, JSON_UNESCAPED_UNICODE),
  5966. 'updated_at' => date('Y-m-d H:i:s')
  5967. ]);
  5968. }
  5969. public function deleteProduct($data) {
  5970. $uid = Site::getUid();
  5971. $cpid = Site::getCpid();
  5972. $role = Site::getRole();
  5973. $id = getProp($data, 'id');
  5974. if (!$id) Utils::throwError('20003:ID不能为空');
  5975. $ids = explode(',', $id);
  5976. $is_public = getProp($data, 'is_public', 0); // 0=个人资产库 1=公共资产库
  5977. // 根据is_public参数确定查询的user_id(公共库user_id=0,cpid保持不变)
  5978. $query_uid = $is_public ? 0 : $uid;
  5979. // 如果是公共库操作,需要admin权限
  5980. if ($is_public && $role !== 'admin') {
  5981. Utils::throwError('20003:只有管理员才能操作公共资产库');
  5982. }
  5983. // 检查是否存在且属于当前用户或公共库
  5984. $role = DB::table('mp_products')
  5985. ->whereIn('id', $ids)
  5986. ->where('cpid', $cpid)
  5987. ->where('user_id', $query_uid)
  5988. ->get();
  5989. if (!$role) Utils::throwError('20003:记录不存在');
  5990. return DB::table('mp_products')
  5991. ->where('cpid', $cpid)
  5992. ->where('user_id', $query_uid)
  5993. ->whereIn('id', $ids)
  5994. ->update([
  5995. 'is_deleted' => 1,
  5996. 'updated_at' => date('Y-m-d H:i:s')
  5997. ]);
  5998. }
  5999. public function generateThreeView($data) {
  6000. $uid = Site::getUid();
  6001. $cpid = Site::getCpid();
  6002. $role = Site::getRole();
  6003. $id = getProp($data, 'id');
  6004. if (!$id) Utils::throwError('20003:ID不能为空');
  6005. $is_public = getProp($data, 'is_public', 0); // 0=个人资产库 1=公共资产库
  6006. // 根据is_public参数确定查询的user_id(公共库user_id=0,cpid保持不变)
  6007. $query_uid = $is_public ? 0 : $uid;
  6008. // 如果是公共库操作,需要admin权限
  6009. if ($is_public && $role !== 'admin') {
  6010. Utils::throwError('20003:只有管理员才能操作公共资产库');
  6011. }
  6012. // 检查是否存在且属于当前用户或公共库
  6013. $product = DB::table('mp_products')
  6014. ->where('id', $id)
  6015. ->where('cpid', $cpid)
  6016. ->where('user_id', $query_uid)
  6017. ->where('type', 1)->first();
  6018. if (!$product) Utils::throwError('20003:资产不存在');
  6019. $prompt = trim(getProp($data, 'prompt', '基于参考图生成主体的标准正面、侧面、后面三视图,主体完整。在最左侧添加主体正视图的特写,主体清晰完整。背景修改成纯白色,整体保持与参考图一致的美术风格和色彩搭配。画面无说明文字'));
  6020. $ref_img_url = trim(getProp($data, 'ref_img_url'));
  6021. if (!$ref_img_url) {
  6022. // 如果没有传入参考图,使用角色表中的图片
  6023. $ref_img_url = $product->url ?? '';
  6024. if (!$ref_img_url) {
  6025. Utils::throwError('20003:参考图不能为空');
  6026. }
  6027. }
  6028. $pic_prompt = getProp($product, 'pic_prompt');
  6029. if ($pic_prompt) {
  6030. $prompt .= '\n参考图原始提示词: '.$pic_prompt;
  6031. }
  6032. // 检查参考图是否是正确的图片格式
  6033. $allowedExtensions = ['jpg', 'jpeg', 'png', 'gif', 'webp', 'bmp'];
  6034. $urlPath = parse_url($ref_img_url, PHP_URL_PATH);
  6035. $extension = strtolower(pathinfo($urlPath, PATHINFO_EXTENSION));
  6036. if (!in_array($extension, $allowedExtensions)) {
  6037. Utils::throwError('20003:参考图格式不正确,仅支持 jpg、jpeg、png、gif、webp、bmp 格式');
  6038. }
  6039. // 处理图片模型
  6040. $model = getProp($data, 'model');
  6041. if (!$model) {
  6042. // 使用默认模型
  6043. $model = 'doubao-seedream-5-0-lite-260128';
  6044. }
  6045. // 验证模型是否在可用模型表中
  6046. if (!DB::table('mp_image_models')->where('model', $model)->where('is_enabled', 1)->exists()) {
  6047. Utils::throwError('20003:该模型已不可用,请更换!');
  6048. }
  6049. $ratio = getProp($data, 'ratio', '16:9');
  6050. $resolution = getProp($data, 'resolution', '2k');
  6051. // 定义分辨率和宽高比对应的尺寸映射表
  6052. $sizeMap = [
  6053. '2k' => [
  6054. '1:1' => ['width' => 2048, 'height' => 2048],
  6055. '4:3' => ['width' => 2304, 'height' => 1728],
  6056. '3:4' => ['width' => 1728, 'height' => 2304],
  6057. '16:9' => ['width' => 2848, 'height' => 1600],
  6058. '9:16' => ['width' => 1600, 'height' => 2848],
  6059. '3:2' => ['width' => 2496, 'height' => 1664],
  6060. '2:3' => ['width' => 1664, 'height' => 2496],
  6061. '21:9' => ['width' => 3136, 'height' => 1344],
  6062. ],
  6063. '3k' => [
  6064. '1:1' => ['width' => 3072, 'height' => 3072],
  6065. '4:3' => ['width' => 3456, 'height' => 2592],
  6066. '3:4' => ['width' => 2592, 'height' => 3456],
  6067. '16:9' => ['width' => 4096, 'height' => 2304],
  6068. '9:16' => ['width' => 2304, 'height' => 4096],
  6069. '2:3' => ['width' => 2496, 'height' => 3744],
  6070. '3:2' => ['width' => 3744, 'height' => 2496],
  6071. '21:9' => ['width' => 4704, 'height' => 2016],
  6072. ],
  6073. '4k' => [
  6074. '1:1' => ['width' => 4096, 'height' => 4096],
  6075. '3:4' => ['width' => 3520, 'height' => 4704],
  6076. '4:3' => ['width' => 4704, 'height' => 3520],
  6077. '16:9' => ['width' => 5504, 'height' => 3040],
  6078. '9:16' => ['width' => 3040, 'height' => 5504],
  6079. '2:3' => ['width' => 3328, 'height' => 4992],
  6080. '3:2' => ['width' => 4992, 'height' => 3328],
  6081. '21:9' => ['width' => 6240, 'height' => 2656],
  6082. ],
  6083. ];
  6084. // 参数验证
  6085. $resolution = strtolower($resolution);
  6086. if (!isset($sizeMap[$resolution])) {
  6087. Utils::throwError('20003:分辨率参数错误,仅支持 2k、3k、4k');
  6088. }
  6089. if (!isset($sizeMap[$resolution][$ratio])) {
  6090. Utils::throwError('20003:宽高比参数错误,该分辨率下不支持 ' . $ratio . ' 比例');
  6091. }
  6092. // 根据 ratio 和 resolution 确定宽高
  6093. $width = $sizeMap[$resolution][$ratio]['width'];
  6094. $height = $sizeMap[$resolution][$ratio]['height'];
  6095. try {
  6096. // 创建图片生成任务
  6097. $params = [
  6098. 'prompt' => $prompt,
  6099. 'model' => $model,
  6100. 'ref_img_urls' => [$ref_img_url],
  6101. 'width' => $width,
  6102. 'height' => $height
  6103. ];
  6104. $task = $this->aiImageGenerationService->createImageGenerationTask($params);
  6105. $task_id = $task->id;
  6106. if (!$task_id) {
  6107. Utils::throwError('20003:创建图片生成任务失败');
  6108. }
  6109. // 轮询获取结果
  6110. // 只查询数据库,不调用API,不更新任务表
  6111. $start_time = time();
  6112. $timeout = 1800;
  6113. $img_url = '';
  6114. while (time() - $start_time < $timeout) {
  6115. sleep(5);
  6116. // 只查询数据库中的任务状态,不调用API,不更新任务表
  6117. $task = DB::table('mp_generate_pic_tasks')
  6118. ->where('id', $task_id)
  6119. ->first();
  6120. if (!$task) {
  6121. Utils::throwError('20003:任务不存在');
  6122. }
  6123. if ($task->status === 'success' && $task->result_url) {
  6124. $result_urls = is_string($task->result_url)
  6125. ? json_decode($task->result_url, true)
  6126. : $task->result_url;
  6127. $img_url = is_array($result_urls) ? $result_urls[0] : $task->result_url;
  6128. break;
  6129. } elseif ($task->status === 'failed') {
  6130. Utils::throwError('20003:三视图生成失败,' . ($task->error_message ?? '未知错误'));
  6131. }
  6132. // 其他状态继续轮询
  6133. }
  6134. if (empty($img_url)) {
  6135. Utils::throwError('20003:三视图生成超时,请稍后重试');
  6136. }
  6137. // 更新 mp_products 表(不是任务表)
  6138. DB::table('mp_products')
  6139. ->where('id', $id)
  6140. ->where('cpid', $cpid)
  6141. ->update([
  6142. 'three_view_image_url' => $img_url,
  6143. 'updated_at' => date('Y-m-d H:i:s')
  6144. ]);
  6145. return ['three_view_image_url' => $img_url];
  6146. } catch (\Exception $e) {
  6147. dLog('anime')->error('生成三视图失败', [
  6148. 'error' => $e->getMessage()
  6149. ]);
  6150. logDB('anime', 'error', '生成三视图失败', ['error' => $e->getMessage()]);
  6151. Utils::throwError('20003:' . $e->getMessage());
  6152. }
  6153. }
  6154. /**
  6155. * 推送(复制)资产或文件夹到目标位置
  6156. * @param array $data 包含 product_id(要推送的资产或文件夹ID)、target_parent_id(目标父文件夹ID,0表示根目录)
  6157. * @return array 返回推送结果
  6158. */
  6159. public function pushProductOrFolder($data) {
  6160. $uid = Site::getUid();
  6161. $cpid = Site::getCpid();
  6162. $role = Site::getRole();
  6163. $product_id = getProp($data, 'product_id');
  6164. $target_parent_id = getProp($data, 'target_parent_id', 0);
  6165. $target_product = getProp($data, 'product'); // 目标 product 类型,用于跨类型推送
  6166. if (!$product_id) {
  6167. Utils::throwError('20003:请选择要推送的项目');
  6168. }
  6169. // 查询源项目(只通过cpid查询,不限制user_id)
  6170. $sourceItem = DB::table('mp_products')
  6171. ->where('id', $product_id)
  6172. ->where('cpid', $cpid)
  6173. ->where('is_deleted', 0)
  6174. ->first();
  6175. if (!$sourceItem) {
  6176. Utils::throwError('20003:要推送的项目不存在');
  6177. }
  6178. // 通过user_id判断源是公共库还是个人库
  6179. $source_uid = $sourceItem->user_id;
  6180. $source_is_public = ($source_uid == 0) ? 1 : 0;
  6181. // 验证目标文件夹并确定目标是公共库还是个人库
  6182. $target_level = 0;
  6183. $target_uid = $uid; // 默认推送到个人库
  6184. $target_is_public = 0;
  6185. $final_product_type = $sourceItem->product; // 默认使用源的 product 类型
  6186. if ($target_parent_id > 0) {
  6187. // 查询目标文件夹(只通过cpid查询,不限制user_id)
  6188. $targetParent = DB::table('mp_products')
  6189. ->where('id', $target_parent_id)
  6190. ->where('cpid', $cpid)
  6191. ->where('type', 2)
  6192. ->where('is_deleted', 0)
  6193. ->first();
  6194. if (!$targetParent) {
  6195. Utils::throwError('20003:目标文件夹不存在');
  6196. }
  6197. // 通过user_id判断目标是公共库还是个人库
  6198. $target_level = $targetParent->level;
  6199. $target_uid = $targetParent->user_id;
  6200. $target_is_public = ($target_uid == 0) ? 1 : 0;
  6201. // 使用目标文件夹的 product 类型
  6202. $final_product_type = $targetParent->product;
  6203. }
  6204. // 如果 target_parent_id = 0(推送到根目录),需要通过参数判断推送到个人库还是公共库
  6205. else {
  6206. $push_to_public = getProp($data, 'push_to_public');
  6207. if ($push_to_public === '') {
  6208. Utils::throwError('20003:请选择是否推送到公共库');
  6209. }
  6210. if ($push_to_public) {
  6211. $target_uid = 0;
  6212. $target_is_public = 1;
  6213. }
  6214. // 推送到根目录时,必须指定 product 类型
  6215. if ($target_product === null || $target_product === '') {
  6216. Utils::throwError('20003:推送到根目录时必须指定目标类型(product)');
  6217. }
  6218. $final_product_type = $target_product;
  6219. }
  6220. // 如果目标是公共库,需要admin权限
  6221. if ($target_is_public && $role !== 'admin') {
  6222. Utils::throwError('20003:只有管理员才能推送到公共资产库');
  6223. }
  6224. // 权限验证:验证是否符合允许的推送规则
  6225. $this->validatePushPermission($source_uid, $target_uid, $uid);
  6226. try {
  6227. DB::beginTransaction();
  6228. // 如果是资产,直接复制(支持跨类型推送,更新 product 字段)
  6229. if ($sourceItem->type == 1) {
  6230. $newId = $this->copyProduct($sourceItem, $target_parent_id, $target_level + 1, $cpid, $target_uid, $final_product_type);
  6231. DB::commit();
  6232. return [
  6233. 'product_id' => $newId,
  6234. ];
  6235. }
  6236. // 如果是文件夹,递归复制(支持跨类型推送)
  6237. $newFolderId = $this->copyFolderRecursive($sourceItem, $target_parent_id, $target_level + 1, $cpid, $target_uid, $source_uid, $final_product_type);
  6238. DB::commit();
  6239. return [
  6240. 'product_id' => $newFolderId,
  6241. ];
  6242. } catch (\Exception $e) {
  6243. DB::rollBack();
  6244. dLog('anime')->error('推送失败', [
  6245. 'error' => $e->getMessage(),
  6246. 'product_id' => $product_id
  6247. ]);
  6248. Utils::throwError('20003:' . $e->getMessage());
  6249. }
  6250. }
  6251. /**
  6252. * 验证推送权限
  6253. * 允许的推送规则:
  6254. * 1. 自己推送给自己的个人库(个人库 → 个人库,同一用户)
  6255. * 2. 公共库推送给自己的个人库(公共库 → 个人库)
  6256. * 3. 公共库推送给公共库(公共库 → 公共库)
  6257. *
  6258. * @param int $source_uid 源的user_id
  6259. * @param int $target_uid 目标的user_id
  6260. * @param int $current_uid 当前用户ID
  6261. * @throws \Exception
  6262. */
  6263. private function validatePushPermission($source_uid, $target_uid, $current_uid) {
  6264. // 规则1:自己推送给自己的个人库(个人库 → 个人库,同一用户)
  6265. if ($source_uid == $current_uid && $target_uid == $current_uid) {
  6266. return; // 允许
  6267. }
  6268. // 规则2:公共库推送给自己的个人库(公共库 → 个人库)
  6269. if ($source_uid == 0 && $target_uid == $current_uid) {
  6270. return; // 允许
  6271. }
  6272. // 规则3:公共库推送给公共库(公共库 → 公共库)
  6273. if ($source_uid == 0 && $target_uid == 0) {
  6274. return; // 允许
  6275. }
  6276. // 其他情况都不允许
  6277. if ($source_uid != 0 && $source_uid != $current_uid) {
  6278. // 源是别人的个人库
  6279. Utils::throwError('20003:无权限访问该资产');
  6280. } elseif ($source_uid == $current_uid && $target_uid == 0) {
  6281. // 个人库推送给公共库(不允许)
  6282. Utils::throwError('20003:不允许将个人资产推送到公共库');
  6283. } elseif ($source_uid != 0 && $target_uid != 0 && $source_uid != $target_uid) {
  6284. // 不同用户的个人库之间推送(不允许)
  6285. Utils::throwError('20003:不允许推送到其他用户的个人库');
  6286. } else {
  6287. // 其他未知情况
  6288. Utils::throwError('20003:不允许的推送操作');
  6289. }
  6290. }
  6291. /**
  6292. * 复制单个资产
  6293. * @param object $sourceProduct 源资产对象
  6294. * @param int $targetParentId 目标父文件夹ID
  6295. * @param int $targetLevel 目标层级
  6296. * @param int $cpid 公司ID
  6297. * @param int $targetUid 目标用户ID
  6298. * @return int 返回新资产ID
  6299. */
  6300. private function copyProduct($sourceProduct, $targetParentId, $targetLevel, $cpid, $targetUid, $productType = null) {
  6301. // 如果指定了 productType,使用指定的;否则使用源的 product 类型
  6302. $finalProductType = ($productType !== null) ? $productType : $sourceProduct->product;
  6303. $newProductData = [
  6304. 'user_id' => $targetUid,
  6305. 'cpid' => $cpid,
  6306. 'type' => 1,
  6307. 'parent_id' => $targetParentId,
  6308. 'level' => $targetLevel,
  6309. 'product_name' => $sourceProduct->product_name,
  6310. 'url' => $sourceProduct->url,
  6311. 'pic_prompt' => $sourceProduct->pic_prompt ?? '',
  6312. 'three_view_image_url' => $sourceProduct->three_view_image_url ?? '',
  6313. 'product' => $finalProductType,
  6314. 'versions' => $sourceProduct->versions ?? '',
  6315. 'sort_order' => time(),
  6316. 'is_deleted' => 0,
  6317. 'created_at' => date('Y-m-d H:i:s'),
  6318. 'updated_at' => date('Y-m-d H:i:s')
  6319. ];
  6320. return DB::table('mp_products')->insertGetId($newProductData);
  6321. }
  6322. /**
  6323. * 递归复制文件夹及其子项
  6324. * @param object $sourceFolder 源文件夹对象
  6325. * @param int $targetParentId 目标父文件夹ID
  6326. * @param int $targetLevel 目标层级
  6327. * @param int $cpid 公司ID
  6328. * @param int $targetUid 目标用户ID
  6329. * @param int $sourceUid 源用户ID
  6330. * @return int 返回新文件夹ID
  6331. */
  6332. private function copyFolderRecursive($sourceFolder, $targetParentId, $targetLevel, $cpid, $targetUid, $sourceUid, $productType = null) {
  6333. // 如果指定了 productType,使用指定的;否则使用源的 product 类型
  6334. $finalProductType = ($productType !== null) ? $productType : $sourceFolder->product;
  6335. // 创建新文件夹
  6336. $newFolderData = [
  6337. 'user_id' => $targetUid,
  6338. 'cpid' => $cpid,
  6339. 'type' => 2,
  6340. 'parent_id' => $targetParentId,
  6341. 'level' => $targetLevel,
  6342. 'product_name' => $sourceFolder->product_name,
  6343. 'product' => $finalProductType,
  6344. 'sort_order' => time(),
  6345. 'is_deleted' => 0,
  6346. 'created_at' => date('Y-m-d H:i:s'),
  6347. 'updated_at' => date('Y-m-d H:i:s')
  6348. ];
  6349. $newFolderId = DB::table('mp_products')->insertGetId($newFolderData);
  6350. // 获取源文件夹下的所有子项
  6351. $children = DB::table('mp_products')
  6352. ->where('parent_id', $sourceFolder->id)
  6353. ->where('cpid', $cpid)
  6354. ->where('user_id', $sourceUid)
  6355. ->where('is_deleted', 0)
  6356. ->orderByRaw('type DESC, sort_order DESC, created_at DESC')
  6357. ->get();
  6358. // 递归复制子项(子项继承目标文件夹的 product 类型)
  6359. foreach ($children as $child) {
  6360. if ($child->type == 1) {
  6361. // 资产
  6362. $this->copyProduct($child, $newFolderId, $targetLevel + 1, $cpid, $targetUid, $finalProductType);
  6363. } else {
  6364. // 文件夹
  6365. $this->copyFolderRecursive($child, $newFolderId, $targetLevel + 1, $cpid, $targetUid, $sourceUid, $finalProductType);
  6366. }
  6367. }
  6368. return $newFolderId;
  6369. }
  6370. /**
  6371. * 保存剧本资产关联关系
  6372. * @param array $data 请求参数
  6373. * @return bool
  6374. */
  6375. public function saveScriptProducts($data) {
  6376. $uid = Site::getUid();
  6377. $cpid = Site::getCpid();
  6378. $script_id = getProp($data, 'script_id');
  6379. $products = getProp($data, 'products', []);
  6380. $auto_generate_images = getProp($data, 'auto_generate_images', true); // 是否自动生成图片,默认true
  6381. if (!$script_id) {
  6382. Utils::throwError('20003:请提供剧本ID');
  6383. }
  6384. // 验证剧本是否存在
  6385. $script = DB::table('mp_scripts')
  6386. ->where('id', $script_id)
  6387. ->where('is_deleted', 0)
  6388. ->first();
  6389. if (!$script) {
  6390. Utils::throwError('20003:剧本不存在');
  6391. }
  6392. // 处理图片模型
  6393. $model = getProp($data, 'model');
  6394. if (!$model) {
  6395. // 使用默认模型
  6396. $model = 'doubao-seedream-5-0-lite-260128';
  6397. }
  6398. // 验证模型是否在可用模型表中
  6399. if (!DB::table('mp_image_models')->where('model', $model)->where('is_enabled', 1)->exists()) {
  6400. Utils::throwError('20003:该模型已不可用,请更换!');
  6401. }
  6402. $ratio = getProp($data, 'ratio', '9:16');
  6403. $resolution = getProp($data, 'resolution', '2k');
  6404. // 定义分辨率和宽高比对应的尺寸映射表
  6405. $sizeMap = [
  6406. '2k' => [
  6407. '1:1' => ['width' => 2048, 'height' => 2048],
  6408. '4:3' => ['width' => 2304, 'height' => 1728],
  6409. '3:4' => ['width' => 1728, 'height' => 2304],
  6410. '16:9' => ['width' => 2848, 'height' => 1600],
  6411. '9:16' => ['width' => 1600, 'height' => 2848],
  6412. '3:2' => ['width' => 2496, 'height' => 1664],
  6413. '2:3' => ['width' => 1664, 'height' => 2496],
  6414. '21:9' => ['width' => 3136, 'height' => 1344],
  6415. ],
  6416. '3k' => [
  6417. '1:1' => ['width' => 3072, 'height' => 3072],
  6418. '4:3' => ['width' => 3456, 'height' => 2592],
  6419. '3:4' => ['width' => 2592, 'height' => 3456],
  6420. '16:9' => ['width' => 4096, 'height' => 2304],
  6421. '9:16' => ['width' => 2304, 'height' => 4096],
  6422. '2:3' => ['width' => 2496, 'height' => 3744],
  6423. '3:2' => ['width' => 3744, 'height' => 2496],
  6424. '21:9' => ['width' => 4704, 'height' => 2016],
  6425. ],
  6426. '4k' => [
  6427. '1:1' => ['width' => 4096, 'height' => 4096],
  6428. '3:4' => ['width' => 3520, 'height' => 4704],
  6429. '4:3' => ['width' => 4704, 'height' => 3520],
  6430. '16:9' => ['width' => 5504, 'height' => 3040],
  6431. '9:16' => ['width' => 3040, 'height' => 5504],
  6432. '2:3' => ['width' => 3328, 'height' => 4992],
  6433. '3:2' => ['width' => 4992, 'height' => 3328],
  6434. '21:9' => ['width' => 6240, 'height' => 2656],
  6435. ],
  6436. ];
  6437. // 参数验证
  6438. $resolution = strtolower($resolution);
  6439. if (!isset($sizeMap[$resolution])) {
  6440. Utils::throwError('20003:分辨率参数错误,仅支持 2k、3k、4k');
  6441. }
  6442. if (!isset($sizeMap[$resolution][$ratio])) {
  6443. Utils::throwError('20003:宽高比参数错误,该分辨率下不支持 ' . $ratio . ' 比例');
  6444. }
  6445. // 根据 ratio 和 resolution 确定宽高
  6446. $width = $sizeMap[$resolution][$ratio]['width'];
  6447. $height = $sizeMap[$resolution][$ratio]['height'];
  6448. $script_name = $script->script_name ?? 'script_' . $script_id;
  6449. // 检查是否已经有该剧本的资产数据
  6450. $existingMappings = DB::table('mp_script_product_mappings')
  6451. ->where('script_id', $script_id)
  6452. ->get();
  6453. if ($existingMappings->isNotEmpty()) {
  6454. // 已存在资产映射,检查是否所有资产都有图片生成任务
  6455. $productIds = $existingMappings->pluck('product_id')->unique()->toArray();
  6456. // 查询这些资产的图片生成任务状态
  6457. $productsWithTasks = DB::table('mp_products')
  6458. ->whereIn('id', $productIds)
  6459. ->where('is_deleted', 0)
  6460. ->get();
  6461. $productTaskMap = [];
  6462. $typeFolderIds = [];
  6463. $hasAllTasks = true;
  6464. foreach ($productsWithTasks as $product) {
  6465. // 收集类型文件夹ID
  6466. if ($product->parent_id > 0 && !in_array($product->parent_id, $typeFolderIds)) {
  6467. $parentFolder = DB::table('mp_products')
  6468. ->where('id', $product->parent_id)
  6469. ->where('type', 2)
  6470. ->first();
  6471. if ($parentFolder) {
  6472. $typeFolderIds[$parentFolder->product] = $parentFolder->id;
  6473. }
  6474. }
  6475. // 检查是否有图片生成任务
  6476. if (!empty($product->pic_task_id)) {
  6477. $productTaskMap[$product->id] = $product->pic_task_id;
  6478. } else if($product->url && $product->pic_task_status == '生成成功') {
  6479. continue;
  6480. } else {
  6481. // 有资产没有图片任务
  6482. $hasAllTasks = false;
  6483. }
  6484. }
  6485. // 如果所有资产都有任务ID,直接轮询返回结果
  6486. if ($hasAllTasks && !empty($productTaskMap)) {
  6487. dLog('anime')->info('剧本资产已存在且都有图片任务,直接轮询结果', [
  6488. 'script_id' => $script_id,
  6489. 'script_name' => $script_name,
  6490. 'product_count' => count($productTaskMap)
  6491. ]);
  6492. // 直接返回 SSE 流轮询结果
  6493. return $this->pollProductImageTasks($script_id, $script_name, $productTaskMap, $typeFolderIds);
  6494. }
  6495. // 如果部分资产没有任务ID,只为这些资产创建任务
  6496. if (!$hasAllTasks && $auto_generate_images) {
  6497. dLog('anime')->info('剧本资产已存在,但部分资产没有图片任务,为缺失的资产创建任务', [
  6498. 'script_id' => $script_id,
  6499. 'script_name' => $script_name
  6500. ]);
  6501. // 开启事务
  6502. DB::beginTransaction();
  6503. try {
  6504. foreach ($productsWithTasks as $product) {
  6505. // 跳过已有任务的资产
  6506. if (!empty($product->pic_task_id)) {
  6507. continue;
  6508. }
  6509. // 跳过没有提示词的资产
  6510. if (empty($product->pic_prompt)) {
  6511. dLog('anime')->warning('资产没有提示词,跳过图片生成', [
  6512. 'product_id' => $product->id,
  6513. 'product_name' => $product->product_name
  6514. ]);
  6515. continue;
  6516. }
  6517. try {
  6518. // 创建图片生成任务
  6519. $params = [
  6520. 'prompt' => $product->pic_prompt,
  6521. 'model' => $model,
  6522. 'ref_img_urls' => [],
  6523. 'width' => $width,
  6524. 'height' => $height
  6525. ];
  6526. $task = $this->aiImageGenerationService->createImageGenerationTask($params);
  6527. $task_id = $task->id;
  6528. if ($task_id) {
  6529. $productTaskMap[$product->id] = $task_id;
  6530. // 在事务中更新资产表的任务ID和状态
  6531. DB::table('mp_products')
  6532. ->where('id', $product->id)
  6533. ->update([
  6534. 'pic_task_id' => $task_id,
  6535. 'pic_task_status' => '生成中',
  6536. 'updated_at' => now()
  6537. ]);
  6538. dLog('anime')->info('为已存在资产创建图片生成任务', [
  6539. 'product_id' => $product->id,
  6540. 'task_id' => $task_id
  6541. ]);
  6542. }
  6543. } catch (\Exception $e) {
  6544. dLog('anime')->error('创建资产图片生成任务失败', [
  6545. 'product_id' => $product->id,
  6546. 'error' => $e->getMessage()
  6547. ]);
  6548. // 标记为失败(仍在事务中)
  6549. DB::table('mp_products')
  6550. ->where('id', $product->id)
  6551. ->update([
  6552. 'pic_task_status' => '生成失败',
  6553. 'updated_at' => now()
  6554. ]);
  6555. }
  6556. }
  6557. // 提交事务
  6558. DB::commit();
  6559. // 如果有新创建的任务,返回 SSE 流
  6560. if (!empty($productTaskMap)) {
  6561. return $this->pollProductImageTasks($script_id, $script_name, $productTaskMap, $typeFolderIds);
  6562. }
  6563. } catch (\Exception $e) {
  6564. // 回滚事务
  6565. DB::rollback();
  6566. dLog('anime')->error('为已存在资产创建图片任务失败', [
  6567. 'script_id' => $script_id,
  6568. 'error' => $e->getMessage()
  6569. ]);
  6570. Utils::throwError('20003:创建图片任务失败:' . $e->getMessage());
  6571. }
  6572. }
  6573. // 如果不需要生成图片,返回已存在的信息
  6574. return [
  6575. 'success' => true,
  6576. 'message' => '剧本资产已存在',
  6577. 'script_id' => $script_id,
  6578. 'script_name' => $script_name,
  6579. 'type_folder_ids' => $typeFolderIds,
  6580. 'existing_products' => count($productIds),
  6581. 'tasks_count' => count($productTaskMap)
  6582. ];
  6583. }
  6584. // 解析 products(可能是 JSON 字符串或数组)
  6585. if (is_string($products)) {
  6586. $products = json_decode($products, true);
  6587. if (json_last_error() !== JSON_ERROR_NONE) {
  6588. Utils::throwError('20003:产品数据格式错误');
  6589. }
  6590. }
  6591. if (!is_array($products) || empty($products)) {
  6592. Utils::throwError('20003:产品数据不能为空');
  6593. }
  6594. // 以下是原有的创建逻辑...
  6595. // 开启事务
  6596. DB::beginTransaction();
  6597. try {
  6598. $now = now();
  6599. $mappingRecords = [];
  6600. $createdProductIds = []; // 记录所有创建的资产ID
  6601. // 获取剧本名称
  6602. $script_name = $script->script_name ?? 'script_' . $script_id;
  6603. // 存储每个类型的根文件夹ID
  6604. $typeFolderIds = [];
  6605. // 遍历每个产品类型(type: 1=角色, 2=场景, 3=道具)
  6606. foreach ($products as $productGroup) {
  6607. $type = getProp($productGroup, 'type');
  6608. $title = getProp($productGroup, 'title', '');
  6609. $content = getProp($productGroup, 'content', []);
  6610. if (!in_array($type, [1, 2, 3]) || empty($content) || count($content) < 2) {
  6611. continue;
  6612. }
  6613. // 为当前类型创建根文件夹(如果还未创建)
  6614. if (!isset($typeFolderIds[$type])) {
  6615. $typeFolderIds[$type] = DB::table('mp_products')->insertGetId([
  6616. 'user_id' => $uid,
  6617. 'cpid' => $cpid,
  6618. 'type' => 2, // 1.资产 2文件夹
  6619. 'product' => $type, // 1.主体 2.场景 3.道具
  6620. 'parent_id' => 0, // 根文件夹,parent_id=0
  6621. 'level' => 1, // 第一层级
  6622. 'product_name' => $script_name,
  6623. 'sort_order' => time() + $type,
  6624. 'is_deleted' => 0,
  6625. 'created_at' => $now,
  6626. 'updated_at' => $now
  6627. ]);
  6628. }
  6629. $folder_id = $typeFolderIds[$type];
  6630. // 获取表头(第一行)并查找关键列的位置
  6631. $headers = $content[0];
  6632. $nameColumnIndex = -1; // 资产名称列索引
  6633. $sequenceColumnIndex = -1; // 使用范围列索引
  6634. $promptColumnIndex = -1; // 参考提示词列索引
  6635. foreach ($headers as $index => $header) {
  6636. // 查找"资产名称"列
  6637. if (strpos($header, '资产名称') !== false || strpos($header, '名称') !== false) {
  6638. $nameColumnIndex = $index;
  6639. }
  6640. // 查找"使用范围"列
  6641. if (strpos($header, '使用范围') !== false || strpos($header, '范围') !== false) {
  6642. $sequenceColumnIndex = $index;
  6643. }
  6644. // 查找"参考提示词"列(可能是"干净参考图提示词"、"参考提示词"等)
  6645. if (strpos($header, '参考') !== false && strpos($header, '提示词') !== false) {
  6646. $promptColumnIndex = $index;
  6647. }
  6648. }
  6649. // 验证必要的列是否都找到了
  6650. if ($nameColumnIndex === -1) {
  6651. dLog('anime')->warning('未找到资产名称列', ['type' => $type, 'headers' => $headers]);
  6652. continue;
  6653. }
  6654. if ($sequenceColumnIndex === -1) {
  6655. dLog('anime')->warning('未找到使用范围列', ['type' => $type, 'headers' => $headers]);
  6656. continue;
  6657. }
  6658. // 跳过表头,解析每一行数据
  6659. for ($i = 1; $i < count($content); $i++) {
  6660. $row = $content[$i];
  6661. // 确保行数据有效
  6662. if (empty($row) || count($row) <= max($nameColumnIndex, $sequenceColumnIndex)) {
  6663. continue;
  6664. }
  6665. // 根据动态查找的列索引提取数据
  6666. $product_name = isset($row[$nameColumnIndex]) ? trim($row[$nameColumnIndex]) : '';
  6667. $sequence_str = isset($row[$sequenceColumnIndex]) ? trim($row[$sequenceColumnIndex]) : '';
  6668. $pic_prompt = '';
  6669. // 提取参考提示词(如果找到了该列)
  6670. if ($promptColumnIndex >= 0 && isset($row[$promptColumnIndex])) {
  6671. $pic_prompt = trim($row[$promptColumnIndex]);
  6672. }
  6673. // 解析使用范围(逗号分隔的序号)
  6674. $sequences = [];
  6675. if (!empty($sequence_str)) {
  6676. $sequenceParts = array_map('trim', explode(',', $sequence_str));
  6677. foreach ($sequenceParts as $part) {
  6678. if (is_numeric($part)) {
  6679. $sequences[] = (int)$part;
  6680. }
  6681. }
  6682. }
  6683. if (empty($product_name)) {
  6684. continue;
  6685. }
  6686. // 处理product_name两边的符号
  6687. $product_name = preg_replace('/^[\s*\[\]【】[]{}{}\x{3000}]+|[\s*\[\]【】[]{}{}\x{3000}]+$/u', '', $product_name);
  6688. // 如果名称不存在则跳过
  6689. if (!$product_name) continue;
  6690. // 直接插入新资产到 mp_products 表(parent_id 指向对应类型的根文件夹)
  6691. $product_id = DB::table('mp_products')->insertGetId([
  6692. 'product_name' => $product_name,
  6693. 'type' => 1, // 1=资产 2.文件夹
  6694. 'product' => $type, // 1=角色, 2=场景, 3=道具
  6695. 'parent_id' => $folder_id, // 父文件夹是该类型的根文件夹
  6696. 'level' => 2, // 第二层级
  6697. 'pic_prompt' => $pic_prompt,
  6698. 'user_id' => $uid,
  6699. 'cpid' => $cpid,
  6700. 'sort_order' => time(),
  6701. 'is_deleted' => 0,
  6702. 'created_at' => $now,
  6703. 'updated_at' => $now,
  6704. ]);
  6705. // 记录创建的资产ID
  6706. $createdProductIds[] = $product_id;
  6707. // 为每个序号创建映射记录
  6708. if (!empty($sequences)) {
  6709. foreach ($sequences as $sequence) {
  6710. $mappingRecords[] = [
  6711. 'script_id' => $script_id,
  6712. 'product_id' => $product_id,
  6713. 'episode_number' => $sequence,
  6714. 'created_at' => $now,
  6715. 'updated_at' => $now,
  6716. ];
  6717. }
  6718. } else {
  6719. // 如果没有指定序号,创建一个默认映射(序号为0)
  6720. $mappingRecords[] = [
  6721. 'script_id' => $script_id,
  6722. 'product_id' => $product_id,
  6723. 'episode_number' => 0,
  6724. 'created_at' => $now,
  6725. 'updated_at' => $now,
  6726. ];
  6727. }
  6728. }
  6729. }
  6730. if (empty($mappingRecords)) {
  6731. Utils::throwError('20003:没有有效的产品数据');
  6732. }
  6733. // 批量插入映射数据(使用 insertOrIgnore 避免重复插入)
  6734. $insertedCount = DB::table('mp_script_product_mappings')->insertOrIgnore($mappingRecords);
  6735. // 剧本已有资产,同步更新is_products标记
  6736. DB::table('mp_scripts')->where('id', $script_id)->update([
  6737. 'is_products' => 1,
  6738. 'updated_at' => $now
  6739. ]);
  6740. // 如果需要自动生成图片,在事务中创建图片生成任务
  6741. $productTaskMap = [];
  6742. if ($auto_generate_images && !empty($createdProductIds)) {
  6743. // 查询所有创建的资产
  6744. $productsToGenerate = DB::table('mp_products')
  6745. ->whereIn('id', $createdProductIds)
  6746. ->where('is_deleted', 0)
  6747. ->get();
  6748. foreach ($productsToGenerate as $product) {
  6749. if (empty($product->pic_prompt)) {
  6750. dLog('anime')->warning('资产没有提示词,跳过图片生成', [
  6751. 'product_id' => $product->id,
  6752. 'product_name' => $product->product_name
  6753. ]);
  6754. continue;
  6755. }
  6756. try {
  6757. // 创建图片生成任务
  6758. $params = [
  6759. 'prompt' => $product->pic_prompt,
  6760. 'model' => $model,
  6761. 'ref_img_urls' => [],
  6762. 'width' => $width,
  6763. 'height' => $height
  6764. ];
  6765. $task = $this->aiImageGenerationService->createImageGenerationTask($params);
  6766. $task_id = $task->id;
  6767. if ($task_id) {
  6768. $productTaskMap[$product->id] = $task_id;
  6769. // 在事务中更新资产表的任务ID和状态
  6770. DB::table('mp_products')
  6771. ->where('id', $product->id)
  6772. ->update([
  6773. 'pic_task_id' => $task_id,
  6774. 'pic_task_status' => '生成中',
  6775. 'updated_at' => now()
  6776. ]);
  6777. dLog('anime')->info('创建资产图片生成任务', [
  6778. 'product_id' => $product->id,
  6779. 'task_id' => $task_id
  6780. ]);
  6781. }
  6782. } catch (\Exception $e) {
  6783. dLog('anime')->error('创建资产图片生成任务失败', [
  6784. 'product_id' => $product->id,
  6785. 'error' => $e->getMessage()
  6786. ]);
  6787. // 标记为失败(仍在事务中)
  6788. DB::table('mp_products')
  6789. ->where('id', $product->id)
  6790. ->update([
  6791. 'pic_task_status' => '生成失败',
  6792. 'updated_at' => now()
  6793. ]);
  6794. }
  6795. }
  6796. }
  6797. // 提交事务
  6798. DB::commit();
  6799. // 事务提交成功后,如果有图片生成任务,则返回 SSE 流
  6800. if ($auto_generate_images && !empty($productTaskMap)) {
  6801. // 返回 SSE 流(事务外轮询)
  6802. return $this->pollProductImageTasks($script_id, $script_name, $productTaskMap, $typeFolderIds);
  6803. }
  6804. // 如果不需要生成图片,返回普通结果
  6805. return [
  6806. 'success' => true,
  6807. 'type_folder_ids' => $typeFolderIds,
  6808. 'inserted_count' => $insertedCount,
  6809. 'total_records' => count($mappingRecords),
  6810. 'created_products' => count($createdProductIds),
  6811. 'image_tasks_created' => count($productTaskMap)
  6812. ];
  6813. } catch (\Exception $e) {
  6814. // 回滚事务
  6815. DB::rollback();
  6816. // 记录错误日志
  6817. dLog('anime')->error('保存剧本资产失败: ' . $e->getMessage(), [
  6818. 'script_id' => $script_id,
  6819. 'error' => $e->getMessage(),
  6820. 'trace' => $e->getTraceAsString()
  6821. ]);
  6822. // 统一使用 Utils::throwError 抛出错误
  6823. Utils::throwError('20003:保存剧本资产失败:' . $e->getMessage());
  6824. }
  6825. }
  6826. /**
  6827. * 批量为剧本资产生成图片
  6828. *
  6829. * @param array $data 请求参数
  6830. * @return \Generator 返回 SSE 流
  6831. */
  6832. public function batchGenerateProductImages($data) {
  6833. $script_id = getProp($data, 'script_id');
  6834. $type_folder_ids = getProp($data, 'type_folder_ids', []); // {1: 角色文件夹ID, 2: 场景文件夹ID, 3: 道具文件夹ID}
  6835. if (!$script_id) {
  6836. Utils::throwError('20003:请提供剧本ID');
  6837. }
  6838. // 验证剧本是否存在
  6839. $script = DB::table('mp_scripts')
  6840. ->where('id', $script_id)
  6841. ->where('is_deleted', 0)
  6842. ->first();
  6843. if (!$script) {
  6844. Utils::throwError('20003:剧本不存在');
  6845. }
  6846. $script_name = $script->script_name ?? 'script_' . $script_id;
  6847. // 获取需要生成图片的所有资产
  6848. $products = DB::table('mp_products')
  6849. ->whereIn('parent_id', array_values($type_folder_ids))
  6850. ->where('is_deleted', 0)
  6851. ->whereIn('type', [1, 2, 3]) // 只处理资产,不处理文件夹
  6852. ->get();
  6853. if ($products->isEmpty()) {
  6854. Utils::throwError('20003:没有找到需要生成图片的资产');
  6855. }
  6856. // 默认参数
  6857. $model = 'doubao-seedream-5-0-lite-260128';
  6858. $width = 1600;
  6859. $height = 2848;
  6860. // 开始为每个资产创建图片生成任务
  6861. $taskIds = [];
  6862. $productTaskMap = []; // 资产ID到任务ID的映射
  6863. foreach ($products as $product) {
  6864. if (empty($product->pic_prompt)) {
  6865. dLog('anime')->warning('资产没有提示词,跳过', ['product_id' => $product->id, 'product_name' => $product->product_name]);
  6866. continue;
  6867. }
  6868. try {
  6869. // 创建图片生成任务
  6870. $params = [
  6871. 'prompt' => $product->pic_prompt,
  6872. 'model' => $model,
  6873. 'ref_img_urls' => [],
  6874. 'width' => $width,
  6875. 'height' => $height
  6876. ];
  6877. $task = $this->aiImageGenerationService->createImageGenerationTask($params);
  6878. $task_id = $task->id;
  6879. if ($task_id) {
  6880. $taskIds[] = $task_id;
  6881. $productTaskMap[$product->id] = $task_id;
  6882. // 更新资产表的任务ID和状态
  6883. DB::table('mp_products')
  6884. ->where('id', $product->id)
  6885. ->update([
  6886. 'pic_task_id' => $task_id,
  6887. 'pic_task_status' => '生成中',
  6888. 'updated_at' => now()
  6889. ]);
  6890. dLog('anime')->info('创建资产图片生成任务', ['product_id' => $product->id, 'task_id' => $task_id]);
  6891. }
  6892. } catch (\Exception $e) {
  6893. dLog('anime')->error('创建资产图片生成任务失败', [
  6894. 'product_id' => $product->id,
  6895. 'error' => $e->getMessage()
  6896. ]);
  6897. // 标记为失败
  6898. DB::table('mp_products')
  6899. ->where('id', $product->id)
  6900. ->update([
  6901. 'pic_task_status' => '生成失败',
  6902. 'updated_at' => now()
  6903. ]);
  6904. }
  6905. }
  6906. if (empty($taskIds)) {
  6907. Utils::throwError('20003:没有成功创建任何图片生成任务');
  6908. }
  6909. // 返回 SSE 流
  6910. return $this->pollProductImageTasks($script_id, $script_name, $productTaskMap, $type_folder_ids);
  6911. }
  6912. /**
  6913. * 轮询资产图片生成任务状态(SSE流式返回)
  6914. * 只通过查询数据库获取任务状态,不主动调用API
  6915. *
  6916. * @param int $script_id 剧本ID
  6917. * @param string $script_name 剧本名称
  6918. * @param array $productTaskMap 资产ID到任务ID的映射
  6919. * @param array $type_folder_ids 类型文件夹ID映射
  6920. * @return \Generator
  6921. */
  6922. private function pollProductImageTasks($script_id, $script_name, $productTaskMap, $type_folder_ids) {
  6923. $startTime = time();
  6924. $timeout = 1800; // 30分钟超时
  6925. $pollInterval = 10; // 10秒轮询一次
  6926. $lastStatus = []; // 记录上次的状态,用于判断是否有变化
  6927. // 定义类型名称映射
  6928. $typeNames = [
  6929. 1 => 'roles', // 角色
  6930. 2 => 'scenes', // 场景
  6931. 3 => 'props' // 道具
  6932. ];
  6933. while (time() - $startTime < $timeout) {
  6934. sleep($pollInterval);
  6935. // 从 mp_script_product_mappings 表获取该剧本的所有资产ID
  6936. $mappings = DB::table('mp_script_product_mappings')
  6937. ->where('script_id', $script_id)
  6938. ->pluck('product_id')
  6939. ->unique()
  6940. ->toArray();
  6941. if (empty($mappings)) {
  6942. dLog('anime')->warning('该剧本没有关联的资产', [
  6943. 'script_id' => $script_id,
  6944. 'script_name' => $script_name
  6945. ]);
  6946. break;
  6947. }
  6948. // 查询所有资产的当前状态
  6949. $products = DB::table('mp_products')
  6950. ->whereIn('id', $mappings)
  6951. ->where('is_deleted', 0)
  6952. ->get();
  6953. // 统计各类型的状态(使用类型名称作为键名)
  6954. $stats = [
  6955. 'character' => ['total' => 0, 'success' => 0, 'completed' => 0], // 角色
  6956. 'scene' => ['total' => 0, 'success' => 0, 'completed' => 0], // 场景
  6957. 'prop' => ['total' => 0, 'success' => 0, 'completed' => 0], // 道具
  6958. ];
  6959. $allCompleted = true;
  6960. $hasStatusChange = false;
  6961. foreach ($products as $product) {
  6962. $type = $product->product;
  6963. $typeName = $typeNames[$type] ?? 'unknown'; // 使用 unknown 作为未知类型
  6964. // 如果类型名称不在 stats 中,初始化
  6965. if (!isset($stats[$typeName])) {
  6966. $stats[$typeName] = ['total' => 0, 'success' => 0, 'completed' => 0];
  6967. }
  6968. $stats[$typeName]['total']++;
  6969. $task_id = $product->pic_task_id;
  6970. $currentStatus = $product->pic_task_status;
  6971. // 检查状态是否有变化
  6972. if (!isset($lastStatus[$product->id]) || $lastStatus[$product->id] !== $currentStatus) {
  6973. $hasStatusChange = true;
  6974. $lastStatus[$product->id] = $currentStatus;
  6975. }
  6976. // 如果是生成中,查询任务表状态
  6977. if ($currentStatus === '生成中' && $task_id) {
  6978. // 只查询数据库,不调用API
  6979. $task = DB::table('mp_generate_pic_tasks')
  6980. ->where('id', $task_id)
  6981. ->first();
  6982. if ($task) {
  6983. // 检查任务状态
  6984. if ($task->status === 'success' && $task->result_url) {
  6985. // 解析图片URL
  6986. $result_urls = $task->result_url;
  6987. if (is_string($result_urls)) {
  6988. $result_urls = json_decode($result_urls, true);
  6989. }
  6990. $img_url = is_array($result_urls) ? $result_urls[0] : $task->result_url;
  6991. // 更新资产表状态
  6992. DB::table('mp_products')
  6993. ->where('id', $product->id)
  6994. ->update([
  6995. 'pic_task_status' => '生成成功',
  6996. 'url' => $img_url,
  6997. 'updated_at' => now()
  6998. ]);
  6999. $stats[$typeName]['success']++;
  7000. $stats[$typeName]['completed']++;
  7001. $hasStatusChange = true;
  7002. dLog('anime')->info('资产图片生成成功', [
  7003. 'product_id' => $product->id,
  7004. 'task_id' => $task_id,
  7005. 'img_url' => $img_url
  7006. ]);
  7007. } elseif ($task->status === 'failed') {
  7008. // 更新资产表状态
  7009. DB::table('mp_products')
  7010. ->where('id', $product->id)
  7011. ->update([
  7012. 'pic_task_status' => '生成失败',
  7013. 'updated_at' => now()
  7014. ]);
  7015. $stats[$typeName]['completed']++;
  7016. $hasStatusChange = true;
  7017. dLog('anime')->warning('资产图片生成失败', [
  7018. 'product_id' => $product->id,
  7019. 'task_id' => $task_id,
  7020. 'error' => $task->error_message ?? '未知错误'
  7021. ]);
  7022. } else {
  7023. // 任务还在处理中
  7024. $allCompleted = false;
  7025. }
  7026. } else {
  7027. // 任务不存在,标记为失败
  7028. DB::table('mp_products')
  7029. ->where('id', $product->id)
  7030. ->update([
  7031. 'pic_task_status' => '生成失败',
  7032. 'updated_at' => now()
  7033. ]);
  7034. $stats[$type]['completed']++;
  7035. $hasStatusChange = true;
  7036. dLog('anime')->error('图片生成任务不存在', [
  7037. 'product_id' => $product->id,
  7038. 'task_id' => $task_id
  7039. ]);
  7040. }
  7041. } elseif ($currentStatus === '生成成功') {
  7042. $stats[$typeName]['success']++;
  7043. $stats[$typeName]['completed']++;
  7044. } elseif ($currentStatus === '生成失败') {
  7045. $stats[$typeName]['completed']++;
  7046. } else {
  7047. // 其他状态也认为未完成
  7048. $allCompleted = false;
  7049. }
  7050. }
  7051. // 移除没有数据的类型(total=0)
  7052. foreach ($stats as $typeName => $stat) {
  7053. if ($stat['total'] === 0) {
  7054. unset($stats[$typeName]);
  7055. }
  7056. }
  7057. // 如果有状态变化,发送 SSE 更新
  7058. if ($hasStatusChange) {
  7059. $eventType = $allCompleted ? 'complete' : 'update';
  7060. $response = [
  7061. 'type' => $eventType,
  7062. 'script_id' => $script_id,
  7063. 'script_name' => $script_name,
  7064. 'stats' => $stats,
  7065. 'timestamp' => date('Y-m-d H:i:s')
  7066. ];
  7067. yield "data: " . json_encode($response, JSON_UNESCAPED_UNICODE) . "\n\n";
  7068. dLog('anime')->info('SSE更新', [
  7069. 'event_type' => $eventType,
  7070. 'script_id' => $script_id,
  7071. 'script_name' => $script_name,
  7072. 'stats' => $stats
  7073. ]);
  7074. if ($allCompleted) {
  7075. dLog('anime')->info('所有资产图片生成任务已完成', [
  7076. 'script_id' => $script_id,
  7077. 'script_name' => $script_name,
  7078. 'stats' => $stats
  7079. ]);
  7080. break;
  7081. }
  7082. }
  7083. }
  7084. // 超时处理
  7085. if (time() - $startTime >= $timeout && !$allCompleted) {
  7086. $response = [
  7087. 'type' => 'timeout',
  7088. 'message' => '部分任务超时,请稍后查看结果',
  7089. 'script_id' => $script_id,
  7090. 'script_name' => $script_name,
  7091. 'timestamp' => date('Y-m-d H:i:s')
  7092. ];
  7093. yield "data: " . json_encode($response, JSON_UNESCAPED_UNICODE) . "\n\n";
  7094. dLog('anime')->warning('资产图片生成任务超时', [
  7095. 'script_id' => $script_id,
  7096. 'script_name' => $script_name,
  7097. 'timeout' => $timeout
  7098. ]);
  7099. }
  7100. }
  7101. /**
  7102. * 获取剧本关联的资产列表
  7103. * @param array $data 请求参数
  7104. * @return array
  7105. */
  7106. public function getScriptProducts($data) {
  7107. $uid = Site::getUid();
  7108. $cpid = Site::getCpid();
  7109. $script_id = getProp($data, 'script_id');
  7110. $episode_number = getProp($data, 'episode_number');
  7111. if (!$script_id) {
  7112. Utils::throwError('20003:请提供剧本ID');
  7113. }
  7114. // 验证剧本是否存在
  7115. $script = DB::table('mp_scripts')
  7116. ->where('id', $script_id)
  7117. ->where('is_deleted', 0)
  7118. ->first();
  7119. if (!$script) {
  7120. Utils::throwError('20003:剧本不存在');
  7121. }
  7122. // 联表查询资产信息
  7123. $query = DB::table('mp_script_product_mappings as mapping')
  7124. ->join('mp_products as product', 'mapping.product_id', '=', 'product.id')
  7125. ->where('mapping.script_id', $script_id)
  7126. ->where('product.cpid', $cpid)
  7127. ->where('product.is_deleted', 0);
  7128. // 如果提供了 episode_number,则过滤指定集数
  7129. if ($episode_number !== null && $episode_number !== '') {
  7130. $query->where('mapping.episode_number', $episode_number);
  7131. }
  7132. $mappings = $query->select(
  7133. 'mapping.script_id',
  7134. 'mapping.product_id',
  7135. 'mapping.episode_number',
  7136. 'product.product_name',
  7137. 'product.type',
  7138. 'product.product',
  7139. 'product.pic_prompt',
  7140. 'product.url',
  7141. 'product.pic_task_id',
  7142. 'product.pic_task_status',
  7143. 'product.three_view_image_url',
  7144. 'mapping.created_at'
  7145. )
  7146. ->orderBy('mapping.product_id', 'asc')
  7147. ->orderBy('mapping.episode_number', 'asc')
  7148. ->get();
  7149. // 按 product_id 分组,合并 episode_number
  7150. $productMap = [];
  7151. foreach ($mappings as $item) {
  7152. $product_id = $item->product_id;
  7153. if (!isset($productMap[$product_id])) {
  7154. $productMap[$product_id] = [
  7155. 'product_id' => $product_id,
  7156. 'product_name' => $item->product_name,
  7157. 'type' => (int)$item->type,
  7158. 'product' => (int)$item->product,
  7159. 'pic_prompt' => $item->pic_prompt,
  7160. 'url' => $item->url,
  7161. 'pic_task_id' => $item->pic_task_id,
  7162. 'pic_task_status' => $item->pic_task_status,
  7163. 'episode_numbers' => [],
  7164. 'created_at' => $item->created_at,
  7165. ];
  7166. }
  7167. // 添加 episode_number(去重)
  7168. if (!in_array($item->episode_number, $productMap[$product_id]['episode_numbers'])) {
  7169. $productMap[$product_id]['episode_numbers'][] = $item->episode_number;
  7170. }
  7171. }
  7172. // 按类型分组
  7173. $roles = []; // type=1 角色/主体
  7174. $scenes = []; // type=2 场景
  7175. $props = []; // type=3 道具
  7176. foreach ($productMap as $product) {
  7177. // 将 episode_numbers 数组转换为逗号分隔的字符串
  7178. $episodeNumbersStr = implode(',', $product['episode_numbers']);
  7179. // 构造返回数据
  7180. $productData = [
  7181. 'product_id' => $product['product_id'],
  7182. 'product_name' => $product['product_name'],
  7183. 'product' => $product['product'],
  7184. 'pic_prompt' => $product['pic_prompt'],
  7185. 'url' => $product['url'],
  7186. 'pic_task_id' => $product['pic_task_id'],
  7187. 'pic_task_status' => $product['pic_task_status'],
  7188. 'episode_numbers' => $episodeNumbersStr,
  7189. 'created_at' => $product['created_at'],
  7190. ];
  7191. // 根据 type 分类(注意:type 字段表示资产类型,不是文件夹)
  7192. // 根据 product 字段分类(1=角色, 2=场景, 3=道具)
  7193. switch ($product['product']) {
  7194. case 1:
  7195. $roles[] = $productData;
  7196. break;
  7197. case 2:
  7198. $scenes[] = $productData;
  7199. break;
  7200. case 3:
  7201. $props[] = $productData;
  7202. break;
  7203. }
  7204. }
  7205. return [
  7206. 'script_id' => $script_id,
  7207. 'script_name' => $script->script_name ?? '',
  7208. 'roles' => $roles, // 主体
  7209. 'scenes' => $scenes, // 场景
  7210. 'props' => $props, // 道具
  7211. ];
  7212. }
  7213. /**
  7214. * 处理act_content中的{}标记,替换为product_name(图+序号)格式,并收集参考图片
  7215. * @param string $actContent 原始内容
  7216. * @param array $products 产品数组(包含product_name和url)
  7217. * @return array ['content' => 处理后的内容, 'reference_images' => 参考图片数组]
  7218. */
  7219. public function processActContentWithProducts($actContent, $products) {
  7220. if (empty($actContent) || empty($products)) {
  7221. return [
  7222. 'content' => $actContent,
  7223. 'reference_images' => []
  7224. ];
  7225. }
  7226. // 构建产品名称到产品信息的映射
  7227. $product_dict = [];
  7228. foreach ($products as $product) {
  7229. $product_name = getProp($product, 'product_name');
  7230. if ($product_name) {
  7231. $product_dict[$product_name] = [
  7232. 'url' => getProp($product, 'url'),
  7233. 'voice_prompt' => getProp($product, 'voice_prompt')
  7234. ];
  7235. }
  7236. }
  7237. // 第一步:查找内容中所有 {产品名称} 格式的标记(按出现顺序,去重)
  7238. preg_match_all('/\{([^}]+)\}/u', $actContent, $matches);
  7239. $reference_images = [];
  7240. $product_index_map = []; // 产品名称 => 图片序号的映射
  7241. $voice_prompts = []; // 存储需要添加到开头的voice_prompt信息
  7242. $narrator_voice_prompt = ''; // 单独存储旁白的voice_prompt
  7243. $current_index = 1;
  7244. if (!empty($matches[1])) {
  7245. // 按照在内容中第一次出现的顺序,为每个产品分配序号
  7246. $seen_products = []; // 用于去重
  7247. foreach ($matches[1] as $product_name) {
  7248. // 跳过已处理的产品
  7249. if (isset($seen_products[$product_name])) {
  7250. continue;
  7251. }
  7252. $seen_products[$product_name] = true;
  7253. // 检查产品是否在字典中
  7254. if (isset($product_dict[$product_name])) {
  7255. $url = $product_dict[$product_name]['url'];
  7256. $voice_prompt = $product_dict[$product_name]['voice_prompt'];
  7257. // 处理voice_prompt(旁白不在这里处理,旁白是公共的在后面单独处理)
  7258. if (!empty($voice_prompt) && $product_name !== '旁白') {
  7259. $voice_prompts[] = $product_name . ':' . $voice_prompt . "\n";
  7260. }
  7261. // 只有URL非空才分配序号和添加到参考图片
  7262. if (!empty($url)) {
  7263. // 检查URL是否已经在reference_images中(去重)
  7264. if (!in_array($url, $reference_images)) {
  7265. $reference_images[] = $url;
  7266. $product_index_map[$product_name] = $current_index;
  7267. $current_index++;
  7268. } else {
  7269. // URL重复,找到已有的序号
  7270. $existing_index = array_search($url, $reference_images) + 1;
  7271. $product_index_map[$product_name] = $existing_index;
  7272. }
  7273. } else {
  7274. // URL为空,不分配序号(后续直接去掉{})
  7275. $product_index_map[$product_name] = 0;
  7276. }
  7277. } else {
  7278. // 产品不在字典中,不分配序号
  7279. $product_index_map[$product_name] = 0;
  7280. }
  7281. }
  7282. }
  7283. // 第二步:替换内容中的 {产品名称}
  7284. $processedContent = $actContent;
  7285. foreach ($product_index_map as $product_name => $index) {
  7286. $escaped_name = preg_quote($product_name, '/');
  7287. if ($index > 0) {
  7288. // 有图片,替换为:产品名称(图X)
  7289. $replacement = $product_name . '<图片' . $index . '>';
  7290. } else {
  7291. // 无图片,只保留产品名称
  7292. $replacement = $product_name;
  7293. }
  7294. // 替换所有 {产品名称} 为处理后的格式
  7295. $processedContent = preg_replace('/\{' . $escaped_name . '\}/u', $replacement, $processedContent);
  7296. }
  7297. // 第三步:单独处理旁白的voice_prompt(旁白是公共的,不依赖product_dict)
  7298. foreach ($products as $product) {
  7299. $product_name = getProp($product, 'product_name');
  7300. $voice_prompt = getProp($product, 'voice_prompt');
  7301. if ($product_name === '旁白' && !empty($voice_prompt)) {
  7302. $narrator_voice_prompt = $product_name . ':' . $voice_prompt . "\n";
  7303. break; // 找到旁白后退出循环
  7304. }
  7305. }
  7306. // 第四步:将voice_prompt信息添加到内容最前面
  7307. $voice_prompt_prefix = '';
  7308. if (!empty($voice_prompts)) {
  7309. $voice_prompt_prefix .= implode('', $voice_prompts);
  7310. }
  7311. // 旁白的voice_prompt放在最后
  7312. if (!empty($narrator_voice_prompt)) {
  7313. $voice_prompt_prefix .= $narrator_voice_prompt;
  7314. }
  7315. // 如果有voice_prompt信息,添加到内容开头
  7316. if (!empty($voice_prompt_prefix)) {
  7317. $processedContent = "人物音色:\n" . $voice_prompt_prefix . "\n" . $processedContent;
  7318. }
  7319. return [
  7320. 'content' => $processedContent,
  7321. 'reference_images' => $reference_images
  7322. ];
  7323. }
  7324. public function saveActVideoGenerateParams($data) {
  7325. $episode_id = getProp($data, 'episode_id');
  7326. $model = getProp($data, 'video_model');
  7327. if (!in_array($model, ['zhizhen-20', 'zhizhen-20-fas', 'zhizhen-20-mini'])) {
  7328. Utils::throwError('20003:该模型不可用');
  7329. }
  7330. if (!$model) {
  7331. // 使用默认模型
  7332. $model = 'zhizhen-20';
  7333. }
  7334. // 验证模型是否在可用模型表中
  7335. if (!DB::table('mp_video_models')->where('model', $model)->where('is_enabled', 1)->exists()) {
  7336. Utils::throwError('20003:该模型已不可用,请更换!');
  7337. }
  7338. $video_resolution = getProp($data, 'video_resolution', '720p');
  7339. $ratio = getProp($data, 'ratio');
  7340. if (!$ratio) $ratio = '9:16';
  7341. $episode = DB::table('mp_anime_episodes')->where('id', $episode_id)->first(['anime_id']);
  7342. if (!$episode) {
  7343. Utils::throwError('20003:分集不存在');
  7344. }
  7345. try {
  7346. DB::beginTransaction();
  7347. $result = DB::table('mp_anime_episodes')->where('id', $episode_id)->update([
  7348. 'video_model' => $model,
  7349. 'video_resolution' => $video_resolution,
  7350. 'ratio' => $ratio,
  7351. 'updated_at' => date('Y-m-d H:i:s')
  7352. ]);
  7353. if ($result === false) {
  7354. Utils::throwError('20003:分集视频参数保存失败');
  7355. }
  7356. // 同步更新mp_animes表
  7357. $anime_result = DB::table('mp_animes')->where('id', $episode->anime_id)->update([
  7358. 'video_model' => $model,
  7359. 'video_resolution' => $video_resolution,
  7360. 'video_ratio' => $ratio,
  7361. 'updated_at' => date('Y-m-d H:i:s')
  7362. ]);
  7363. if ($anime_result === false) {
  7364. Utils::throwError('20003:动漫视频参数保存失败');
  7365. }
  7366. } catch (\Exception $e) {
  7367. DB::rollBack();
  7368. Utils::throwError('20003:'.$e->getMessage());
  7369. }
  7370. DB::commit();
  7371. return $result;
  7372. }
  7373. public function confirmActs($data) {
  7374. $episode_id = getProp($data, 'episode_id');
  7375. $episode = DB::table('mp_anime_episodes')->where('id', $episode_id)->first();
  7376. if (!$episode) {
  7377. Utils::throwError('20003:分集不存在');
  7378. }
  7379. $roles = json_decode(getProp($episode, 'roles'), true) ?: [];
  7380. $scenes = json_decode(getProp($episode, 'scenes'), true) ?: [];
  7381. $props = json_decode(getProp($episode, 'props'), true) ?: [];
  7382. // 获取所有片段数据
  7383. $acts = DB::table('mp_episode_segments')->where('episode_id', $episode_id)->orderBy('act_number')->get();
  7384. // 收集所有资产名称(角色、场景、道具)
  7385. $product_names = [];
  7386. // 收集角色名称
  7387. foreach ($roles as $role) {
  7388. $role_name = getProp($role, 'role');
  7389. if ($role_name && $role_name != '旁白') {
  7390. $product_names[] = $role_name;
  7391. }
  7392. }
  7393. // 收集场景名称
  7394. foreach ($scenes as $scene) {
  7395. $scene_name = getProp($scene, 'scene');
  7396. if ($scene_name) {
  7397. $product_names[] = $scene_name;
  7398. }
  7399. }
  7400. // 收集道具名称
  7401. foreach ($props as $prop) {
  7402. $prop_name = getProp($prop, 'prop');
  7403. if ($prop_name) {
  7404. $product_names[] = $prop_name;
  7405. }
  7406. }
  7407. // 去重并按长度降序排序(避免短名称先匹配到长名称的一部分)
  7408. $product_names = array_unique($product_names);
  7409. usort($product_names, function($a, $b) {
  7410. return mb_strlen($b) - mb_strlen($a);
  7411. });
  7412. try {
  7413. DB::beginTransaction();
  7414. // 处理每个片段
  7415. foreach ($acts as $act) {
  7416. $act_content = getProp($act, 'act_content');
  7417. if (!$act_content) continue;
  7418. $processed_content = $act_content;
  7419. // 统一替换所有资产名称为 {资产名} 格式
  7420. // 使用占位符避免嵌套替换问题
  7421. $placeholder_map = [];
  7422. $placeholder_index = 0;
  7423. foreach ($product_names as $product_name) {
  7424. // 转义特殊字符
  7425. $escaped_product = preg_quote($product_name, '/');
  7426. // 检查是否匹配且未被 {} 包裹
  7427. $processed_content = preg_replace_callback(
  7428. '/(?<![{])(' . $escaped_product . ')(?![}])/u',
  7429. function($matches) use (&$placeholder_map, &$placeholder_index) {
  7430. // 使用唯一占位符
  7431. $placeholder = '<<<PLACEHOLDER_' . $placeholder_index . '>>>';
  7432. $placeholder_map[$placeholder] = '{' . $matches[1] . '}';
  7433. $placeholder_index++;
  7434. return $placeholder;
  7435. },
  7436. $processed_content
  7437. );
  7438. }
  7439. // 将所有占位符替换回实际内容
  7440. foreach ($placeholder_map as $placeholder => $replacement) {
  7441. $processed_content = str_replace($placeholder, $replacement, $processed_content);
  7442. }
  7443. // 处理【镜头X】或【分镜X】重新编号为从1开始的连续整数【镜头X】
  7444. $shot_counter = 0;
  7445. $processed_content = preg_replace_callback(
  7446. '/【(?:镜头|分镜)(\d+)】/u',
  7447. function($matches) use (&$shot_counter) {
  7448. $shot_counter++;
  7449. return '【镜头' . $shot_counter . '】';
  7450. },
  7451. $processed_content
  7452. );
  7453. // 更新数据库
  7454. $boolen = DB::table('mp_episode_segments')
  7455. ->where('id', $act->id)
  7456. ->update([
  7457. 'act_show_content' => $processed_content,
  7458. 'updated_at' => date('Y-m-d H:i:s')
  7459. ]);
  7460. if (!$boolen) {
  7461. Utils::throwError('20003:片段处理失败');
  7462. }
  7463. }
  7464. }catch (\Exception $e) {
  7465. DB::rollBack();
  7466. Utils::throwError('20003:'.$e->getMessage());
  7467. }
  7468. $boolen1 = DB::table('mp_anime_episodes')->where('id', $episode_id)->update([
  7469. 'is_generated' => 1,
  7470. 'updated_at' => date('Y-m-d H:i:s')
  7471. ]);
  7472. if (!$boolen1) {
  7473. DB::rollBack();
  7474. Utils::throwError('20003:分集处理失败!');
  7475. }
  7476. DB::commit();
  7477. // 重新查询更新后的片段数据
  7478. $acts = DB::table('mp_episode_segments')->where('episode_id', $episode_id)->orderBy('act_number')->get();
  7479. // 合并角色、场景、道具和extra_products作为products,统一字段名为product_name
  7480. // extra_products优先级更高,会覆盖同名的roles、scenes和props
  7481. $products = [];
  7482. // 先处理角色数组
  7483. foreach ($roles as $role) {
  7484. $product = $role;
  7485. // 将role字段重命名为product_name
  7486. if (isset($product['role'])) {
  7487. $product['product_name'] = $product['role'];
  7488. unset($product['role']);
  7489. $product['product'] = 1; // 标记类型为角色
  7490. $products[$product['product_name']] = $product; // 使用product_name作为key便于后续覆盖
  7491. }
  7492. }
  7493. // 处理场景数组
  7494. foreach ($scenes as $scene) {
  7495. $product = $scene;
  7496. // 将scene字段重命名为product_name
  7497. if (isset($product['scene'])) {
  7498. $product['product_name'] = $product['scene'];
  7499. unset($product['scene']);
  7500. $product['product'] = 2; // 标记类型为场景
  7501. $products[$product['product_name']] = $product; // 使用product_name作为key便于后续覆盖
  7502. }
  7503. }
  7504. // 处理道具数组(逻辑与场景一致)
  7505. foreach ($props as $prop) {
  7506. $product = $prop;
  7507. // 将prop字段重命名为product_name
  7508. if (isset($product['prop'])) {
  7509. $product['product_name'] = $product['prop'];
  7510. unset($product['prop']);
  7511. $product['product'] = 3; // 标记类型为道具
  7512. $products[$product['product_name']] = $product; // 使用product_name作为key便于后续覆盖
  7513. }
  7514. }
  7515. // extra_products优先级更高,直接覆盖同名的roles和scenes
  7516. $extra_products = json_decode(getProp($episode, 'extra_products', '[]'), true) ?: [];
  7517. foreach ($extra_products as $extra_product) {
  7518. $product_name = getProp($extra_product, 'product_name');
  7519. if ($product_name) {
  7520. $products[$product_name] = $extra_product; // 覆盖同名数据
  7521. }
  7522. }
  7523. // 重新索引数组(去除key)
  7524. $products = array_values($products);
  7525. // 构建返回的acts数组
  7526. $return_acts = [];
  7527. foreach ($acts as $act) {
  7528. $return_acts[] = [
  7529. 'act_id' => getProp($act, 'id'),
  7530. 'act_number' => getProp($act, 'act_number'),
  7531. 'act_duration' => getProp($act, 'video_duration') ? getProp($act, 'video_duration') : getProp($act, 'act_duration'),
  7532. 'act_show_content' => getProp($act, 'act_show_content'),
  7533. 'video_url' => getProp($act, 'video_url'),
  7534. 'video_duration' => getProp($act, 'video_duration'),
  7535. 'video_time_point_start' => getProp($act, 'video_time_point_start'),
  7536. 'video_time_point_end' => getProp($act, 'video_time_point_end'),
  7537. ];
  7538. }
  7539. return [
  7540. 'anime_id' => getProp($episode, 'anime_id'),
  7541. 'episode_id' => $episode_id,
  7542. 'title' => getProp($episode, 'title'),
  7543. 'episode_number' => getProp($episode, 'episode_number'),
  7544. 'is_generated' => getProp($episode, 'is_generated'),
  7545. 'video_params' => [
  7546. 'video_model' => getProp($episode, 'video_model'),
  7547. 'video_resolution' => getProp($episode, 'video_resolution'),
  7548. 'ratio' => getProp($episode, 'ratio'),
  7549. ],
  7550. 'products' => $products,
  7551. 'acts' => $return_acts
  7552. ];
  7553. }
  7554. }