AnimeService.php 518 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695705715725735745755765775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206216226236246256266276286296306316326336346356366376386396406416426436446456466476486496506516526536546556566576586596606616626636646656666676686696706716726736746756766776786796806816826836846856866876886896906916926936946956966976986997007017027037047057067077087097107117127137147157167177187197207217227237247257267277287297307317327337347357367377387397407417427437447457467477487497507517527537547557567577587597607617627637647657667677687697707717727737747757767777787797807817827837847857867877887897907917927937947957967977987998008018028038048058068078088098108118128138148158168178188198208218228238248258268278288298308318328338348358368378388398408418428438448458468478488498508518528538548558568578588598608618628638648658668678688698708718728738748758768778788798808818828838848858868878888898908918928938948958968978988999009019029039049059069079089099109119129139149159169179189199209219229239249259269279289299309319329339349359369379389399409419429439449459469479489499509519529539549559569579589599609619629639649659669679689699709719729739749759769779789799809819829839849859869879889899909919929939949959969979989991000100110021003100410051006100710081009101010111012101310141015101610171018101910201021102210231024102510261027102810291030103110321033103410351036103710381039104010411042104310441045104610471048104910501051105210531054105510561057105810591060106110621063106410651066106710681069107010711072107310741075107610771078107910801081108210831084108510861087108810891090109110921093109410951096109710981099110011011102110311041105110611071108110911101111111211131114111511161117111811191120112111221123112411251126112711281129113011311132113311341135113611371138113911401141114211431144114511461147114811491150115111521153115411551156115711581159116011611162116311641165116611671168116911701171117211731174117511761177117811791180118111821183118411851186118711881189119011911192119311941195119611971198119912001201120212031204120512061207120812091210121112121213121412151216121712181219122012211222122312241225122612271228122912301231123212331234123512361237123812391240124112421243124412451246124712481249125012511252125312541255125612571258125912601261126212631264126512661267126812691270127112721273127412751276127712781279128012811282128312841285128612871288128912901291129212931294129512961297129812991300130113021303130413051306130713081309131013111312131313141315131613171318131913201321132213231324132513261327132813291330133113321333133413351336133713381339134013411342134313441345134613471348134913501351135213531354135513561357135813591360136113621363136413651366136713681369137013711372137313741375137613771378137913801381138213831384138513861387138813891390139113921393139413951396139713981399140014011402140314041405140614071408140914101411141214131414141514161417141814191420142114221423142414251426142714281429143014311432143314341435143614371438143914401441144214431444144514461447144814491450145114521453145414551456145714581459146014611462146314641465146614671468146914701471147214731474147514761477147814791480148114821483148414851486148714881489149014911492149314941495149614971498149915001501150215031504150515061507150815091510151115121513151415151516151715181519152015211522152315241525152615271528152915301531153215331534153515361537153815391540154115421543154415451546154715481549155015511552155315541555155615571558155915601561156215631564156515661567156815691570157115721573157415751576157715781579158015811582158315841585158615871588158915901591159215931594159515961597159815991600160116021603160416051606160716081609161016111612161316141615161616171618161916201621162216231624162516261627162816291630163116321633163416351636163716381639164016411642164316441645164616471648164916501651165216531654165516561657165816591660166116621663166416651666166716681669167016711672167316741675167616771678167916801681168216831684168516861687168816891690169116921693169416951696169716981699170017011702170317041705170617071708170917101711171217131714171517161717171817191720172117221723172417251726172717281729173017311732173317341735173617371738173917401741174217431744174517461747174817491750175117521753175417551756175717581759176017611762176317641765176617671768176917701771177217731774177517761777177817791780178117821783178417851786178717881789179017911792179317941795179617971798179918001801180218031804180518061807180818091810181118121813181418151816181718181819182018211822182318241825182618271828182918301831183218331834183518361837183818391840184118421843184418451846184718481849185018511852185318541855185618571858185918601861186218631864186518661867186818691870187118721873187418751876187718781879188018811882188318841885188618871888188918901891189218931894189518961897189818991900190119021903190419051906190719081909191019111912191319141915191619171918191919201921192219231924192519261927192819291930193119321933193419351936193719381939194019411942194319441945194619471948194919501951195219531954195519561957195819591960196119621963196419651966196719681969197019711972197319741975197619771978197919801981198219831984198519861987198819891990199119921993199419951996199719981999200020012002200320042005200620072008200920102011201220132014201520162017201820192020202120222023202420252026202720282029203020312032203320342035203620372038203920402041204220432044204520462047204820492050205120522053205420552056205720582059206020612062206320642065206620672068206920702071207220732074207520762077207820792080208120822083208420852086208720882089209020912092209320942095209620972098209921002101210221032104210521062107210821092110211121122113211421152116211721182119212021212122212321242125212621272128212921302131213221332134213521362137213821392140214121422143214421452146214721482149215021512152215321542155215621572158215921602161216221632164216521662167216821692170217121722173217421752176217721782179218021812182218321842185218621872188218921902191219221932194219521962197219821992200220122022203220422052206220722082209221022112212221322142215221622172218221922202221222222232224222522262227222822292230223122322233223422352236223722382239224022412242224322442245224622472248224922502251225222532254225522562257225822592260226122622263226422652266226722682269227022712272227322742275227622772278227922802281228222832284228522862287228822892290229122922293229422952296229722982299230023012302230323042305230623072308230923102311231223132314231523162317231823192320232123222323232423252326232723282329233023312332233323342335233623372338233923402341234223432344234523462347234823492350235123522353235423552356235723582359236023612362236323642365236623672368236923702371237223732374237523762377237823792380238123822383238423852386238723882389239023912392239323942395239623972398239924002401240224032404240524062407240824092410241124122413241424152416241724182419242024212422242324242425242624272428242924302431243224332434243524362437243824392440244124422443244424452446244724482449245024512452245324542455245624572458245924602461246224632464246524662467246824692470247124722473247424752476247724782479248024812482248324842485248624872488248924902491249224932494249524962497249824992500250125022503250425052506250725082509251025112512251325142515251625172518251925202521252225232524252525262527252825292530253125322533253425352536253725382539254025412542254325442545254625472548254925502551255225532554255525562557255825592560256125622563256425652566256725682569257025712572257325742575257625772578257925802581258225832584258525862587258825892590259125922593259425952596259725982599260026012602260326042605260626072608260926102611261226132614261526162617261826192620262126222623262426252626262726282629263026312632263326342635263626372638263926402641264226432644264526462647264826492650265126522653265426552656265726582659266026612662266326642665266626672668266926702671267226732674267526762677267826792680268126822683268426852686268726882689269026912692269326942695269626972698269927002701270227032704270527062707270827092710271127122713271427152716271727182719272027212722272327242725272627272728272927302731273227332734273527362737273827392740274127422743274427452746274727482749275027512752275327542755275627572758275927602761276227632764276527662767276827692770277127722773277427752776277727782779278027812782278327842785278627872788278927902791279227932794279527962797279827992800280128022803280428052806280728082809281028112812281328142815281628172818281928202821282228232824282528262827282828292830283128322833283428352836283728382839284028412842284328442845284628472848284928502851285228532854285528562857285828592860286128622863286428652866286728682869287028712872287328742875287628772878287928802881288228832884288528862887288828892890289128922893289428952896289728982899290029012902290329042905290629072908290929102911291229132914291529162917291829192920292129222923292429252926292729282929293029312932293329342935293629372938293929402941294229432944294529462947294829492950295129522953295429552956295729582959296029612962296329642965296629672968296929702971297229732974297529762977297829792980298129822983298429852986298729882989299029912992299329942995299629972998299930003001300230033004300530063007300830093010301130123013301430153016301730183019302030213022302330243025302630273028302930303031303230333034303530363037303830393040304130423043304430453046304730483049305030513052305330543055305630573058305930603061306230633064306530663067306830693070307130723073307430753076307730783079308030813082308330843085308630873088308930903091309230933094309530963097309830993100310131023103310431053106310731083109311031113112311331143115311631173118311931203121312231233124312531263127312831293130313131323133313431353136313731383139314031413142314331443145314631473148314931503151315231533154315531563157315831593160316131623163316431653166316731683169317031713172317331743175317631773178317931803181318231833184318531863187318831893190319131923193319431953196319731983199320032013202320332043205320632073208320932103211321232133214321532163217321832193220322132223223322432253226322732283229323032313232323332343235323632373238323932403241324232433244324532463247324832493250325132523253325432553256325732583259326032613262326332643265326632673268326932703271327232733274327532763277327832793280328132823283328432853286328732883289329032913292329332943295329632973298329933003301330233033304330533063307330833093310331133123313331433153316331733183319332033213322332333243325332633273328332933303331333233333334333533363337333833393340334133423343334433453346334733483349335033513352335333543355335633573358335933603361336233633364336533663367336833693370337133723373337433753376337733783379338033813382338333843385338633873388338933903391339233933394339533963397339833993400340134023403340434053406340734083409341034113412341334143415341634173418341934203421342234233424342534263427342834293430343134323433343434353436343734383439344034413442344334443445344634473448344934503451345234533454345534563457345834593460346134623463346434653466346734683469347034713472347334743475347634773478347934803481348234833484348534863487348834893490349134923493349434953496349734983499350035013502350335043505350635073508350935103511351235133514351535163517351835193520352135223523352435253526352735283529353035313532353335343535353635373538353935403541354235433544354535463547354835493550355135523553355435553556355735583559356035613562356335643565356635673568356935703571357235733574357535763577357835793580358135823583358435853586358735883589359035913592359335943595359635973598359936003601360236033604360536063607360836093610361136123613361436153616361736183619362036213622362336243625362636273628362936303631363236333634363536363637363836393640364136423643364436453646364736483649365036513652365336543655365636573658365936603661366236633664366536663667366836693670367136723673367436753676367736783679368036813682368336843685368636873688368936903691369236933694369536963697369836993700370137023703370437053706370737083709371037113712371337143715371637173718371937203721372237233724372537263727372837293730373137323733373437353736373737383739374037413742374337443745374637473748374937503751375237533754375537563757375837593760376137623763376437653766376737683769377037713772377337743775377637773778377937803781378237833784378537863787378837893790379137923793379437953796379737983799380038013802380338043805380638073808380938103811381238133814381538163817381838193820382138223823382438253826382738283829383038313832383338343835383638373838383938403841384238433844384538463847384838493850385138523853385438553856385738583859386038613862386338643865386638673868386938703871387238733874387538763877387838793880388138823883388438853886388738883889389038913892389338943895389638973898389939003901390239033904390539063907390839093910391139123913391439153916391739183919392039213922392339243925392639273928392939303931393239333934393539363937393839393940394139423943394439453946394739483949395039513952395339543955395639573958395939603961396239633964396539663967396839693970397139723973397439753976397739783979398039813982398339843985398639873988398939903991399239933994399539963997399839994000400140024003400440054006400740084009401040114012401340144015401640174018401940204021402240234024402540264027402840294030403140324033403440354036403740384039404040414042404340444045404640474048404940504051405240534054405540564057405840594060406140624063406440654066406740684069407040714072407340744075407640774078407940804081408240834084408540864087408840894090409140924093409440954096409740984099410041014102410341044105410641074108410941104111411241134114411541164117411841194120412141224123412441254126412741284129413041314132413341344135413641374138413941404141414241434144414541464147414841494150415141524153415441554156415741584159416041614162416341644165416641674168416941704171417241734174417541764177417841794180418141824183418441854186418741884189419041914192419341944195419641974198419942004201420242034204420542064207420842094210421142124213421442154216421742184219422042214222422342244225422642274228422942304231423242334234423542364237423842394240424142424243424442454246424742484249425042514252425342544255425642574258425942604261426242634264426542664267426842694270427142724273427442754276427742784279428042814282428342844285428642874288428942904291429242934294429542964297429842994300430143024303430443054306430743084309431043114312431343144315431643174318431943204321432243234324432543264327432843294330433143324333433443354336433743384339434043414342434343444345434643474348434943504351435243534354435543564357435843594360436143624363436443654366436743684369437043714372437343744375437643774378437943804381438243834384438543864387438843894390439143924393439443954396439743984399440044014402440344044405440644074408440944104411441244134414441544164417441844194420442144224423442444254426442744284429443044314432443344344435443644374438443944404441444244434444444544464447444844494450445144524453445444554456445744584459446044614462446344644465446644674468446944704471447244734474447544764477447844794480448144824483448444854486448744884489449044914492449344944495449644974498449945004501450245034504450545064507450845094510451145124513451445154516451745184519452045214522452345244525452645274528452945304531453245334534453545364537453845394540454145424543454445454546454745484549455045514552455345544555455645574558455945604561456245634564456545664567456845694570457145724573457445754576457745784579458045814582458345844585458645874588458945904591459245934594459545964597459845994600460146024603460446054606460746084609461046114612461346144615461646174618461946204621462246234624462546264627462846294630463146324633463446354636463746384639464046414642464346444645464646474648464946504651465246534654465546564657465846594660466146624663466446654666466746684669467046714672467346744675467646774678467946804681468246834684468546864687468846894690469146924693469446954696469746984699470047014702470347044705470647074708470947104711471247134714471547164717471847194720472147224723472447254726472747284729473047314732473347344735473647374738473947404741474247434744474547464747474847494750475147524753475447554756475747584759476047614762476347644765476647674768476947704771477247734774477547764777477847794780478147824783478447854786478747884789479047914792479347944795479647974798479948004801480248034804480548064807480848094810481148124813481448154816481748184819482048214822482348244825482648274828482948304831483248334834483548364837483848394840484148424843484448454846484748484849485048514852485348544855485648574858485948604861486248634864486548664867486848694870487148724873487448754876487748784879488048814882488348844885488648874888488948904891489248934894489548964897489848994900490149024903490449054906490749084909491049114912491349144915491649174918491949204921492249234924492549264927492849294930493149324933493449354936493749384939494049414942494349444945494649474948494949504951495249534954495549564957495849594960496149624963496449654966496749684969497049714972497349744975497649774978497949804981498249834984498549864987498849894990499149924993499449954996499749984999500050015002500350045005500650075008500950105011501250135014501550165017501850195020502150225023502450255026502750285029503050315032503350345035503650375038503950405041504250435044504550465047504850495050505150525053505450555056505750585059506050615062506350645065506650675068506950705071507250735074507550765077507850795080508150825083508450855086508750885089509050915092509350945095509650975098509951005101510251035104510551065107510851095110511151125113511451155116511751185119512051215122512351245125512651275128512951305131513251335134513551365137513851395140514151425143514451455146514751485149515051515152515351545155515651575158515951605161516251635164516551665167516851695170517151725173517451755176517751785179518051815182518351845185518651875188518951905191519251935194519551965197519851995200520152025203520452055206520752085209521052115212521352145215521652175218521952205221522252235224522552265227522852295230523152325233523452355236523752385239524052415242524352445245524652475248524952505251525252535254525552565257525852595260526152625263526452655266526752685269527052715272527352745275527652775278527952805281528252835284528552865287528852895290529152925293529452955296529752985299530053015302530353045305530653075308530953105311531253135314531553165317531853195320532153225323532453255326532753285329533053315332533353345335533653375338533953405341534253435344534553465347534853495350535153525353535453555356535753585359536053615362536353645365536653675368536953705371537253735374537553765377537853795380538153825383538453855386538753885389539053915392539353945395539653975398539954005401540254035404540554065407540854095410541154125413541454155416541754185419542054215422542354245425542654275428542954305431543254335434543554365437543854395440544154425443544454455446544754485449545054515452545354545455545654575458545954605461546254635464546554665467546854695470547154725473547454755476547754785479548054815482548354845485548654875488548954905491549254935494549554965497549854995500550155025503550455055506550755085509551055115512551355145515551655175518551955205521552255235524552555265527552855295530553155325533553455355536553755385539554055415542554355445545554655475548554955505551555255535554555555565557555855595560556155625563556455655566556755685569557055715572557355745575557655775578557955805581558255835584558555865587558855895590559155925593559455955596559755985599560056015602560356045605560656075608560956105611561256135614561556165617561856195620562156225623562456255626562756285629563056315632563356345635563656375638563956405641564256435644564556465647564856495650565156525653565456555656565756585659566056615662566356645665566656675668566956705671567256735674567556765677567856795680568156825683568456855686568756885689569056915692569356945695569656975698569957005701570257035704570557065707570857095710571157125713571457155716571757185719572057215722572357245725572657275728572957305731573257335734573557365737573857395740574157425743574457455746574757485749575057515752575357545755575657575758575957605761576257635764576557665767576857695770577157725773577457755776577757785779578057815782578357845785578657875788578957905791579257935794579557965797579857995800580158025803580458055806580758085809581058115812581358145815581658175818581958205821582258235824582558265827582858295830583158325833583458355836583758385839584058415842584358445845584658475848584958505851585258535854585558565857585858595860586158625863586458655866586758685869587058715872587358745875587658775878587958805881588258835884588558865887588858895890589158925893589458955896589758985899590059015902590359045905590659075908590959105911591259135914591559165917591859195920592159225923592459255926592759285929593059315932593359345935593659375938593959405941594259435944594559465947594859495950595159525953595459555956595759585959596059615962596359645965596659675968596959705971597259735974597559765977597859795980598159825983598459855986598759885989599059915992599359945995599659975998599960006001600260036004600560066007600860096010601160126013601460156016601760186019602060216022602360246025602660276028602960306031603260336034603560366037603860396040604160426043604460456046604760486049605060516052605360546055605660576058605960606061606260636064606560666067606860696070607160726073607460756076607760786079608060816082608360846085608660876088608960906091609260936094609560966097609860996100610161026103610461056106610761086109611061116112611361146115611661176118611961206121612261236124612561266127612861296130613161326133613461356136613761386139614061416142614361446145614661476148614961506151615261536154615561566157615861596160616161626163616461656166616761686169617061716172617361746175617661776178617961806181618261836184618561866187618861896190619161926193619461956196619761986199620062016202620362046205620662076208620962106211621262136214621562166217621862196220622162226223622462256226622762286229623062316232623362346235623662376238623962406241624262436244624562466247624862496250625162526253625462556256625762586259626062616262626362646265626662676268626962706271627262736274627562766277627862796280628162826283628462856286628762886289629062916292629362946295629662976298629963006301630263036304630563066307630863096310631163126313631463156316631763186319632063216322632363246325632663276328632963306331633263336334633563366337633863396340634163426343634463456346634763486349635063516352635363546355635663576358635963606361636263636364636563666367636863696370637163726373637463756376637763786379638063816382638363846385638663876388638963906391639263936394639563966397639863996400640164026403640464056406640764086409641064116412641364146415641664176418641964206421642264236424642564266427642864296430643164326433643464356436643764386439644064416442644364446445644664476448644964506451645264536454645564566457645864596460646164626463646464656466646764686469647064716472647364746475647664776478647964806481648264836484648564866487648864896490649164926493649464956496649764986499650065016502650365046505650665076508650965106511651265136514651565166517651865196520652165226523652465256526652765286529653065316532653365346535653665376538653965406541654265436544654565466547654865496550655165526553655465556556655765586559656065616562656365646565656665676568656965706571657265736574657565766577657865796580658165826583658465856586658765886589659065916592659365946595659665976598659966006601660266036604660566066607660866096610661166126613661466156616661766186619662066216622662366246625662666276628662966306631663266336634663566366637663866396640664166426643664466456646664766486649665066516652665366546655665666576658665966606661666266636664666566666667666866696670667166726673667466756676667766786679668066816682668366846685668666876688668966906691669266936694669566966697669866996700670167026703670467056706670767086709671067116712671367146715671667176718671967206721672267236724672567266727672867296730673167326733673467356736673767386739674067416742674367446745674667476748674967506751675267536754675567566757675867596760676167626763676467656766676767686769677067716772677367746775677667776778677967806781678267836784678567866787678867896790679167926793679467956796679767986799680068016802680368046805680668076808680968106811681268136814681568166817681868196820682168226823682468256826682768286829683068316832683368346835683668376838683968406841684268436844684568466847684868496850685168526853685468556856685768586859686068616862686368646865686668676868686968706871687268736874687568766877687868796880688168826883688468856886688768886889689068916892689368946895689668976898689969006901690269036904690569066907690869096910691169126913691469156916691769186919692069216922692369246925692669276928692969306931693269336934693569366937693869396940694169426943694469456946694769486949695069516952695369546955695669576958695969606961696269636964696569666967696869696970697169726973697469756976697769786979698069816982698369846985698669876988698969906991699269936994699569966997699869997000700170027003700470057006700770087009701070117012701370147015701670177018701970207021702270237024702570267027702870297030703170327033703470357036703770387039704070417042704370447045704670477048704970507051705270537054705570567057705870597060706170627063706470657066706770687069707070717072707370747075707670777078707970807081708270837084708570867087708870897090709170927093709470957096709770987099710071017102710371047105710671077108710971107111711271137114711571167117711871197120712171227123712471257126712771287129713071317132713371347135713671377138713971407141714271437144714571467147714871497150715171527153715471557156715771587159716071617162716371647165716671677168716971707171717271737174717571767177717871797180718171827183718471857186718771887189719071917192719371947195719671977198719972007201720272037204720572067207720872097210721172127213721472157216721772187219722072217222722372247225722672277228722972307231723272337234723572367237723872397240724172427243724472457246724772487249725072517252725372547255725672577258725972607261726272637264726572667267726872697270727172727273727472757276727772787279728072817282728372847285728672877288728972907291729272937294729572967297729872997300730173027303730473057306730773087309731073117312731373147315731673177318731973207321732273237324732573267327732873297330733173327333733473357336733773387339734073417342734373447345734673477348734973507351735273537354735573567357735873597360736173627363736473657366736773687369737073717372737373747375737673777378737973807381738273837384738573867387738873897390739173927393739473957396739773987399740074017402740374047405740674077408740974107411741274137414741574167417741874197420742174227423742474257426742774287429743074317432743374347435743674377438743974407441744274437444744574467447744874497450745174527453745474557456745774587459746074617462746374647465746674677468746974707471747274737474747574767477747874797480748174827483748474857486748774887489749074917492749374947495749674977498749975007501750275037504750575067507750875097510751175127513751475157516751775187519752075217522752375247525752675277528752975307531753275337534753575367537753875397540754175427543754475457546754775487549755075517552755375547555755675577558755975607561756275637564756575667567756875697570757175727573757475757576757775787579758075817582758375847585758675877588758975907591759275937594759575967597759875997600760176027603760476057606760776087609761076117612761376147615761676177618761976207621762276237624762576267627762876297630763176327633763476357636763776387639764076417642764376447645764676477648764976507651765276537654765576567657765876597660766176627663766476657666766776687669767076717672767376747675767676777678767976807681768276837684768576867687768876897690769176927693769476957696769776987699770077017702770377047705770677077708770977107711771277137714771577167717771877197720772177227723772477257726772777287729773077317732773377347735773677377738773977407741774277437744774577467747774877497750775177527753775477557756775777587759776077617762776377647765776677677768776977707771777277737774777577767777777877797780778177827783778477857786778777887789779077917792779377947795779677977798779978007801780278037804780578067807780878097810781178127813781478157816781778187819782078217822782378247825782678277828782978307831783278337834783578367837783878397840784178427843784478457846784778487849785078517852785378547855785678577858785978607861786278637864786578667867786878697870787178727873787478757876787778787879788078817882788378847885788678877888788978907891789278937894789578967897789878997900790179027903790479057906790779087909791079117912791379147915791679177918791979207921792279237924792579267927792879297930793179327933793479357936793779387939794079417942794379447945794679477948794979507951795279537954795579567957795879597960796179627963796479657966796779687969797079717972797379747975797679777978797979807981798279837984798579867987798879897990799179927993799479957996799779987999800080018002800380048005800680078008800980108011801280138014801580168017801880198020802180228023802480258026802780288029803080318032803380348035803680378038803980408041804280438044804580468047804880498050805180528053805480558056805780588059806080618062806380648065806680678068806980708071807280738074807580768077807880798080808180828083808480858086808780888089809080918092809380948095809680978098809981008101810281038104810581068107810881098110811181128113811481158116811781188119812081218122812381248125812681278128812981308131813281338134813581368137813881398140814181428143814481458146814781488149815081518152815381548155815681578158815981608161816281638164816581668167816881698170817181728173817481758176817781788179818081818182818381848185818681878188818981908191819281938194819581968197819881998200820182028203820482058206820782088209821082118212821382148215821682178218821982208221822282238224822582268227822882298230823182328233823482358236823782388239824082418242824382448245824682478248824982508251825282538254825582568257825882598260826182628263826482658266826782688269827082718272827382748275827682778278827982808281828282838284828582868287828882898290829182928293829482958296829782988299830083018302830383048305830683078308830983108311831283138314831583168317831883198320832183228323832483258326832783288329833083318332833383348335833683378338833983408341834283438344834583468347834883498350835183528353835483558356835783588359836083618362836383648365836683678368836983708371837283738374837583768377837883798380838183828383838483858386838783888389839083918392839383948395839683978398839984008401840284038404840584068407840884098410841184128413841484158416841784188419842084218422842384248425842684278428842984308431843284338434843584368437843884398440844184428443844484458446844784488449845084518452845384548455845684578458845984608461846284638464846584668467846884698470847184728473847484758476847784788479848084818482848384848485848684878488848984908491849284938494849584968497849884998500850185028503850485058506850785088509851085118512851385148515851685178518851985208521852285238524852585268527852885298530853185328533853485358536853785388539854085418542854385448545854685478548854985508551855285538554855585568557855885598560856185628563856485658566856785688569857085718572857385748575857685778578857985808581858285838584858585868587858885898590859185928593859485958596859785988599860086018602860386048605860686078608860986108611861286138614861586168617861886198620862186228623862486258626862786288629863086318632863386348635863686378638863986408641864286438644864586468647864886498650865186528653865486558656865786588659866086618662866386648665866686678668866986708671867286738674867586768677867886798680868186828683868486858686868786888689869086918692869386948695869686978698869987008701870287038704870587068707870887098710871187128713871487158716871787188719872087218722872387248725872687278728872987308731873287338734873587368737873887398740874187428743874487458746874787488749875087518752875387548755875687578758875987608761876287638764876587668767876887698770877187728773877487758776877787788779878087818782878387848785878687878788878987908791879287938794879587968797879887998800880188028803880488058806880788088809881088118812881388148815881688178818881988208821882288238824882588268827882888298830883188328833883488358836883788388839884088418842884388448845884688478848884988508851885288538854885588568857885888598860886188628863886488658866886788688869887088718872887388748875887688778878887988808881888288838884888588868887888888898890889188928893889488958896889788988899890089018902890389048905890689078908890989108911891289138914891589168917891889198920892189228923892489258926892789288929893089318932893389348935893689378938893989408941894289438944894589468947894889498950895189528953895489558956895789588959896089618962896389648965896689678968896989708971897289738974897589768977897889798980898189828983898489858986898789888989899089918992899389948995899689978998899990009001900290039004900590069007900890099010901190129013901490159016901790189019902090219022902390249025902690279028902990309031903290339034903590369037903890399040904190429043904490459046904790489049905090519052905390549055905690579058905990609061906290639064906590669067906890699070907190729073907490759076907790789079908090819082908390849085908690879088908990909091909290939094909590969097909890999100910191029103910491059106910791089109911091119112911391149115911691179118911991209121912291239124912591269127912891299130913191329133913491359136913791389139914091419142914391449145914691479148914991509151915291539154915591569157915891599160916191629163916491659166916791689169917091719172917391749175917691779178917991809181918291839184918591869187918891899190919191929193919491959196919791989199920092019202920392049205920692079208920992109211921292139214921592169217921892199220922192229223922492259226922792289229923092319232923392349235923692379238923992409241924292439244924592469247924892499250925192529253925492559256925792589259926092619262926392649265926692679268926992709271927292739274927592769277927892799280928192829283928492859286928792889289929092919292929392949295929692979298929993009301930293039304930593069307930893099310931193129313931493159316931793189319932093219322932393249325932693279328932993309331933293339334933593369337933893399340934193429343934493459346934793489349935093519352935393549355935693579358935993609361936293639364936593669367936893699370937193729373937493759376937793789379938093819382938393849385938693879388938993909391939293939394939593969397939893999400940194029403940494059406940794089409941094119412941394149415941694179418941994209421942294239424942594269427942894299430943194329433943494359436943794389439944094419442944394449445944694479448944994509451945294539454945594569457945894599460946194629463946494659466946794689469947094719472947394749475947694779478947994809481948294839484948594869487948894899490949194929493949494959496949794989499950095019502950395049505950695079508950995109511951295139514951595169517951895199520952195229523952495259526952795289529953095319532953395349535953695379538953995409541954295439544954595469547954895499550955195529553955495559556955795589559956095619562956395649565956695679568956995709571957295739574957595769577957895799580958195829583958495859586958795889589959095919592959395949595959695979598959996009601960296039604960596069607960896099610961196129613961496159616961796189619962096219622962396249625962696279628962996309631963296339634963596369637963896399640964196429643964496459646964796489649965096519652965396549655965696579658965996609661966296639664966596669667966896699670967196729673967496759676967796789679968096819682968396849685968696879688968996909691969296939694969596969697969896999700970197029703970497059706970797089709971097119712971397149715971697179718971997209721972297239724972597269727972897299730973197329733973497359736973797389739974097419742974397449745974697479748974997509751975297539754975597569757975897599760976197629763976497659766976797689769977097719772977397749775977697779778977997809781978297839784978597869787978897899790979197929793979497959796979797989799980098019802980398049805980698079808980998109811981298139814981598169817981898199820982198229823982498259826982798289829983098319832983398349835983698379838983998409841984298439844984598469847984898499850985198529853985498559856985798589859986098619862986398649865986698679868986998709871987298739874987598769877987898799880988198829883988498859886988798889889989098919892989398949895989698979898989999009901990299039904990599069907990899099910991199129913991499159916991799189919992099219922992399249925992699279928992999309931993299339934993599369937993899399940994199429943994499459946994799489949995099519952995399549955995699579958995999609961996299639964996599669967996899699970997199729973997499759976997799789979998099819982998399849985998699879988998999909991999299939994999599969997999899991000010001100021000310004100051000610007100081000910010100111001210013100141001510016100171001810019100201002110022100231002410025100261002710028100291003010031100321003310034100351003610037100381003910040100411004210043100441004510046100471004810049100501005110052100531005410055100561005710058100591006010061100621006310064100651006610067100681006910070100711007210073100741007510076100771007810079100801008110082100831008410085100861008710088100891009010091100921009310094100951009610097100981009910100101011010210103101041010510106101071010810109101101011110112101131011410115101161011710118101191012010121101221012310124101251012610127101281012910130101311013210133101341013510136101371013810139101401014110142101431014410145101461014710148101491015010151101521015310154101551015610157101581015910160101611016210163101641016510166101671016810169101701017110172101731017410175101761017710178101791018010181101821018310184101851018610187101881018910190101911019210193101941019510196101971019810199102001020110202102031020410205102061020710208102091021010211102121021310214102151021610217102181021910220102211022210223102241022510226102271022810229102301023110232102331023410235102361023710238102391024010241102421024310244102451024610247102481024910250102511025210253102541025510256102571025810259102601026110262102631026410265102661026710268102691027010271102721027310274102751027610277102781027910280102811028210283102841028510286102871028810289102901029110292102931029410295102961029710298102991030010301103021030310304103051030610307103081030910310103111031210313103141031510316103171031810319103201032110322103231032410325103261032710328103291033010331103321033310334103351033610337103381033910340103411034210343103441034510346103471034810349103501035110352103531035410355103561035710358103591036010361103621036310364103651036610367103681036910370103711037210373103741037510376103771037810379103801038110382103831038410385103861038710388103891039010391103921039310394103951039610397103981039910400104011040210403104041040510406104071040810409104101041110412104131041410415104161041710418104191042010421104221042310424104251042610427104281042910430104311043210433104341043510436104371043810439104401044110442104431044410445104461044710448104491045010451104521045310454104551045610457104581045910460104611046210463104641046510466104671046810469104701047110472104731047410475104761047710478104791048010481104821048310484104851048610487104881048910490104911049210493104941049510496104971049810499105001050110502105031050410505105061050710508105091051010511105121051310514105151051610517105181051910520105211052210523105241052510526105271052810529105301053110532105331053410535105361053710538105391054010541105421054310544105451054610547105481054910550105511055210553105541055510556105571055810559105601056110562105631056410565105661056710568105691057010571105721057310574105751057610577105781057910580105811058210583105841058510586105871058810589105901059110592105931059410595105961059710598105991060010601106021060310604106051060610607106081060910610106111061210613106141061510616106171061810619106201062110622106231062410625106261062710628106291063010631106321063310634106351063610637106381063910640106411064210643106441064510646106471064810649106501065110652106531065410655106561065710658106591066010661106621066310664106651066610667106681066910670106711067210673106741067510676106771067810679106801068110682106831068410685106861068710688106891069010691106921069310694106951069610697106981069910700107011070210703107041070510706107071070810709107101071110712107131071410715107161071710718107191072010721107221072310724107251072610727107281072910730107311073210733107341073510736107371073810739107401074110742107431074410745107461074710748107491075010751107521075310754107551075610757107581075910760107611076210763107641076510766107671076810769107701077110772107731077410775107761077710778107791078010781107821078310784107851078610787107881078910790107911079210793107941079510796107971079810799108001080110802108031080410805108061080710808108091081010811108121081310814108151081610817108181081910820108211082210823108241082510826108271082810829108301083110832108331083410835108361083710838108391084010841108421084310844108451084610847108481084910850108511085210853108541085510856108571085810859108601086110862108631086410865108661086710868108691087010871108721087310874108751087610877108781087910880108811088210883108841088510886108871088810889108901089110892108931089410895108961089710898108991090010901109021090310904109051090610907109081090910910109111091210913109141091510916109171091810919109201092110922109231092410925109261092710928109291093010931109321093310934109351093610937109381093910940109411094210943109441094510946109471094810949109501095110952109531095410955109561095710958109591096010961109621096310964109651096610967109681096910970109711097210973109741097510976109771097810979109801098110982109831098410985109861098710988109891099010991109921099310994109951099610997109981099911000110011100211003110041100511006110071100811009110101101111012110131101411015110161101711018110191102011021110221102311024110251102611027110281102911030110311103211033110341103511036110371103811039110401104111042110431104411045110461104711048110491105011051110521105311054110551105611057110581105911060110611106211063110641106511066110671106811069110701107111072110731107411075110761107711078110791108011081110821108311084110851108611087110881108911090110911109211093110941109511096110971109811099111001110111102111031110411105111061110711108111091111011111111121111311114111151111611117111181111911120111211112211123111241112511126111271112811129111301113111132111331113411135111361113711138111391114011141111421114311144111451114611147111481114911150111511115211153111541115511156111571115811159111601116111162111631116411165111661116711168111691117011171111721117311174111751117611177111781117911180111811118211183111841118511186111871118811189111901119111192111931119411195111961119711198111991120011201112021120311204112051120611207112081120911210112111121211213112141121511216112171121811219112201122111222112231122411225112261122711228112291123011231112321123311234112351123611237112381123911240112411124211243112441124511246112471124811249112501125111252112531125411255112561125711258112591126011261112621126311264112651126611267112681126911270112711127211273112741127511276112771127811279112801128111282112831128411285112861128711288112891129011291112921129311294112951129611297112981129911300113011130211303113041130511306113071130811309113101131111312113131131411315113161131711318113191132011321113221132311324113251132611327113281132911330113311133211333113341133511336113371133811339113401134111342113431134411345113461134711348113491135011351113521135311354113551135611357113581135911360113611136211363113641136511366113671136811369113701137111372113731137411375113761137711378113791138011381113821138311384113851138611387113881138911390113911139211393113941139511396113971139811399114001140111402114031140411405114061140711408114091141011411114121141311414114151141611417114181141911420114211142211423114241142511426114271142811429114301143111432114331143411435114361143711438114391144011441114421144311444114451144611447114481144911450114511145211453114541145511456114571145811459114601146111462114631146411465114661146711468114691147011471114721147311474114751147611477114781147911480114811148211483114841148511486114871148811489114901149111492114931149411495114961149711498114991150011501115021150311504115051150611507115081150911510115111151211513115141151511516115171151811519115201152111522115231152411525115261152711528115291153011531115321153311534115351153611537115381153911540115411154211543115441154511546115471154811549115501155111552115531155411555115561155711558115591156011561115621156311564115651156611567115681156911570115711157211573115741157511576115771157811579115801158111582115831158411585115861158711588115891159011591115921159311594115951159611597115981159911600116011160211603116041160511606116071160811609116101161111612116131161411615116161161711618116191162011621116221162311624116251162611627116281162911630116311163211633116341163511636116371163811639116401164111642116431164411645116461164711648116491165011651116521165311654116551165611657116581165911660116611166211663116641166511666116671166811669116701167111672116731167411675116761167711678116791168011681116821168311684116851168611687116881168911690116911169211693116941169511696116971169811699117001170111702117031170411705117061170711708117091171011711117121171311714117151171611717117181171911720117211172211723117241172511726117271172811729117301173111732117331173411735117361173711738117391174011741117421174311744117451174611747117481174911750117511175211753117541175511756117571175811759117601176111762117631176411765117661176711768117691177011771117721177311774117751177611777117781177911780117811178211783117841178511786117871178811789117901179111792117931179411795117961179711798117991180011801118021180311804118051180611807118081180911810118111181211813118141181511816118171181811819118201182111822118231182411825118261182711828118291183011831118321183311834118351183611837118381183911840118411184211843118441184511846118471184811849118501185111852118531185411855118561185711858118591186011861118621186311864118651186611867118681186911870118711187211873118741187511876118771187811879118801188111882118831188411885118861188711888118891189011891118921189311894118951189611897118981189911900119011190211903119041190511906119071190811909119101191111912119131191411915119161191711918119191192011921119221192311924119251192611927119281192911930119311193211933119341193511936119371193811939119401194111942119431194411945119461194711948119491195011951119521195311954119551195611957119581195911960119611196211963119641196511966119671196811969119701197111972119731197411975119761197711978119791198011981119821198311984119851198611987119881198911990119911199211993119941199511996119971199811999120001200112002120031200412005120061200712008120091201012011120121201312014120151201612017120181201912020120211202212023120241202512026120271202812029120301203112032120331203412035120361203712038120391204012041120421204312044120451204612047120481204912050120511205212053120541205512056120571205812059120601206112062120631206412065120661206712068120691207012071120721207312074120751207612077120781207912080120811208212083120841208512086120871208812089120901209112092120931209412095120961209712098120991210012101121021210312104121051210612107121081210912110121111211212113121141211512116121171211812119121201212112122121231212412125121261212712128121291213012131121321213312134121351213612137121381213912140121411214212143121441214512146121471214812149121501215112152121531215412155121561215712158121591216012161121621216312164121651216612167121681216912170121711217212173121741217512176121771217812179121801218112182121831218412185121861218712188121891219012191121921219312194121951219612197
  1. <?php
  2. namespace App\Services\Anime;
  3. use App\Consts\BaseConst;
  4. use App\Consts\ErrorConst;
  5. use App\Exceptions\ApiException;
  6. use App\Facade\Site;
  7. use App\Libs\Utils;
  8. use App\Models\MpGeneratePicTask;
  9. use App\Models\MpTaskCenter;
  10. use App\Services\AIGeneration\AIImageGenerationService;
  11. use App\Services\AIGeneration\AIVideoGenerationService;
  12. use App\Services\DeepSeek\DeepSeekService;
  13. use App\Services\PointsService;
  14. use App\Services\TaskCenterService;
  15. use Dflydev\DotAccessData\Util;
  16. use GuzzleHttp\Client;
  17. use Illuminate\Support\Facades\DB;
  18. use Illuminate\Support\Facades\Log;
  19. use Illuminate\Support\Facades\Redis;
  20. use OSS\Core\OssException;
  21. use OSS\OssClient;
  22. use PhpOffice\PhpSpreadsheet\IOFactory;
  23. class AnimeService
  24. {
  25. protected $aiImageGenerationService;
  26. protected $aiVideoGenerationService;
  27. protected $DeepSeekService;
  28. protected $pointsService;
  29. protected $taskCenterService;
  30. private $url;
  31. private $api_key;
  32. private $headers;
  33. public function __construct(
  34. AIImageGenerationService $aiImageGenerationService,
  35. AIVideoGenerationService $aiVideoGenerationService,
  36. DeepSeekService $DeepSeekService,
  37. PointsService $pointsService,
  38. TaskCenterService $taskCenterService
  39. ) {
  40. $this->aiImageGenerationService = $aiImageGenerationService;
  41. $this->aiVideoGenerationService = $aiVideoGenerationService;
  42. $this->DeepSeekService = $DeepSeekService;
  43. $this->pointsService = $pointsService;
  44. $this->taskCenterService = $taskCenterService;
  45. $this->url = 'https://api.deepseek.com/chat/completions';
  46. $this->api_key = env('DEEPSEEK_API_KEY');
  47. $this->headers = [
  48. 'Authorization' => 'Bearer '.$this->api_key,
  49. 'Content-Type' => 'application/json; charset=UTF-8'
  50. ];
  51. }
  52. /**
  53. * 构建统一的分镜数据结构(episodeInfo格式)
  54. * @param array $segments 分镜数据数组
  55. * @return array 返回包含acts和total_duration的数组
  56. */
  57. public function buildEpisodeSegmentsStructure($segments) {
  58. $acts = [];
  59. $totalDuration = 0; // 初始化总时长
  60. foreach($segments as $segment) {
  61. // 计算分镜时长,优先级:video_duration > audio_duration > 默认5秒
  62. $videoDuration = getProp($segment, 'video_duration');
  63. $audioDuration = getProp($segment, 'audio_duration');
  64. if (!empty($videoDuration) && is_numeric($videoDuration)) {
  65. $totalDuration += floatval($videoDuration);
  66. } elseif (!empty($audioDuration) && is_numeric($audioDuration)) {
  67. $totalDuration += floatval($audioDuration);
  68. } else {
  69. $totalDuration += 5; // 默认5秒
  70. }
  71. $segment_content = getProp($segment, 'segment_content');
  72. // 判断是否有尾帧描述,如果有则去掉这部分内容
  73. if (strpos($segment_content, '尾帧') !== false) {
  74. // 使用正则表达式匹配"尾帧"及其后面的内容并移除(s修饰符让.匹配换行符)
  75. $segment_content = preg_replace('/尾帧.*$/s', '', $segment_content);
  76. }
  77. // 构建分镜信息
  78. $segmentInfo = [
  79. 'segment_id' => getProp($segment, 'segment_id'),
  80. 'segment_number' => getProp($segment, 'segment_number'),
  81. 'segment_content' => $segment_content,
  82. 'description' => getProp($segment, 'description'),
  83. 'composition' => getProp($segment, 'composition'),
  84. 'camera_movement' => getProp($segment, 'camera_movement'),
  85. 'voice_actor' => getProp($segment, 'voice_actor'),
  86. 'dialogue' => getProp($segment, 'dialogue'),
  87. 'frame_type' => getProp($segment, 'frame_type'),
  88. 'scene' => getProp($segment, 'scene'),
  89. 'characters' => getProp($segment, 'characters'),
  90. 'tail_frame' => getProp($segment, 'tail_frame'),
  91. 'emotion' => getProp($segment, 'emotion'),
  92. 'emotion_type' => getProp($segment, 'emotion_type'),
  93. 'gender' => getProp($segment, 'gender'),
  94. 'speed_ratio' => getProp($segment, 'speed_ratio'),
  95. 'loudness_ratio' => getProp($segment, 'loudness_ratio'),
  96. 'emotion_scale' => getProp($segment, 'emotion_scale'),
  97. 'pitch' => getProp($segment, 'pitch'),
  98. 'voice_name' => getProp($segment, 'voice_name'),
  99. 'voice_type' => getProp($segment, 'voice_type'),
  100. 'voice_audio_url' => getProp($segment, 'voice_audio_url'),
  101. 'img_url' => getProp($segment, 'img_url'),
  102. 'audio_url' => getProp($segment, 'audio_url'),
  103. 'audio_duration' => getProp($segment, 'audio_duration', 0),
  104. 'video_url' => getProp($segment, 'video_url'),
  105. 'video_duration' => getProp($segment, 'video_duration', 0),
  106. 'video_time_point_start' => getProp($segment, 'video_time_point_start', 0),
  107. 'video_time_point_end' => getProp($segment, 'video_time_point_end', getProp($segment, 'video_duration', 0)),
  108. 'last_frame_url' => getProp($segment, 'last_frame_url'),
  109. 'current_type' => getProp($segment, 'current_type'),
  110. ];
  111. $actNumber = getProp($segment, 'act_number');
  112. if (isset($acts[$actNumber])) {
  113. $acts[$actNumber]['segments'][] = $segmentInfo;
  114. } else {
  115. $acts[$actNumber] = [
  116. 'act_number' => $actNumber,
  117. 'act_title' => getProp($segment, 'act_title'),
  118. 'act_duration' => getProp($segment, 'act_duration'),
  119. 'segments' => [$segmentInfo]
  120. ];
  121. }
  122. }
  123. return [
  124. 'acts' => array_values($acts),
  125. 'total_duration' => intval(round($totalDuration))
  126. ];
  127. }
  128. /**
  129. * 构建统一的分段数据结构(episodeInfoForAce格式)
  130. * @param array $segments 分段数据数组
  131. * @return array 返回包含acts和total_duration的数组
  132. */
  133. public function buildEpisodeActsStructureForAce($segments) {
  134. $acts = [];
  135. $totalDuration = 0; // 初始化总时长
  136. foreach($segments as $segment) {
  137. // 计算分镜时长,优先级:video_duration > act_duration > 默认5秒
  138. $videoDuration = getProp($segment, 'video_duration');
  139. $actDuration = getProp($segment, 'act_duration');
  140. if (!empty($videoDuration) && is_numeric($videoDuration)) {
  141. $totalDuration += floatval($videoDuration);
  142. } elseif (!empty($actDuration) && is_numeric($actDuration)) {
  143. $totalDuration += floatval($actDuration);
  144. } else {
  145. $totalDuration += 5; // 默认5秒
  146. }
  147. // 构建分镜信息
  148. $segmentInfo = [
  149. 'act_id' => getProp($segment, 'id'),
  150. 'act_number' => getProp($segment, 'act_number'),
  151. 'act_title' => getProp($segment, 'act_title'),
  152. 'act_duration' => getProp($segment, 'act_duration'),
  153. 'act_content' => getProp($segment, 'act_content'),
  154. 'video_url' => getProp($segment, 'video_url'),
  155. 'video_duration' => getProp($segment, 'video_duration', 0),
  156. 'video_time_point_start' => getProp($segment, 'video_time_point_start', 0),
  157. 'video_time_point_end' => getProp($segment, 'video_time_point_end', getProp($segment, 'video_duration', 0)),
  158. 'last_frame_url' => getProp($segment, 'last_frame_url'),
  159. 'current_type' => getProp($segment, 'current_type'),
  160. ];
  161. $acts[] = $segmentInfo;
  162. }
  163. return [
  164. 'acts' => array_values($acts),
  165. 'total_duration' => intval(round($totalDuration))
  166. ];
  167. }
  168. /**
  169. * 验证画面比例是否有效
  170. * @param string $ratio 画面比例
  171. * @return bool
  172. */
  173. public function validateRatio($ratio) {
  174. return isset(BaseConst::IMAGE_RATIOS[$ratio]);
  175. }
  176. /**
  177. * 获取画面比例对应的宽高
  178. * @param string $ratio 画面比例
  179. * @return array ['width' => int, 'height' => int]
  180. * @throws \Exception
  181. */
  182. private function getRatioDimensions($ratio) {
  183. if ($ratio && !$this->validateRatio($ratio)) {
  184. $validRatios = implode('、', array_keys(BaseConst::IMAGE_RATIOS));
  185. Utils::throwError("1002:画面比例选择不正确,只支持{$validRatios}");
  186. }
  187. return isset(BaseConst::IMAGE_RATIOS[$ratio]) ? BaseConst::IMAGE_RATIOS[$ratio] : ['width' => 1600, 'height' => 2848];
  188. }
  189. public function createAnime($data) {
  190. $uid = Site::getUid();
  191. $cpid = Site::getCpid();
  192. $input_art_style = getProp($data, 'art_style');
  193. $file = getProp($data, 'file');
  194. $content = getProp($data, 'content', '');
  195. $bid = getProp($data, 'bid', 0);
  196. $script_id = getProp($data, 'script_id', 0);
  197. $ace_mode = getProp($data, 'ace_mode', 0);
  198. $extra_products = getProp($data, 'products', []);
  199. if (is_string($extra_products)) $extra_products = json_decode($extra_products, true);
  200. if (!is_array($extra_products)) {
  201. Utils::throwError('20003:传入的资产格式不正确');
  202. }
  203. // 替换美术风格
  204. $mappedArtStyle = $this->DeepSeekService->getArtStylePromptByInput($input_art_style);
  205. // 提取文件内容
  206. if ($file) {
  207. $content = $this->DeepSeekService->extractFileContent($file);
  208. if (!$content) {
  209. Utils::throwError('20003:无法提取文件内容,请检查文件格式');
  210. }
  211. } elseif ($script_id) {
  212. $content = $this->DeepSeekService->getContentByScriptId($script_id);
  213. if (!$content) {
  214. Utils::throwError('20003:无法获取剧本内容,请检查剧本');
  215. }
  216. } elseif ($bid) {
  217. $content = $this->DeepSeekService->getContentByBid($bid);
  218. if (!$content) {
  219. Utils::throwError('20003:无法获取书籍内容,请检查书籍');
  220. }
  221. } elseif ($content) {
  222. $content = filterContent($content);
  223. }else {
  224. $content = '';
  225. }
  226. $anime_data = [
  227. 'user_id' => $uid,
  228. 'cpid' => $cpid,
  229. 'anime_name' => '新剧本策划',
  230. 'is_multi' => getProp($data, 'is_multi', 1),
  231. 'content' => $content,
  232. 'art_style_type' => $input_art_style,
  233. 'ace_mode' => $ace_mode,
  234. 'script_id' => $script_id,
  235. 'extra_products' => json_encode($extra_products, 256),
  236. 'created_at' => date('Y-m-d H:i:s'),
  237. 'updated_at' => date('Y-m-d H:i:s'),
  238. ];
  239. // 处理文本模型
  240. $model = getProp($data, 'model');
  241. if (!$model) {
  242. // 用户没有输入,使用默认值
  243. $model = 'deepseek-v4-pro';
  244. }
  245. // 验证模型是否在可用模型表中
  246. if (!DB::table('mp_text_models')->where('model', $model)->where('is_enabled', 1)->exists()) {
  247. $model = 'deepseek-v4-pro';
  248. }
  249. $anime_data['model'] = $model;
  250. if ($mappedArtStyle) $anime_data['art_style'] = $mappedArtStyle;
  251. return DB::table('mp_animes')->insertGetId($anime_data);
  252. }
  253. public function chatList($data) {
  254. $uid = Site::getUid();
  255. $anime_name = getProp($data, 'anime_name');
  256. $query = DB::table('mp_animes')->where('is_deleted', 0)->where('user_id', $uid);
  257. if ($anime_name) {
  258. $query->where('anime_name', 'like', "%$anime_name%");
  259. }
  260. return $query->orderBy('id', 'desc')->paginate();
  261. }
  262. public function chatHistory($data) {
  263. $anime_id = getProp($data, 'anime_id');
  264. $sequence = getProp($data, 'sequence', 0);
  265. if (!$anime_id) Utils::throwError('20003:请选择对话!');
  266. $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)
  267. ->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');
  268. return $query->orderBy('ar.id')->get()->map(function ($value) {
  269. $value = (array)$value;
  270. if ($value['role'] == 'assistant') $value['content'] = filterScriptContent($value['content']);
  271. $value['created_at'] = transDate($value['created_at']);
  272. $value['episode_created_at'] = transDate($value['episode_created_at']);
  273. return $value;
  274. })->toArray();
  275. }
  276. public function batchSetRoleImg($data) {
  277. $episode_id = getProp($data, 'episode_id');
  278. if (!$episode_id) Utils::throwError('1002:请选择分集');
  279. $episode = DB::table('mp_anime_episodes')->where('id', $episode_id)->first();
  280. $roles = json_decode(getProp($data, 'roles'), true) ?: [];
  281. $art_style = getProp($episode, 'art_style');
  282. $anime_id = getProp($episode, 'anime_id');
  283. $anime = DB::table('mp_animes')->where('id', $anime_id)->first();
  284. $art_style_type = getProp($anime, 'art_style_type');
  285. $character_prefix = '';
  286. $scene_prefix = '';
  287. if ($art_style_type) {
  288. $art_style_arr = $this->DeepSeekService->getArtStyleShortPromptByInput($art_style_type);
  289. $character_prefix = isset($art_style_arr['character_prefix']) ? $art_style_arr['character_prefix'] : '';
  290. $scene_prefix = isset($art_style_arr['scene_prefix']) ? $art_style_arr['scene_prefix'] : '';
  291. }
  292. foreach ($roles as &$role) {
  293. $role_name = getProp($role, 'role');
  294. if ($role_name == '旁白') continue;
  295. // 优先使用 pic_prompt,如果没有则使用 description
  296. $pic_prompt = getProp($role, 'pic_prompt');
  297. $description = !empty($pic_prompt) ? trim((string)$pic_prompt) : getProp($role, 'description');
  298. // if ($art_style) $description = "美术风格:\n{$art_style}\n主体描述:{$description}\n图片要求:图片侧重点是人物,不要出现场景或背景,并且只能生成一个人物";
  299. $description = "{$character_prefix}。\n主体描述:{$description}\n超高清,高细节,主体突出,构图合理,画面干净,无场景或背景,单人物,无文字,无水印,无字幕,电影级光影,视觉焦点明确";
  300. // 参考图地址
  301. $ref_img_url = getProp($role, 'url');
  302. if ($ref_img_url) continue; // 已有图片则跳过
  303. // 此处调用AIImageGenerationService的生成图片任务接口: createImageGenerationTask(注意使用默认参数,prompt使用角色描述),并返回任务id
  304. try {
  305. $params = [
  306. 'prompt' => $description,
  307. 'ref_img_urls' => !empty($ref_img_url) ? [$ref_img_url] : []
  308. ];
  309. $task = $this->aiImageGenerationService->createImageGenerationTask($params);
  310. $task_id = $task->id;
  311. if (!$task_id) {
  312. Utils::throwError("20003:角色({$role_name})生成图片失败");
  313. }
  314. $role['task_id'] = $task_id;
  315. $role['task_status'] = 'processing';
  316. } catch (\Exception $e) {
  317. logDB('anime', 'error', "角色({$role_name})生成图片失败", ['error' => $e->getMessage()]);
  318. Utils::throwError("20003:" . $e->getMessage());
  319. }
  320. }
  321. // 保存角色信息
  322. $boolen = DB::table('mp_anime_episodes')->where('id', $episode_id)->update([
  323. 'roles' => json_encode($roles, 256),
  324. 'generate_status' => '执行中',
  325. 'generate_at' => date('Y-m-d H:i:s'),
  326. 'updated_at' => date('Y-m-d H:i:s')
  327. ]);
  328. if (!$boolen) {
  329. Utils::throwError('20003:保存角色信息失败');
  330. }
  331. return $boolen;
  332. }
  333. public function batchSetSceneImg($data) {
  334. $episode_id = getProp($data, 'episode_id');
  335. if (!$episode_id) Utils::throwError('1002:请选择分集');
  336. $episode = DB::table('mp_anime_episodes')->where('id', $episode_id)->first();
  337. $scenes = json_decode(getProp($episode, 'scenes'), true);
  338. $art_style = getProp($episode, 'art_style');
  339. $target_scene = getProp($data, 'target_scene');
  340. $anime_id = getProp($episode, 'anime_id');
  341. $anime = DB::table('mp_animes')->where('id', $anime_id)->first();
  342. $art_style_type = getProp($anime, 'art_style_type');
  343. $character_prefix = '';
  344. $scene_prefix = '';
  345. if ($art_style_type) {
  346. $art_style_arr = $this->DeepSeekService->getArtStyleShortPromptByInput($art_style_type);
  347. $character_prefix = isset($art_style_arr['character_prefix']) ? $art_style_arr['character_prefix'] : '';
  348. $scene_prefix = isset($art_style_arr['scene_prefix']) ? $art_style_arr['scene_prefix'] : '';
  349. }
  350. foreach ($scenes as &$scene) {
  351. $scene_name = getProp($scene, 'scene');
  352. if ($scene_name != $target_scene) continue;
  353. // 优先使用 pic_prompt,如果没有则使用 description
  354. $pic_prompt = getProp($scene, 'pic_prompt');
  355. $description = !empty($pic_prompt) ? trim((string)$pic_prompt) : getProp($scene, 'description');
  356. // if ($art_style) $description = "美术风格:\n{$art_style}\n\n场景描述:{$description}\n图片要求: 图片侧重点是场景,生成的是场景环境图片,不要出现人物(此为第一优先要求)";
  357. $description = "{$scene_prefix}。\n场景描述:{$description}\n无人物,超高清,高细节,主体突出,构图合理,画面干净,无文字,无水印,无字幕,电影级光影,视觉焦点明确";
  358. // 参考图地址
  359. $ref_img_url = getProp($scene, 'url');
  360. if ($ref_img_url) continue; // 已有图片则跳过
  361. // 此处调用AIImageGenerationService的生成图片任务接口: createImageGenerationTask(注意使用默认参数,prompt使用角色描述),并返回任务id
  362. try {
  363. $params = [
  364. 'prompt' => $description,
  365. 'ref_img_urls' => !empty($ref_img_url) ? [$ref_img_url] : []
  366. ];
  367. $task = $this->aiImageGenerationService->createImageGenerationTask($params);
  368. $task_id = $task->id;
  369. if (!$task_id) {
  370. Utils::throwError("20003:场景({$scene_name})生成图片失败");
  371. }
  372. $scene['task_id'] = $task_id;
  373. $scene['task_status'] = 'processing';
  374. } catch (\Exception $e) {
  375. logDB('anime', 'error', "场景({$scene_name})生成图片失败", ['error' => $e->getMessage()]);
  376. Utils::throwError("20003:" . $e->getMessage());
  377. }
  378. }
  379. // 保存场景信息
  380. $boolen = DB::table('mp_anime_episodes')->where('id', $episode_id)->update([
  381. 'scenes' => json_encode($scenes, 256),
  382. 'generate_status' => '执行中',
  383. 'generate_at' => date('Y-m-d H:i:s'),
  384. 'updated_at' => date('Y-m-d H:i:s')
  385. ]);
  386. if (!$boolen) {
  387. Utils::throwError('20003:保存角色信息失败');
  388. }
  389. return $boolen;
  390. }
  391. public function editAnime($data) {
  392. $anime_id = getProp($data, 'anime_id');
  393. $anime_name = trim(getProp($data, 'anime_name'));
  394. // 确认对话名称唯一性
  395. if ($id = DB::table('mp_animes')->where('anime_name', $anime_name)->value('id')) {
  396. if ($id != $anime_id) $anime_name = $anime_name . '_' . date('YmdHis');
  397. }
  398. if (!$anime_id || !$anime_name) {
  399. Utils::throwError('20003:参数异常');
  400. }
  401. return DB::table('mp_animes')->where('id', $anime_id)->update([
  402. 'anime_name' => $anime_name,
  403. 'updated_at' => date('Y-m-d H:i:s')
  404. ]);
  405. // $script_arr =getProp($data, 'script', []);
  406. // if (!$script_arr) Utils::throwError('20003:剧本内容不能为空');
  407. // $start_episode_sequence = getProp($data, 'start_episode_sequence', 1);
  408. // $anime_id = getProp($data, 'anime_id');
  409. // try {
  410. // DB::beginTransaction();
  411. // $table_data = [
  412. // 'intro' => isset($script_arr['intro']) ? $script_arr['intro'] : '',
  413. // 'highlights' => isset($script_arr['highlights']) ? $script_arr['highlights'] : '',
  414. // 'role_relationship' => isset($script_arr['role_relationship']) ? $script_arr['role_relationship'] : '',
  415. // 'core_contradiction' => isset($script_arr['core_contradiction']) ? $script_arr['core_contradiction'] : '',
  416. // 'roles' => isset($script_arr['roles']) ? json_encode($script_arr['roles'], 256) : '',
  417. // 'art_style' => isset($script_arr['art_style']) ? $script_arr['art_style'] : '',
  418. // 'scenes' => isset($script_arr['scenes']) ? json_encode($script_arr['scenes'], 256) : '',
  419. // 'status' => 3,
  420. // 'start_episode_sequence' => $start_episode_sequence,
  421. // 'end_episode_sequence' => $start_episode_sequence + count($script_arr['episodes']) - 1,
  422. // 'episode_num' => count($script_arr['episodes']),
  423. // 'updated_at' => date('Y-m-d H:i:s')
  424. // ];
  425. // // 保存剧本内容
  426. // if (!empty($anime_id)) {
  427. // $boolen = DB::table('mp_animes')->where('id', $anime_id)->update($table_data);
  428. // if (!$boolen) {
  429. // dLog('anime')->info('对话保存失败', $table_data);
  430. // Utils::throwError('20003:对话保存失败');
  431. // }
  432. // }else {
  433. // $table['created_at'] = $table_data['updated_at'];
  434. // $anime_id = DB::table('mp_animes')->insertGetId($table_data);
  435. // if (!$anime_id) {
  436. // dLog('anime')->info('对话保存失败', $table_data);
  437. // Utils::throwError('20003:对话保存失败');
  438. // }
  439. // }
  440. // // 保存分集内容
  441. // // 删除历史分集内容
  442. // $boolen1 = DB::table('mp_anime_episodes')->where('anime_id', $anime_id)->delete();
  443. // $episodes = [];
  444. // $sequence = 1;
  445. // foreach ($script_arr['episodes'] as $episode) {
  446. // $segment_number = 1;
  447. // foreach($episode['segments'] as $segment) {
  448. // $episodes[] = [
  449. // 'anime_id' => $anime_id,
  450. // 'episode_number' => $episode['episode_number'],
  451. // 'title' => $episode['title'],
  452. // // 'content' => $episode['content'],
  453. // 'content' => '',
  454. // 'segment_number' => $segment_number,
  455. // 'segment_content' => $segment['segment_content'],
  456. // 'sequence' => $sequence,
  457. // 'created_at' => date('Y-m-d H:i:s'),
  458. // 'updated_at' => date('Y-m-d H:i:s')
  459. // ];
  460. // $sequence++;
  461. // $segment_number++;
  462. // }
  463. // }
  464. // $boolen2 = DB::table('mp_anime_episodes')->insert($episodes);
  465. // if (!$boolen2) {
  466. // dLog('deepseek')->info('分集内容保存失败', $episodes);
  467. // logDB('deepseek', 'error', '分集内容保存失败', ['episodes_count' => count($episodes)]);
  468. // Utils::throwError('20003:分集内容保存失败');
  469. // }
  470. // } catch (\Exception $e) {
  471. // DB::rollBack();
  472. // Utils::throwError('20003:'.$e->getMessage());
  473. // }
  474. // DB::commit();
  475. // return true;
  476. }
  477. public function delAnime($data) {
  478. $anime_id = getProp($data, 'anime_id');
  479. if (!$anime_id) {
  480. Utils::throwError('20003:请选择剧本');
  481. }
  482. return DB::table('mp_animes')->where('id', $anime_id)->update([
  483. 'is_deleted' => 1,
  484. 'updated_at' => date('Y-m-d H:i:s')
  485. ]);
  486. }
  487. public function animeDetail($data) {
  488. $uid = Site::getUid();
  489. $anime_id = getProp($data, 'anime_id');
  490. $anime = DB::table('mp_animes')->where('id', $anime_id)->where('is_deleted', 0)->where('user_id', $uid)
  491. ->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();
  492. if (!$anime) Utils::throwError('20003:权限不足');
  493. $anime = (array)$anime;
  494. $anime['roles'] = json_decode($anime['roles']);
  495. $anime['scenes'] = json_decode($anime['scenes']);
  496. // 获取分集信息
  497. $episodes = DB::table('mp_anime_episodes')->where('anime_id', $anime_id)->where('is_default', 1)
  498. ->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"))
  499. ->orderBy('episode_number')->get()->map(function ($value) {
  500. return (array)$value;
  501. })->toArray();
  502. $anime['episodes'] = $episodes;
  503. // 获取当前仍在批量生成中的剧集任务(只展示 episodes 中尚未出现的剧集序号)
  504. $episodeNumbers = array_map('intval', array_column($episodes, 'episode_number'));
  505. $episodeTasks = DB::table('mp_batch_episode_generation_details')
  506. ->where('anime_id', $anime_id)
  507. ->whereIn('status', ['pending', 'processing', 'failed']) // 只获取待生成/生成中任务,已完成或失败的不显示
  508. ->orderBy('episode_number')
  509. ->get()
  510. ->map(function ($task) use ($episodeNumbers) {
  511. if (in_array((int)$task->episode_number, $episodeNumbers, true)) {
  512. return null;
  513. }
  514. return [
  515. 'episode_number' => (int)$task->episode_number,
  516. 'status' => $task->status,
  517. 'error_message' => $task->status == 'failed' ? $task->error_message : '',
  518. ];
  519. })
  520. ->filter()
  521. ->values()
  522. ->toArray();
  523. $anime['episode_tasks'] = $episodeTasks;
  524. return $anime;
  525. }
  526. public function episodeInfo($data) {
  527. $uid = Site::getUid();
  528. $anime_id = getProp($data, 'anime_id');
  529. $episode_id = getProp($data, 'episode_id');
  530. if (!$anime_id || !$episode_id) {
  531. Utils::throwError('1002:请选择剧集');
  532. }
  533. // 验证用户权限
  534. $anime = DB::table('mp_animes')->where('id', $anime_id)->where('user_id', $uid)->where('is_deleted', 0)->first();
  535. if (!$anime) Utils::throwError('20003:权限不足');
  536. $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();
  537. if (!$episode) Utils::throwError('20003:该剧集不存在!');
  538. $episode = (array)$episode;
  539. $episode['roles'] = json_decode($episode['roles'], true);
  540. // foreach($episode['roles'] as &$item) {
  541. // if (isset($item['pic_prompt']) && mb_substr($item['pic_prompt'], 0, 11) != '写实。全景,正面拍摄。') $item['pic_prompt'] = '写实。全景,正面拍摄。'.$item['pic_prompt'];
  542. // }
  543. $episode['scenes'] = json_decode($episode['scenes'], true);
  544. // foreach($episode['scenes'] as &$item) {
  545. // if (isset($item['pic_prompt']) && mb_substr($item['pic_prompt'], 0, 3) != '写实。') $item['pic_prompt'] = '写实。'.$item['pic_prompt'];
  546. // }
  547. // 获取分镜信息
  548. $segments = DB::table('mp_episode_segments')->where('anime_id', $anime_id)->where('episode_id', getProp($episode, 'episode_id'))->orderBy('segment_number')
  549. ->select('*')->get()->map(function ($value) {
  550. return (array)$value;
  551. })->toArray();
  552. // 使用公共方法构建分镜结构
  553. $segmentsStructure = $this->buildEpisodeSegmentsStructure($segments);
  554. $episode['acts'] = $segmentsStructure['acts'];
  555. $episode['total_duration'] = $segmentsStructure['total_duration'];
  556. return $episode;
  557. }
  558. public function episodeInfoForAce($data) {
  559. $anime_id = getProp($data, 'anime_id');
  560. $episode_id = getProp($data, 'episode_id');
  561. if (!$anime_id || !$episode_id) {
  562. Utils::throwError('1002:请选择剧集');
  563. }
  564. $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();
  565. if (!$episode) Utils::throwError('20003:该剧集不存在!');
  566. $episode = (array)$episode;
  567. $episode['roles'] = json_decode($episode['roles'], true);
  568. // foreach($episode['roles'] as &$item) {
  569. // if (isset($item['pic_prompt']) && mb_substr($item['pic_prompt'], 0, 11) != '写实。全景,正面拍摄。') $item['pic_prompt'] = '写实。全景,正面拍摄。'.$item['pic_prompt'];
  570. // }
  571. $episode['scenes'] = json_decode($episode['scenes'], true);
  572. // foreach($episode['scenes'] as &$item) {
  573. // if (isset($item['pic_prompt']) && mb_substr($item['pic_prompt'], 0, 3) != '写实。') $item['pic_prompt'] = '写实。'.$item['pic_prompt'];
  574. // }
  575. $episode['props'] = $episode['props'] ? json_decode($episode['props'], true) : [];
  576. // 获取分镜信息
  577. $segments = DB::table('mp_episode_segments')->where('anime_id', $anime_id)->where('episode_id', getProp($episode, 'episode_id'))->orderBy('act_number')
  578. ->select('*')->get()->map(function ($value) {
  579. return (array)$value;
  580. })->toArray();
  581. $segmentsStructure = $this->buildEpisodeActsStructureForAce($segments);
  582. $episode['acts'] = $segmentsStructure['acts'];
  583. $episode['total_duration'] = $segmentsStructure['total_duration'];
  584. // 获取mp_animes表中的视频参数
  585. $anime = DB::table('mp_animes')->where('id', $anime_id)->first(['video_model', 'video_resolution', 'video_ratio']);
  586. $episode['video_params'] = [
  587. 'video_model' => getProp($anime, 'video_model'),
  588. 'video_resolution' => getProp($anime, 'video_resolution'),
  589. 'ratio' => getProp($anime, 'video_ratio'),
  590. ];
  591. return $episode;
  592. }
  593. public function segmentInfo($data) {
  594. $uid = Site::getUid();
  595. $segment_id = getProp($data, 'segment_id');
  596. if (!$segment_id) {
  597. Utils::throwError('1002:请选择分镜');
  598. }
  599. // 获取分镜信息
  600. $segment = DB::table('mp_episode_segments')->where('segment_id', $segment_id)->first();
  601. // 验证用户权限
  602. if ($segment) {
  603. $anime = DB::table('mp_animes')->where('id', getProp($segment, 'anime_id'))->where('user_id', $uid)->where('is_deleted', 0)->first();
  604. if (!$anime) Utils::throwError('20003:权限不足');
  605. }
  606. $result = [
  607. 'segment_id' => getProp($segment, 'segment_id'),
  608. 'segment_number' => getProp($segment, 'segment_number'),
  609. 'segment_content' => getProp($segment, 'segment_content'),
  610. 'description' => getProp($segment, 'description'),
  611. 'composition' => getProp($segment, 'composition'),
  612. 'camera_movement' => getProp($segment, 'camera_movement'),
  613. 'voice_actor' => getProp($segment, 'voice_actor'),
  614. 'dialogue' => getProp($segment, 'dialogue'),
  615. 'frame_type' => getProp($segment, 'frame_type'),
  616. 'scene' => getProp($segment, 'scene'),
  617. 'characters' => getProp($segment, 'characters'),
  618. 'tail_frame' => getProp($segment, 'tail_frame'),
  619. 'emotion' => getProp($segment, 'emotion'),
  620. 'emotion_type' => getProp($segment, 'emotion_type'),
  621. 'gender' => getProp($segment, 'gender'),
  622. 'speed_ratio' => getProp($segment, 'speed_ratio'),
  623. 'loudness_ratio' => getProp($segment, 'loudness_ratio'),
  624. 'emotion_scale' => getProp($segment, 'emotion_scale'),
  625. 'pitch' => getProp($segment, 'pitch'),
  626. 'voice_name' => getProp($segment, 'voice_name'),
  627. 'voice_type' => getProp($segment, 'voice_type'),
  628. 'voice_audio_url' => getProp($segment, 'voice_audio_url'),
  629. 'img_url' => getProp($segment, 'img_url'),
  630. 'video_url' => getProp($segment, 'video_url'),
  631. 'last_frame_url' => getProp($segment, 'last_frame_url'),
  632. ];
  633. return $result;
  634. }
  635. public function copyEpisodeVersion($data) {
  636. $episode_id = getProp($data, 'episode_id');
  637. $uid = Site::getUid();
  638. $cpid = Site::getCpid();
  639. $episode = DB::table('mp_anime_episodes')->where('id', $episode_id)->first();
  640. if (!$episode) Utils::throwError('20003:该剧集不存在');
  641. $episode = (array)$episode;
  642. $anime_id = $episode['anime_id'];
  643. $episode_number = $episode['episode_number'];
  644. $count = DB::table('mp_anime_episodes')->where('anime_id', $anime_id)->where('episode_number', $episode_number)->count('id');
  645. $sequence = $count + 1;
  646. unset($episode['id']);
  647. $now = date('Y-m-d H:i:s');
  648. $episode['created_at'] = $now;
  649. $episode['updated_at'] = $now;
  650. $episode['is_default'] = 1;
  651. // 获取版本中含有"(副本"字样的个数
  652. $copy_count = DB::table('mp_anime_episodes')->where('anime_id', $anime_id)->where('episode_number', $episode_number)->where('title', 'like', '%(副本%')->count('id');
  653. $episode['title'] = $copy_count > 0 ? $episode['title']."(副本{$copy_count})" : $episode['title']."(副本)"; // 生成带(副本)字样的标题
  654. $episode['sequence'] = $sequence;
  655. $episode['is_generated'] = 0;
  656. $episode['cpid'] = $cpid;
  657. // 获取ace_mode
  658. $ace_mode = DB::table('mp_animes')->where('id', $anime_id)->value('ace_mode');
  659. try {
  660. DB::beginTransaction();
  661. DB::table('mp_anime_episodes')->where('anime_id', $anime_id)->where('episode_number', $episode_number)->update(['is_default' => 0, 'updated_at'=>$now]);
  662. // 新增副本
  663. $new_episode_id = DB::table('mp_anime_episodes')->insertGetId($episode);
  664. if (!$new_episode_id) {
  665. Utils::throwError('20003:创建副本失败!');
  666. }
  667. // 获取分镜数据并准备插入
  668. $segments_for_insert = DB::table('mp_episode_segments')
  669. ->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')
  670. ->where('episode_id', $episode_id)->orderBy('segment_number')->get()->map(function($item) use ($new_episode_id,$ace_mode) {
  671. $item = (array)$item;
  672. $item['episode_id'] = $new_episode_id;
  673. if ((int)$ace_mode !== 1) $item['segment_id'] = date('YmdHis').mt_rand(1000,9999).str_pad($item['segment_number'], 3, "0", STR_PAD_LEFT);
  674. $item['created_at'] = $item['updated_at'] = date('Y-m-d H:i:s');
  675. return $item;
  676. })->toArray();
  677. // 写入分镜数据
  678. $boolen2 = DB::table('mp_episode_segments')->insert($segments_for_insert);
  679. if (!$boolen2) {
  680. Utils::throwError('20003:写入分镜数据失败!');
  681. }
  682. // 写入对话历史
  683. $records = [
  684. [
  685. 'uid' => $uid,
  686. 'anime_id' => $anime_id,
  687. 'role' => 'user',
  688. 'content' => '创建副本',
  689. 'sequence' => $episode_number,
  690. 'episode_id' => $new_episode_id,
  691. 'created_at' => $now,
  692. 'updated_at' => $now
  693. ],
  694. [
  695. 'uid' => $uid,
  696. 'anime_id' => $anime_id,
  697. 'role' => 'assistant',
  698. 'content' => '好的,已为您创建副本',
  699. 'sequence' => $episode_number,
  700. 'episode_id' => $new_episode_id,
  701. 'created_at' => $now,
  702. 'updated_at' => $now
  703. ]
  704. ];
  705. $boolen3 = DB::table('mp_anime_records')->insert($records);
  706. if (!$boolen3) {
  707. Utils::throwError('20003:对话记录保存失败');
  708. }
  709. }catch (\Exception $e) {
  710. DB::rollBack();
  711. Utils::throwError('20003:'.$e->getMessage());
  712. }
  713. DB::commit();
  714. // 构建与 episodeInfo 方法一致的返回数据结构
  715. $result = [
  716. 'episode_id' => $new_episode_id,
  717. 'anime_id' => $anime_id,
  718. 'episode_number' => $episode_number,
  719. 'title' => $episode['title'],
  720. 'intro' => $episode['intro'],
  721. 'art_style' => $episode['art_style'],
  722. 'roles' => json_decode($episode['roles'], true),
  723. 'scenes' => json_decode($episode['scenes'], true),
  724. 'is_generated' => (int)$episode['is_generated']
  725. ];
  726. if ((int)$ace_mode === 1) {
  727. // 获取分镜信息
  728. $segments = DB::table('mp_episode_segments')->where('anime_id', $anime_id)->where('episode_id', $new_episode_id)->orderBy('act_number')
  729. ->select('*')->get()->map(function ($value) {
  730. return (array)$value;
  731. })->toArray();
  732. $segmentsStructure = $this->buildEpisodeActsStructureForAce($segments);
  733. }else {
  734. // 复用已有的分镜数据,按 act 分组(避免重复查询数据库)
  735. $segmentsStructure = $this->buildEpisodeSegmentsStructure($segments_for_insert);
  736. }
  737. $result['acts'] = $segmentsStructure['acts'];
  738. $result['total_duration'] = $segmentsStructure['total_duration'];
  739. return $result;
  740. }
  741. public function episodeVersions($data) {
  742. $anime_id = getProp($data, 'anime_id');
  743. $episode_id = getProp($data, 'episode_id');
  744. if (!$anime_id || !$episode_id) {
  745. Utils::throwError('1002:请选择剧集');
  746. }
  747. $episode_number = DB::table('mp_anime_episodes')->where('anime_id', $anime_id)->where('id', $episode_id)->value('episode_number');
  748. $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) {
  749. return (array)$value;
  750. })->toArray();
  751. if (!$episodes) Utils::throwError('20003:该剧集不存在!');
  752. foreach($episodes as &$episode) {
  753. $episode['version'] = 'V'.$episode['sequence'];
  754. $episode['roles'] = json_decode($episode['roles'], true);
  755. $episode['scenes'] = json_decode($episode['scenes'], true);
  756. // 获取分镜信息
  757. $segments = DB::table('mp_episode_segments')->where('anime_id', $anime_id)->where('episode_id', getProp($episode, 'episode_id'))->orderBy('segment_number')
  758. ->select('*')->get()->map(function ($value) {
  759. return (array)$value;
  760. })->toArray();
  761. // 使用公共方法构建分镜结构
  762. $segmentsStructure = $this->buildEpisodeSegmentsStructure($segments);
  763. $episode['acts'] = $segmentsStructure['acts'];
  764. $episode['total_duration'] = $segmentsStructure['total_duration'];
  765. }
  766. return $episodes;
  767. }
  768. public function bindEpisodeVersion($data) {
  769. $episode_id = getProp($data, 'episode_id');
  770. $episode = DB::table('mp_anime_episodes')->where('id', $episode_id)->first();
  771. if (!$episode) Utils::throwError('20003:该剧集不存在');
  772. $episode = (array)$episode;
  773. if ((int)$episode['is_default'] === 1) return true;
  774. try {
  775. DB::beginTransaction();
  776. // 移除is_default标志
  777. $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')]);
  778. if (!$boolen) {
  779. Utils::throwError('20003:更新失败!');
  780. }
  781. // 绑定副本
  782. $boolen2 = DB::table('mp_anime_episodes')->where('id', $episode_id)->update(['is_default' => 1, 'updated_at'=>date('Y-m-d H:i:s')]);
  783. if (!$boolen2) {
  784. Utils::throwError('20003:绑定失败!');
  785. }
  786. }catch (\Exception $e) {
  787. DB::rollBack();
  788. Utils::throwError('20003:'.$e->getMessage());
  789. }
  790. DB::commit();
  791. return true;
  792. }
  793. public function chatChangeImg($data) {
  794. $segment_id = getProp($data, 'segment_id');
  795. $type = getProp($data, 'type', 1); // 类型: 1.对话改图 2.图片生成
  796. $prompt = getProp($data, 'prompt');
  797. if (!$prompt || !$segment_id) {
  798. Utils::throwError('1002:请输入提示词,并且选择分镜');
  799. }
  800. $segment = DB::table("mp_episode_segments")->where('segment_id', $segment_id)->first();
  801. if (!$segment) Utils::throwError('20003:该分镜不存在!');
  802. if ((int)$type === 1) $ref_img_url = getProp($segment, 'img_url');
  803. else $ref_img_url = '';
  804. // $ref_img_url = '';
  805. if (empty($prompt)) {
  806. if (empty($ref_img_url)) {
  807. $prompt = getProp($segment, 'segment_content');
  808. }else {
  809. $prompt = '请根据图片生成';
  810. }
  811. }
  812. $anime_id = getProp($segment, 'anime_id');
  813. $episode_id = getProp($segment, 'episode_id');
  814. $episode_number = getProp($segment, 'episode_number');
  815. $episode = DB::table('mp_anime_episodes')->where('id', $episode_id)->first();
  816. $ratio = getProp($data, 'ratio');
  817. if (!$ratio) {
  818. $ratio = getProp($episode, 'ratio');
  819. if (!$ratio) $ratio = '9:16';
  820. }
  821. $art_style = getProp($episode, 'art_style');
  822. if ($art_style) {
  823. $prompt = "美术风格:{$art_style}\n{$prompt}";
  824. }
  825. $dimensions = $this->getRatioDimensions($ratio);
  826. $width = $dimensions['width'];
  827. $height = $dimensions['height'];
  828. try {
  829. $params = [
  830. 'alias_segment_id' => $segment_id,
  831. 'prompt' => $prompt,
  832. 'ref_img_urls' => !empty($ref_img_url) ? [$ref_img_url] : [],
  833. 'width' => $width,
  834. 'height' => $height
  835. ];
  836. // 优化提示词(不要生成字幕)
  837. $params['prompt'] = "前置要求:图片中不要带有任何对话台词或字幕信息\n".$params['prompt'];
  838. $task = $this->aiImageGenerationService->createImageGenerationTask($params);
  839. $task_id = $task->id;
  840. if (!$task_id) {
  841. Utils::throwError("20003:生成图片失败");
  842. }
  843. // 更新任务ID
  844. $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')]);
  845. if (!$boolen) Utils::throwError('20003:更新任务ID失败');
  846. } catch (\Exception $e) {
  847. Utils::throwError("20003:" . $e->getMessage());
  848. }
  849. // 创建任务之后先暂停10s等待异步任务完成
  850. sleep(10);
  851. $img_url = $this->loopGetPicTaskResult($task_id);
  852. if (!$img_url) Utils::throwError('20003:图片生成中,请稍后刷新');
  853. // 图片生成后新增对话记录
  854. try {
  855. $uid = Site::getUid();
  856. $now = date('Y-m-d H:i:s');
  857. // 使用AI反推图片提示词
  858. $pic_prompt = $this->generateImagePromptFromUrl($img_url);
  859. // 保存对话记录
  860. $records = [
  861. [
  862. 'uid' => $uid,
  863. 'anime_id' => $anime_id,
  864. 'sequence' => $episode_number,
  865. 'role' => 'user',
  866. 'content' => $prompt,
  867. 'segment_id' => $segment_id,
  868. 'pic_task_id' => $task_id,
  869. 'image_url' => '',
  870. 'created_at' => $now,
  871. 'updated_at' => $now
  872. ],
  873. [
  874. 'uid' => $uid,
  875. 'anime_id' => $anime_id,
  876. 'sequence' => $episode_number,
  877. 'role' => 'assistant',
  878. 'content' => $pic_prompt,
  879. 'segment_id' => $segment_id,
  880. 'pic_task_id' => $task_id,
  881. 'image_url' => $img_url,
  882. 'created_at' => $now,
  883. 'updated_at' => $now
  884. ]
  885. ];
  886. DB::table('mp_anime_records')->insert($records);
  887. } catch (\Exception $e) {
  888. // 记录日志但不影响主流程
  889. dLog('anime')->error('保存对话记录失败: ' . $e->getMessage(), [
  890. 'segment_id' => $segment_id,
  891. 'img_url' => $img_url
  892. ]);
  893. logDB('anime', 'error', '保存对话记录失败', [
  894. 'segment_id' => $segment_id,
  895. 'img_url' => $img_url,
  896. 'error' => $e->getMessage()
  897. ]);
  898. }
  899. return $img_url;
  900. }
  901. public function segmentChatHistory($data) {
  902. $segment_id = getProp($data, 'segment_id');
  903. if (!$segment_id) Utils::throwError('20003:请选择分镜!');
  904. $query = DB::table('mp_anime_records')->where('segment_id', $segment_id)->select('role', 'content', 'segment_id', 'image_url', 'video_url', 'video_task_id', 'pic_task_id', 'created_at');
  905. $chat = $query->orderBy('id')->get()->map(function ($value) {
  906. $value = (array)$value;
  907. $value['created_at'] = transDate($value['created_at']);
  908. return $value;
  909. })->toArray();
  910. // 获取历史图片
  911. $url = [];
  912. $pic_history = DB::table('mp_generate_pic_tasks')->where('alias_segment_id', $segment_id)->where('status', 'success')->orderBy('created_at', 'desc')->get();
  913. foreach($pic_history as $task) {
  914. $result_url = getProp($task, 'result_url');
  915. if (is_json($result_url)) {
  916. $url = array_merge($url, json_decode($result_url, true));
  917. }else {
  918. $url[] = $result_url;
  919. }
  920. }
  921. // 获取历史视频
  922. $video_history = DB::table('mp_generate_video_tasks')->where('alias_segment_id', $segment_id)->where('status', 'success')->orderBy('created_at', 'desc')->get();
  923. foreach($video_history as $task) {
  924. $result_url = getProp($task, 'compressed_url');
  925. if (is_json($result_url)) {
  926. $url = array_merge($url, json_decode($result_url, true));
  927. }else {
  928. $url[] = $result_url;
  929. }
  930. }
  931. return compact('chat', 'url');
  932. }
  933. public function changeEpisodeRoles($data) {
  934. $anime_id = getProp($data, 'anime_id');
  935. $episode_id = getProp($data, 'episode_id');
  936. $target_roles = getProp($data, 'roles');
  937. // 删除标志优先取最外层入参 is_deleted,兼容角色对象内部(roles.is_deleted)的传参
  938. $is_deleted = getProp($data, 'is_deleted', getProp($target_roles, 'is_deleted', 0));
  939. // 控制字段不随角色内容写入分集roles存储
  940. if (is_array($target_roles)) {
  941. unset($target_roles['is_deleted']);
  942. }
  943. // 参数验证
  944. if (!$anime_id) Utils::throwError('20003:请提供动漫ID');
  945. if (!$episode_id) Utils::throwError('20003:请提供剧集ID');
  946. if (!$target_roles) Utils::throwError('20003:请提供角色信息');
  947. // 验证剧集是否存在
  948. $episode = DB::table('mp_anime_episodes')
  949. ->where('anime_id', $anime_id)
  950. ->where('id', $episode_id)
  951. ->first();
  952. if (!$episode) Utils::throwError('20003:该剧集不存在');
  953. $roles = json_decode(getProp($episode, 'roles'), true);
  954. // 获取anime信息,检查是否有关联的script_id
  955. $anime = DB::table('mp_animes')->where('id', $anime_id)->first();
  956. if (!$anime) Utils::throwError('20003:动漫不存在');
  957. $script_id = getProp($anime, 'script_id');
  958. $episode_number = getProp($episode, 'episode_number', 1);
  959. $uid = Site::getUid();
  960. $cpid = Site::getCpid();
  961. try {
  962. $target_role_name = getProp($target_roles, 'role');
  963. if (empty($target_role_name)) {
  964. Utils::throwError('20003:角色名称不能为空');
  965. }
  966. // 如果是删除操作
  967. if ($is_deleted == 1) {
  968. // 从角色列表中移除该角色
  969. $roles = array_values(array_filter($roles, function($role) use ($target_role_name) {
  970. return getProp($role, 'role') !== $target_role_name;
  971. }));
  972. // 更新角色列表
  973. $result = DB::table('mp_anime_episodes')
  974. ->where('anime_id', $anime_id)
  975. ->where('id', $episode_id)
  976. ->update([
  977. 'roles' => json_encode($roles, 256),
  978. 'updated_at' => date('Y-m-d H:i:s')
  979. ]);
  980. if ($result === false) {
  981. Utils::throwError('20003:删除角色失败');
  982. }
  983. } else {
  984. // 新增或更新操作
  985. $role_found = false;
  986. $is_new_role = false;
  987. // 查找并更新已存在的角色
  988. foreach($roles as &$role) {
  989. if (getProp($role, 'role') === $target_role_name) {
  990. $role = $target_roles;
  991. $role_found = true;
  992. break;
  993. }
  994. }
  995. // 如果角色不存在,则新增
  996. if (!$role_found) {
  997. $roles[] = $target_roles;
  998. $is_new_role = true;
  999. }
  1000. // 更新角色列表
  1001. $result = DB::table('mp_anime_episodes')
  1002. ->where('anime_id', $anime_id)
  1003. ->where('id', $episode_id)
  1004. ->update([
  1005. 'roles' => json_encode($roles, 256),
  1006. 'updated_at' => date('Y-m-d H:i:s')
  1007. ]);
  1008. if ($result === false) {
  1009. Utils::throwError('20003:更新角色列表失败');
  1010. }
  1011. // 同步更新分镜表中对应主体的音色信息
  1012. $voice_name = getProp($target_roles, 'voice_name');
  1013. $voice_type = getProp($target_roles, 'voice_type');
  1014. $voice_audio_url = getProp($target_roles, 'voice_audio_url');
  1015. DB::table('mp_episode_segments')
  1016. ->where('anime_id', $anime_id)
  1017. ->where('episode_id', $episode_id)
  1018. ->where('voice_actor', $target_role_name)
  1019. ->update([
  1020. 'voice_name' => $voice_name,
  1021. 'voice_type' => $voice_type,
  1022. 'voice_audio_url' => $voice_audio_url,
  1023. 'updated_at' => date('Y-m-d H:i:s')
  1024. ]);
  1025. // 如果有关联的script_id,则同步到mp_products表
  1026. if ($script_id) {
  1027. // 查询剧本信息
  1028. $script = DB::table('mp_scripts')
  1029. ->where('id', $script_id)
  1030. ->where('is_deleted', 0)
  1031. ->first();
  1032. if ($script) {
  1033. $script_name = $script->script_name ?? 'script_' . $script_id;
  1034. $product_name = getProp($target_roles, 'role');
  1035. $pic_prompt = getProp($target_roles, 'pic_prompt', '');
  1036. $url = getProp($target_roles, 'url', '');
  1037. $product_type = 1; // 1=角色
  1038. // 查找或创建以script_name命名的文件夹
  1039. $folder = DB::table('mp_products')
  1040. ->where('cpid', $cpid)
  1041. ->where('type', 2) // 文件夹类型
  1042. ->where('product', $product_type) // 角色类型
  1043. ->where('product_name', $script_name)
  1044. ->where('parent_id', 0)
  1045. ->where('is_deleted', 0)
  1046. ->first();
  1047. if (!$folder) {
  1048. // 创建文件夹
  1049. $folder_id = DB::table('mp_products')->insertGetId([
  1050. 'user_id' => $uid,
  1051. 'cpid' => $cpid,
  1052. 'type' => 2, // 文件夹
  1053. 'product' => $product_type, // 角色类型
  1054. 'parent_id' => 0,
  1055. 'level' => 1,
  1056. 'product_name' => $script_name,
  1057. 'sort_order' => time(),
  1058. 'is_deleted' => 0,
  1059. 'created_at' => date('Y-m-d H:i:s'),
  1060. 'updated_at' => date('Y-m-d H:i:s')
  1061. ]);
  1062. } else {
  1063. $folder_id = $folder->id;
  1064. }
  1065. // 查找该文件夹下是否已存在同名资产
  1066. $existing_product = DB::table('mp_products')
  1067. ->where('cpid', $cpid)
  1068. ->where('type', 1) // 资产类型
  1069. ->where('product', $product_type)
  1070. ->where('parent_id', $folder_id)
  1071. ->where('product_name', $product_name)
  1072. ->where('is_deleted', 0)
  1073. ->first();
  1074. if ($existing_product) {
  1075. // 更新已存在的资产
  1076. $updateData = [
  1077. 'pic_task_status' => '生成成功',
  1078. ];
  1079. if ($pic_prompt) $updateData['pic_prompt'] = $pic_prompt;
  1080. if ($url) $updateData['url'] = $url;
  1081. // 处理versions字段
  1082. $versions = getProp($target_roles, 'versions', []);
  1083. if ($versions && is_array($versions)) {
  1084. $updateData['versions'] = json_encode($versions, 256);
  1085. }
  1086. $updateData['updated_at'] = date('Y-m-d H:i:s');
  1087. DB::table('mp_products')
  1088. ->where('id', $existing_product->id)
  1089. ->update($updateData);
  1090. $product_id = $existing_product->id;
  1091. } else {
  1092. // 创建新资产
  1093. $versions = getProp($target_roles, 'versions', []);
  1094. $product_id = DB::table('mp_products')->insertGetId([
  1095. 'user_id' => $uid,
  1096. 'cpid' => $cpid,
  1097. 'type' => 1, // 资产
  1098. 'product' => $product_type, // 角色
  1099. 'parent_id' => $folder_id,
  1100. 'level' => 2,
  1101. 'product_name' => $product_name,
  1102. 'url' => $url,
  1103. 'pic_prompt' => $pic_prompt,
  1104. 'versions' => is_array($versions) ? json_encode($versions, 256) : '[]',
  1105. 'sort_order' => time(),
  1106. 'is_deleted' => 0,
  1107. 'pic_task_status' => '生成成功',
  1108. 'created_at' => date('Y-m-d H:i:s'),
  1109. 'updated_at' => date('Y-m-d H:i:s')
  1110. ]);
  1111. }
  1112. // 建立或更新绑定关系
  1113. $existing_mapping = DB::table('mp_script_product_mappings')
  1114. ->where('script_id', $script_id)
  1115. ->where('product_id', $product_id)
  1116. ->where('episode_number', $episode_number)
  1117. ->first();
  1118. if (!$existing_mapping) {
  1119. // 创建绑定关系
  1120. DB::table('mp_script_product_mappings')->insert([
  1121. 'script_id' => $script_id,
  1122. 'product_id' => $product_id,
  1123. 'episode_number' => $episode_number,
  1124. 'created_at' => date('Y-m-d H:i:s'),
  1125. 'updated_at' => date('Y-m-d H:i:s')
  1126. ]);
  1127. }
  1128. }
  1129. }
  1130. }
  1131. } catch (\Exception $e) {
  1132. dLog('anime')->error('更新剧集角色失败', [
  1133. 'anime_id' => $anime_id,
  1134. 'episode_id' => $episode_id,
  1135. 'error' => $e->getMessage()
  1136. ]);
  1137. Utils::throwError('20003:更新角色列表失败 ' . $e->getMessage());
  1138. }
  1139. return true;
  1140. }
  1141. public function changeEpisodeScenes($data) {
  1142. $anime_id = getProp($data, 'anime_id');
  1143. $episode_id = getProp($data, 'episode_id');
  1144. $target_scenes = getProp($data, 'scenes');
  1145. // 删除标志优先取最外层入参 is_deleted,兼容场景对象内部(scenes.is_deleted)的传参
  1146. $is_deleted = getProp($data, 'is_deleted', getProp($target_scenes, 'is_deleted', 0));
  1147. // 控制字段不随场景内容写入分集scenes存储
  1148. if (is_array($target_scenes)) {
  1149. unset($target_scenes['is_deleted']);
  1150. }
  1151. // 参数验证
  1152. if (!$anime_id) Utils::throwError('20003:请提供动漫ID');
  1153. if (!$episode_id) Utils::throwError('20003:请提供剧集ID');
  1154. if (!$target_scenes) Utils::throwError('20003:请提供场景信息');
  1155. // 验证剧集是否存在
  1156. $episode = DB::table('mp_anime_episodes')
  1157. ->where('anime_id', $anime_id)
  1158. ->where('id', $episode_id)
  1159. ->first();
  1160. if (!$episode) Utils::throwError('20003:该剧集不存在');
  1161. $scenes = json_decode(getProp($episode, 'scenes'), true);
  1162. // 获取anime信息,检查是否有关联的script_id
  1163. $anime = DB::table('mp_animes')->where('id', $anime_id)->first();
  1164. if (!$anime) Utils::throwError('20003:动漫不存在');
  1165. $script_id = getProp($anime, 'script_id');
  1166. $episode_number = getProp($episode, 'episode_number', 1);
  1167. $uid = Site::getUid();
  1168. $cpid = Site::getCpid();
  1169. try {
  1170. $target_scene_name = getProp($target_scenes, 'scene');
  1171. if (empty($target_scene_name)) {
  1172. Utils::throwError('20003:场景名称不能为空');
  1173. }
  1174. // 如果是删除操作
  1175. if ($is_deleted == 1) {
  1176. // 从场景列表中移除该场景
  1177. $scenes = array_values(array_filter($scenes, function($scene) use ($target_scene_name) {
  1178. return getProp($scene, 'scene') !== $target_scene_name;
  1179. }));
  1180. // 更新场景列表
  1181. $result = DB::table('mp_anime_episodes')
  1182. ->where('anime_id', $anime_id)
  1183. ->where('id', $episode_id)
  1184. ->update([
  1185. 'scenes' => json_encode($scenes, 256),
  1186. 'updated_at' => date('Y-m-d H:i:s')
  1187. ]);
  1188. if ($result === false) {
  1189. Utils::throwError('20003:删除场景失败');
  1190. }
  1191. } else {
  1192. // 新增或更新操作
  1193. $scene_found = false;
  1194. $is_new_scene = false;
  1195. // 查找并更新已存在的场景
  1196. foreach($scenes as &$scene) {
  1197. if (getProp($scene, 'scene') === $target_scene_name) {
  1198. $scene = $target_scenes;
  1199. $scene_found = true;
  1200. break;
  1201. }
  1202. }
  1203. // 如果场景不存在,则新增
  1204. if (!$scene_found) {
  1205. $scenes[] = $target_scenes;
  1206. $is_new_scene = true;
  1207. }
  1208. // 更新场景列表
  1209. $result = DB::table('mp_anime_episodes')
  1210. ->where('anime_id', $anime_id)
  1211. ->where('id', $episode_id)
  1212. ->update([
  1213. 'scenes' => json_encode($scenes, 256),
  1214. 'updated_at' => date('Y-m-d H:i:s')
  1215. ]);
  1216. if ($result === false) {
  1217. Utils::throwError('20003:更新场景列表失败');
  1218. }
  1219. // 如果有关联的script_id,则同步到mp_products表
  1220. if ($script_id) {
  1221. // 查询剧本信息
  1222. $script = DB::table('mp_scripts')
  1223. ->where('id', $script_id)
  1224. ->where('is_deleted', 0)
  1225. ->first();
  1226. if ($script) {
  1227. $script_name = $script->script_name ?? 'script_' . $script_id;
  1228. $product_name = getProp($target_scenes, 'scene');
  1229. $pic_prompt = getProp($target_scenes, 'pic_prompt', '');
  1230. $url = getProp($target_scenes, 'url', '');
  1231. $product_type = 2; // 2=场景
  1232. // 查找或创建以script_name命名的文件夹
  1233. $folder = DB::table('mp_products')
  1234. ->where('cpid', $cpid)
  1235. ->where('type', 2) // 文件夹类型
  1236. ->where('product', $product_type) // 场景类型
  1237. ->where('product_name', $script_name)
  1238. ->where('parent_id', 0)
  1239. ->where('is_deleted', 0)
  1240. ->first();
  1241. if (!$folder) {
  1242. // 创建文件夹
  1243. $folder_id = DB::table('mp_products')->insertGetId([
  1244. 'user_id' => $uid,
  1245. 'cpid' => $cpid,
  1246. 'type' => 2, // 文件夹
  1247. 'product' => $product_type, // 场景类型
  1248. 'parent_id' => 0,
  1249. 'level' => 1,
  1250. 'product_name' => $script_name,
  1251. 'sort_order' => time(),
  1252. 'is_deleted' => 0,
  1253. 'created_at' => date('Y-m-d H:i:s'),
  1254. 'updated_at' => date('Y-m-d H:i:s')
  1255. ]);
  1256. } else {
  1257. $folder_id = $folder->id;
  1258. }
  1259. // 查找该文件夹下是否已存在同名资产
  1260. $existing_product = DB::table('mp_products')
  1261. ->where('cpid', $cpid)
  1262. ->where('type', 1) // 资产类型
  1263. ->where('product', $product_type)
  1264. ->where('parent_id', $folder_id)
  1265. ->where('product_name', $product_name)
  1266. ->where('is_deleted', 0)
  1267. ->first();
  1268. if ($existing_product) {
  1269. // 更新已存在的资产
  1270. $updateData = [
  1271. 'pic_task_status' => '生成成功'
  1272. ];
  1273. if ($pic_prompt) $updateData['pic_prompt'] = $pic_prompt;
  1274. if ($url) $updateData['url'] = $url;
  1275. // 处理versions字段
  1276. $versions = getProp($target_scenes, 'versions', []);
  1277. if ($versions && is_array($versions)) {
  1278. $updateData['versions'] = json_encode($versions, 256);
  1279. }
  1280. $updateData['updated_at'] = date('Y-m-d H:i:s');
  1281. DB::table('mp_products')
  1282. ->where('id', $existing_product->id)
  1283. ->update($updateData);
  1284. $product_id = $existing_product->id;
  1285. } else {
  1286. // 创建新资产
  1287. $versions = getProp($target_scenes, 'versions', []);
  1288. $product_id = DB::table('mp_products')->insertGetId([
  1289. 'user_id' => $uid,
  1290. 'cpid' => $cpid,
  1291. 'type' => 1, // 资产
  1292. 'product' => $product_type, // 场景
  1293. 'parent_id' => $folder_id,
  1294. 'level' => 2,
  1295. 'product_name' => $product_name,
  1296. 'url' => $url,
  1297. 'pic_prompt' => $pic_prompt,
  1298. 'versions' => is_array($versions) ? json_encode($versions, 256) : '[]',
  1299. 'sort_order' => time(),
  1300. 'is_deleted' => 0,
  1301. 'pic_task_status' => '生成成功',
  1302. 'created_at' => date('Y-m-d H:i:s'),
  1303. 'updated_at' => date('Y-m-d H:i:s')
  1304. ]);
  1305. }
  1306. // 建立或更新绑定关系
  1307. $existing_mapping = DB::table('mp_script_product_mappings')
  1308. ->where('script_id', $script_id)
  1309. ->where('product_id', $product_id)
  1310. ->where('episode_number', $episode_number)
  1311. ->first();
  1312. if (!$existing_mapping) {
  1313. // 创建绑定关系
  1314. DB::table('mp_script_product_mappings')->insert([
  1315. 'script_id' => $script_id,
  1316. 'product_id' => $product_id,
  1317. 'episode_number' => $episode_number,
  1318. 'created_at' => date('Y-m-d H:i:s'),
  1319. 'updated_at' => date('Y-m-d H:i:s')
  1320. ]);
  1321. }
  1322. }
  1323. }
  1324. }
  1325. } catch (\Exception $e) {
  1326. dLog('anime')->error('更新剧集场景失败', [
  1327. 'anime_id' => $anime_id,
  1328. 'episode_id' => $episode_id,
  1329. 'error' => $e->getMessage()
  1330. ]);
  1331. Utils::throwError('20003:更新场景列表失败 ' . $e->getMessage());
  1332. }
  1333. return true;
  1334. }
  1335. public function changeEpisodeProps($data) {
  1336. $anime_id = getProp($data, 'anime_id');
  1337. $episode_id = getProp($data, 'episode_id');
  1338. $target_props = getProp($data, 'props');
  1339. // 删除标志优先取最外层入参 is_deleted,兼容道具对象内部(props.is_deleted)的传参
  1340. $is_deleted = getProp($data, 'is_deleted', getProp($target_props, 'is_deleted', 0));
  1341. // 控制字段不随道具内容写入分集props存储
  1342. if (is_array($target_props)) {
  1343. unset($target_props['is_deleted']);
  1344. }
  1345. // 参数验证
  1346. if (!$anime_id) Utils::throwError('20003:请提供动漫ID');
  1347. if (!$episode_id) Utils::throwError('20003:请提供剧集ID');
  1348. if (!$target_props) Utils::throwError('20003:请提供道具信息');
  1349. // 验证剧集是否存在
  1350. $episode = DB::table('mp_anime_episodes')
  1351. ->where('anime_id', $anime_id)
  1352. ->where('id', $episode_id)
  1353. ->first();
  1354. if (!$episode) Utils::throwError('20003:该剧集不存在');
  1355. $props = json_decode(getProp($episode, 'props'), true);
  1356. // 获取anime信息,检查是否有关联的script_id
  1357. $anime = DB::table('mp_animes')->where('id', $anime_id)->first();
  1358. if (!$anime) Utils::throwError('20003:动漫不存在');
  1359. $script_id = getProp($anime, 'script_id');
  1360. $episode_number = getProp($episode, 'episode_number', 1);
  1361. $uid = Site::getUid();
  1362. $cpid = Site::getCpid();
  1363. try {
  1364. $target_prop_name = getProp($target_props, 'prop');
  1365. if (empty($target_prop_name)) {
  1366. Utils::throwError('20003:道具名称不能为空');
  1367. }
  1368. // 如果是删除操作
  1369. if ($is_deleted == 1) {
  1370. // 从道具列表中移除该道具
  1371. $props = array_values(array_filter($props, function($prop) use ($target_prop_name) {
  1372. return getProp($prop, 'prop') !== $target_prop_name;
  1373. }));
  1374. // 更新道具列表
  1375. $result = DB::table('mp_anime_episodes')
  1376. ->where('anime_id', $anime_id)
  1377. ->where('id', $episode_id)
  1378. ->update([
  1379. 'props' => json_encode($props, 256),
  1380. 'updated_at' => date('Y-m-d H:i:s')
  1381. ]);
  1382. if ($result === false) {
  1383. Utils::throwError('20003:删除道具失败');
  1384. }
  1385. } else {
  1386. // 新增或更新操作
  1387. $prop_found = false;
  1388. $is_new_prop = false;
  1389. // 查找并更新已存在的道具
  1390. foreach($props as &$prop) {
  1391. if (getProp($prop, 'prop') === $target_prop_name) {
  1392. $prop = $target_props;
  1393. $prop_found = true;
  1394. break;
  1395. }
  1396. }
  1397. // 如果道具不存在,则新增
  1398. if (!$prop_found) {
  1399. $props[] = $target_props;
  1400. $is_new_prop = true;
  1401. }
  1402. // 更新道具列表
  1403. $result = DB::table('mp_anime_episodes')
  1404. ->where('anime_id', $anime_id)
  1405. ->where('id', $episode_id)
  1406. ->update([
  1407. 'props' => json_encode($props, 256),
  1408. 'updated_at' => date('Y-m-d H:i:s')
  1409. ]);
  1410. if ($result === false) {
  1411. Utils::throwError('20003:更新道具列表失败');
  1412. }
  1413. // 如果有关联的script_id,则同步到mp_products表
  1414. if ($script_id) {
  1415. // 查询剧本信息
  1416. $script = DB::table('mp_scripts')
  1417. ->where('id', $script_id)
  1418. ->where('is_deleted', 0)
  1419. ->first();
  1420. if ($script) {
  1421. $script_name = $script->script_name ?? 'script_' . $script_id;
  1422. $product_name = getProp($target_props, 'prop');
  1423. $pic_prompt = getProp($target_props, 'pic_prompt', '');
  1424. $url = getProp($target_props, 'url', '');
  1425. $product_type = 3; // 3=道具
  1426. // 查找或创建以script_name命名的文件夹
  1427. $folder = DB::table('mp_products')
  1428. ->where('cpid', $cpid)
  1429. ->where('type', 2) // 文件夹类型
  1430. ->where('product', $product_type) // 道具类型
  1431. ->where('product_name', $script_name)
  1432. ->where('parent_id', 0)
  1433. ->where('is_deleted', 0)
  1434. ->first();
  1435. if (!$folder) {
  1436. // 创建文件夹
  1437. $folder_id = DB::table('mp_products')->insertGetId([
  1438. 'user_id' => $uid,
  1439. 'cpid' => $cpid,
  1440. 'type' => 2, // 文件夹
  1441. 'product' => $product_type, // 道具类型
  1442. 'parent_id' => 0,
  1443. 'level' => 1,
  1444. 'product_name' => $script_name,
  1445. 'sort_order' => time(),
  1446. 'is_deleted' => 0,
  1447. 'created_at' => date('Y-m-d H:i:s'),
  1448. 'updated_at' => date('Y-m-d H:i:s')
  1449. ]);
  1450. } else {
  1451. $folder_id = $folder->id;
  1452. }
  1453. // 查找该文件夹下是否已存在同名资产
  1454. $existing_product = DB::table('mp_products')
  1455. ->where('cpid', $cpid)
  1456. ->where('type', 1) // 资产类型
  1457. ->where('product', $product_type)
  1458. ->where('parent_id', $folder_id)
  1459. ->where('product_name', $product_name)
  1460. ->where('is_deleted', 0)
  1461. ->first();
  1462. if ($existing_product) {
  1463. // 更新已存在的资产
  1464. $updateData = [
  1465. 'pic_task_status' => '生成成功'
  1466. ];
  1467. if ($pic_prompt) $updateData['pic_prompt'] = $pic_prompt;
  1468. if ($url) $updateData['url'] = $url;
  1469. // 处理versions字段
  1470. $versions = getProp($target_props, 'versions', []);
  1471. if ($versions && is_array($versions)) {
  1472. $updateData['versions'] = json_encode($versions, 256);
  1473. }
  1474. $updateData['updated_at'] = date('Y-m-d H:i:s');
  1475. DB::table('mp_products')
  1476. ->where('id', $existing_product->id)
  1477. ->update($updateData);
  1478. $product_id = $existing_product->id;
  1479. } else {
  1480. // 创建新资产
  1481. $versions = getProp($target_props, 'versions', []);
  1482. $product_id = DB::table('mp_products')->insertGetId([
  1483. 'user_id' => $uid,
  1484. 'cpid' => $cpid,
  1485. 'type' => 1, // 资产
  1486. 'product' => $product_type, // 道具
  1487. 'parent_id' => $folder_id,
  1488. 'level' => 2,
  1489. 'product_name' => $product_name,
  1490. 'url' => $url,
  1491. 'pic_prompt' => $pic_prompt,
  1492. 'versions' => is_array($versions) ? json_encode($versions, 256) : '[]',
  1493. 'sort_order' => time(),
  1494. 'is_deleted' => 0,
  1495. 'pic_task_status' => '生成成功',
  1496. 'created_at' => date('Y-m-d H:i:s'),
  1497. 'updated_at' => date('Y-m-d H:i:s')
  1498. ]);
  1499. }
  1500. // 建立或更新绑定关系
  1501. $existing_mapping = DB::table('mp_script_product_mappings')
  1502. ->where('script_id', $script_id)
  1503. ->where('product_id', $product_id)
  1504. ->where('episode_number', $episode_number)
  1505. ->first();
  1506. if (!$existing_mapping) {
  1507. // 创建绑定关系
  1508. DB::table('mp_script_product_mappings')->insert([
  1509. 'script_id' => $script_id,
  1510. 'product_id' => $product_id,
  1511. 'episode_number' => $episode_number,
  1512. 'created_at' => date('Y-m-d H:i:s'),
  1513. 'updated_at' => date('Y-m-d H:i:s')
  1514. ]);
  1515. }
  1516. }
  1517. }
  1518. }
  1519. } catch (\Exception $e) {
  1520. dLog('anime')->error('更新剧集道具失败', [
  1521. 'anime_id' => $anime_id,
  1522. 'episode_id' => $episode_id,
  1523. 'error' => $e->getMessage()
  1524. ]);
  1525. Utils::throwError('20003:更新道具列表失败 ' . $e->getMessage());
  1526. }
  1527. return true;
  1528. }
  1529. public function editSegment($data) {
  1530. $segment_id = getProp($data, 'segment_id');
  1531. $segment_content = getProp($data, 'segment_content');
  1532. $image_url = getProp($data, 'image_url');
  1533. $video_url = getProp($data, 'video_url');
  1534. // 参数验证
  1535. if (!$segment_id) Utils::throwError('20003:请提供分镜ID');
  1536. // 验证分镜是否存在
  1537. $segment = DB::table('mp_episode_segments')
  1538. ->where('segment_id', $segment_id)
  1539. ->first();
  1540. if (!$segment) Utils::throwError('20003:该分镜不存在');
  1541. $dubTaskId = 0;
  1542. try {
  1543. DB::beginTransaction();
  1544. // 准备更新数据
  1545. $update_data = [
  1546. 'updated_at' => date('Y-m-d H:i:s')
  1547. ];
  1548. if ($segment_content) {
  1549. // 先将segment_content赋值到update_data
  1550. $update_data['segment_content'] = $segment_content;
  1551. // 使用现有方法分析segment_content,提取各个字段
  1552. $this->handleSegmentContent($update_data);
  1553. // 如果有对话内容,创建视频配音合成任务
  1554. $dialogue = getProp($update_data, 'dialogue');
  1555. if (!empty($dialogue)) {
  1556. $now = date('Y-m-d H:i:s');
  1557. $generate_json = [
  1558. 'text' => $dialogue,
  1559. 'role' => getProp($update_data, 'voice_actor'),
  1560. 'voice_type' => getProp($update_data, 'voice_type'),
  1561. 'voice_name' => getProp($update_data, 'voice_name'),
  1562. 'emotion' => getProp($update_data, 'emotion'),
  1563. 'emotion_type' => getProp($update_data, 'emotion_type'),
  1564. 'gender' => getProp($update_data, 'gender'),
  1565. 'speed_ratio' => getProp($update_data, 'speed_ratio', 0),
  1566. 'loudness_ratio' => getProp($update_data, 'loudness_ratio', 0),
  1567. 'emotion_scale' => getProp($update_data, 'emotion_scale', 0),
  1568. 'pitch' => getProp($update_data, 'pitch', 0),
  1569. ];
  1570. // 插入视频配音合成任务
  1571. $dubTaskId = DB::table('mp_dub_video_tasks')->insertGetId([
  1572. 'alias_segment_id' => $segment_id,
  1573. 'generate_status' => '执行中',
  1574. 'audio_url' => '',
  1575. 'generate_json' => json_encode($generate_json, 256),
  1576. 'created_at' => $now,
  1577. 'updated_at' => $now,
  1578. ]);
  1579. if (!$dubTaskId) {
  1580. Utils::throwError('20003:创建配音任务失败!');
  1581. }
  1582. $update_data['audio_url'] = '';
  1583. } else {
  1584. // dialogue为空时,直接写入默认音频信息
  1585. $update_data['audio_url'] = 'https://zw-audiobook.tos-cn-beijing.volces.com/effects/ellipses_2s.mp3';
  1586. $update_data['audio_duration'] = 2.0;
  1587. $update_data['subtitle_info'] = json_encode(['duration' => 2.0, 'words' => []], 256);
  1588. }
  1589. }
  1590. if ($image_url) {
  1591. $update_data['img_url'] = $image_url;
  1592. // 同时写入一个简单的图片生成任务
  1593. $pic_task = [
  1594. 'alias_segment_id' => $segment_id,
  1595. 'ref_img_url' => json_encode([]),
  1596. 'status' => 'success',
  1597. 'result_url' => json_encode([$image_url], 256),
  1598. 'model' => '',
  1599. 'created_at' => date('Y-m-d H:i:s'),
  1600. 'updated_at' => date('Y-m-d H:i:s'),
  1601. ];
  1602. DB::table('mp_generate_pic_tasks')->insert($pic_task);
  1603. }
  1604. if ($video_url) {
  1605. $update_data['origin_video_url'] = $video_url;
  1606. $compressed_video_url = compressVideo($video_url);
  1607. $update_data['current_type'] = 2;
  1608. $update_data['video_url'] = $compressed_video_url ?: $video_url;
  1609. // 同时写入一个简单的视频生成任务
  1610. $video_task = [
  1611. 'alias_segment_id' => $segment_id,
  1612. 'status' => 'success',
  1613. 'result_url' => $update_data['origin_video_url'],
  1614. 'compressed_url' => $update_data['video_url'],
  1615. 'created_at' => date('Y-m-d H:i:s'),
  1616. 'updated_at' => date('Y-m-d H:i:s'),
  1617. ];
  1618. DB::table('mp_generate_video_tasks')->insert($video_task);
  1619. }
  1620. // 更新分镜信息
  1621. $result = DB::table('mp_episode_segments')
  1622. ->where('segment_id', $segment_id)
  1623. ->update($update_data);
  1624. if ($result === false) {
  1625. Utils::throwError('20003:更新分镜剧本失败');
  1626. }
  1627. DB::commit();
  1628. // 如果有创建音频生成任务则调用API
  1629. if ($dubTaskId) {
  1630. // 请求远程服务器执行生成
  1631. $client = new Client(['timeout' => 300, 'verify' => false]);
  1632. $result = $client->get("http://122.9.129.83:5000/api/anime/genAudio?taskId={$dubTaskId}");
  1633. $response = $result->getBody()->getContents();
  1634. $response_arr = json_decode($response, true);
  1635. if (!isset($response_arr['code']) || (int)$response_arr['code'] !== 0) {
  1636. $error_msg = isset($response_arr['msg']) ? $response_arr['msg'] : '未知错误';
  1637. dLog('anime')->error('火山生成音频失败', ['error' => $error_msg, 'task_id' => $dubTaskId, 'segment_id'=>$segment_id]);
  1638. logDB('anime', 'error', '火山生成音频失败', ['error' => $error_msg, 'task_id' => $dubTaskId, 'segment_id'=>$segment_id]);
  1639. Utils::throwError('20003:火山生成音频失败');
  1640. }
  1641. }
  1642. return true;
  1643. } catch (\Exception $e) {
  1644. DB::rollBack();
  1645. dLog('anime')->error('更新分镜剧本失败', [
  1646. 'segment_id' => $segment_id,
  1647. 'error' => $e->getMessage()
  1648. ]);
  1649. Utils::throwError('20003:更新分镜剧本失败 ' . $e->getMessage());
  1650. }
  1651. }
  1652. public function batchSetSegmentPics($data) {
  1653. $anime_id = getProp($data, 'anime_id');
  1654. $episode_id = getProp($data, 'episode_id');
  1655. $ratio = getProp($data, 'ratio');
  1656. $dimensions = $this->getRatioDimensions($ratio);
  1657. $width = $dimensions['width'];
  1658. $height = $dimensions['height'];
  1659. if (!$anime_id || !$episode_id) {
  1660. Utils::throwError('1002:请选择剧集');
  1661. }
  1662. // 获取剧集信息
  1663. $episode = DB::table('mp_anime_episodes')
  1664. ->where('anime_id', $anime_id)
  1665. ->where('id', $episode_id)
  1666. ->where('is_default', 1)
  1667. ->select('id as episode_id', 'anime_id', 'episode_number', 'roles', 'scenes', 'image_model')
  1668. ->first();
  1669. if (!$episode) {
  1670. Utils::throwError('20003:该剧集不存在');
  1671. }
  1672. $model = getProp($data, 'model');
  1673. if (!$model) {
  1674. $model = getProp($episode, 'image_model');
  1675. if (!$model) {
  1676. // episode表也没有,使用默认值
  1677. $model = 'gpt-image-2';
  1678. }
  1679. }
  1680. // 验证模型是否在可用模型表中
  1681. if (!DB::table('mp_image_models')->where('model', $model)->where('is_enabled', 1)->exists()) {
  1682. $model = 'gpt-image-2';
  1683. }
  1684. $roles = json_decode(getProp($episode, 'roles'), true);
  1685. if (!$roles) {
  1686. Utils::throwError('20003:角色信息格式错误');
  1687. }
  1688. // 构建角色名称到参考图的映射
  1689. $role_map = [];
  1690. foreach ($roles as $role) {
  1691. $role_name = getProp($role, 'role');
  1692. $role_url = getProp($role, 'url');
  1693. if (!empty($role_name) && !empty($role_url)) {
  1694. // // 处理角色名称,去除装扮后缀(如:许芸-校服装 -> 许芸)- 修复中文乱码问题(弃用,容易产生重复图片)
  1695. // $base_name = preg_replace('/[--].*$/u', '', $role_name);
  1696. // $role_map[$base_name] = $role_url;
  1697. // 同时保存完整名称的映射
  1698. $role_map[$role_name] = $role_url;
  1699. }
  1700. }
  1701. $scenes = json_decode(getProp($episode, 'roles'), true);
  1702. if (!$scenes) {
  1703. Utils::throwError('20003:场景信息格式错误');
  1704. }
  1705. // 构建角色名称到参考图的映射
  1706. $scene_map = [];
  1707. foreach ($scenes as $scene) {
  1708. $scene_name = getProp($scene, 'scene');
  1709. $scene_url = getProp($scene, 'url');
  1710. if (!empty($scene_name) && !empty($scene_url)) {
  1711. $scene_map[$scene_name] = $scene_url;
  1712. }
  1713. }
  1714. // 获取所有分镜信息
  1715. $segments = DB::table('mp_episode_segments')
  1716. ->where('anime_id', $anime_id)
  1717. ->where('episode_id', $episode_id)
  1718. ->whereNotIn('pic_task_status', ['已完成', '生成中'])
  1719. ->orderBy('segment_number')
  1720. ->get()
  1721. ->toArray();
  1722. if (empty($segments)) {
  1723. Utils::throwError('20003:所有分镜图片已完成或正在生成中');
  1724. }
  1725. // 保存图片比例
  1726. DB::table('mp_anime_episodes')->where('id', $episode_id)->update(['ratio' => $ratio, 'updated_at' => date('Y-m-d H:i:s')]);
  1727. $updated_segments = [];
  1728. $failed_segments = [];
  1729. // 批量为每个分镜生成图片任务
  1730. foreach ($segments as $segment) {
  1731. $segment_id = $segment->segment_id;
  1732. $segment_content = $segment->segment_content;
  1733. if (empty($segment_content)) {
  1734. $failed_segments[] = [
  1735. 'segment_id' => $segment_id,
  1736. 'error' => '分镜内容为空'
  1737. ];
  1738. continue;
  1739. }
  1740. try {
  1741. $dubTaskId = 0;
  1742. // 解析分镜内容,提取画面描述作为主要提示词
  1743. $prompt = $segment_content;
  1744. $ref_img_urls = [];
  1745. // 分镜场景
  1746. $scene = getProp($segment, 'scene');
  1747. $matched_scene = '';
  1748. if (isset($scene_map[$scene])) {
  1749. $img_index = count($ref_img_urls) + 1;
  1750. $prompt = "场景:$scene(图$img_index)\n$prompt";
  1751. $ref_img_urls[] = $scene_map[$scene];
  1752. $matched_scene = $scene;
  1753. }
  1754. // 分镜角色
  1755. $characters = getProp($segment, 'characters');
  1756. $characters = str_replace(['、', ',', ';'], ',', $characters);
  1757. $roles = explode(',', $characters);
  1758. // 从分镜内容中提取涉及的角色
  1759. $segment_characters = $this->extractCharactersFromSegment($segment_content, array_keys($role_map), $roles);
  1760. // 获取匹配角色的参考图
  1761. foreach ($segment_characters as $character) {
  1762. if (isset($role_map[$character])) {
  1763. // 将$prompt中出现的角色替换成角色(图1、2、3,序号是$ref_img_urls的个数加1)
  1764. $img_index = count($ref_img_urls) + 1;
  1765. $prompt = str_replace($character, $character . '(图' . $img_index . ')', $prompt);
  1766. $ref_img_urls[] = $role_map[$character];
  1767. }
  1768. }
  1769. // 如果没有找到匹配的角色参考图,不使用参考图
  1770. if (empty($ref_img_urls)) {
  1771. $ref_img_urls = [];
  1772. }
  1773. // 准备生成任务参数
  1774. $params = [
  1775. 'model' => $model,
  1776. 'alias_segment_id' => $segment_id,
  1777. 'prompt' => $prompt,
  1778. 'ref_img_urls' => $ref_img_urls,
  1779. 'width' => $width,
  1780. 'height' => $height,
  1781. ];
  1782. // 优化提示词(不要生成字幕)
  1783. $params['prompt'] = "前置要求:图片中不要带有任何对话台词或字幕信息\n".$params['prompt'];
  1784. // $task_id = mt_rand(100000, 999999);
  1785. // 调用AI图片生成服务
  1786. $task = $this->aiImageGenerationService->createImageGenerationTask($params);
  1787. $task_id = $task->id;
  1788. if (!$task_id) {
  1789. $failed_segments[] = [
  1790. 'segment_id' => $segment_id,
  1791. 'error' => '创建生成任务失败'
  1792. ];
  1793. continue;
  1794. }
  1795. $update_data = [
  1796. 'pic_task_id' => $task_id,
  1797. 'pic_task_status' => '生成中',
  1798. 'audio_url' => '',
  1799. 'updated_at' => date('Y-m-d H:i:s')
  1800. ];
  1801. // 如果有对话内容,创建视频配音合成任务
  1802. $dialogue = getProp($segment, 'dialogue');
  1803. if (!empty($dialogue)) {
  1804. $now = date('Y-m-d H:i:s');
  1805. $generate_json = [
  1806. 'text' => $dialogue,
  1807. 'role' => getProp($segment, 'voice_actor'),
  1808. 'voice_type' => getProp($segment, 'voice_type'),
  1809. 'voice_name' => getProp($segment, 'voice_name'),
  1810. 'emotion' => getProp($segment, 'emotion'),
  1811. 'emotion_type' => getProp($segment, 'emotion_type'),
  1812. 'gender' => getProp($segment, 'gender'),
  1813. 'speed_ratio' => getProp($segment, 'speed_ratio', 0),
  1814. 'loudness_ratio' => getProp($segment, 'loudness_ratio', 0),
  1815. 'emotion_scale' => getProp($segment, 'emotion_scale', 0),
  1816. 'pitch' => getProp($segment, 'pitch', 0),
  1817. ];
  1818. // 插入视频配音合成任务
  1819. $dubTaskId = DB::table('mp_dub_video_tasks')->insertGetId([
  1820. 'alias_segment_id' => $segment_id,
  1821. 'generate_status' => '执行中',
  1822. 'audio_url' => '',
  1823. 'generate_json' => json_encode($generate_json, 256),
  1824. 'created_at' => $now,
  1825. 'updated_at' => $now,
  1826. ]);
  1827. if (!$dubTaskId) {
  1828. dLog('anime')->error('火山生成音频失败', ['segment_id' => $segment_id, 'generate_json'=>$generate_json]);
  1829. logDB('anime', 'error', '火山生成音频失败', ['segment_id' => $segment_id, 'generate_json'=>$generate_json]);
  1830. // Utils::throwError('20003:创建配音任务失败!');
  1831. }
  1832. } else {
  1833. // dialogue为空时,直接写入默认音频信息到分镜表
  1834. $update_data['audio_url'] = 'https://zw-audiobook.tos-cn-beijing.volces.com/effects/ellipses_2s.mp3';
  1835. $update_data['audio_duration'] = 2.0;
  1836. $update_data['subtitle_info'] = json_encode(['duration' => 2.0, 'words' => []], 256);
  1837. }
  1838. // 更新分镜的任务信息
  1839. $update_result = DB::table('mp_episode_segments')
  1840. ->where('segment_id', $segment_id)
  1841. ->update($update_data);
  1842. // 如果是第一集的首帧图片,则存入待更新数组
  1843. if ($update_result && (int)getProp($segment, 'episode_number') === 1 && (int)getProp($segment, 'segment_number') === 1) {
  1844. Redis::sadd('anime_first_frame_urls', $segment_id);
  1845. }
  1846. if ($update_result) {
  1847. $updated_segments[] = [
  1848. 'segment_id' => $segment_id,
  1849. 'task_id' => $task_id,
  1850. 'status' => '生成中',
  1851. 'matched_scenes' => $matched_scene,
  1852. 'matched_roles' => $segment_characters,
  1853. 'ref_urls_count' => count($ref_img_urls)
  1854. ];
  1855. } else {
  1856. $failed_segments[] = [
  1857. 'segment_id' => $segment_id,
  1858. 'error' => '更新分镜任务状态失败'
  1859. ];
  1860. }
  1861. if ($dubTaskId) {
  1862. sleep(1);
  1863. // 请求远程服务器执行生成
  1864. $client = new Client(['timeout' => 300, 'verify' => false]);
  1865. $result = $client->get("http://122.9.129.83:5000/api/anime/genAudio?taskId={$dubTaskId}");
  1866. $response = $result->getBody()->getContents();
  1867. $response_arr = json_decode($response, true);
  1868. if (!isset($response_arr['code']) || (int)$response_arr['code'] !== 0) {
  1869. $error_msg = isset($response_arr['msg']) ? $response_arr['msg'] : '未知错误';
  1870. dLog('anime')->error('火山生成音频失败', ['error' => $error_msg, 'task_id' => $dubTaskId, 'segment_id' => $segment_id]);
  1871. logDB('anime', 'error', '火山生成音频失败', ['error' => $error_msg, 'task_id' => $dubTaskId, 'segment_id' => $segment_id]);
  1872. }
  1873. }
  1874. } catch (\Exception $e) {
  1875. $failed_segments[] = [
  1876. 'segment_id' => $segment_id,
  1877. 'error' => $e->getMessage()
  1878. ];
  1879. }
  1880. }
  1881. // 更新剧集生成状态
  1882. if (!empty($updated_segments)) {
  1883. DB::table('mp_anime_episodes')
  1884. ->where('id', $episode_id)
  1885. ->update([
  1886. 'is_generated' => 1,
  1887. 'updated_at' => date('Y-m-d H:i:s')
  1888. ]);
  1889. }
  1890. return [
  1891. 'success_count' => count($updated_segments),
  1892. 'failed_count' => count($failed_segments),
  1893. 'success_segments' => $updated_segments,
  1894. 'failed_segments' => $failed_segments,
  1895. 'total_segments' => count($segments)
  1896. ];
  1897. }
  1898. public function reGenerateSegment($data) {
  1899. $segment_id = getProp($data, 'segment_id');
  1900. $segment = DB::table('mp_episode_segments')->where('segment_id', $segment_id)->first();
  1901. $anime_id = getProp($segment, 'anime_id');
  1902. $episode_id = getProp($segment, 'episode_id');
  1903. $episode_number = getProp($segment, 'episode_number');
  1904. $segment_content = getProp($data, 'segment_content');
  1905. $ratio = getProp($data, 'ratio');
  1906. if (!$ratio) {
  1907. $ratio = DB::table('mp_anime_episodes')->where('id', $episode_id)->value('ratio');
  1908. if (!$ratio) $ratio = '9:16';
  1909. }
  1910. $dimensions = $this->getRatioDimensions($ratio);
  1911. $width = $dimensions['width'];
  1912. $height = $dimensions['height'];
  1913. if (!$anime_id || !$episode_id) {
  1914. Utils::throwError('1002:请选择分镜');
  1915. }
  1916. // 使用文生文模型重新解析segment_content
  1917. if (!empty($segment_content)) {
  1918. $segment_content = $this->parseSegmentContentWithAI($segment_content);
  1919. }
  1920. // 获取动漫的角色信息(包含参考图)
  1921. $anime = DB::table('mp_animes')
  1922. ->where('id', $anime_id)
  1923. ->select('roles', 'scenes')
  1924. ->first();
  1925. if (!$anime || !$anime->roles) {
  1926. Utils::throwError('20003:未找到角色信息');
  1927. }
  1928. $roles = json_decode($anime->roles, true);
  1929. if (!$roles) {
  1930. Utils::throwError('20003:角色信息格式错误');
  1931. }
  1932. // 构建角色名称到参考图的映射
  1933. $role_map = [];
  1934. foreach ($roles as $role) {
  1935. $role_name = getProp($role, 'role');
  1936. $role_url = getProp($role, 'url');
  1937. if (!empty($role_name) && !empty($role_url)) {
  1938. $role_map[$role_name] = $role_url;
  1939. }
  1940. }
  1941. $scenes = json_decode($anime->scenes, true);
  1942. if (!$scenes) {
  1943. Utils::throwError('20003:角色信息格式错误');
  1944. }
  1945. // 构建角色名称到参考图的映射
  1946. $scene_map = [];
  1947. foreach ($scenes as $scene) {
  1948. $scene_name = getProp($scene, 'scene');
  1949. $scene_url = getProp($scene, 'url');
  1950. if (!empty($scene_name) && !empty($scene_url)) {
  1951. $scene_map[$scene_name] = $scene_url;
  1952. }
  1953. }
  1954. $segment_id = $segment->segment_id;
  1955. $original_segment_content = $segment->segment_content;
  1956. // 如果传入了新的segment_content,使用新的内容,否则使用原有内容
  1957. $final_segment_content = !empty($segment_content) ? $segment_content : $original_segment_content;
  1958. if (empty($final_segment_content)) {
  1959. Utils::throwError('20003:分镜内容不存在,请填写内容后重试');
  1960. }
  1961. try {
  1962. $dubTaskId = 0;
  1963. // 分镜剧本数组
  1964. $update_data = [
  1965. 'segment_content' => $final_segment_content,
  1966. 'pic_task_status' => '生成中',
  1967. 'updated_at' => date('Y-m-d H:i:s')
  1968. ];
  1969. // 解析分镜内容,提取画面描述作为主要提示词
  1970. $prompt = $final_segment_content;
  1971. $ref_img_urls = [];
  1972. // 分镜场景
  1973. $scene = getProp($data, 'scene');
  1974. if ($scene) {
  1975. $matched_scene = '';
  1976. if (isset($scene_map[$scene])) {
  1977. $img_index = count($ref_img_urls) + 1;
  1978. $prompt = "场景:$scene(图$img_index)\n$prompt";
  1979. $ref_img_urls[] = $scene_map[$scene];
  1980. $matched_scene = $scene;
  1981. }
  1982. $update_data['scene'] = $scene;
  1983. }
  1984. // 分镜角色
  1985. $characters = getProp($data, 'characters');
  1986. if ($characters) {
  1987. $update_data['characters'] = $characters;
  1988. $characters = str_replace(['、', ',', ';'], ',', $characters);
  1989. $characters = explode(',', $characters);
  1990. // 从分镜内容中提取涉及的角色
  1991. $segment_characters = $this->extractCharactersFromSegment($final_segment_content, array_keys($role_map), $characters);
  1992. // 获取匹配角色的参考图
  1993. foreach ($segment_characters as $character) {
  1994. if (isset($role_map[$character])) {
  1995. // 将$prompt中出现的角色替换成角色(图1、2、3,序号是$ref_img_urls的个数加1)
  1996. $img_index = count($ref_img_urls) + 1;
  1997. $prompt = str_replace($character, $character . '(图' . $img_index . ')', $prompt);
  1998. $ref_img_urls[] = $role_map[$character];
  1999. }
  2000. }
  2001. }
  2002. // 如果没有找到匹配的角色参考图,不使用参考图
  2003. if (empty($ref_img_urls)) {
  2004. $ref_img_urls = [];
  2005. }
  2006. // 准备生成任务参数
  2007. $params = [
  2008. 'alias_segment_id' => $segment_id,
  2009. 'prompt' => $prompt,
  2010. 'ref_img_urls' => $ref_img_urls,
  2011. 'width' => $width,
  2012. 'height' => $height,
  2013. ];
  2014. // 优化提示词(不要生成字幕)
  2015. $params['prompt'] = "前置要求:图片中不要带有任何对话台词或字幕信息\n".$params['prompt'];
  2016. // 调用AI图片生成服务
  2017. $task = $this->aiImageGenerationService->createImageGenerationTask($params);
  2018. $task_id = $task->id;
  2019. if (!$task_id) {
  2020. Utils::throwError('20003:创建生成任务失败!');
  2021. }
  2022. $update_data['pic_task_id'] = $task_id;
  2023. // 更新分镜剧本信息
  2024. $this->handleSegmentContent($update_data);
  2025. // 如果有对话内容,创建视频配音合成任务(有更改分镜内容时创建)
  2026. if ($segment_content) {
  2027. $dialogue = getProp($update_data, 'dialogue');
  2028. if (!empty($dialogue)) {
  2029. $now = date('Y-m-d H:i:s');
  2030. $generate_json = [
  2031. 'text' => $dialogue,
  2032. 'role' => getProp($update_data, 'voice_actor'),
  2033. 'voice_type' => getProp($update_data, 'voice_type'),
  2034. 'voice_name' => getProp($update_data, 'voice_name'),
  2035. 'emotion' => getProp($update_data, 'emotion'),
  2036. 'emotion_type' => getProp($update_data, 'emotion_type'),
  2037. 'gender' => getProp($update_data, 'gender'),
  2038. 'speed_ratio' => getProp($update_data, 'speed_ratio', 0),
  2039. 'loudness_ratio' => getProp($update_data, 'loudness_ratio', 0),
  2040. 'emotion_scale' => getProp($update_data, 'emotion_scale', 0),
  2041. 'pitch' => getProp($update_data, 'pitch', 0),
  2042. ];
  2043. // 插入视频配音合成任务
  2044. $dubTaskId = DB::table('mp_dub_video_tasks')->insertGetId([
  2045. 'alias_segment_id' => $segment_id,
  2046. 'generate_status' => '执行中',
  2047. 'audio_url' => '',
  2048. 'generate_json' => json_encode($generate_json, 256),
  2049. 'created_at' => date('Y-m-d H:i:s'),
  2050. 'updated_at' => date('Y-m-d H:i:s'),
  2051. ]);
  2052. if (!$dubTaskId) {
  2053. Utils::throwError('20003:创建配音任务失败!');
  2054. }
  2055. $update_data['audio_url'] = '';
  2056. } else {
  2057. // dialogue为空时,直接写入默认音频信息
  2058. $update_data['audio_url'] = 'https://zw-audiobook.tos-cn-beijing.volces.com/effects/ellipses_2s.mp3';
  2059. $update_data['audio_duration'] = 2.0;
  2060. $update_data['subtitle_info'] = json_encode(['duration' => 2.0, 'words' => []], 256);
  2061. }
  2062. }
  2063. $boolen = DB::table('mp_episode_segments')
  2064. ->where('segment_id', $segment_id)
  2065. ->update($update_data);
  2066. // 如果是第一集的首帧图片,则存入待更新数组
  2067. if ($boolen && (int)getProp($segment, 'episode_number') === 1 && (int)getProp($segment, 'segment_number') === 1) {
  2068. Redis::sadd('anime_first_frame_urls', $segment_id);
  2069. }
  2070. if ($dubTaskId) {
  2071. // 请求远程服务器执行生成
  2072. $client = new Client(['timeout' => 300, 'verify' => false]);
  2073. $result = $client->get("http://122.9.129.83:5000/api/anime/genAudio?taskId={$dubTaskId}");
  2074. $response = $result->getBody()->getContents();
  2075. $response_arr = json_decode($response, true);
  2076. if (!isset($response_arr['code']) || (int)$response_arr['code'] !== 0) {
  2077. $error_msg = isset($response_arr['msg']) ? $response_arr['msg'] : '未知错误';
  2078. dLog('anime')->error('火山生成音频失败', ['error' => $error_msg, 'task_id' => $dubTaskId]);
  2079. logDB('anime', 'error', '火山生成音频失败', ['error' => $error_msg, 'task_id' => $dubTaskId]);
  2080. Utils::throwError('20003:火山生成音频失败');
  2081. }
  2082. }
  2083. } catch (\Exception $e) {
  2084. $failed_segments[] = [
  2085. 'segment_id' => $segment_id,
  2086. 'error' => $e->getMessage()
  2087. ];
  2088. }
  2089. // 创建任务之后先暂停10s等待异步任务完成
  2090. sleep(10);
  2091. $img_url = $this->loopGetPicTaskResult($task_id);
  2092. if (!$img_url) Utils::throwError('20003:图片生成中,请稍后刷新');
  2093. // 图片生成后新增对话记录
  2094. try {
  2095. $uid = Site::getUid();
  2096. $now = date('Y-m-d H:i:s');
  2097. // 使用AI反推图片提示词
  2098. $pic_prompt = $this->generateImagePromptFromUrl($img_url);
  2099. // 保存对话记录
  2100. $records = [
  2101. [
  2102. 'uid' => $uid,
  2103. 'anime_id' => $anime_id,
  2104. 'sequence' => $episode_number,
  2105. 'role' => 'user',
  2106. 'content' => '重新生成',
  2107. 'segment_id' => $segment_id,
  2108. 'pic_task_id' => $task_id,
  2109. 'image_url' => '',
  2110. 'created_at' => $now,
  2111. 'updated_at' => $now
  2112. ],
  2113. [
  2114. 'uid' => $uid,
  2115. 'anime_id' => $anime_id,
  2116. 'sequence' => $episode_number,
  2117. 'role' => 'assistant',
  2118. 'content' => $pic_prompt,
  2119. 'segment_id' => $segment_id,
  2120. 'pic_task_id' => $task_id,
  2121. 'image_url' => $img_url,
  2122. 'created_at' => $now,
  2123. 'updated_at' => $now
  2124. ]
  2125. ];
  2126. DB::table('mp_anime_records')->insert($records);
  2127. } catch (\Exception $e) {
  2128. // 记录日志但不影响主流程
  2129. dLog('anime')->error('保存对话记录失败: ' . $e->getMessage(), [
  2130. 'segment_id' => $segment_id,
  2131. 'img_url' => $img_url
  2132. ]);
  2133. }
  2134. return $img_url;
  2135. }
  2136. public function addSegment($data) {
  2137. $prev_segment_id = getProp($data, 'prev_segment_id');
  2138. $img_url = getProp($data, 'img_url');
  2139. $video_url = getProp($data, 'video_url');
  2140. $segment = DB::table('mp_episode_segments')->where('segment_id', $prev_segment_id)->first();
  2141. if (!$segment) Utils::throwError('20003:该分镜不存在');
  2142. $anime_id = getProp($segment, 'anime_id');
  2143. $episode_id = getProp($segment, 'episode_id');
  2144. $episode_number = getProp($segment, 'episode_number');
  2145. $segment_number = getProp($segment, 'segment_number');
  2146. $new_segment_number = $segment_number + 1;
  2147. $segment_id = date('YmdHis') . mt_rand(1000, 9999) . str_pad($new_segment_number, 3, "0", STR_PAD_LEFT);
  2148. // 分镜剧本数组
  2149. $insert_data = [
  2150. 'anime_id' => $anime_id,
  2151. 'episode_id' => $episode_id,
  2152. 'episode_number' => $episode_number,
  2153. 'act_number' => getProp($segment, 'act_number'),
  2154. 'act_title' => getProp($segment, 'act_title'),
  2155. 'segment_id' => $segment_id,
  2156. 'segment_number' => $new_segment_number,
  2157. 'segment_content' => '',
  2158. 'img_url' => '',
  2159. 'video_url' => '',
  2160. 'created_at' => date('Y-m-d H:i:s'),
  2161. 'updated_at' => date('Y-m-d H:i:s')
  2162. ];
  2163. if ($img_url) $insert_data['img_url'] = $img_url;
  2164. if ($video_url) {
  2165. $insert_data['origin_video_url'] = $video_url;
  2166. $insert_data['current_type'] = 2;
  2167. $compressed_video_url = compressVideo($video_url);
  2168. $insert_data['video_url'] = $compressed_video_url ?: $video_url;
  2169. }
  2170. try {
  2171. DB::beginTransaction();
  2172. // 先更新序号
  2173. DB::table('mp_episode_segments')->where('anime_id', $anime_id)->where('episode_id', $episode_id)->where('segment_number', '>', $segment_number)->increment('segment_number');
  2174. $id = DB::table('mp_episode_segments')->insertGetId($insert_data);
  2175. if (!$id) {
  2176. Utils::throwError('20003:新增分镜失败!');
  2177. }
  2178. }catch (\Exception $e) {
  2179. DB::rollBack();
  2180. Utils::throwError('20003:'.$e->getMessage());
  2181. }
  2182. DB::commit();
  2183. $segment = DB::table('mp_episode_segments')->where('id', $id)->first();
  2184. $segment = $segment ? (array)$segment : [];
  2185. return $segment;
  2186. // 以下代码暂弃用
  2187. $anime_id = getProp($segment, 'anime_id');
  2188. $episode_id = getProp($segment, 'episode_id');
  2189. $episode_number = getProp($segment, 'episode_number');
  2190. $segment_number = getProp($segment, 'segment_number');
  2191. $segment_content = getProp($data, 'segment_content');
  2192. $img_url = getProp($data, 'img_url');
  2193. $video_url = getProp($data, 'video_url');
  2194. $ratio = getProp($data, 'ratio');
  2195. $dimensions = $this->getRatioDimensions($ratio);
  2196. $width = $dimensions['width'];
  2197. $height = $dimensions['height'];
  2198. if (!$anime_id || !$episode_id) {
  2199. Utils::throwError('1002:请选择分镜');
  2200. }
  2201. // 使用文生文模型重新解析segment_content
  2202. if (!empty($segment_content)) {
  2203. $segment_content = $this->parseSegmentContentWithAI($segment_content);
  2204. }
  2205. // 获取动漫的角色信息(包含参考图)
  2206. $anime = DB::table('mp_animes')
  2207. ->where('id', $anime_id)
  2208. ->select('roles', 'scenes')
  2209. ->first();
  2210. if (!$anime || !$anime->roles) {
  2211. Utils::throwError('20003:未找到角色信息');
  2212. }
  2213. $roles = json_decode($anime->roles, true);
  2214. if (!$roles) {
  2215. Utils::throwError('20003:角色信息格式错误');
  2216. }
  2217. // 构建角色名称到参考图的映射
  2218. $role_map = [];
  2219. foreach ($roles as $role) {
  2220. $role_name = getProp($role, 'role');
  2221. $role_url = getProp($role, 'url');
  2222. if (!empty($role_name) && !empty($role_url)) {
  2223. $role_map[$role_name] = $role_url;
  2224. }
  2225. }
  2226. $scenes = json_decode($anime->scenes, true);
  2227. if (!$scenes) {
  2228. Utils::throwError('20003:角色信息格式错误');
  2229. }
  2230. // 构建角色名称到参考图的映射
  2231. $scene_map = [];
  2232. foreach ($scenes as $scene) {
  2233. $scene_name = getProp($scene, 'scene');
  2234. $scene_url = getProp($scene, 'url');
  2235. if (!empty($scene_name) && !empty($scene_url)) {
  2236. $scene_map[$scene_name] = $scene_url;
  2237. }
  2238. }
  2239. $segment_id = $segment->segment_id;
  2240. $original_segment_content = $segment->segment_content;
  2241. // 如果传入了新的segment_content,使用新的内容,否则使用原有内容
  2242. $final_segment_content = !empty($segment_content) ? $segment_content : $original_segment_content;
  2243. if (empty($final_segment_content)) {
  2244. Utils::throwError('20003:分镜内容不存在,请填写内容后重试');
  2245. }
  2246. try {
  2247. $dubTaskId = 0;
  2248. DB::beginTransaction();
  2249. $new_segment_number = $segment_number + 1;
  2250. $segment_id = date('YmdHis') . mt_rand(1000, 9999) . str_pad($new_segment_number, 3, "0", STR_PAD_LEFT);
  2251. // 分镜剧本数组
  2252. $insert_data = [
  2253. 'anime_id' => $anime_id,
  2254. 'episode_id' => $episode_id,
  2255. 'episode_number' => $episode_number,
  2256. 'act_number' => getProp($segment, 'act_number'),
  2257. 'act_title' => getProp($segment, 'act_title'),
  2258. 'segment_id' => $segment_id,
  2259. 'segment_number' => $new_segment_number,
  2260. 'segment_content' => $final_segment_content,
  2261. 'img_url' => $img_url,
  2262. 'video_url' => $video_url,
  2263. 'created_at' => date('Y-m-d H:i:s'),
  2264. 'updated_at' => date('Y-m-d H:i:s')
  2265. ];
  2266. // 更新分镜剧本信息
  2267. $this->handleSegmentContent($insert_data);
  2268. // 如果有对话内容,创建视频配音合成任务
  2269. $dialogue = getProp($insert_data, 'dialogue');
  2270. if (!empty($dialogue)) {
  2271. $now = date('Y-m-d H:i:s');
  2272. $generate_json = [
  2273. 'text' => $dialogue,
  2274. 'role' => getProp($insert_data, 'voice_actor'),
  2275. 'voice_type' => getProp($insert_data, 'voice_type'),
  2276. 'voice_name' => getProp($insert_data, 'voice_name'),
  2277. 'emotion' => getProp($insert_data, 'emotion'),
  2278. 'emotion_type' => getProp($insert_data, 'emotion_type'),
  2279. 'gender' => getProp($insert_data, 'gender'),
  2280. 'speed_ratio' => getProp($insert_data, 'speed_ratio', 0),
  2281. 'loudness_ratio' => getProp($insert_data, 'loudness_ratio', 0),
  2282. 'emotion_scale' => getProp($insert_data, 'emotion_scale', 0),
  2283. 'pitch' => getProp($insert_data, 'pitch', 0),
  2284. ];
  2285. // 插入视频配音合成任务
  2286. $dubTaskId = DB::table('mp_dub_video_tasks')->insertGetId([
  2287. 'alias_segment_id' => $segment_id,
  2288. 'generate_status' => '执行中',
  2289. 'audio_url' => '',
  2290. 'generate_json' => json_encode($generate_json, 256),
  2291. 'created_at' => $now,
  2292. 'updated_at' => $now,
  2293. ]);
  2294. if (!$dubTaskId) {
  2295. Utils::throwError('20003:创建配音任务失败!');
  2296. }
  2297. $insert_data['audio_url'] = '';
  2298. } else {
  2299. // dialogue为空时,直接写入默认音频信息
  2300. $insert_data['audio_url'] = 'https://zw-audiobook.tos-cn-beijing.volces.com/effects/ellipses_2s.mp3';
  2301. $insert_data['audio_duration'] = 2.0;
  2302. $insert_data['subtitle_info'] = json_encode(['duration' => 2.0, 'words' => []], 256);
  2303. }
  2304. // 如果没有上传图片则使用当前描述进行生成
  2305. if (!$img_url) {
  2306. // 解析分镜内容,提取画面描述作为主要提示词
  2307. $prompt = $final_segment_content;
  2308. $ref_img_urls = [];
  2309. // 分镜场景
  2310. $scene = getProp($insert_data, 'scene');
  2311. if ($scene) {
  2312. $matched_scene = '';
  2313. if (isset($scene_map[$scene])) {
  2314. $img_index = count($ref_img_urls) + 1;
  2315. $prompt = "场景:$scene(图$img_index)\n$prompt";
  2316. $ref_img_urls[] = $scene_map[$scene];
  2317. $matched_scene = $scene;
  2318. }
  2319. $update_data['scene'] = $scene;
  2320. }
  2321. // 分镜角色
  2322. $characters = getProp($insert_data, 'characters');
  2323. if ($characters) {
  2324. $update_data['characters'] = $characters;
  2325. $characters = str_replace(['、', ',', ';'], ',', $characters);
  2326. $characters = explode(',', $characters);
  2327. // 从分镜内容中提取涉及的角色
  2328. $segment_characters = $this->extractCharactersFromSegment($final_segment_content, array_keys($role_map), $characters);
  2329. // 获取匹配角色的参考图
  2330. foreach ($segment_characters as $character) {
  2331. if (isset($role_map[$character])) {
  2332. // 将$prompt中出现的角色替换成角色(图1、2、3,序号是$ref_img_urls的个数加1)
  2333. $img_index = count($ref_img_urls) + 1;
  2334. $prompt = str_replace($character, $character . '(图' . $img_index . ')', $prompt);
  2335. $ref_img_urls[] = $role_map[$character];
  2336. }
  2337. }
  2338. }
  2339. // 如果没有找到匹配的角色参考图,不使用参考图
  2340. if (empty($ref_img_urls)) {
  2341. $ref_img_urls = [];
  2342. }
  2343. // 准备生成任务参数
  2344. $params = [
  2345. 'alias_segment_id' => $segment_id,
  2346. 'prompt' => $prompt,
  2347. 'ref_img_urls' => $ref_img_urls,
  2348. 'width' => $width,
  2349. 'height' => $height,
  2350. ];
  2351. // 调用AI图片生成服务
  2352. $task = $this->aiImageGenerationService->createImageGenerationTask($params);
  2353. $task_id = $task->id;
  2354. // $task_id = 'whatever';
  2355. if (!$task_id) {
  2356. Utils::throwError('20003:创建生成任务失败!');
  2357. }
  2358. $insert_data['pic_task_status'] = '生成中';
  2359. $insert_data['pic_task_id'] = $task_id;
  2360. }
  2361. // 先更新序号
  2362. DB::table('mp_episode_segments')->where('anime_id', $anime_id)->where('episode_id', $episode_id)->where('segment_number', '>', $segment_number)->increment('segment_number');
  2363. $boolen = DB::table('mp_episode_segments')->insert($insert_data);
  2364. if (!$boolen) {
  2365. Utils::throwError('20003:新增分镜失败!');
  2366. }
  2367. // 如果是第一集的首帧图片,则存入待更新数组
  2368. if ($boolen && (int)$episode_number === 1 && (int)$new_segment_number === 1) {
  2369. Redis::sadd('anime_first_frame_urls', $segment_id);
  2370. }
  2371. if ($dubTaskId) {
  2372. // 请求远程服务器执行生成
  2373. $client = new Client(['timeout' => 300, 'verify' => false]);
  2374. $result = $client->get("http://122.9.129.83:5000/api/anime/genAudio?taskId={$dubTaskId}");
  2375. $response = $result->getBody()->getContents();
  2376. $response_arr = json_decode($response, true);
  2377. if (!isset($response_arr['code']) || (int)$response_arr['code'] !== 0) {
  2378. $error_msg = isset($response_arr['msg']) ? $response_arr['msg'] : '未知错误';
  2379. dLog('anime')->error('火山生成音频失败', ['error' => $error_msg, 'task_id' => $dubTaskId]);
  2380. Utils::throwError('20003:火山生成音频失败');
  2381. }
  2382. }
  2383. } catch (\Exception $e) {
  2384. DB::rollBack();
  2385. Utils::throwError('20003:'.$e->getMessage());
  2386. }
  2387. DB::commit();
  2388. // 创建任务之后先暂停10s等待异步任务完成
  2389. sleep(10);
  2390. if (isset($task_id)) $img_url = $this->loopGetPicTaskResult($task_id);
  2391. if (!$img_url) Utils::throwError('20003:图片生成中,请稍后刷新');
  2392. $segment = DB::table('mp_episode_segments')->where('segment_id', $segment_id)->first();
  2393. $segment = $segment ? (array)$segment : [];
  2394. return $segment;
  2395. }
  2396. public function copySegment($data) {
  2397. $segment_id = getProp($data, 'segment_id');
  2398. $segment = DB::table('mp_episode_segments')->where('segment_id', $segment_id)->first();
  2399. if (!$segment) Utils::throwError('20003:请选择分镜');
  2400. $anime_id = getProp($segment, 'anime_id');
  2401. $episode_id = getProp($segment, 'episode_id');
  2402. $episode_number = getProp($segment, 'episode_number');
  2403. $segment_number = getProp($segment, 'segment_number');
  2404. $new_segment_id = 0;
  2405. try {
  2406. DB::beginTransaction();
  2407. $segment = (array)$segment;
  2408. unset($segment['id']);
  2409. $segment['segment_number'] += 1;
  2410. $segment['segment_id'] = date('YmdHis') . mt_rand(1000, 9999) . str_pad($segment['segment_number'], 3, "0", STR_PAD_LEFT);
  2411. // $segment['pic_task_id'] = $segment['pic_task_status'] = $segment['video_task_id'] = $segment['video_task_status'] = '';
  2412. $segment['created_at'] = $segment['updated_at'] = date('Y-m-d H:i:s');
  2413. // 更新其他分镜序号
  2414. DB::table('mp_episode_segments')->where('anime_id', $anime_id)->where('episode_id', $episode_id)->where('segment_number', '>', $segment_number)->increment('segment_number');
  2415. // 复制分镜
  2416. $id = DB::table('mp_episode_segments')->insertGetId($segment);
  2417. if (!$id) {
  2418. Utils::throwError('20003:复制分镜失败');
  2419. }
  2420. }catch (\Exception $e) {
  2421. DB::rollBack();
  2422. Utils::throwError('20003:'.$e->getMessage());
  2423. }
  2424. DB::commit();
  2425. $segment = DB::table('mp_episode_segments')->where('id', $id)->first();
  2426. $segment = $segment ? (array)$segment : [];
  2427. return $segment;
  2428. }
  2429. public function moveSegment($data) {
  2430. $segment_id = getProp($data, 'segment_id');
  2431. $target_segment_id = getProp($data, 'target_segment_id');
  2432. // 获取源分镜信息
  2433. $source_segment = DB::table('mp_episode_segments')->where('segment_id', $segment_id)->first();
  2434. if (!$source_segment) Utils::throwError('20003:请选择分镜');
  2435. // 获取目标分镜信息
  2436. $target_segment = DB::table('mp_episode_segments')->where('segment_id', $target_segment_id)->first();
  2437. if (!$target_segment) Utils::throwError('20003:目标分镜不存在');
  2438. $anime_id = getProp($source_segment, 'anime_id');
  2439. $episode_id = getProp($source_segment, 'episode_id');
  2440. $episode_number = getProp($source_segment, 'episode_number');
  2441. $source_segment_number = getProp($source_segment, 'segment_number');
  2442. $target_segment_number = getProp($target_segment, 'segment_number');
  2443. // 验证源分镜和目标分镜必须属于同一个动漫的同一集
  2444. $target_anime_id = getProp($target_segment, 'anime_id');
  2445. $target_episode_number = getProp($target_segment, 'episode_number');
  2446. if ($anime_id != $target_anime_id || $episode_number != $target_episode_number) {
  2447. Utils::throwError('20003:只能在同一动漫的同一集内移动分镜');
  2448. }
  2449. // 如果源分镜和目标分镜相同,无需移动
  2450. if ($source_segment_number == $target_segment_number) {
  2451. return true;
  2452. }
  2453. try {
  2454. DB::beginTransaction();
  2455. if ($source_segment_number < $target_segment_number) {
  2456. // 向后移动:源分镜移动到目标分镜之后
  2457. // 1. 将源分镜和目标分镜之间的所有分镜序号减1
  2458. DB::table('mp_episode_segments')
  2459. ->where('anime_id', $anime_id)
  2460. ->where('episode_id', $episode_id)
  2461. ->where('segment_number', '>', $source_segment_number)
  2462. ->where('segment_number', '<=', $target_segment_number)
  2463. ->decrement('segment_number');
  2464. // 2. 将源分镜移动到目标分镜之后
  2465. $new_segment_number = $target_segment_number;
  2466. } else {
  2467. // 向前移动:源分镜移动到目标分镜之后
  2468. // 1. 将目标分镜之后到源分镜之前的所有分镜序号加1
  2469. DB::table('mp_episode_segments')
  2470. ->where('anime_id', $anime_id)
  2471. ->where('episode_id', $episode_id)
  2472. ->where('segment_number', '>', $target_segment_number)
  2473. ->where('segment_number', '<', $source_segment_number)
  2474. ->increment('segment_number');
  2475. // 2. 将源分镜移动到目标分镜之后
  2476. $new_segment_number = $target_segment_number + 1;
  2477. }
  2478. // 3. 更新源分镜的序号
  2479. $update_result = DB::table('mp_episode_segments')
  2480. ->where('segment_id', $segment_id)
  2481. ->update([
  2482. 'segment_number' => $new_segment_number,
  2483. 'updated_at' => date('Y-m-d H:i:s')
  2484. ]);
  2485. if (!$update_result) {
  2486. Utils::throwError('20003:更新分镜序号失败');
  2487. }
  2488. DB::commit();
  2489. return true;
  2490. } catch (\Exception $e) {
  2491. DB::rollBack();
  2492. Utils::throwError('20003:' . $e->getMessage());
  2493. }
  2494. }
  2495. public function delSegment($data) {
  2496. $segment_id = getProp($data, 'segment_id');
  2497. $segment = DB::table('mp_episode_segments')->where('segment_id', $segment_id)->first();
  2498. if (!$segment) Utils::throwError('20003:请选择分镜');
  2499. $anime_id = getProp($segment, 'anime_id');
  2500. $episode_id = getProp($segment, 'episode_id');
  2501. $episode_number = getProp($segment, 'episode_number');
  2502. $segment_number = getProp($segment, 'segment_number');
  2503. try {
  2504. DB::beginTransaction();
  2505. // 删除分镜
  2506. $boolen = DB::table('mp_episode_segments')->where('segment_id', $segment_id)->delete();
  2507. if (!$boolen) {
  2508. Utils::throwError('20003:删除分镜失败');
  2509. }
  2510. // 更新其他分镜序号
  2511. DB::table('mp_episode_segments')->where('anime_id', $anime_id)->where('episode_id', $episode_id)->where('segment_number', '>', $segment_number)->decrement('segment_number');
  2512. }catch (\Exception $e) {
  2513. DB::rollBack();
  2514. Utils::throwError('20003:'.$e->getMessage());
  2515. }
  2516. DB::commit();
  2517. return true;
  2518. }
  2519. public function applySegment($data) {
  2520. $segment_id = getProp($data, 'segment_id');
  2521. $url = getProp($data, 'url');
  2522. if (!$segment_id) Utils::throwError('20003:请选择分镜');
  2523. if (!$url) Utils::throwError('20003:URL不能为空');
  2524. // 获取URL的文件扩展名
  2525. $urlPath = parse_url($url, PHP_URL_PATH);
  2526. $extension = strtolower(pathinfo($urlPath, PATHINFO_EXTENSION));
  2527. // 定义图片和视频的扩展名
  2528. $imageExtensions = ['jpg', 'jpeg', 'png', 'gif', 'bmp', 'webp', 'svg'];
  2529. $videoExtensions = ['mp4', 'avi', 'mov', 'wmv', 'flv', 'mkv', 'webm', 'm4v'];
  2530. // 判断是图片还是视频
  2531. $updateData = ['updated_at' => date('Y-m-d H:i:s')];
  2532. if (in_array($extension, $imageExtensions)) {
  2533. // 图片类型
  2534. $updateData['img_url'] = $url;
  2535. $updateData['current_type'] = 1;
  2536. } elseif (in_array($extension, $videoExtensions)) {
  2537. // 视频类型
  2538. $updateData['video_url'] = $url;
  2539. $updateData['current_type'] = 2;
  2540. } else {
  2541. Utils::throwError('20003:不支持的文件类型');
  2542. }
  2543. // 更新分镜表
  2544. $result = DB::table('mp_episode_segments')
  2545. ->where('segment_id', $segment_id)
  2546. ->update($updateData);
  2547. if (!$result) {
  2548. Utils::throwError('20003:更新分镜失败');
  2549. }
  2550. return true;
  2551. }
  2552. public function segmentHistory($data) {
  2553. $segment_id = getProp($data, 'segment_id');
  2554. // 获取历史图片
  2555. $pics = [];
  2556. $pic_history = DB::table('mp_generate_pic_tasks')->where('alias_segment_id', $segment_id)->where('status', 'success')->orderBy('created_at', 'desc')->get();
  2557. foreach($pic_history as $task) {
  2558. $result_url = getProp($task, 'result_url');
  2559. if (is_json($result_url)) {
  2560. $pics = array_merge($pics, json_decode($result_url, true));
  2561. }else {
  2562. $pics[] = $result_url;
  2563. }
  2564. }
  2565. // 获取历史视频
  2566. $videos = [];
  2567. $video_history = DB::table('mp_generate_video_tasks')->where('alias_segment_id', $segment_id)->where('status', 'success')->orderBy('created_at', 'desc')->get();
  2568. foreach($video_history as $task) {
  2569. $result_url = getProp($task, 'result_url');
  2570. if (is_json($result_url)) {
  2571. $videos = array_merge($videos, json_decode($result_url, true));
  2572. }else {
  2573. $videos[] = $result_url;
  2574. }
  2575. }
  2576. return compact('pics', 'videos');
  2577. }
  2578. public function addAct($data) {
  2579. $prev_act_id = getProp($data, 'prev_act_id');
  2580. $act_title = getProp($data, 'act_title', '');
  2581. $act_content = getProp($data, 'act_content', '');
  2582. $act_duration = getProp($data, 'act_duration', 5);
  2583. $video_url = getProp($data, 'video_url');
  2584. // 根据prev_act_id获取记录
  2585. $prev_segment = DB::table('mp_episode_segments')->where('id', $prev_act_id)->first();
  2586. if (!$prev_segment) Utils::throwError('20003:该片段不存在');
  2587. $anime_id = getProp($prev_segment, 'anime_id');
  2588. $episode_id = getProp($prev_segment, 'episode_id');
  2589. $episode_number = getProp($prev_segment, 'episode_number');
  2590. $prev_act_number = getProp($prev_segment, 'act_number');
  2591. // 获取新的act_number
  2592. $new_act_number = $prev_act_number + 1;
  2593. try {
  2594. DB::beginTransaction();
  2595. // 更新后续所有act的act_number(全能模式下每个act只有一条记录)
  2596. DB::table('mp_episode_segments')
  2597. ->where('anime_id', $anime_id)
  2598. ->where('episode_id', $episode_id)
  2599. ->where('act_number', '>', $prev_act_number)
  2600. ->increment('act_number');
  2601. // 插入新片段记录
  2602. $insert_data = [
  2603. 'anime_id' => $anime_id,
  2604. 'episode_id' => $episode_id,
  2605. 'episode_number' => $episode_number,
  2606. 'act_number' => $new_act_number,
  2607. 'created_at' => date('Y-m-d H:i:s'),
  2608. 'updated_at' => date('Y-m-d H:i:s')
  2609. ];
  2610. if ($act_title) {
  2611. $insert_data['act_title'] = $act_title;
  2612. }
  2613. if ($act_content) {
  2614. $insert_data['act_content'] = $act_content;
  2615. }
  2616. if ($act_duration) {
  2617. $insert_data['act_duration'] = $act_duration;
  2618. }
  2619. if ($video_url) {
  2620. $insert_data['origin_video_url'] = $video_url;
  2621. $insert_data['current_type'] = 2;
  2622. $compressed_video_url = compressVideo($video_url);
  2623. $insert_data['video_url'] = $compressed_video_url ?: $video_url;
  2624. }
  2625. $id = DB::table('mp_episode_segments')->insertGetId($insert_data);
  2626. if (!$id) {
  2627. Utils::throwError('20003:新增片段失败!');
  2628. }
  2629. DB::commit();
  2630. }catch (\Exception $e) {
  2631. DB::rollBack();
  2632. Utils::throwError('20003:'.$e->getMessage());
  2633. }
  2634. $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();
  2635. $segment = $segment ? (array)$segment : [];
  2636. return $segment;
  2637. }
  2638. public function editAct($data) {
  2639. $act_id = getProp($data, 'act_id');
  2640. $act_content = getProp($data, 'act_content');
  2641. $act_duration = getProp($data, 'act_duration');
  2642. $act_title = getProp($data, 'act_title');
  2643. $image_url = getProp($data, 'image_url');
  2644. $video_url = getProp($data, 'video_url');
  2645. // 参数验证
  2646. if (!$act_id) Utils::throwError('20003:请提供片段ID');
  2647. // 验证片段是否存在(全能模式下每个act只有一条记录)
  2648. $segment = DB::table('mp_episode_segments')
  2649. ->where('id', $act_id)
  2650. ->first();
  2651. if (!$segment) Utils::throwError('20003:该片段不存在');
  2652. try {
  2653. DB::beginTransaction();
  2654. // 准备更新数据
  2655. $update_data = [
  2656. 'updated_at' => date('Y-m-d H:i:s')
  2657. ];
  2658. // 更新act相关字段
  2659. if (!empty($act_content)) {
  2660. $update_data['act_show_content'] = $act_content;
  2661. $update_data['act_content'] = str_replace(["@", "{", "}"], "", $act_content);
  2662. // 处理【镜头X】或【分镜X】重新编号为从1开始的连续整数【镜头X】
  2663. $shot_counter = 0;
  2664. $update_data['act_show_content'] = preg_replace_callback(
  2665. '/【(?:镜头|分镜)(\d+)】/u',
  2666. function($matches) use (&$shot_counter) {
  2667. $shot_counter++;
  2668. return '【镜头' . $shot_counter . '】';
  2669. },
  2670. $update_data['act_show_content']
  2671. );
  2672. }
  2673. if (!empty($act_duration)) {
  2674. $update_data['act_duration'] = $act_duration;
  2675. }
  2676. if (!empty($act_title)) {
  2677. $update_data['act_title'] = $act_title;
  2678. }
  2679. // 处理图片上传
  2680. if ($image_url) {
  2681. $update_data['img_url'] = $image_url;
  2682. $update_data['current_type'] = 1;
  2683. // 同时写入一个图片生成任务记录
  2684. if ($act_id) {
  2685. $pic_task = [
  2686. 'alias_act_id' => $act_id,
  2687. 'ref_img_url' => json_encode([]),
  2688. 'status' => 'success',
  2689. 'result_url' => json_encode([$image_url], 256),
  2690. 'model' => '',
  2691. 'created_at' => date('Y-m-d H:i:s'),
  2692. 'updated_at' => date('Y-m-d H:i:s'),
  2693. ];
  2694. DB::table('mp_generate_pic_tasks')->insert($pic_task);
  2695. }
  2696. }
  2697. // 处理视频上传
  2698. if ($video_url) {
  2699. $update_data['origin_video_url'] = $video_url;
  2700. $compressed_video_url = compressVideo($video_url);
  2701. $update_data['current_type'] = 2;
  2702. $update_data['video_url'] = $compressed_video_url ?: $video_url;
  2703. // 同时写入一个视频生成任务记录
  2704. if ($act_id) {
  2705. $video_task = [
  2706. 'alias_act_id' => $act_id,
  2707. 'status' => 'success',
  2708. 'result_url' => $update_data['origin_video_url'],
  2709. 'compressed_url' => $update_data['video_url'],
  2710. 'created_at' => date('Y-m-d H:i:s'),
  2711. 'updated_at' => date('Y-m-d H:i:s'),
  2712. ];
  2713. DB::table('mp_generate_video_tasks')->insert($video_task);
  2714. }
  2715. }
  2716. // 更新片段信息
  2717. $result = DB::table('mp_episode_segments')
  2718. ->where('id', $act_id)
  2719. ->update($update_data);
  2720. if ($result === false) {
  2721. Utils::throwError('20003:更新片段失败');
  2722. }
  2723. DB::commit();
  2724. // 返回新复制的记录
  2725. $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();
  2726. $new_segment = (array)$new_segment;
  2727. return $new_segment;
  2728. } catch (\Exception $e) {
  2729. DB::rollBack();
  2730. dLog('anime')->error('更新片段失败', [
  2731. 'act_id' => $act_id,
  2732. 'error' => $e->getMessage()
  2733. ]);
  2734. Utils::throwError('20003:更新片段失败 ' . $e->getMessage());
  2735. }
  2736. }
  2737. public function copyAct($data) {
  2738. $act_id = getProp($data, 'act_id');
  2739. // 根据act_id获取记录(全能模式下每个act只有一条记录)
  2740. $source_segment = DB::table('mp_episode_segments')->where('id', $act_id)->first();
  2741. if (!$source_segment) Utils::throwError('20003:请选择片段');
  2742. $anime_id = getProp($source_segment, 'anime_id');
  2743. $episode_id = getProp($source_segment, 'episode_id');
  2744. $episode_number = getProp($source_segment, 'episode_number');
  2745. $act_number = getProp($source_segment, 'act_number');
  2746. try {
  2747. DB::beginTransaction();
  2748. // 新act的编号
  2749. $new_act_number = $act_number + 1;
  2750. // 更新后续所有act的act_number
  2751. DB::table('mp_episode_segments')
  2752. ->where('anime_id', $anime_id)
  2753. ->where('episode_id', $episode_id)
  2754. ->where('act_number', '>', $act_number)
  2755. ->increment('act_number');
  2756. // 复制该片段记录
  2757. $segment_data = (array)$source_segment;
  2758. unset($segment_data['id']);
  2759. $segment_data['video_url'] = '';
  2760. $segment_data['video_task_id'] = '';
  2761. $segment_data['video_task_status'] = '';
  2762. $segment_data['act_number'] = $new_act_number;
  2763. $segment_data['created_at'] = $segment_data['updated_at'] = date('Y-m-d H:i:s');
  2764. $id = DB::table('mp_episode_segments')->insertGetId($segment_data);
  2765. if (!$id) {
  2766. Utils::throwError('20003:复制片段失败');
  2767. }
  2768. DB::commit();
  2769. }catch (\Exception $e) {
  2770. DB::rollBack();
  2771. Utils::throwError('20003:'.$e->getMessage());
  2772. }
  2773. // 返回新复制的记录
  2774. $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();
  2775. $new_segment = $new_segment ? (array)$new_segment : [];
  2776. $new_segment['act_id'] = $id;
  2777. return $new_segment;
  2778. }
  2779. public function moveAct($data) {
  2780. $act_id = getProp($data, 'act_id');
  2781. $target_act_id = getProp($data, 'target_act_id');
  2782. // 获取源片段信息
  2783. $source_segment = DB::table('mp_episode_segments')->where('id', $act_id)->first();
  2784. if (!$source_segment) Utils::throwError('20003:请选择片段');
  2785. // 获取目标片段信息
  2786. $target_segment = DB::table('mp_episode_segments')->where('id', $target_act_id)->first();
  2787. if (!$target_segment) Utils::throwError('20003:目标片段不存在');
  2788. $anime_id = getProp($source_segment, 'anime_id');
  2789. $episode_id = getProp($source_segment, 'episode_id');
  2790. $source_act_number = getProp($source_segment, 'act_number');
  2791. $target_act_number = getProp($target_segment, 'act_number');
  2792. // 验证源片段和目标片段必须属于同一个动漫的同一集
  2793. $target_anime_id = getProp($target_segment, 'anime_id');
  2794. $target_episode_id = getProp($target_segment, 'episode_id');
  2795. if ($anime_id != $target_anime_id || $episode_id != $target_episode_id) {
  2796. Utils::throwError('20003:只能在同一动漫的同一集内移动片段');
  2797. }
  2798. // 如果源片段和目标片段相同,无需移动
  2799. if ($source_act_number == $target_act_number) {
  2800. return true;
  2801. }
  2802. try {
  2803. DB::beginTransaction();
  2804. if ($source_act_number < $target_act_number) {
  2805. // 向后移动:源片段移动到目标片段之后
  2806. // 1. 将源片段和目标片段之间的所有片段编号减1
  2807. DB::table('mp_episode_segments')
  2808. ->where('anime_id', $anime_id)
  2809. ->where('episode_id', $episode_id)
  2810. ->where('act_number', '>', $source_act_number)
  2811. ->where('act_number', '<=', $target_act_number)
  2812. ->decrement('act_number');
  2813. // 2. 将源片段移动到目标片段之后
  2814. $new_act_number = $target_act_number;
  2815. } else {
  2816. // 向前移动:源片段移动到目标片段之后
  2817. // 1. 将目标片段之后到源片段之前的所有片段编号加1
  2818. DB::table('mp_episode_segments')
  2819. ->where('anime_id', $anime_id)
  2820. ->where('episode_id', $episode_id)
  2821. ->where('act_number', '>', $target_act_number)
  2822. ->where('act_number', '<', $source_act_number)
  2823. ->increment('act_number');
  2824. // 2. 将源片段移动到目标片段之后
  2825. $new_act_number = $target_act_number + 1;
  2826. }
  2827. // 3. 更新源片段的编号
  2828. $update_result = DB::table('mp_episode_segments')
  2829. ->where('id', $act_id)
  2830. ->update([
  2831. 'act_number' => $new_act_number,
  2832. 'updated_at' => date('Y-m-d H:i:s')
  2833. ]);
  2834. if (!$update_result) {
  2835. Utils::throwError('20003:更新片段编号失败');
  2836. }
  2837. DB::commit();
  2838. return true;
  2839. } catch (\Exception $e) {
  2840. DB::rollBack();
  2841. Utils::throwError('20003:' . $e->getMessage());
  2842. }
  2843. }
  2844. public function delAct($data) {
  2845. $act_id = getProp($data, 'act_id');
  2846. // 根据act_id获取记录(全能模式下每个act只有一条记录)
  2847. $segment = DB::table('mp_episode_segments')->where('id', $act_id)->first();
  2848. if (!$segment) Utils::throwError('20003:请选择片段');
  2849. $anime_id = getProp($segment, 'anime_id');
  2850. $episode_id = getProp($segment, 'episode_id');
  2851. $act_number = getProp($segment, 'act_number');
  2852. try {
  2853. DB::beginTransaction();
  2854. // 删除该片段记录
  2855. $deleted = DB::table('mp_episode_segments')->where('id', $act_id)->delete();
  2856. if (!$deleted) {
  2857. Utils::throwError('20003:删除片段失败');
  2858. }
  2859. // 更新后续act的编号
  2860. DB::table('mp_episode_segments')
  2861. ->where('anime_id', $anime_id)
  2862. ->where('episode_id', $episode_id)
  2863. ->where('act_number', '>', $act_number)
  2864. ->decrement('act_number');
  2865. DB::commit();
  2866. }catch (\Exception $e) {
  2867. DB::rollBack();
  2868. Utils::throwError('20003:'.$e->getMessage());
  2869. }
  2870. return true;
  2871. }
  2872. public function applyAct($data) {
  2873. $act_id = getProp($data, 'act_id');
  2874. $url = getProp($data, 'url');
  2875. if (!$act_id) Utils::throwError('20003:请选择片段');
  2876. if (!$url) Utils::throwError('20003:URL不能为空');
  2877. // 获取URL的文件扩展名
  2878. $urlPath = parse_url($url, PHP_URL_PATH);
  2879. $extension = strtolower(pathinfo($urlPath, PATHINFO_EXTENSION));
  2880. // 定义图片和视频的扩展名
  2881. $imageExtensions = ['jpg', 'jpeg', 'png', 'gif', 'bmp', 'webp', 'svg'];
  2882. $videoExtensions = ['mp4', 'avi', 'mov', 'wmv', 'flv', 'mkv', 'webm', 'm4v'];
  2883. // 判断是图片还是视频
  2884. $updateData = ['updated_at' => date('Y-m-d H:i:s')];
  2885. if (in_array($extension, $imageExtensions)) {
  2886. // 图片类型
  2887. $updateData['img_url'] = $url;
  2888. $updateData['current_type'] = 1;
  2889. } elseif (in_array($extension, $videoExtensions)) {
  2890. // 视频类型
  2891. $updateData['video_url'] = $url;
  2892. $updateData['current_type'] = 2;
  2893. } else {
  2894. Utils::throwError('20003:不支持的文件类型');
  2895. }
  2896. // 更新片段记录(全能模式下每个act只有一条记录)
  2897. $result = DB::table('mp_episode_segments')
  2898. ->where('id', $act_id)
  2899. ->update($updateData);
  2900. if (!$result) {
  2901. Utils::throwError('20003:更新片段失败');
  2902. }
  2903. return true;
  2904. }
  2905. public function actChatHistory($data) {
  2906. $act_id = getProp($data, 'act_id');
  2907. if (!$act_id) Utils::throwError('20003:请选择片段!');
  2908. $query = DB::table('mp_anime_records')->where('act_id', $act_id)->select('role', 'content', 'act_id', 'image_url', 'video_url', 'video_task_id', 'pic_task_id', 'reference_images', 'created_at');
  2909. $chat = $query->orderBy('id')->get()->map(function ($value) {
  2910. $value = (array)$value;
  2911. $value['created_at'] = transDate($value['created_at']);
  2912. if ($value['reference_images']) $value['reference_images'] = json_decode($value['reference_images'], 256);
  2913. else $value['reference_images'] = [];
  2914. return $value;
  2915. })->toArray();
  2916. // 获取历史图片
  2917. $url = [];
  2918. $pic_history = DB::table('mp_generate_pic_tasks')->where('alias_act_id', $act_id)->where('status', 'success')->orderBy('created_at', 'desc')->get();
  2919. foreach($pic_history as $task) {
  2920. $result_url = getProp($task, 'result_url');
  2921. if (is_json($result_url)) {
  2922. $url = array_merge($url, json_decode($result_url, true));
  2923. }else {
  2924. $url[] = $result_url;
  2925. }
  2926. }
  2927. // 获取历史视频
  2928. $video_history = DB::table('mp_generate_video_tasks')->where('alias_act_id', $act_id)->where('status', 'success')->orderBy('created_at', 'desc')->get();
  2929. foreach($video_history as $task) {
  2930. $result_url = getProp($task, 'result_url');
  2931. if (is_json($result_url)) {
  2932. $url = array_merge($url, json_decode($result_url, true));
  2933. }else {
  2934. $url[] = $result_url;
  2935. }
  2936. }
  2937. // 获取资产库
  2938. $products = [];
  2939. // 通过act_id查询片段信息获取episode_id
  2940. $segment = DB::table('mp_episode_segments')->where('id', $act_id)->first();
  2941. if ($segment) {
  2942. $episode_id = getProp($segment, 'episode_id');
  2943. // 查询剧集信息获取roles、scenes和extra_products
  2944. $episode = DB::table('mp_anime_episodes')->where('id', $episode_id)->first();
  2945. if ($episode) {
  2946. $roles = json_decode(getProp($episode, 'roles', '[]'), true) ?: [];
  2947. $scenes = json_decode(getProp($episode, 'scenes', '[]'), true) ?: [];
  2948. $props = json_decode(getProp($episode, 'props', '[]'), true) ?: [];
  2949. $extra_products = json_decode(getProp($episode, 'extra_products', '[]'), true) ?: [];
  2950. // 先合并roles、scenes和props
  2951. // 处理角色数组
  2952. foreach ($roles as $role) {
  2953. $product = $role;
  2954. // 将role字段重命名为product_name
  2955. if (is_array($product) && !empty($product['role'] ?? null)) {
  2956. $product['product_name'] = $product['role'];
  2957. unset($product['role']);
  2958. $product['product'] = 1; // 标记类型为角色
  2959. $products[$product['product_name']] = $product; // 使用product_name作为key便于后续覆盖
  2960. }
  2961. }
  2962. // 处理场景数组
  2963. foreach ($scenes as $scene) {
  2964. $product = $scene;
  2965. // 将scene字段重命名为product_name
  2966. if (is_array($product) && !empty($product['scene'] ?? null)) {
  2967. $product['product_name'] = $product['scene'];
  2968. unset($product['scene']);
  2969. $product['product'] = 2; // 标记类型为场景
  2970. $products[$product['product_name']] = $product; // 使用product_name作为key便于后续覆盖
  2971. }
  2972. }
  2973. // 处理道具数组
  2974. foreach ($props as $prop) {
  2975. $product = $prop;
  2976. // 将prop字段重命名为product_name
  2977. if (is_array($product) && !empty($product['prop'] ?? null)) {
  2978. $product['product_name'] = $product['prop'];
  2979. unset($product['prop']);
  2980. $product['product'] = 3; // 标记类型为道具
  2981. $products[$product['product_name']] = $product; // 使用product_name作为key便于后续覆盖
  2982. }
  2983. }
  2984. // extra_products优先级更高,直接覆盖同名的roles和scenes
  2985. foreach ($extra_products as $extra_product) {
  2986. $product_name = getProp($extra_product, 'product_name');
  2987. if ($product_name) {
  2988. $products[$product_name] = $extra_product; // 覆盖同名数据
  2989. }
  2990. }
  2991. // 重新索引数组(去除key)
  2992. $products = array_values($products);
  2993. }
  2994. }
  2995. // 获取执行中的任务
  2996. $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) {
  2997. $value = (array)$value;
  2998. if ($value['ref_image_url']) $value['ref_image_url'] = json_decode($value['ref_image_url'], true);
  2999. else $value['ref_image_url'] = [];
  3000. $value['status'] = $value['status'] == 'pending' ? '视频待生成' : '视频生成中';
  3001. // 处理prompt:删除人物音色部分,保留【镜头】开始的内容,并去掉<图片X>标记
  3002. if (!empty($value['prompt'])) {
  3003. $prompt = $value['prompt'];
  3004. // 查找第一个【镜头】的位置
  3005. if (preg_match('/【镜头\d+】/u', $prompt, $matches, PREG_OFFSET_CAPTURE)) {
  3006. // 从【镜头】开始截取
  3007. $prompt = substr($prompt, $matches[0][1]);
  3008. }
  3009. // 去除所有<图片X>格式的标记(X可以是任意数字)
  3010. $prompt = preg_replace('/<图片\d+>/u', '', $prompt);
  3011. $value['prompt'] = $prompt;
  3012. }
  3013. return $value;
  3014. })->toArray();
  3015. return compact('chat', 'url', 'products', 'tasks');
  3016. }
  3017. public function applyAudioData($data) {
  3018. $segment_id = getProp($data, 'segment_id');
  3019. $global_data = getProp($data, 'global_data');
  3020. $segment_data = getProp($data, 'segment_data');
  3021. if (!$segment_id) Utils::throwError('20003:请选择分镜');
  3022. $global_data = is_array($global_data) ? $global_data : [];
  3023. $segment_data = is_array($segment_data) ? $segment_data : [];
  3024. // dialogue只能在segment_data中,如果在global_data中则移到segment_data
  3025. $dialogue_item = null;
  3026. foreach ($global_data as $key => $item) {
  3027. if (trim((string)getProp($item, 'name')) === 'dialogue') {
  3028. $dialogue_item = $item;
  3029. unset($global_data[$key]);
  3030. break;
  3031. }
  3032. }
  3033. if ($dialogue_item) {
  3034. $segment_data[] = $dialogue_item;
  3035. }
  3036. // 特殊参数: audio_url,audio_duration,subtitle_info
  3037. // 这些特殊参数必须同时存在才对当前分镜有效,直接保存但不创建音频任务
  3038. // 如果不是全部存在,则仍需创建音频任务
  3039. $special_fields = ['audio_url', 'audio_duration', 'subtitle_info'];
  3040. $special_update_data = [];
  3041. $has_all_special_params = false;
  3042. // 从segment_data中提取特殊参数
  3043. $filtered_segment_data = [];
  3044. foreach ($segment_data as $item) {
  3045. $field_name = trim((string)getProp($item, 'name'));
  3046. if (in_array($field_name, $special_fields)) {
  3047. $special_update_data[$field_name] = getProp($item, 'value');
  3048. } else {
  3049. // 非特殊参数保留,继续后续处理
  3050. $filtered_segment_data[] = $item;
  3051. }
  3052. }
  3053. // 检查是否三个特殊参数都存在
  3054. if (count($special_update_data) === 3 &&
  3055. isset($special_update_data['audio_url']) &&
  3056. isset($special_update_data['audio_duration']) &&
  3057. isset($special_update_data['subtitle_info'])) {
  3058. $has_all_special_params = true;
  3059. // 立即更新到当前分镜
  3060. $special_update_data['updated_at'] = date('Y-m-d H:i:s');
  3061. DB::table('mp_episode_segments')
  3062. ->where('segment_id', $segment_id)
  3063. ->update($special_update_data);
  3064. }
  3065. // 使用过滤后的segment_data继续处理其他参数
  3066. $segment_data = $filtered_segment_data;
  3067. $allow_fields = ['dialogue', 'voice_type', 'speed_ratio', 'loudness_ratio', 'emotion_scale', 'pitch'];
  3068. $global_update_data = [];
  3069. $segment_update_data = [];
  3070. $global_voice_type = '';
  3071. $target_segment = DB::table('mp_episode_segments')->where('segment_id', $segment_id)->first();
  3072. if (!$target_segment) Utils::throwError('20003:分镜不存在');
  3073. $episode_id = getProp($target_segment, 'episode_id');
  3074. $target_voice_actor = trim((string)getProp($target_segment, 'voice_actor'));
  3075. $episode = DB::table('mp_anime_episodes')->where('id', $episode_id)->first();
  3076. if (!$episode) Utils::throwError('20003:分集不存在');
  3077. foreach ($global_data as $item) {
  3078. $field_name = trim((string)getProp($item, 'name'));
  3079. if (!$field_name || !in_array($field_name, $allow_fields)) {
  3080. continue;
  3081. }
  3082. $global_update_data[$field_name] = getProp($item, 'value');
  3083. if ($field_name === 'voice_type') {
  3084. $global_voice_type = trim((string)getProp($item, 'value'));
  3085. }
  3086. }
  3087. foreach ($segment_data as $item) {
  3088. $field_name = trim((string)getProp($item, 'name'));
  3089. if (!$field_name || !in_array($field_name, $allow_fields)) {
  3090. continue;
  3091. }
  3092. $segment_update_data[$field_name] = getProp($item, 'value');
  3093. }
  3094. if ($global_voice_type) {
  3095. $timbre_info = DB::table('mp_timbres')
  3096. ->where('timbre_type', $global_voice_type)
  3097. ->select('audio_url', 'timbre_name')
  3098. ->first();
  3099. if ($timbre_info) {
  3100. $global_update_data['voice_audio_url'] = getProp($timbre_info, 'audio_url');
  3101. $global_update_data['voice_name'] = str_replace('(多情感)', '', getProp($timbre_info, 'timbre_name'));
  3102. }
  3103. }
  3104. try {
  3105. DB::beginTransaction();
  3106. // 收集需要创建音频合成任务的segment_id和对应的分镜数据
  3107. $segment_ids_to_create_task = [];
  3108. $segments_data = [];
  3109. // 如果有全局更新,获取该角色的所有分镜数据并检查是否有变化
  3110. if (!empty($global_update_data)) {
  3111. // 如果角色不存在,则只更新当前分镜
  3112. if (!$target_voice_actor) {
  3113. // 只处理当前分镜
  3114. $affected_segments = DB::table('mp_episode_segments')
  3115. ->where('segment_id', $segment_id)
  3116. ->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')
  3117. ->get();
  3118. } else {
  3119. // 获取该角色的所有分镜
  3120. $affected_segments = DB::table('mp_episode_segments')
  3121. ->where('episode_id', $episode_id)
  3122. ->where('voice_actor', $target_voice_actor)
  3123. ->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')
  3124. ->get();
  3125. }
  3126. foreach ($affected_segments as $seg) {
  3127. $seg = (array)$seg;
  3128. $sid = getProp($seg, 'segment_id');
  3129. // 检查参数是否发生变化
  3130. $has_changed = false;
  3131. foreach ($global_update_data as $field => $new_value) {
  3132. $old_value = getProp($seg, $field);
  3133. if ($old_value != $new_value) {
  3134. $has_changed = true;
  3135. break;
  3136. }
  3137. }
  3138. if ($has_changed) {
  3139. $segment_ids_to_create_task[] = $sid;
  3140. $segments_data[$sid] = $seg;
  3141. }
  3142. }
  3143. // 只有在有变化的分镜时才更新
  3144. if (!empty($segment_ids_to_create_task)) {
  3145. $global_segment_update_data = $global_update_data;
  3146. $global_segment_update_data['audio_url'] = ''; // 清空音频URL
  3147. $global_segment_update_data['updated_at'] = date('Y-m-d H:i:s');
  3148. DB::table('mp_episode_segments')
  3149. ->where('episode_id', $episode_id)
  3150. ->where('voice_actor', $target_voice_actor)
  3151. ->whereIn('segment_id', $segment_ids_to_create_task)
  3152. ->update($global_segment_update_data);
  3153. }
  3154. if ($global_voice_type) {
  3155. $episode_roles = json_decode((string)getProp($episode, 'roles'), true);
  3156. $episode_roles = is_array($episode_roles) ? $episode_roles : [];
  3157. $roles_updated = false;
  3158. foreach ($episode_roles as &$role) {
  3159. // 通过 role 字段匹配角色名,而不是 voice_name
  3160. if (trim((string)getProp($role, 'role')) !== $target_voice_actor) {
  3161. continue;
  3162. }
  3163. $role['voice_type'] = $global_voice_type;
  3164. $role['voice_audio_url'] = getProp($global_update_data, 'voice_audio_url');
  3165. $role['voice_name'] = getProp($global_update_data, 'voice_name');
  3166. $roles_updated = true;
  3167. }
  3168. unset($role);
  3169. if ($roles_updated) {
  3170. DB::table('mp_anime_episodes')->where('id', $episode_id)->update([
  3171. 'roles' => json_encode($episode_roles, 256),
  3172. 'updated_at' => date('Y-m-d H:i:s'),
  3173. ]);
  3174. }
  3175. }
  3176. }
  3177. // 如果有单个分镜更新,检查是否有变化
  3178. if (!empty($segment_update_data)) {
  3179. // 获取当前分镜数据
  3180. $current_segment = DB::table('mp_episode_segments')
  3181. ->where('segment_id', $segment_id)
  3182. ->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')
  3183. ->first();
  3184. if ($current_segment) {
  3185. $current_segment = (array)$current_segment;
  3186. // 检查参数是否发生变化
  3187. $has_changed = false;
  3188. foreach ($segment_update_data as $field => $new_value) {
  3189. $old_value = getProp($current_segment, $field);
  3190. if ($old_value != $new_value) {
  3191. $has_changed = true;
  3192. break;
  3193. }
  3194. }
  3195. if ($has_changed) {
  3196. // 如果该分镜还未在列表中,添加进去
  3197. if (!in_array($segment_id, $segment_ids_to_create_task)) {
  3198. $segment_ids_to_create_task[] = $segment_id;
  3199. $segments_data[$segment_id] = $current_segment;
  3200. }
  3201. // 更新分镜数据并清空音频URL
  3202. $segment_update_data['audio_url'] = '';
  3203. $segment_update_data['updated_at'] = date('Y-m-d H:i:s');
  3204. DB::table('mp_episode_segments')->where('segment_id', $segment_id)->update($segment_update_data);
  3205. }
  3206. }
  3207. }
  3208. // 为所有有变化的分镜创建音频合成任务
  3209. // 但如果当前分镜同时设置了全部三个特殊参数(audio_url, audio_duration, subtitle_info),则跳过该分镜
  3210. if (!empty($segment_ids_to_create_task)) {
  3211. foreach ($segment_ids_to_create_task as $sid) {
  3212. // 如果当前分镜同时设置了全部三个特殊参数,则跳过音频任务创建
  3213. if ($sid === $segment_id && $has_all_special_params) {
  3214. continue;
  3215. }
  3216. // 重新获取更新后的分镜数据
  3217. $updated_segment = DB::table('mp_episode_segments')
  3218. ->where('segment_id', $sid)
  3219. ->select('voice_actor', 'dialogue', 'voice_type', 'voice_name', 'emotion', 'emotion_type', 'gender', 'speed_ratio', 'loudness_ratio', 'emotion_scale', 'pitch')
  3220. ->first();
  3221. if (!$updated_segment) continue;
  3222. $updated_segment = (array)$updated_segment;
  3223. // 检查dialogue是否为空
  3224. $dialogue = getProp($updated_segment, 'dialogue');
  3225. if (empty($dialogue)) {
  3226. // dialogue为空时,直接写入默认音频信息
  3227. DB::table('mp_episode_segments')->where('segment_id', $sid)->update([
  3228. 'audio_url' => 'https://zw-audiobook.tos-cn-beijing.volces.com/effects/ellipses_2s.mp3',
  3229. 'audio_duration' => 2.0,
  3230. 'subtitle_info' => json_encode(['duration' => 2.0, 'words' => []], 256),
  3231. 'updated_at' => date('Y-m-d H:i:s')
  3232. ]);
  3233. continue;
  3234. }
  3235. $generate_json = [
  3236. 'text' => $dialogue,
  3237. 'role' => getProp($updated_segment, 'voice_actor'),
  3238. 'voice_type' => getProp($updated_segment, 'voice_type'),
  3239. 'voice_name' => getProp($updated_segment, 'voice_name'),
  3240. 'emotion' => getProp($updated_segment, 'emotion'),
  3241. 'emotion_type' => getProp($updated_segment, 'emotion_type'),
  3242. 'gender' => getProp($updated_segment, 'gender'),
  3243. 'speed_ratio' => getProp($updated_segment, 'speed_ratio', 0),
  3244. 'loudness_ratio' => getProp($updated_segment, 'loudness_ratio', 0),
  3245. 'emotion_scale' => getProp($updated_segment, 'emotion_scale', 0),
  3246. 'pitch' => getProp($updated_segment, 'pitch', 0),
  3247. ];
  3248. // 插入视频配音合成任务
  3249. $dubTaskId = DB::table('mp_dub_video_tasks')->insertGetId([
  3250. 'alias_segment_id' => $sid,
  3251. 'generate_status' => '执行中',
  3252. 'audio_url' => '',
  3253. 'generate_json' => json_encode($generate_json, 256),
  3254. 'created_at' => date('Y-m-d H:i:s'),
  3255. 'updated_at' => date('Y-m-d H:i:s'),
  3256. ]);
  3257. if (!$dubTaskId) {
  3258. dLog('anime')->error('创建配音任务失败', ['segment_id' => $sid]);
  3259. continue;
  3260. }
  3261. // 将任务ID添加到Redis列表中
  3262. Redis::lpush('dub_video_task_queue', $dubTaskId);
  3263. // 请求远程服务器执行生成
  3264. try {
  3265. sleep(1);
  3266. $client = new Client(['timeout' => 300, 'verify' => false]);
  3267. $result = $client->get("http://122.9.129.83:5000/api/anime/genAudio?taskId={$dubTaskId}");
  3268. $response = $result->getBody()->getContents();
  3269. $response_arr = json_decode($response, true);
  3270. if (!isset($response_arr['code']) || (int)$response_arr['code'] !== 0) {
  3271. $error_msg = isset($response_arr['msg']) ? $response_arr['msg'] : '未知错误';
  3272. dLog('anime')->error('火山生成音频失败', ['error' => $error_msg, 'task_id' => $dubTaskId, 'segment_id' => $sid]);
  3273. logDB('anime', 'error', '火山生成音频失败', ['error' => $error_msg, 'task_id' => $dubTaskId, 'segment_id' => $sid]);
  3274. }
  3275. } catch (\Exception $e) {
  3276. dLog('anime')->error('调用音频生成API失败', ['error' => $e->getMessage(), 'task_id' => $dubTaskId, 'segment_id' => $sid]);
  3277. logDB('anime', 'error', '调用音频生成API失败', ['error' => $e->getMessage(), 'task_id' => $dubTaskId, 'segment_id' => $sid]);
  3278. }
  3279. }
  3280. }
  3281. DB::commit();
  3282. } catch (\Exception $e) {
  3283. DB::rollBack();
  3284. Utils::throwError('20003:'.$e->getMessage());
  3285. }
  3286. return true;
  3287. }
  3288. public function episodePicsInfo($data) {
  3289. $anime_id = getProp($data, 'anime_id');
  3290. $episode_id = getProp($data, 'episode_id');
  3291. // 参数验证
  3292. if (!$anime_id && !$episode_id) {
  3293. Utils::throwError('20003:请提供动漫ID或分集ID');
  3294. }
  3295. // 根据参数获取数据源
  3296. if ($episode_id) {
  3297. // 从剧集表获取
  3298. $source = DB::table('mp_anime_episodes')->where('id', $episode_id)->first();
  3299. if (!$source) Utils::throwError('20003:该剧集不存在');
  3300. $table_name = 'mp_anime_episodes';
  3301. $id_field = 'id';
  3302. $id_value = $episode_id;
  3303. // 获取剧集的anime_id用于继承全局数据
  3304. $anime_id = getProp($source, 'anime_id');
  3305. } else {
  3306. // 从动漫表获取
  3307. $source = DB::table('mp_animes')->where('id', $anime_id)->where('is_deleted', 0)->first();
  3308. if (!$source) Utils::throwError('20003:该动漫不存在');
  3309. $table_name = 'mp_animes';
  3310. $id_field = 'id';
  3311. $id_value = $anime_id;
  3312. }
  3313. $source = (array)$source;
  3314. $roles = json_decode(getProp($source, 'roles', '[]'), true) ?: [];
  3315. $scenes = json_decode(getProp($source, 'scenes', '[]'), true) ?: [];
  3316. $props = json_decode(getProp($source, 'props', '[]'), true) ?: [];
  3317. // 如果是分集数据,需要处理继承和任务创建逻辑
  3318. if ($episode_id) {
  3319. $this->processEpisodeRolesAndScenes($episode_id, $anime_id, $roles, $scenes, $source);
  3320. }
  3321. // 返回生成器函数,用于 SSE 流式输出
  3322. return function() use ($roles, $scenes, $props, $table_name, $id_field, $id_value) {
  3323. $startTime = time();
  3324. $maxDuration = 600; // 10分钟超时
  3325. $checkInterval = 3; // 每3秒检查一次
  3326. // Redis 缓存键
  3327. $cacheKey = "anime:pics_info:{$table_name}:{$id_value}";
  3328. // 生成当前数据的哈希值用于比较
  3329. $generateHash = function($roles, $scenes, $props) {
  3330. return md5(json_encode(['roles' => $roles, 'scenes' => $scenes, 'props' => $props], JSON_UNESCAPED_UNICODE));
  3331. };
  3332. // 发送初始数据
  3333. $currentHash = $generateHash($roles, $scenes, $props);
  3334. Redis::setex($cacheKey, 600, $currentHash); // 缓存10分钟
  3335. echo "data: " . json_encode([
  3336. 'type' => 'init',
  3337. 'data' => [
  3338. 'roles' => $roles,
  3339. 'scenes' => $scenes,
  3340. 'props' => $props,
  3341. 'start_time' => $startTime
  3342. ]
  3343. ], JSON_UNESCAPED_UNICODE) . "\n\n";
  3344. if (ob_get_level() > 0) {
  3345. ob_flush();
  3346. }
  3347. flush();
  3348. // 持续轮询任务状态
  3349. while (time() - $startTime < $maxDuration) {
  3350. $hasProcessing = false;
  3351. $updated = false;
  3352. // 检查角色任务状态
  3353. foreach ($roles as $index => &$role) {
  3354. $task_id = getProp($role, 'task_id');
  3355. $task_status = getProp($role, 'task_status');
  3356. $existing_url = getProp($role, 'url');
  3357. // 只处理有任务ID且状态为processing的角色,或者状态为processing但没有URL的角色
  3358. if ($task_id && ($task_status === 'processing' || (in_array($task_status, ['success', 'completed']) && empty($existing_url)))) {
  3359. $hasProcessing = ($task_status === 'processing');
  3360. // 查询任务状态
  3361. $task = DB::table('mp_generate_pic_tasks')
  3362. ->where('id', $task_id)
  3363. ->select('id', 'status', 'result_url', 'error_message')
  3364. ->first();
  3365. if ($task) {
  3366. $task = (array)$task;
  3367. $status = getProp($task, 'status');
  3368. // 如果任务完成或失败
  3369. if (in_array($status, ['success', 'failed'])) {
  3370. $role['task_status'] = $status;
  3371. if ($status === 'success') {
  3372. $result_url = getProp($task, 'result_url');
  3373. if ($result_url) {
  3374. $result_urls = is_json($result_url) ? json_decode($result_url, true) : [$result_url];
  3375. if (is_array($result_urls) && !empty($result_urls[0])) {
  3376. $role['url'] = $result_urls[0];
  3377. }
  3378. }
  3379. }
  3380. $updated = true;
  3381. } else if ($status === 'processing') {
  3382. $hasProcessing = true;
  3383. }
  3384. }
  3385. }
  3386. }
  3387. // 检查场景任务状态
  3388. foreach ($scenes as $index => &$scene) {
  3389. $task_id = getProp($scene, 'task_id');
  3390. $task_status = getProp($scene, 'task_status');
  3391. $existing_url = getProp($scene, 'url');
  3392. // 只处理有任务ID且状态为processing的场景,或者状态为success但没有URL的场景
  3393. if ($task_id && ($task_status === 'processing' || (in_array($task_status, ['success', 'completed']) && empty($existing_url)))) {
  3394. $hasProcessing = ($task_status === 'processing');
  3395. // 查询任务状态
  3396. $task = DB::table('mp_generate_pic_tasks')
  3397. ->where('id', $task_id)
  3398. ->select('id', 'status', 'result_url', 'error_message')
  3399. ->first();
  3400. if ($task) {
  3401. $task = (array)$task;
  3402. $status = getProp($task, 'status');
  3403. // 如果任务完成或失败
  3404. if (in_array($status, ['success', 'failed'])) {
  3405. $scene['task_status'] = $status;
  3406. if ($status === 'success') {
  3407. $result_url = getProp($task, 'result_url');
  3408. if ($result_url) {
  3409. $result_urls = is_json($result_url) ? json_decode($result_url, true) : [$result_url];
  3410. if (is_array($result_urls) && !empty($result_urls[0])) {
  3411. $scene['url'] = $result_urls[0];
  3412. }
  3413. }
  3414. }
  3415. $updated = true;
  3416. } else if ($status === 'processing') {
  3417. $hasProcessing = true;
  3418. }
  3419. }
  3420. }
  3421. }
  3422. // 检查道具任务状态
  3423. foreach ($props as $index => &$prop) {
  3424. $task_id = getProp($prop, 'task_id');
  3425. $task_status = getProp($prop, 'task_status');
  3426. $existing_url = getProp($prop, 'url');
  3427. // 只处理有任务ID且状态为processing的道具,或者状态为success但没有URL的道具
  3428. if ($task_id && ($task_status === 'processing' || (in_array($task_status, ['success', 'completed']) && empty($existing_url)))) {
  3429. $hasProcessing = ($task_status === 'processing');
  3430. // 查询任务状态
  3431. $task = DB::table('mp_generate_pic_tasks')
  3432. ->where('id', $task_id)
  3433. ->select('id', 'status', 'result_url', 'error_message')
  3434. ->first();
  3435. if ($task) {
  3436. $task = (array)$task;
  3437. $status = getProp($task, 'status');
  3438. // 如果任务完成或失败
  3439. if (in_array($status, ['success', 'failed'])) {
  3440. $prop['task_status'] = $status;
  3441. if ($status === 'success') {
  3442. $result_url = getProp($task, 'result_url');
  3443. if ($result_url) {
  3444. $result_urls = is_json($result_url) ? json_decode($result_url, true) : [$result_url];
  3445. if (is_array($result_urls) && !empty($result_urls[0])) {
  3446. $prop['url'] = $result_urls[0];
  3447. }
  3448. }
  3449. }
  3450. $updated = true;
  3451. } else if ($status === 'processing') {
  3452. $hasProcessing = true;
  3453. }
  3454. }
  3455. }
  3456. }
  3457. // 如果有更新,检查数据是否真的变化了(通过哈希对比)
  3458. if ($updated) {
  3459. $newHash = $generateHash($roles, $scenes, $props);
  3460. $cachedHash = Redis::get($cacheKey);
  3461. // 只有当数据真正变化时才更新数据库和发送事件
  3462. if ($newHash !== $cachedHash) {
  3463. try {
  3464. // 更新数据库
  3465. DB::table($table_name)->where($id_field, $id_value)->update([
  3466. 'roles' => json_encode($roles, JSON_UNESCAPED_UNICODE),
  3467. 'scenes' => json_encode($scenes, JSON_UNESCAPED_UNICODE),
  3468. 'props' => json_encode($props, JSON_UNESCAPED_UNICODE),
  3469. 'updated_at' => date('Y-m-d H:i:s')
  3470. ]);
  3471. // 更新缓存
  3472. Redis::setex($cacheKey, 600, $newHash);
  3473. // 发送更新事件
  3474. echo "data: " . json_encode([
  3475. 'type' => 'update',
  3476. 'data' => [
  3477. 'roles' => $roles,
  3478. 'scenes' => $scenes,
  3479. 'props' => $props,
  3480. 'elapsed_time' => time() - $startTime
  3481. ]
  3482. ], JSON_UNESCAPED_UNICODE) . "\n\n";
  3483. if (ob_get_level() > 0) {
  3484. ob_flush();
  3485. }
  3486. flush();
  3487. } catch (\Exception $e) {
  3488. dLog('anime')->error('更新角色/场景/道具信息失败: ' . $e->getMessage());
  3489. }
  3490. } else {
  3491. // 即使哈希相同,如果有URL更新也要发送事件
  3492. $hasUrlUpdate = false;
  3493. foreach ($roles as $role) {
  3494. if (!empty(getProp($role, 'url')) && getProp($role, 'task_status') === 'success') {
  3495. $hasUrlUpdate = true;
  3496. break;
  3497. }
  3498. }
  3499. if (!$hasUrlUpdate) {
  3500. foreach ($scenes as $scene) {
  3501. if (!empty(getProp($scene, 'url')) && getProp($scene, 'task_status') === 'success') {
  3502. $hasUrlUpdate = true;
  3503. break;
  3504. }
  3505. }
  3506. }
  3507. if (!$hasUrlUpdate) {
  3508. foreach ($props as $prop) {
  3509. if (!empty(getProp($prop, 'url')) && getProp($prop, 'task_status') === 'success') {
  3510. $hasUrlUpdate = true;
  3511. break;
  3512. }
  3513. }
  3514. }
  3515. if ($hasUrlUpdate) {
  3516. // 强制更新数据库和发送事件
  3517. try {
  3518. DB::table($table_name)->where($id_field, $id_value)->update([
  3519. 'roles' => json_encode($roles, JSON_UNESCAPED_UNICODE),
  3520. 'scenes' => json_encode($scenes, JSON_UNESCAPED_UNICODE),
  3521. 'props' => json_encode($props, JSON_UNESCAPED_UNICODE),
  3522. 'updated_at' => date('Y-m-d H:i:s')
  3523. ]);
  3524. // 更新缓存
  3525. Redis::setex($cacheKey, 600, $newHash);
  3526. // 发送更新事件
  3527. echo "data: " . json_encode([
  3528. 'type' => 'update',
  3529. 'data' => [
  3530. 'roles' => $roles,
  3531. 'scenes' => $scenes,
  3532. 'props' => $props,
  3533. 'elapsed_time' => time() - $startTime
  3534. ]
  3535. ], JSON_UNESCAPED_UNICODE) . "\n\n";
  3536. if (ob_get_level() > 0) {
  3537. ob_flush();
  3538. }
  3539. flush();
  3540. } catch (\Exception $e) {
  3541. dLog('anime')->error('强制更新角色/场景/道具信息失败: ' . $e->getMessage());
  3542. }
  3543. }
  3544. }
  3545. }
  3546. // 如果所有任务都已完成,发送完成事件并退出
  3547. if (!$hasProcessing) {
  3548. // 查询数据库中的最终数据,确保返回最新的完整数据
  3549. try {
  3550. $finalSource = DB::table($table_name)->where($id_field, $id_value)->first();
  3551. if ($finalSource) {
  3552. $finalSource = (array)$finalSource;
  3553. $finalRoles = json_decode(getProp($finalSource, 'roles', '[]'), true) ?: [];
  3554. $finalScenes = json_decode(getProp($finalSource, 'scenes', '[]'), true) ?: [];
  3555. $finalProps = json_decode(getProp($finalSource, 'props', '[]'), true) ?: [];
  3556. // 使用数据库中的最终数据
  3557. $roles = $finalRoles;
  3558. $scenes = $finalScenes;
  3559. $props = $finalProps;
  3560. }
  3561. } catch (\Exception $e) {
  3562. dLog('anime')->error('查询最终数据失败: ' . $e->getMessage());
  3563. // 如果查询失败,继续使用内存中的数据
  3564. }
  3565. // 清理缓存
  3566. Redis::del($cacheKey);
  3567. echo "data: " . json_encode([
  3568. 'type' => 'completed',
  3569. 'data' => [
  3570. 'roles' => $roles,
  3571. 'scenes' => $scenes,
  3572. 'props' => $props,
  3573. 'total_time' => time() - $startTime
  3574. ]
  3575. ], JSON_UNESCAPED_UNICODE) . "\n\n";
  3576. if (ob_get_level() > 0) {
  3577. ob_flush();
  3578. }
  3579. flush();
  3580. break;
  3581. }
  3582. // 等待下次检查
  3583. sleep($checkInterval);
  3584. }
  3585. // 超时处理
  3586. if (time() - $startTime >= $maxDuration) {
  3587. // 查询数据库中的最终数据,即使超时也要返回最新数据
  3588. try {
  3589. $finalSource = DB::table($table_name)->where($id_field, $id_value)->first();
  3590. if ($finalSource) {
  3591. $finalSource = (array)$finalSource;
  3592. $finalRoles = json_decode(getProp($finalSource, 'roles', '[]'), true) ?: [];
  3593. $finalScenes = json_decode(getProp($finalSource, 'scenes', '[]'), true) ?: [];
  3594. $finalProps = json_decode(getProp($finalSource, 'props', '[]'), true) ?: [];
  3595. // 使用数据库中的最终数据
  3596. $roles = $finalRoles;
  3597. $scenes = $finalScenes;
  3598. $props = $finalProps;
  3599. }
  3600. } catch (\Exception $e) {
  3601. dLog('anime')->error('超时时查询最终数据失败: ' . $e->getMessage());
  3602. // 如果查询失败,继续使用内存中的数据
  3603. }
  3604. // 清理缓存
  3605. Redis::del($cacheKey);
  3606. echo "data: " . json_encode([
  3607. 'type' => 'timeout',
  3608. 'message' => '轮询超时,请刷新页面查看最新状态',
  3609. 'data' => [
  3610. 'roles' => $roles,
  3611. 'scenes' => $scenes,
  3612. 'props' => $props
  3613. ]
  3614. ], JSON_UNESCAPED_UNICODE) . "\n\n";
  3615. if (ob_get_level() > 0) {
  3616. ob_flush();
  3617. }
  3618. flush();
  3619. }
  3620. };
  3621. }
  3622. public function clipSegmentVideo($data) {
  3623. $segment_id = getProp($data, 'segment_id');
  3624. $video_time_point_start = getProp($data, 'video_time_point_start');
  3625. $video_time_point_end = getProp($data, 'video_time_point_end');
  3626. if (!$segment_id || !$video_time_point_start || !$video_time_point_end) {
  3627. Utils::throwError('20003:参数异常');
  3628. }
  3629. if (!DB::table('mp_episode_segments')->where('segment_id', $segment_id)->value('video_url')) {
  3630. Utils::throwError('20003:该分镜没有视频,无法裁剪');
  3631. }
  3632. $video_duration = $video_time_point_end - $video_time_point_start;
  3633. if (!$video_duration < 0) Utils::throwError('20003:参数异常');
  3634. return DB::table('mp_episode_segments')->where('segment_id', $segment_id)->update([
  3635. 'video_duration' => $video_duration,
  3636. 'video_time_point_start' => $video_time_point_start,
  3637. 'video_time_point_end' => $video_time_point_end,
  3638. 'updated_at' => date('Y-m-d H:i:s')
  3639. ]);
  3640. }
  3641. // 轮训获取图片任务结果
  3642. private function loopGetPicTaskResult($task_id) {
  3643. $task = MpGeneratePicTask::where('id', $task_id)->first();
  3644. if (!$task) {
  3645. return '';
  3646. }
  3647. // 检查任务模型类型(火山模型和GPT模型都支持直接检查任务状态)
  3648. $model = getProp($task, 'model');
  3649. $isVolcModel = in_array($model, \App\Consts\BaseConst::VOLC_PIC_MODELS);
  3650. $isGptModel = in_array($model, \App\Consts\BaseConst::GPT_IMAGE2_MODELS);
  3651. $isSyncModel = $isVolcModel || $isGptModel;
  3652. // 轮询查询任务状态(火山API和即梦AI都需要轮询)
  3653. $start_count = 0;
  3654. $img_url = '';
  3655. while ($start_count <= 60) { // 循环20次请求,每3s一次
  3656. sleep(3);
  3657. $task = MpGeneratePicTask::where('id', $task_id)->first();
  3658. // 如果任务已经完成,直接返回结果
  3659. if ($task->status === 'success' && $task->result_url) {
  3660. $result_urls = is_array($task->result_url) ? $task->result_url : json_decode($task->result_url, true);
  3661. return is_array($result_urls) ? $result_urls[0] : $task->result_url;
  3662. }
  3663. // 如果任务已失败,返回空
  3664. if ($task->status === 'failed') {
  3665. return '';
  3666. }
  3667. if ($isSyncModel) continue;
  3668. // 查询任务状态
  3669. $statusInfo = $this->aiImageGenerationService->queryTaskStatus($task);
  3670. if ($statusInfo['status'] === 'success') {
  3671. $task->updateStatus('success', [
  3672. 'result_url' => $statusInfo['result_url'],
  3673. 'result_json' => $statusInfo['result_json'] ?? []
  3674. ]);
  3675. // 同步调整分镜图片状态和结果
  3676. if (getProp($task, 'alias_segment_id')) {
  3677. DB::table('mp_episode_segments')->where('segment_id', getProp($task, 'alias_segment_id'))->update([
  3678. 'img_url' => $statusInfo['result_url'][0],
  3679. 'pic_task_status' => '已完成',
  3680. ]);
  3681. }
  3682. $img_url = $statusInfo['result_url'][0];
  3683. break;
  3684. } elseif ($statusInfo['status'] === 'failed') {
  3685. $task->updateStatus('failed', [
  3686. 'error_message' => $statusInfo['error_message'],
  3687. 'result_json' => $statusInfo['result_json'] ?? []
  3688. ]);
  3689. if (getProp($task, 'alias_segment_id')) {
  3690. DB::table('mp_episode_segments')->where('segment_id', getProp($task, 'alias_segment_id'))->update([
  3691. 'pic_task_status' => '失败',
  3692. ]);
  3693. }
  3694. break;
  3695. }
  3696. $start_count++;
  3697. }
  3698. return $img_url;
  3699. }
  3700. /**
  3701. * 从分镜内容中提取涉及的角色
  3702. */
  3703. private function extractCharactersFromSegment($segment_content, $available_characters, $roles) {
  3704. $found_characters = [];
  3705. foreach ($available_characters as $character) {
  3706. // 检查角色名称是否在分镜内容中出现
  3707. if (strpos($segment_content, $character) !== false) {
  3708. $found_characters[] = $character;
  3709. }
  3710. }
  3711. if (!$found_characters) {
  3712. foreach ($roles as $character) {
  3713. // 检查角色名称是否在分镜内容中出现
  3714. if (strpos($segment_content, $character) !== false) {
  3715. $found_characters[] = $character;
  3716. }
  3717. }
  3718. }
  3719. return array_unique($found_characters);
  3720. }
  3721. // 从分镜剧本中提取关键字段
  3722. private function handleSegmentContent(&$data) {
  3723. $segmentContent = getProp($data, 'segment_content');
  3724. // 解析分镜详细信息 - 与 Helpers.php 中 handleEpisodeContent 的 segmentData 结构保持一致
  3725. $segmentData = [
  3726. 'description' => '',
  3727. 'composition' => '',
  3728. 'camera_movement' => '',
  3729. 'voice_actor' => '',
  3730. 'dialogue' => '',
  3731. 'frame_type' => '',
  3732. 'scene' => '', // 场景
  3733. 'characters' => '', // 出镜角色
  3734. 'tail_frame' => '', // 尾帧描述
  3735. 'emotion' => '中性', // 情感
  3736. 'gender' => '0', // 性别(0未知,1男,2女)
  3737. 'speed_ratio' => 0, // 语速
  3738. 'loudness_ratio' => 0, // 音量
  3739. 'emotion_scale' => 4, // 情感强度
  3740. 'pitch' => 0, // 音调
  3741. ];
  3742. // 用于存储需要从 segment_content 中移除的匹配项
  3743. $replaceEmptyArr = [];
  3744. // 提取各个字段 - 兼容中文冒号和英文冒号,支持多种表达方式
  3745. if (preg_match('/(?:画面描述|镜头描述|场景描述)[::]\s*([^\n]+)/u', $segmentContent, $descMatch)) {
  3746. $segmentData['description'] = trim($descMatch[1]);
  3747. $data['description'] = trim($descMatch[1]);
  3748. }
  3749. if (preg_match('/(?:构图设计|构图|镜头构图)[::]\s*([^\n]+)/u', $segmentContent, $compMatch)) {
  3750. $segmentData['composition'] = trim($compMatch[1]);
  3751. $data['composition'] = trim($compMatch[1]);
  3752. }
  3753. if (preg_match('/(?:运镜调度|运镜|镜头运动|摄影机运动)[::]\s*([^\n]+)/u', $segmentContent, $cameraMatch)) {
  3754. $segmentData['camera_movement'] = trim($cameraMatch[1]);
  3755. $data['camera_movement'] = trim($cameraMatch[1]);
  3756. }
  3757. if (preg_match('/(?:配音角色|配音|角色|声优)[::]\s*([^\n]+)/u', $segmentContent, $voiceMatch)) {
  3758. $segmentData['voice_actor'] = trim($voiceMatch[1]);
  3759. $data['voice_actor'] = trim($voiceMatch[1]);
  3760. }
  3761. if (preg_match('/(?:台词内容|台词|对白|对话)[::]\s*([^\n]+)/u', $segmentContent, $dialogueMatch)) {
  3762. $segmentData['dialogue'] = trim($dialogueMatch[1]);
  3763. $data['dialogue'] = trim($dialogueMatch[1]);
  3764. }
  3765. if (preg_match('/(?:画面类型|镜头类型|类型)[::]\s*([^\n]+)/u', $segmentContent, $frameMatch)) {
  3766. $segmentData['frame_type'] = trim($frameMatch[1]);
  3767. $data['frame_type'] = trim($frameMatch[1]);
  3768. }
  3769. // 场景字段
  3770. if (preg_match('/(?:场景|拍摄场景|背景场景|环境)[::]\s*([^\n]+)/u', $segmentContent, $sceneMatch)) {
  3771. $segmentData['scene'] = trim($sceneMatch[1]);
  3772. $data['scene'] = trim($sceneMatch[1]);
  3773. }
  3774. // 出镜角色字段
  3775. if (preg_match('/(?:出镜角色|角色出镜|登场角色|人物)[::]\s*([^\n]+)/u', $segmentContent, $charactersMatch)) {
  3776. $segmentData['characters'] = trim($charactersMatch[1]);
  3777. $data['characters'] = trim($charactersMatch[1]);
  3778. }
  3779. // 尾帧描述字段
  3780. if (preg_match('/(?:尾帧描述|尾帧|结束帧|最后一帧|结尾画面|结束画面)[::]\s*([^\n]+)/u', $segmentContent, $tailFrameMatch)) {
  3781. $segmentData['tail_frame'] = trim($tailFrameMatch[1]);
  3782. $data['tail_frame'] = trim($tailFrameMatch[1]);
  3783. }
  3784. // 情感字段
  3785. if (preg_match('/(?:情感|情绪|感情)[::]\s*([^\n]+)/u', $segmentContent, $emotionMatch)) {
  3786. $replaceEmptyArr[] = trim($emotionMatch[0]);
  3787. $segmentData['emotion'] = trim($emotionMatch[1]);
  3788. $data['emotion'] = trim($emotionMatch[1]);
  3789. }
  3790. // 性别字段
  3791. if (preg_match('/(?:性别)[::]\s*([^\n]+)/u', $segmentContent, $genderMatch)) {
  3792. $replaceEmptyArr[] = trim($genderMatch[0]);
  3793. $genderStr = trim($genderMatch[1]);
  3794. if (strpos($genderStr, '男') !== false || $genderStr === '1') {
  3795. $segmentData['gender'] = '1';
  3796. $data['gender'] = '1';
  3797. } elseif (strpos($genderStr, '女') !== false || $genderStr === '2') {
  3798. $segmentData['gender'] = '2';
  3799. $data['gender'] = '2';
  3800. } else {
  3801. $segmentData['gender'] = '0';
  3802. $data['gender'] = '0';
  3803. }
  3804. }
  3805. // 语速字段
  3806. if (preg_match('/(?:语速|说话速度)[::]\s*([-+]?[0-9]*\.?[0-9]+)/u', $segmentContent, $speedMatch)) {
  3807. $replaceEmptyArr[] = trim($speedMatch[0]);
  3808. $segmentData['speed_ratio'] = (float)trim($speedMatch[1]);
  3809. $data['speed_ratio'] = (float)trim($speedMatch[1]);
  3810. }
  3811. // 音量字段
  3812. if (preg_match('/(?:音量|声音大小)[::]\s*([-+]?[0-9]*\.?[0-9]+)/u', $segmentContent, $loudnessMatch)) {
  3813. $replaceEmptyArr[] = trim($loudnessMatch[0]);
  3814. $segmentData['loudness_ratio'] = (float)trim($loudnessMatch[1]);
  3815. $data['loudness_ratio'] = (float)trim($loudnessMatch[1]);
  3816. }
  3817. // 情感强度字段
  3818. if (preg_match('/(?:情感强度|情绪强度)[::]\s*([0-9]+)/u', $segmentContent, $scaleMatch)) {
  3819. $replaceEmptyArr[] = trim($scaleMatch[0]);
  3820. $segmentData['emotion_scale'] = (int)trim($scaleMatch[1]);
  3821. $data['emotion_scale'] = (int)trim($scaleMatch[1]);
  3822. }
  3823. // 音调字段
  3824. if (preg_match('/(?:音调|音高)[::]\s*([-+]?[0-9]+)/u', $segmentContent, $pitchMatch)) {
  3825. $replaceEmptyArr[] = trim($pitchMatch[0]);
  3826. $segmentData['pitch'] = (int)trim($pitchMatch[1]);
  3827. $data['pitch'] = (int)trim($pitchMatch[1]);
  3828. }
  3829. // 从 segment_content 中移除已提取的配音参数字段
  3830. if (!empty($replaceEmptyArr)) {
  3831. $data['segment_content'] = str_replace($replaceEmptyArr, '', $segmentContent);
  3832. }
  3833. // 如果有配音角色,查询音色信息并验证情感
  3834. $voice_actor = $segmentData['voice_actor'];
  3835. if (!empty($voice_actor) && $voice_actor !== '旁白') {
  3836. // 从当前分镜所属的剧集或动漫中查找角色音色信息
  3837. $anime_id = getProp($data, 'anime_id');
  3838. $episode_id = getProp($data, 'episode_id');
  3839. // 优先从剧集的角色列表中查找
  3840. $roles = [];
  3841. if ($episode_id) {
  3842. $episode = DB::table('mp_anime_episodes')->where('id', $episode_id)->first();
  3843. if ($episode && getProp($episode, 'roles')) {
  3844. $roles = json_decode(getProp($episode, 'roles'), true) ?: [];
  3845. }
  3846. }
  3847. // 如果剧集中没有,从动漫的角色列表中查找
  3848. if (empty($roles) && $anime_id) {
  3849. $anime = DB::table('mp_animes')->where('id', $anime_id)->first();
  3850. if ($anime && getProp($anime, 'roles')) {
  3851. $roles = json_decode(getProp($anime, 'roles'), true) ?: [];
  3852. }
  3853. }
  3854. // 查找匹配的角色音色信息
  3855. $timbre_info = null;
  3856. foreach ($roles as $role) {
  3857. if (getProp($role, 'role') === $voice_actor) {
  3858. $timbre_info = $role;
  3859. break;
  3860. }
  3861. }
  3862. // 如果找到音色信息,添加到数据中
  3863. if ($timbre_info) {
  3864. $voice_type = getProp($timbre_info, 'voice_type');
  3865. $voice_name = getProp($timbre_info, 'voice_name');
  3866. $voice_audio_url = getProp($timbre_info, 'voice_audio_url');
  3867. if ($voice_type) {
  3868. $data['voice_type'] = $voice_type;
  3869. $segmentData['voice_type'] = $voice_type;
  3870. }
  3871. if ($voice_name) {
  3872. $data['voice_name'] = $voice_name;
  3873. $segmentData['voice_name'] = $voice_name;
  3874. }
  3875. if ($voice_audio_url) {
  3876. $data['voice_audio_url'] = $voice_audio_url;
  3877. $segmentData['voice_audio_url'] = $voice_audio_url;
  3878. }
  3879. // 验证情感是否在音色支持的情感列表中
  3880. if ($voice_type) {
  3881. $timbre_emotion = DB::table('mp_timbres')->where('timbre_type', $voice_type)->value('emotion');
  3882. if ($timbre_emotion) {
  3883. $timbre_emotion = explode(',', $timbre_emotion);
  3884. } else {
  3885. $timbre_emotion = [];
  3886. }
  3887. $emotion = getProp($segmentData, 'emotion', '中性');
  3888. if (!in_array($emotion, $timbre_emotion)) {
  3889. $emotion = '中性';
  3890. }
  3891. $emotion_list = DB::table('mp_emotion_list')->where('is_enabled', 1)->pluck('emotion_name', 'emotion_code')->toArray();
  3892. $emotion_list = array_flip($emotion_list);
  3893. $emotion_type = isset($emotion_list[$emotion]) ? $emotion_list[$emotion] : 'neutral';
  3894. $data['emotion_type'] = $emotion_type;
  3895. $segmentData['emotion_type'] = $emotion_type;
  3896. }
  3897. }
  3898. }
  3899. return $segmentData;
  3900. }
  3901. public function createSegmentVideoTask($data) {
  3902. $segment_id = getProp($data, 'segment_id');
  3903. $tail_frame = getProp($data, 'tail_frame');
  3904. $first_frame_url = getProp($data, 'first_frame_url');
  3905. $tail_frame_url = getProp($data, 'tail_frame_url');
  3906. $generate_audio = getProp($data, 'generate_audio', 0);
  3907. if (!$segment_id) {
  3908. Utils::throwError('1002:分镜ID不能为空');
  3909. }
  3910. // 获取分镜信息
  3911. $segment = DB::table('mp_episode_segments')->where('segment_id', $segment_id)->first();
  3912. if (!$segment) {
  3913. Utils::throwError('20003:分镜不存在');
  3914. }
  3915. $segment = (array)$segment;
  3916. $episode_id = getProp($segment, 'episode_id');
  3917. $ratio = DB::table('mp_anime_episodes')->where('id', $episode_id)->value('ratio');
  3918. if (!$ratio) $ratio = '9:16';
  3919. // 获取分镜内容
  3920. $segmentContent = getProp($segment, 'segment_content', '');
  3921. // 检查 $segmentContent 中是否已有尾帧描述
  3922. $contentHasTailFrame = preg_match('/(?:尾帧描述|尾帧)[::]\s*([^\n]+)/u', $segmentContent, $contentTailFrameMatch);
  3923. // 确定最终使用的尾帧描述(优先级:用户输入 > segmentContent自带 > 分镜表字段)
  3924. $finalTailFrame = '';
  3925. if ($tail_frame) {
  3926. // 用户输入了尾帧描述,优先使用
  3927. $finalTailFrame = $tail_frame;
  3928. // 如果 segmentContent 中已有尾帧描述,需要替换
  3929. if ($contentHasTailFrame) {
  3930. $segmentContent = preg_replace('/(?:尾帧描述|尾帧)[::]\s*[^\n]+/u', "尾帧描述:$tail_frame", $segmentContent);
  3931. }
  3932. } elseif ($contentHasTailFrame) {
  3933. // segmentContent 中有尾帧描述,使用它
  3934. $finalTailFrame = trim($contentTailFrameMatch[1]);
  3935. } else {
  3936. // 两者都没有,使用分镜表中的尾帧描述
  3937. $finalTailFrame = getProp($segment, 'tail_frame', '');
  3938. }
  3939. // 判断 $segmentContent 是否有台词内容,如果有则确保使用中文左右双引号
  3940. $hasDialogue = false;
  3941. if (preg_match('/(?:台词内容|台词|对白|对话)[::]\s*([^\n]+)/u', $segmentContent, $dialogueMatch)) {
  3942. $dialogue = trim($dialogueMatch[1]);
  3943. // 如果台词不为空且不是"无"
  3944. if (!empty($dialogue) && $dialogue !== '无') {
  3945. // 过滤掉所有符号(引号、标点、空格等),只保留文字内容来判断是否有实际台词
  3946. $dialogueFiltered = preg_replace('/[""\'\',。!?、;:…—\-\s\p{P}\p{S}]/u', '', $dialogue);
  3947. if (!empty($dialogueFiltered) && $dialogueFiltered !== '无') {
  3948. $hasDialogue = true;
  3949. }
  3950. $dialogue = preg_replace('/^["”]/u', '“', $dialogue); // 替换句首英文双引号或中文右双引号
  3951. $dialogue = preg_replace('/["“]$/u', '”', $dialogue); // 替换句尾英文双引号或中文左双引号
  3952. // 句首或句尾没有中文双引号,则分别添加中文左右双引号
  3953. if (!preg_match('/^[“]/', $dialogue)) {
  3954. $dialogue = '“' . $dialogue;
  3955. }
  3956. if (!preg_match('/[”]$/', $dialogue)) {
  3957. $dialogue .= '”';
  3958. }
  3959. // 将修改后的台词替换回 $segmentContent
  3960. $originalDialogue = $dialogueMatch[1];
  3961. $segmentContent = str_replace($originalDialogue, $dialogue, $segmentContent);
  3962. }
  3963. }
  3964. // 构建完整的提示词
  3965. $fullPrompt = $segmentContent;
  3966. if ($finalTailFrame && !$contentHasTailFrame) {
  3967. // 只有当 segmentContent 中没有尾帧描述时才追加
  3968. $fullPrompt .= "\n尾帧描述:$finalTailFrame";
  3969. }
  3970. // 去除多余的换行符(将连续多个换行符替换为单个换行符)
  3971. $fullPrompt = preg_replace('/\n{2,}/', "\n", $fullPrompt);
  3972. $fullPrompt = trim($fullPrompt);
  3973. // 当前是否启用音效同出(没台词强制关闭音效同出,节省资源收费)
  3974. $current_generate_audio = $hasDialogue ? $generate_audio : 0;
  3975. // 智能选择视频时长
  3976. // $videoDuration = $this->calculateOptimalVideoDuration($segmentContent, $tail_frame);
  3977. $videoDuration = -1;
  3978. // 处理视频模型
  3979. $model = getProp($data, 'model');
  3980. if (!$model) {
  3981. // 用户没有输入,从episode表获取
  3982. $episode = DB::table('mp_anime_episodes')->where('id', getProp($segment, 'episode_id'))->first();
  3983. $model = getProp($episode, 'video_model');
  3984. if (!$model) {
  3985. // episode表也没有,使用默认值
  3986. $model = 'doubao-seedance-1-5-pro-251215';
  3987. }
  3988. }
  3989. // 验证模型是否在可用模型表中
  3990. if (!DB::table('mp_video_models')->where('model', $model)->where('is_enabled', 1)->exists()) {
  3991. $model = 'doubao-seedance-1-5-pro-251215';
  3992. }
  3993. // 保存到episode表
  3994. $episode_id = getProp($segment, 'episode_id');
  3995. DB::table('mp_anime_episodes')->where('id', $episode_id)->update([
  3996. 'video_model' => $model,
  3997. 'updated_at' => date('Y-m-d H:i:s')
  3998. ]);
  3999. // 构建视频生成参数
  4000. $videoParams = [
  4001. 'model' => $model,
  4002. 'alias_segment_id' => $segment_id,
  4003. 'prompt' => trim($fullPrompt),
  4004. 'video_duration' => $videoDuration,
  4005. 'video_resolution' => '720P',
  4006. 'seed' => -1,
  4007. 'ratio' => $ratio,
  4008. 'generate_audio' => (int)$current_generate_audio === 0 ? false : true,
  4009. 'draft' => false,
  4010. 'watermark' => false,
  4011. 'camera_fixed' => false,
  4012. // 'callback_url' => 'http://mpaudio.yqsd.cn/api/video/seedanceCallback'
  4013. ];
  4014. // 如果分镜有图片,作为首帧
  4015. $hasImage = !empty(getProp($segment, 'img_url')) || $first_frame_url;
  4016. $hasVideo = !empty(getProp($segment, 'video_url'));
  4017. if ($hasImage) {
  4018. if ($first_frame_url) {
  4019. $videoParams['first_frame_url'] = $first_frame_url;
  4020. }else {
  4021. $videoParams['first_frame_url'] = getProp($segment, 'img_url');
  4022. }
  4023. if ($tail_frame_url) $videoParams['tail_frame_url'] = $tail_frame_url;
  4024. }
  4025. // 构建content数组
  4026. $videoParams['content'] = [
  4027. [
  4028. 'type' => 'text',
  4029. 'text' => $videoParams['prompt'],
  4030. ]
  4031. ];
  4032. // 如果有首帧图片,添加到content中
  4033. if ($hasImage) {
  4034. if (in_array($model, ['doubao-seedance-2-0-260128', 'doubao-seedance-2-0-fast-260128', 'baidu-doubao-seedance-2-5-260628', 'baidu-doubao-seedance-2-0-260128', 'baidu-doubao-seedance-2-0-fast-260128', 'baidu-doubao-seedance-2-0-mini-260615', 'baidu-dreamina-seedance-2-0-260128', 'baidu-dreamina-seedance-2-0-fast-260128', 'baidu-dreamina-seedance-2-0-mini-260615', 'baidu-dreamina-seedance-2-5-260628'])) {
  4035. $videoParams['content'][] = [
  4036. 'type' => 'image_url',
  4037. 'image_url' => [
  4038. 'url' => $videoParams['first_frame_url'],
  4039. ],
  4040. 'role' => 'reference_image',
  4041. ];
  4042. if (isset($videoParams['tail_frame_url'])) {
  4043. $videoParams['content'][] = [
  4044. 'type' => 'image_url',
  4045. 'image_url' => [
  4046. 'url' => $videoParams['tail_frame_url'],
  4047. ],
  4048. 'role' => 'reference_image',
  4049. ];
  4050. }
  4051. }else {
  4052. $videoParams['content'][] = [
  4053. 'type' => 'image_url',
  4054. 'image_url' => [
  4055. 'url' => $videoParams['first_frame_url'],
  4056. ],
  4057. 'role' => 'first_frame',
  4058. ];
  4059. if (isset($videoParams['tail_frame_url'])) {
  4060. $videoParams['content'][] = [
  4061. 'type' => 'image_url',
  4062. 'image_url' => [
  4063. 'url' => $videoParams['tail_frame_url'],
  4064. ],
  4065. 'role' => 'last_frame',
  4066. ];
  4067. }
  4068. }
  4069. }
  4070. // 获取配音音频URL
  4071. $audioUrl = getProp($segment, 'audio_url');
  4072. $audioDuration = getProp($segment, 'audio_duration');
  4073. // 音频传入的前提:必须有至少一张图片或一个视频
  4074. $canUseAudio = ($hasImage || $hasVideo) && !empty($audioUrl);
  4075. // 余额预检:按预估时长计算所需积分,不足直接报错
  4076. $chargeDuration = (int)ceil((float)$audioDuration);
  4077. if ($chargeDuration <= 0) {
  4078. $chargeDuration = 5; // 无音频时长时按默认5秒预估
  4079. }
  4080. $this->pointsService->checkUserPointsEnough(
  4081. $this->pointsService->getVideoChargePoints([
  4082. 'model' => $model,
  4083. 'video_resolution' => strtolower($videoParams['video_resolution'] ?? '720P'),
  4084. 'video_duration' => $chargeDuration,
  4085. 'ratio' => $ratio,
  4086. 'generate_audio' => $current_generate_audio,
  4087. ])
  4088. );
  4089. // dd($videoParams);
  4090. // 根据模型选择不同的视频生成方法
  4091. if (strpos($model, 'jimeng') !== false) {
  4092. // 即梦模型参数调整
  4093. $videoParams['video_duration'] = $audioDuration > 5 ? 10 : 5; // 即梦只支持5s或10s
  4094. unset($videoParams['content']); // 即梦不使用content格式
  4095. $task = $this->aiVideoGenerationService->createJimengTask($videoParams);
  4096. } elseif (strpos($model, 'kling') !== false) {
  4097. // Keling模型参数调整
  4098. $videoParams['video_duration'] = max(3, min(15, ceil($audioDuration))); // Keling支持3-15秒
  4099. $videoParams['aspect_ratio'] = $videoParams['ratio']; // Keling使用aspect_ratio
  4100. unset($videoParams['ratio']);
  4101. unset($videoParams['content']); // Keling不使用content格式
  4102. $task = $this->aiVideoGenerationService->createKelingOmniTask($videoParams);
  4103. } elseif (strpos($model, 'zhizhen') !== false) {
  4104. // 智帧20等新模型使用统一API
  4105. // 构建统一API参数
  4106. $unifiedParams = [
  4107. 'model_code' => $model,
  4108. 'alias_segment_id' => $segment_id,
  4109. 'prompt' => trim($fullPrompt),
  4110. 'video_duration' => $audioDuration > 0 ? max(5, min(15, ceil($audioDuration))) : 5,
  4111. 'video_resolution' => strtolower($videoParams['video_resolution']),
  4112. 'video_ratio' => $ratio,
  4113. 'seed' => -1,
  4114. ];
  4115. // 构建parameters参数
  4116. $parameters = [
  4117. 'seconds' => $unifiedParams['video_duration'],
  4118. 'resolution' => $unifiedParams['video_resolution'],
  4119. 'ratio' => $ratio,
  4120. // 'video_mode' => 'multi_image',
  4121. // 'mode' => 'multi_image',
  4122. 'generate_audio' => (int)$current_generate_audio === 1 ? true : false,
  4123. ];
  4124. $hasImage = false;
  4125. // 处理首帧和尾帧(智帧20模型必须要有首帧图片)
  4126. if ($hasImage) {
  4127. $parameters['first_frame_url'] = $videoParams['first_frame_url'];
  4128. if (isset($videoParams['tail_frame_url'])) {
  4129. $parameters['last_frame_url'] = $videoParams['tail_frame_url'];
  4130. }
  4131. // 只有在有图片的情况下才能添加参考音频
  4132. if ($audioUrl) {
  4133. // $parameters['reference_audios'] = [$audioUrl];
  4134. }
  4135. } else {
  4136. // 没有图片时,记录错误日志
  4137. logDB('anime', 'error', '智帧20模型缺少首帧图片', [
  4138. 'segment_id' => $segment_id,
  4139. 'model' => $model
  4140. ]);
  4141. }
  4142. $unifiedParams['parameters'] = $parameters;
  4143. // 调用统一API创建任务
  4144. $task = $this->aiVideoGenerationService->createUnifiedApiTask($unifiedParams);
  4145. } else {
  4146. // Seedance模型(默认)
  4147. // 快快AI Seedance 2.0/2.5:配音音频需先上传为素材,走聚合网关 /v1/video/generations
  4148. if ($this->isKuaikuaiSeedanceModel($model)) {
  4149. $videoParams['gateway_base_url'] = env('KUAIKUAI_AI_BASE_URL', 'https://ai-api.kkidc.com');
  4150. if ($canUseAudio && $audioUrl) {
  4151. // 上传配音音频为素材(上传失败时同步清理提示词中的<音频N>标记,不阻断任务)
  4152. $reference_audio_assets = $this->aiVideoGenerationService->processReferenceAudiosToKuaikuaiAssets([$audioUrl], $fullPrompt);
  4153. $videoParams['reference_audio_assets'] = $reference_audio_assets;
  4154. // 优化提示词,增加音频相关描述
  4155. $audioPrompt = "全程使用音频1作为视频配音。" . $fullPrompt;
  4156. $videoParams['prompt'] = $audioPrompt;
  4157. } elseif ($audioDuration) { // 有音频时长则需将视频时长设置为比音频时长更长的整数
  4158. $videoParams['video_duration'] = max(4, min(12, ceil($audioDuration)));
  4159. }
  4160. $task = $this->aiVideoGenerationService->createKuaikuaiVideoTask($videoParams);
  4161. } elseif ($canUseAudio && in_array($model, ['doubao-seedance-2-0-260128', 'doubao-seedance-2-0-fast-260128', 'baidu-doubao-seedance-2-5-260628', 'baidu-doubao-seedance-2-0-260128', 'baidu-doubao-seedance-2-0-fast-260128', 'baidu-doubao-seedance-2-0-mini-260615', 'baidu-dreamina-seedance-2-0-260128', 'baidu-dreamina-seedance-2-0-fast-260128', 'baidu-dreamina-seedance-2-0-mini-260615', 'baidu-dreamina-seedance-2-5-260628'])) {
  4162. // 检查是否为 Seedance 2.0 模型,如果是则需要处理配音音频
  4163. // 添加配音音频到content中
  4164. $videoParams['content'][] = [
  4165. 'type' => 'audio_url',
  4166. 'audio_url' => [
  4167. 'url' => $audioUrl,
  4168. ],
  4169. 'role' => 'reference_audio',
  4170. ];
  4171. // 优化提示词,增加音频相关描述
  4172. $audioPrompt = "全程使用音频1作为视频配音。" . $fullPrompt;
  4173. $videoParams['prompt'] = $audioPrompt;
  4174. $videoParams['content'][0]['text'] = $audioPrompt;
  4175. } else {
  4176. if ($audioDuration) { // 有音频时长则需将视频时长设置为比音频时长更长的整数
  4177. $videoParams['video_duration'] = max(4, min(12, ceil($audioDuration))); // seedance支持2-12s
  4178. }
  4179. $task = $this->aiVideoGenerationService->createSeedanceTask($videoParams);
  4180. }
  4181. }
  4182. // 更新分镜表的视频任务信息
  4183. DB::table('mp_episode_segments')->where('segment_id', $segment_id)->update([
  4184. 'video_task_id' => $task->id,
  4185. 'video_task_status' => '生成中',
  4186. 'generate_audio' => $generate_audio,
  4187. 'updated_at' => date('Y-m-d H:i:s')
  4188. ]);
  4189. return [
  4190. 'task_id' => $task->id,
  4191. 'status' => $task->status,
  4192. 'segment_id' => $segment_id,
  4193. 'video_duration' => $videoDuration
  4194. ];
  4195. }
  4196. /**
  4197. * 是否为快快AI Seedance 2.0/2.5 系列模型
  4198. * 快快AI平台模型ID:seed-2-fast / seed-2-mini / seed-2.5 / seed-2
  4199. *
  4200. * @param string $model
  4201. * @return bool
  4202. */
  4203. public function isKuaikuaiSeedanceModel(string $model): bool
  4204. {
  4205. return in_array($model, ['seed-2-fast', 'seed-2-mini', 'seed-2.5', 'seed-2'], true);
  4206. }
  4207. /**
  4208. * 是否为百度AI网关Seedance 2.0系列模型(系统内使用 baidu- 前缀名,请求网关时映射为 doubao- 原名)
  4209. *
  4210. * @param string $model
  4211. * @return bool
  4212. */
  4213. public function isBaiduSeedanceModel(string $model): bool
  4214. {
  4215. return in_array($model, [
  4216. 'baidu-doubao-seedance-2-0-260128',
  4217. 'baidu-doubao-seedance-2-0-fast-260128',
  4218. 'baidu-doubao-seedance-2-0-mini-260615',
  4219. 'baidu-doubao-seedance-2-5-260628',
  4220. ], true);
  4221. }
  4222. /**
  4223. * 是否为海外百度Seedance(dreamina真人素材空间)模型
  4224. * 系统内使用 baidu-dreamina- 前缀名,请求网关时映射为 dreamina-* 原名
  4225. *
  4226. * @param string $model
  4227. * @return bool
  4228. */
  4229. public function isOverseasBaiduSeedanceModel(string $model): bool
  4230. {
  4231. return in_array($model, [
  4232. 'baidu-dreamina-seedance-2-0-260128',
  4233. 'baidu-dreamina-seedance-2-0-fast-260128',
  4234. 'baidu-dreamina-seedance-2-0-mini-260615',
  4235. 'baidu-dreamina-seedance-2-5-260628',
  4236. ], true);
  4237. }
  4238. /**
  4239. * 是否为 Seedance 2.0 系列模型(百度 doubao-seedance-2.0 / baidu-doubao-* / baidu-dreamina-* / 快快AI seed-2 系列)
  4240. * 供单条与批量生成入口统一判断,避免各入口各自维护模型白名单
  4241. *
  4242. * @param string $model
  4243. * @return bool
  4244. */
  4245. public function isSeedance20SeriesModel(string $model): bool
  4246. {
  4247. return strpos($model, 'doubao-seedance-2.0') !== false
  4248. || $this->isKuaikuaiSeedanceModel($model)
  4249. || $this->isBaiduSeedanceModel($model)
  4250. || $this->isOverseasBaiduSeedanceModel($model);
  4251. }
  4252. public function createActVideoTask($data) {
  4253. $act_id = getProp($data, 'act_id');
  4254. $first_frame_url = getProp($data, 'first_frame_url');
  4255. $tail_frame_url = getProp($data, 'tail_frame_url');
  4256. $generate_audio = getProp($data, 'generate_audio', 1);
  4257. $video_duration = getProp($data, 'video_duration');
  4258. $video_resolution = getProp($data, 'video_resolution');
  4259. $ratio = getProp($data, 'ratio');
  4260. $products = getProp($data, 'products', []);
  4261. $reference_images = array_unique(getProp($data, 'reference_images', []));
  4262. if (!is_array($reference_images) || !is_array($products)) {
  4263. Utils::throwError('20003:传入的参考图或资产格式不正确');
  4264. }
  4265. if (!$act_id) {
  4266. Utils::throwError('1002:片段ID不能为空');
  4267. }
  4268. // 获取片段信息
  4269. $act = DB::table('mp_episode_segments')->where('id', $act_id)->first();
  4270. if (!$act) {
  4271. Utils::throwError('20003:片段不存在');
  4272. }
  4273. $act = (array)$act;
  4274. $anime_id = getProp($act, 'anime_id');
  4275. $episode_id = getProp($act, 'episode_id');
  4276. $anime = DB::table('mp_animes')->where('id', $anime_id)->first();
  4277. $ace_mode = getProp($anime, 'ace_mode');
  4278. $art_style_type = getProp($anime, 'art_style_type');
  4279. $art_style = getProp($anime, 'art_style');
  4280. $episode = DB::table('mp_anime_episodes')->where('id', $episode_id)->first();
  4281. if (!$ratio) $ratio = getProp($episode, 'ratio', '9:16');
  4282. if (!$video_resolution) $video_resolution = getProp($episode, 'video_resolution', '720p');
  4283. // 将资产中新出现的资产放到extra_products中
  4284. // 满足以下要求: 遍历传入的$products,将product_name与$episode中的roles、scenes和props做比对,如果不在其中,则与$episode中的extra_products做比对,如果有同名的则覆盖,没有则新增后存入$episode中的extra_products字段中
  4285. if (!empty($products) && $episode) {
  4286. // 获取剧集中的角色、场景和道具列表
  4287. $roles = json_decode(getProp($episode, 'roles', '[]'), true) ?: [];
  4288. $scenes = json_decode(getProp($episode, 'scenes', '[]'), true) ?: [];
  4289. $props = json_decode(getProp($episode, 'props', '[]'), true) ?: [];
  4290. $extra_products = json_decode(getProp($episode, 'extra_products', '[]'), true) ?: [];
  4291. // 构建角色名称列表
  4292. $role_names = array_column($roles, 'role');
  4293. // 构建场景名称列表
  4294. $scene_names = array_column($scenes, 'scene');
  4295. // 构建道具名称列表
  4296. $prop_names = array_column($props, 'prop');
  4297. // 遍历传入的products
  4298. foreach ($products as $product) {
  4299. $product_name = getProp($product, 'product_name');
  4300. // 如果product_name不在roles、scenes和props中
  4301. if (!in_array($product_name, $role_names) && !in_array($product_name, $scene_names) && !in_array($product_name, $prop_names)) {
  4302. // 查找是否在extra_products中存在同名的
  4303. $found = false;
  4304. foreach ($extra_products as $key => $extra_product) {
  4305. if (getProp($extra_product, 'product_name') === $product_name) {
  4306. // 有同名的则覆盖
  4307. $extra_products[$key] = $product;
  4308. $found = true;
  4309. break;
  4310. }
  4311. }
  4312. // 没有则新增
  4313. if (!$found) {
  4314. $extra_products[] = $product;
  4315. }
  4316. }
  4317. }
  4318. if ($extra_products) {
  4319. // 保存到数据库
  4320. DB::table('mp_anime_episodes')
  4321. ->where('id', $episode_id)
  4322. ->update([
  4323. 'extra_products' => json_encode($extra_products, 256),
  4324. 'updated_at' => date('Y-m-d H:i:s')
  4325. ]);
  4326. }
  4327. }
  4328. // 获取分镜内容
  4329. $actContent = getProp($act, 'act_show_content', '');
  4330. // 音效同出(默认使用)
  4331. $current_generate_audio = $generate_audio ? 1 : 0;
  4332. // 构建完整的提示词
  4333. $processResult = $this->processActContentWithProducts($actContent, $products);
  4334. $fullPrompt = $processResult['content'];
  4335. // if ($art_style_type == '3D真人风格') $fullPrompt = "美术风格: $art_style\n\n".$fullPrompt;
  4336. $reference_images = array_merge($processResult['reference_images'], $reference_images);
  4337. $videoDuration = $video_duration ? $video_duration : getProp($act, 'act_duration');
  4338. // 处理视频模型
  4339. $model = getProp($data, 'model');
  4340. if (!$model) {
  4341. $model = getProp($episode, 'video_model');
  4342. if (!$model) {
  4343. // episode表也没有,使用默认值
  4344. $model = 'seed-2';
  4345. }
  4346. }
  4347. // 验证模型是否在可用模型表中(全能模式片段转视频仅允许 ace_mode=1 的模型)
  4348. $valid_models = DB::table('mp_video_models')->where('ace_mode', 1)->select('model')->pluck('model')->toArray();
  4349. if (!in_array($model, $valid_models)) {
  4350. $model = 'seed-2';
  4351. }
  4352. // 保存到episode表(仅在专用方法中更新模型)
  4353. // DB::table('mp_anime_episodes')->where('id', $episode_id)->update([
  4354. // 'video_model' => $model,
  4355. // 'updated_at' => date('Y-m-d H:i:s')
  4356. // ]);
  4357. // 余额预检:按预估时长计算所需积分,不足直接报错
  4358. $chargeDuration = (int)$videoDuration;
  4359. if ($chargeDuration <= 0) {
  4360. $chargeDuration = 5; // 无时长时按默认5秒预估
  4361. }
  4362. $this->pointsService->checkUserPointsEnough(
  4363. $this->pointsService->getVideoChargePoints([
  4364. 'model' => $model,
  4365. 'video_resolution' => strtolower($video_resolution ?? '720p'),
  4366. 'video_duration' => $chargeDuration,
  4367. 'ratio' => $ratio,
  4368. 'generate_audio' => $current_generate_audio,
  4369. ])
  4370. );
  4371. // 构建视频生成参数
  4372. $videoParams = [
  4373. 'model' => $model,
  4374. 'alias_act_id' => $act_id,
  4375. 'prompt' => trim($fullPrompt),
  4376. 'video_duration' => $videoDuration,
  4377. 'video_resolution' => $video_resolution,
  4378. 'seed' => -1,
  4379. 'ratio' => $ratio,
  4380. 'generate_audio' => (int)$current_generate_audio === 0 ? false : true,
  4381. 'draft' => false,
  4382. 'watermark' => false,
  4383. 'camera_fixed' => false,
  4384. // 'callback_url' => 'http://mpaudio.yqsd.cn/api/video/seedanceCallback'
  4385. ];
  4386. // 如果分镜有图片,作为首帧
  4387. $hasImage = !empty(getProp($act, 'img_url')) || $first_frame_url;
  4388. $hasVideo = !empty(getProp($act, 'video_url'));
  4389. if ($hasImage) {
  4390. if ($first_frame_url) {
  4391. $videoParams['first_frame_url'] = $first_frame_url;
  4392. }else {
  4393. $videoParams['first_frame_url'] = getProp($act, 'img_url');
  4394. }
  4395. if ($tail_frame_url) $videoParams['tail_frame_url'] = $tail_frame_url;
  4396. }
  4397. // 构建content数组
  4398. $videoParams['content'] = [
  4399. [
  4400. 'type' => 'text',
  4401. 'text' => $videoParams['prompt'],
  4402. ]
  4403. ];
  4404. // 如果有首帧图片,添加到content中
  4405. if ($hasImage) {
  4406. if (in_array($model, ['doubao-seedance-2-0-260128', 'doubao-seedance-2-0-fast-260128', 'doubao-seedance-2.0', 'baidu-doubao-seedance-2-5-260628', 'baidu-doubao-seedance-2-0-260128', 'baidu-doubao-seedance-2-0-fast-260128', 'baidu-doubao-seedance-2-0-mini-260615', 'baidu-dreamina-seedance-2-0-260128', 'baidu-dreamina-seedance-2-0-fast-260128', 'baidu-dreamina-seedance-2-0-mini-260615', 'baidu-dreamina-seedance-2-5-260628'])) {
  4407. $videoParams['content'][] = [
  4408. 'type' => 'image_url',
  4409. 'image_url' => [
  4410. 'url' => $videoParams['first_frame_url'],
  4411. ],
  4412. 'role' => 'reference_image',
  4413. ];
  4414. if (isset($videoParams['tail_frame_url'])) {
  4415. $videoParams['content'][] = [
  4416. 'type' => 'image_url',
  4417. 'image_url' => [
  4418. 'url' => $videoParams['tail_frame_url'],
  4419. ],
  4420. 'role' => 'reference_image',
  4421. ];
  4422. }
  4423. }else {
  4424. $videoParams['content'][] = [
  4425. 'type' => 'image_url',
  4426. 'image_url' => [
  4427. 'url' => $videoParams['first_frame_url'],
  4428. ],
  4429. 'role' => 'first_frame',
  4430. ];
  4431. if (isset($videoParams['tail_frame_url'])) {
  4432. $videoParams['content'][] = [
  4433. 'type' => 'image_url',
  4434. 'image_url' => [
  4435. 'url' => $videoParams['tail_frame_url'],
  4436. ],
  4437. 'role' => 'last_frame',
  4438. ];
  4439. }
  4440. }
  4441. }
  4442. // dd($videoParams);
  4443. // 根据模型选择不同的视频生成方法
  4444. try {
  4445. if (strpos($model, 'jimeng') !== false) {
  4446. // 即梦模型参数调整
  4447. unset($videoParams['content']); // 即梦不使用content格式
  4448. $task = $this->aiVideoGenerationService->createJimengTask($videoParams);
  4449. } elseif (strpos($model, 'kling') !== false) {
  4450. // Keling模型参数调整
  4451. $videoParams['aspect_ratio'] = $videoParams['ratio']; // Keling使用aspect_ratio
  4452. unset($videoParams['ratio']);
  4453. unset($videoParams['content']); // Keling不使用content格式
  4454. $task = $this->aiVideoGenerationService->createKelingOmniTask($videoParams);
  4455. } elseif (strpos($model, 'zhizhen') !== false) {
  4456. // 智帧20等新模型使用统一API
  4457. // 构建统一API参数
  4458. $unifiedParams = [
  4459. 'model_code' => $model,
  4460. 'alias_act_id' => $act_id,
  4461. 'prompt' => trim($fullPrompt),
  4462. 'video_duration' => $videoDuration,
  4463. 'video_resolution' => strtolower($videoParams['video_resolution']),
  4464. 'video_ratio' => $ratio,
  4465. 'seed' => -1,
  4466. ];
  4467. // 构建parameters参数
  4468. $parameters = [
  4469. 'seconds' => $unifiedParams['video_duration'],
  4470. 'resolution' => $unifiedParams['video_resolution'],
  4471. 'ratio' => $ratio,
  4472. // 'video_mode' => 'multi_image',
  4473. // 'mode' => 'multi_image',
  4474. 'generate_audio' => (int)$current_generate_audio === 1 ? true : false,
  4475. ];
  4476. $hasImage = false;
  4477. // 处理首帧和尾帧(智帧20模型必须要有首帧图片)
  4478. if ($hasImage) {
  4479. $parameters['first_frame_url'] = $videoParams['first_frame_url'];
  4480. if (isset($videoParams['tail_frame_url'])) {
  4481. $parameters['last_frame_url'] = $videoParams['tail_frame_url'];
  4482. }
  4483. } else {
  4484. // 没有图片时,记录错误日志
  4485. logDB('anime', 'error', '智帧20模型缺少首帧图片', [
  4486. 'act_id' => $act_id,
  4487. 'model' => $model
  4488. ]);
  4489. }
  4490. if ($reference_images) {
  4491. // 限制只传入9张参考图
  4492. $reference_images = array_slice($reference_images, 0, 9);
  4493. // 在处理之前先保存原始reference_images到任务参数中
  4494. $unifiedParams['ref_image_url'] = json_encode($reference_images, 256);
  4495. $reference_images = $this->aiImageGenerationService->processReferenceImagesToAssets($reference_images, $unifiedParams['prompt']);
  4496. $parameters['reference_images'] = $reference_images;
  4497. $parameters['video_mode'] = 'multi_image';
  4498. $parameters['mode'] = 'multi_image';
  4499. }
  4500. $unifiedParams['parameters'] = $parameters;
  4501. // 调用统一API创建任务
  4502. $task = $this->aiVideoGenerationService->createUnifiedApiTask($unifiedParams);
  4503. } elseif ($this->isSeedance20SeriesModel($model)) {
  4504. // 豆包Seedance 2.0(百度AI网关)/ 快快AI Seedance 2.0/2.5:图片需要先上传为素材
  4505. $isKuaikuai = $this->isKuaikuaiSeedanceModel($model);
  4506. $isDreamina = $this->isOverseasBaiduSeedanceModel($model);
  4507. // 保存原始参考图用于任务记录
  4508. $videoParams['reference_images'] = $reference_images;
  4509. if ($reference_images) {
  4510. // 限制只传入9张参考图
  4511. $reference_images = array_slice($reference_images, 0, 9);
  4512. // 维护ref_image_url字段(参考图URL,JSON数组,与智帧分支保持一致)
  4513. $videoParams['ref_image_url'] = json_encode($reference_images, 256);
  4514. // 参考图上传为素材(国内百度/海外百度dreamina/快快AI),上传失败时同步清理提示词中的<图片N>标记
  4515. $reference_image_assets = $isKuaikuai
  4516. ? $this->aiVideoGenerationService->processReferenceImagesToKuaikuaiAssets($reference_images, $fullPrompt)
  4517. : ($isDreamina
  4518. ? $this->aiVideoGenerationService->processReferenceImagesToBaiduDreaminaAssets($reference_images, $fullPrompt)
  4519. : $this->aiVideoGenerationService->processReferenceImagesToSeedance20Assets($reference_images, $fullPrompt));
  4520. // 素材上传失败后提示词可能被清理,同步更新视频参数中的提示词
  4521. $videoParams['prompt'] = trim($fullPrompt);
  4522. $videoParams['content'][0]['text'] = trim($fullPrompt);
  4523. $videoParams['reference_image_assets'] = $reference_image_assets;
  4524. }
  4525. // 快快AI走聚合网关 /v1/video/generations(火山豆包格式)
  4526. if ($isKuaikuai) {
  4527. $videoParams['gateway_base_url'] = env('KUAIKUAI_AI_BASE_URL', 'https://ai-api.kkidc.com');
  4528. $task = $this->aiVideoGenerationService->createKuaikuaiVideoTask($videoParams);
  4529. } else {
  4530. $task = $this->aiVideoGenerationService->createSeedance20Task($videoParams);
  4531. }
  4532. } else {
  4533. $task = $this->aiVideoGenerationService->createSeedanceTask($videoParams);
  4534. }
  4535. } catch (ApiException $e) {
  4536. // 上游调用抛出的网关异常统一做友好化处理;本地业务错误(非1001)保持原提示不变
  4537. if ($e->getCode() === 1001) {
  4538. Utils::throwError('1001:' . mapErrorMessage($e->getMessage()));
  4539. }
  4540. throw $e;
  4541. } catch (\Exception $e) {
  4542. // 其他未包装的异常,同样只对报错信息做格式化,便于前端展示友好提示
  4543. Utils::throwError('20003:' . mapErrorMessage($e->getMessage()));
  4544. }
  4545. // 更新分镜表的视频任务信息
  4546. DB::table('mp_episode_segments')->where('id', $act_id)->update([
  4547. 'video_task_id' => $task->id,
  4548. 'video_task_status' => '生成中',
  4549. 'generate_audio' => $generate_audio,
  4550. 'updated_at' => date('Y-m-d H:i:s')
  4551. ]);
  4552. // 如果是全能模式,并且是第一集的第一个片段,将act_id存入Redis
  4553. $episode_number = getProp($act, 'episode_number');
  4554. $act_number = getProp($act, 'act_number');
  4555. if ((int)$ace_mode === 1 && (int)$episode_number === 1 && (int)$act_number === 1) {
  4556. Redis::sadd('anime_act_first_frame_urls', $act_id);
  4557. }
  4558. $result = [
  4559. 'task_id' => $task->id,
  4560. 'status' => $task->status,
  4561. 'act_id' => $act_id,
  4562. 'video_duration' => $videoDuration
  4563. ];
  4564. // 仅当任务提交阶段就已失败时,附带格式化后的错误信息;正常返回结构不受影响
  4565. if ($task->status === 'failed' && !empty($task->error_message)) {
  4566. $result['error_message'] = mapErrorMessage($task->error_message);
  4567. }
  4568. return $result;
  4569. }
  4570. /**
  4571. * 文生视频通用方法
  4572. * 支持传入视频参数、提示词、参考图等信息,不支持products入参
  4573. * 用户提示词不做任何处理,直接组装参数后根据模型调用
  4574. *
  4575. * @param array $data 请求参数
  4576. * @return array
  4577. */
  4578. public function generateVideo($data) {
  4579. $prompt = getProp($data, 'prompt');
  4580. if (empty($prompt)) {
  4581. Utils::throwError('20003:提示词不能为空');
  4582. }
  4583. $model = getProp($data, 'model');
  4584. if (!$model) {
  4585. $model = 'seed-2';
  4586. }
  4587. // 验证模型是否在可用模型表中
  4588. if (!DB::table('mp_video_models')->where('model', $model)->where('is_enabled', 1)->exists()) {
  4589. Utils::throwError('20003:该模型已不可用,请更换!');
  4590. }
  4591. $video_duration = getProp($data, 'video_duration', 5);
  4592. // 默认超分720p档(按480p生成后本地超分到720p);480p为原始档需前端显式指定
  4593. $video_resolution = getProp($data, 'video_resolution', 'sr_720p');
  4594. $ratio = getProp($data, 'ratio', '9:16');
  4595. $generate_audio = getProp($data, 'generate_audio', 1);
  4596. $seed = getProp($data, 'seed', -1);
  4597. $first_frame_url = getProp($data, 'first_frame_url');
  4598. $tail_frame_url = getProp($data, 'tail_frame_url');
  4599. // 参考图(支持数组或JSON字符串,最多9张)
  4600. $reference_images = getProp($data, 'reference_images', []);
  4601. if (is_string($reference_images)) {
  4602. $reference_images = json_decode($reference_images, true) ?: [];
  4603. }
  4604. if (!is_array($reference_images)) {
  4605. Utils::throwError('20003:参考图格式不正确');
  4606. }
  4607. $reference_images = array_values(array_unique(array_filter($reference_images)));
  4608. $reference_images = array_slice($reference_images, 0, 9);
  4609. // 参考视频(支持数组或JSON字符串,最多3个)
  4610. $reference_videos = getProp($data, 'reference_videos', []);
  4611. if (is_string($reference_videos)) {
  4612. $reference_videos = json_decode($reference_videos, true) ?: [];
  4613. }
  4614. if (!is_array($reference_videos)) {
  4615. Utils::throwError('20003:参考视频格式不正确');
  4616. }
  4617. $reference_videos = array_values(array_unique(array_filter($reference_videos)));
  4618. if (count($reference_videos) > 3) {
  4619. Utils::throwError('20003:参考视频最多选择3个');
  4620. }
  4621. $reference_videos = array_slice($reference_videos, 0, 3);
  4622. // 参考音频(支持数组或JSON字符串,最多3个)
  4623. $reference_audios = getProp($data, 'reference_audios', []);
  4624. if (is_string($reference_audios)) {
  4625. $reference_audios = json_decode($reference_audios, true) ?: [];
  4626. }
  4627. if (!is_array($reference_audios)) {
  4628. Utils::throwError('20003:参考音频格式不正确');
  4629. }
  4630. $reference_audios = array_values(array_unique(array_filter($reference_audios)));
  4631. if (count($reference_audios) > 3) {
  4632. Utils::throwError('20003:参考音频最多选择3个');
  4633. }
  4634. $reference_audios = array_slice($reference_audios, 0, 3);
  4635. // 余额预检:按预估时长计算所需积分,不足直接报错
  4636. $chargeDuration = (int)ceil((float)$video_duration);
  4637. if ($chargeDuration <= 0) {
  4638. $chargeDuration = 5; // 无时长时按默认5秒预估
  4639. }
  4640. $this->pointsService->checkUserPointsEnough(
  4641. $this->pointsService->getVideoChargePoints([
  4642. 'model' => $model,
  4643. 'video_resolution' => strtolower($video_resolution ?? '720p'),
  4644. 'video_duration' => $chargeDuration,
  4645. 'ratio' => $ratio,
  4646. 'generate_audio' => (int)$generate_audio,
  4647. ])
  4648. );
  4649. // 构建视频生成参数(用户参数直接透传,提示词不做处理)
  4650. $videoParams = [
  4651. 'model' => $model,
  4652. 'prompt' => $prompt,
  4653. 'video_duration' => $video_duration,
  4654. 'video_resolution' => $video_resolution,
  4655. 'seed' => $seed,
  4656. 'ratio' => $ratio,
  4657. 'generate_audio' => (int)$generate_audio === 1 ? true : false,
  4658. 'draft' => getProp($data, 'draft', false),
  4659. 'watermark' => getProp($data, 'watermark', false),
  4660. 'camera_fixed' => getProp($data, 'camera_fixed', false),
  4661. ];
  4662. if ($first_frame_url) $videoParams['first_frame_url'] = $first_frame_url;
  4663. if ($tail_frame_url) $videoParams['tail_frame_url'] = $tail_frame_url;
  4664. // 构建content数组
  4665. $videoParams['content'] = [
  4666. [
  4667. 'type' => 'text',
  4668. 'text' => $prompt,
  4669. ]
  4670. ];
  4671. // 根据模型选择不同的视频生成方法
  4672. if (strpos($model, 'jimeng') !== false) {
  4673. // 即梦模型参数调整
  4674. unset($videoParams['content']); // 即梦不使用content格式
  4675. $task = $this->aiVideoGenerationService->createJimengTask($videoParams);
  4676. } elseif (strpos($model, 'kling') !== false) {
  4677. // 可灵模型参数调整
  4678. $videoParams['aspect_ratio'] = $videoParams['ratio']; // 可灵使用aspect_ratio
  4679. unset($videoParams['ratio']);
  4680. unset($videoParams['content']); // 可灵不使用content格式
  4681. $task = $this->aiVideoGenerationService->createKelingOmniTask($videoParams);
  4682. } elseif (strpos($model, 'zhizhen') !== false) {
  4683. // 智帧等新模型使用统一API
  4684. $unifiedParams = [
  4685. 'model_code' => $model,
  4686. 'prompt' => $prompt,
  4687. 'video_duration' => $video_duration,
  4688. 'video_resolution' => strtolower($video_resolution),
  4689. 'video_ratio' => $ratio,
  4690. 'seed' => $seed,
  4691. ];
  4692. // 构建parameters参数
  4693. $parameters = [
  4694. 'seconds' => $unifiedParams['video_duration'],
  4695. 'resolution' => $unifiedParams['video_resolution'],
  4696. 'ratio' => $ratio,
  4697. 'generate_audio' => (int)$generate_audio === 1 ? true : false,
  4698. ];
  4699. // 首帧和尾帧
  4700. if ($first_frame_url) $parameters['first_frame_url'] = $first_frame_url;
  4701. if ($tail_frame_url) $parameters['last_frame_url'] = $tail_frame_url;
  4702. // 维护ref_image_url字段(参考图+参考视频+参考音频URL,JSON数组,与参考图处理方式一致)
  4703. $refImageUrls = array_merge($reference_images, $reference_videos, $reference_audios);
  4704. if ($refImageUrls) {
  4705. $unifiedParams['ref_image_url'] = json_encode(array_values(array_filter($refImageUrls)), 256);
  4706. }
  4707. // 参考图处理
  4708. if ($reference_images) {
  4709. $reference_images = $this->aiImageGenerationService->processReferenceImagesToAssets($reference_images, $unifiedParams['prompt']);
  4710. $parameters['reference_images'] = $reference_images;
  4711. $parameters['video_mode'] = 'multi_image';
  4712. $parameters['mode'] = 'multi_image';
  4713. }
  4714. // 参考视频和参考音频(与参考图一致,先上传为智帧素材)
  4715. if ($reference_videos) {
  4716. $reference_videos = $this->aiImageGenerationService->processReferenceVideosToAssets($reference_videos, $unifiedParams['prompt']);
  4717. $parameters['reference_videos'] = $reference_videos;
  4718. }
  4719. if ($reference_audios) {
  4720. $reference_audios = $this->aiImageGenerationService->processReferenceAudiosToAssets($reference_audios, $unifiedParams['prompt']);
  4721. $parameters['reference_audios'] = $reference_audios;
  4722. }
  4723. $unifiedParams['parameters'] = $parameters;
  4724. // 调用统一API创建任务
  4725. $task = $this->aiVideoGenerationService->createUnifiedApiTask($unifiedParams);
  4726. } elseif ($this->isSeedance20SeriesModel($model)) {
  4727. // 豆包Seedance 2.0(百度AI网关)/ 快快AI Seedance 2.0/2.5:图片/视频/音频需要先上传为素材
  4728. $isKuaikuai = $this->isKuaikuaiSeedanceModel($model);
  4729. $isDreamina = $this->isOverseasBaiduSeedanceModel($model);
  4730. $videoParams['reference_images'] = $reference_images;
  4731. // 维护ref_image_url字段(参考图+参考视频+参考音频URL,JSON数组)
  4732. $refImageUrls = array_merge($reference_images, $reference_videos, $reference_audios);
  4733. if ($refImageUrls) {
  4734. $videoParams['ref_image_url'] = json_encode(array_values(array_filter($refImageUrls)), 256);
  4735. }
  4736. if ($reference_images) {
  4737. // 参考图上传为素材(国内百度/海外百度dreamina/快快AI)
  4738. $reference_image_assets = $isKuaikuai
  4739. ? $this->aiVideoGenerationService->processReferenceImagesToKuaikuaiAssets($reference_images, $videoParams['prompt'])
  4740. : ($isDreamina
  4741. ? $this->aiVideoGenerationService->processReferenceImagesToBaiduDreaminaAssets($reference_images, $videoParams['prompt'])
  4742. : $this->aiVideoGenerationService->processReferenceImagesToSeedance20Assets($reference_images, $videoParams['prompt']));
  4743. $videoParams['reference_image_assets'] = $reference_image_assets;
  4744. }
  4745. // 参考视频上传为素材(国内百度/海外百度dreamina/快快AI)
  4746. if ($reference_videos) {
  4747. $reference_video_assets = $isKuaikuai
  4748. ? $this->aiVideoGenerationService->processReferenceVideosToKuaikuaiAssets($reference_videos, $videoParams['prompt'])
  4749. : ($isDreamina
  4750. ? $this->aiVideoGenerationService->processReferenceVideosToBaiduDreaminaAssets($reference_videos, $videoParams['prompt'])
  4751. : $this->aiVideoGenerationService->processReferenceVideosToSeedance20Assets($reference_videos, $videoParams['prompt']));
  4752. $videoParams['reference_video_assets'] = $reference_video_assets;
  4753. }
  4754. // 参考音频上传为素材(国内百度/海外百度dreamina/快快AI)
  4755. if ($reference_audios) {
  4756. $reference_audio_assets = $isKuaikuai
  4757. ? $this->aiVideoGenerationService->processReferenceAudiosToKuaikuaiAssets($reference_audios, $videoParams['prompt'])
  4758. : ($isDreamina
  4759. ? $this->aiVideoGenerationService->processReferenceAudiosToBaiduDreaminaAssets($reference_audios, $videoParams['prompt'])
  4760. : $this->aiVideoGenerationService->processReferenceAudiosToSeedance20Assets($reference_audios, $videoParams['prompt']));
  4761. $videoParams['reference_audio_assets'] = $reference_audio_assets;
  4762. }
  4763. // 参考素材上传失败时可能清理提示词中的素材标记,需要同步回content文本
  4764. if ($reference_images || $reference_videos || $reference_audios) {
  4765. $videoParams['content'][0]['text'] = $videoParams['prompt'];
  4766. }
  4767. // 快快AI走聚合网关 /v1/video/generations(火山豆包格式)
  4768. if ($isKuaikuai) {
  4769. $videoParams['gateway_base_url'] = env('KUAIKUAI_AI_BASE_URL', 'https://ai-api.kkidc.com');
  4770. $task = $this->aiVideoGenerationService->createKuaikuaiVideoTask($videoParams);
  4771. } else {
  4772. $task = $this->aiVideoGenerationService->createSeedance20Task($videoParams);
  4773. }
  4774. } else {
  4775. // 官方Seedance模型:兼容参考视频和参考音频(content直接透传公网URL)
  4776. // 维护ref_image_url字段(参考图+参考视频+参考音频URL,JSON数组)
  4777. $refImageUrls = array_merge($reference_images, $reference_videos, $reference_audios);
  4778. if ($refImageUrls) {
  4779. $videoParams['ref_image_url'] = json_encode(array_values(array_filter($refImageUrls)), 256);
  4780. }
  4781. if ($reference_videos) {
  4782. foreach ($reference_videos as $videoUrl) {
  4783. $videoParams['content'][] = [
  4784. 'type' => 'video_url',
  4785. 'video_url' => [
  4786. 'url' => $videoUrl,
  4787. ],
  4788. 'role' => 'reference_video',
  4789. ];
  4790. }
  4791. }
  4792. if ($reference_audios) {
  4793. foreach ($reference_audios as $audioUrl) {
  4794. $videoParams['content'][] = [
  4795. 'type' => 'audio_url',
  4796. 'audio_url' => [
  4797. 'url' => $audioUrl,
  4798. ],
  4799. 'role' => 'reference_audio',
  4800. ];
  4801. }
  4802. }
  4803. $task = $this->aiVideoGenerationService->createSeedanceTask($videoParams);
  4804. }
  4805. return [
  4806. 'task_id' => $task->id,
  4807. 'status' => $task->status,
  4808. 'model' => $model,
  4809. 'video_duration' => $video_duration,
  4810. 'video_resolution' => $video_resolution,
  4811. 'ratio' => $ratio
  4812. ];
  4813. }
  4814. /**
  4815. * 预估生成所需积分(mode=chat/image/video,支持多数量总额)
  4816. *
  4817. * chat : count(默认1,AI对话单次10积分);批量分集可传 anime_id + generate_episode_number 按实际待创建集数估算
  4818. * image : model 必传;resolution(1k/2k/4k)或 width/height 自动归一化;image_num(默认1)
  4819. * video : model 必传;video_resolution(默认720p);video_duration(默认5秒);count(默认1);scene(默认video_generation)
  4820. *
  4821. * @param array $data
  4822. * @return array
  4823. */
  4824. public function previewCharge(array $data): array
  4825. {
  4826. $mode = (string)getProp($data, 'mode', '');
  4827. if (!in_array($mode, ['chat', 'image', 'video'])) {
  4828. Utils::throwError('1003:请传入mode参数(chat/image/video)');
  4829. }
  4830. // 视频计费场景(video_generation/video_to_video),默认视频生成
  4831. $scene = (string)getProp($data, 'scene', 'video_generation');
  4832. // 未显式传scene且带参考视频时,自动按video_to_video定价
  4833. if ($mode === 'video' && !array_key_exists('scene', $data) && !empty(getProp($data, 'reference_videos', []))) {
  4834. $scene = 'video_to_video';
  4835. }
  4836. $items = [];
  4837. $model = '';
  4838. $resolution = '';
  4839. if ($mode === 'video') {
  4840. // 通用视频预估:单价/秒 × 时长 × 数量(多个视频计算总额)
  4841. $model = (string)getProp($data, 'model', '');
  4842. if (!$model) {
  4843. Utils::throwError('1002:model参数不能为空');
  4844. }
  4845. $resolution = strtolower((string)getProp($data, 'video_resolution', '720p'));
  4846. $duration = (int)getProp($data, 'video_duration', 5);
  4847. if ($duration <= 0) {
  4848. $duration = 5;
  4849. }
  4850. $count = max(1, (int)getProp($data, 'count', 1));
  4851. $pointsPerVideo = $this->pointsService->getVideoChargePoints([
  4852. 'model' => $model,
  4853. 'video_resolution' => $resolution,
  4854. 'video_duration' => $duration,
  4855. 'mode' => $scene,
  4856. ]);
  4857. $points = $pointsPerVideo * $count;
  4858. $items[] = [
  4859. 'type' => 'video',
  4860. 'model' => $model,
  4861. 'video_resolution' => $resolution,
  4862. 'video_duration' => $duration,
  4863. 'count' => $count,
  4864. 'points' => $points,
  4865. ];
  4866. } elseif ($mode === 'image') {
  4867. // 通用图片预估:单张价格 × 张数(resolution 可直传,或传 width/height 自动归一化)
  4868. $model = (string)getProp($data, 'model', '');
  4869. if (!$model) {
  4870. Utils::throwError('1002:model参数不能为空');
  4871. }
  4872. $resolution = strtolower((string)getProp($data, 'resolution', ''));
  4873. if (!$resolution) {
  4874. $width = (int)getProp($data, 'width', 0);
  4875. $height = (int)getProp($data, 'height', 0);
  4876. if ($width <= 0 || $height <= 0) {
  4877. $width = 1600;
  4878. $height = 2848;
  4879. }
  4880. $resolution = $this->pointsService->normalizeImageResolutionKey($width, $height);
  4881. }
  4882. $imageNum = max(1, (int)getProp($data, 'image_num', 1));
  4883. $points = $this->pointsService->getImageChargePoints([
  4884. 'model' => $model,
  4885. 'resolution' => $resolution,
  4886. ]) * $imageNum;
  4887. $items[] = [
  4888. 'type' => 'image',
  4889. 'model' => $model,
  4890. 'resolution' => $resolution,
  4891. 'image_num' => $imageNum,
  4892. 'points' => $points,
  4893. ];
  4894. } else {
  4895. // AI对话预估:按 price_type 档位取价(special 默认10 / normal 3);
  4896. // 批量生成分集传 anime_id + generate_episode_number 时按实际待创建集数估算(该场景实际扣费固定 special 档)
  4897. $priceType = (string)getProp($data, 'price_type', 'special');
  4898. if (!in_array($priceType, ['special', 'normal'], true)) {
  4899. Utils::throwError('1003:price_type参数仅支持special或normal');
  4900. }
  4901. $count = max(1, (int)getProp($data, 'count', 1));
  4902. $animeId = getProp($data, 'anime_id');
  4903. $generateEpisodes = (int)getProp($data, 'generate_episode_number', 0);
  4904. if ($animeId && $generateEpisodes > 0) {
  4905. // 批量生成分集按 special 档预估,与实际扣费口径一致
  4906. $priceType = 'special';
  4907. $currentMaxEpisode = DB::table('mp_anime_episodes')
  4908. ->where('anime_id', $animeId)
  4909. ->where('is_default', 1)
  4910. ->max('episode_number');
  4911. $currentMaxEpisode = $currentMaxEpisode ?: 0;
  4912. $startEpisodeNumber = $currentMaxEpisode + 1;
  4913. $endEpisodeNumber = $startEpisodeNumber + $generateEpisodes - 1;
  4914. $existingSkipped = DB::table('mp_batch_episode_generation_details')
  4915. ->where('anime_id', $animeId)
  4916. ->whereBetween('episode_number', [$startEpisodeNumber, $endEpisodeNumber])
  4917. ->whereIn('status', ['pending', 'processing', 'completed'])
  4918. ->count();
  4919. $count = ($endEpisodeNumber - $startEpisodeNumber + 1) - $existingSkipped;
  4920. if ($count < 0) {
  4921. $count = 0;
  4922. }
  4923. }
  4924. $points = $this->pointsService->getChatChargePoints((string)$model, $priceType) * $count;
  4925. $items[] = [
  4926. 'type' => 'chat',
  4927. 'count' => $count,
  4928. 'price_type' => $priceType,
  4929. 'points' => $points,
  4930. ];
  4931. }
  4932. $totalPoints = 0;
  4933. foreach ($items as $item) {
  4934. $totalPoints += $item['points'];
  4935. }
  4936. return [
  4937. 'mode' => $mode,
  4938. 'total_points' => $totalPoints,
  4939. 'items' => $items,
  4940. 'points_balance' => $this->pointsService->getUserPointsBalance(),
  4941. 'remark' => '积分为预估值,实际扣费以生成完成后的实际消耗为准',
  4942. ];
  4943. }
  4944. /**
  4945. * 根据提示词内容智能计算最优视频时长
  4946. *
  4947. * @param string $segmentContent 分镜内容
  4948. * @param string $tailFrame 尾帧描述
  4949. * @return int 视频时长(2-12秒)
  4950. */
  4951. public function calculateOptimalVideoDuration($segmentContent, $tailFrame = '') {
  4952. // 合并所有文本内容
  4953. $fullText = trim($segmentContent . ' ' . $tailFrame);
  4954. // 如果没有内容,返回默认时长
  4955. if (empty($fullText)) {
  4956. return 5;
  4957. }
  4958. // 计算文本长度(中文字符按2个字符计算)
  4959. $textLength = mb_strlen($fullText, 'UTF-8');
  4960. $chineseCharCount = preg_match_all('/[\x{4e00}-\x{9fff}]/u', $fullText);
  4961. $adjustedLength = $textLength + $chineseCharCount; // 中文字符权重更高
  4962. // 分析内容复杂度
  4963. $complexityScore = $this->analyzeContentComplexity($fullText);
  4964. // 基础时长计算(根据文本长度)
  4965. $baseDuration = 3; // 默认2秒
  4966. // if ($adjustedLength <= 20) {
  4967. // $baseDuration = 3;
  4968. // } elseif ($adjustedLength <= 40) {
  4969. // $baseDuration = 4;
  4970. // } elseif ($adjustedLength <= 60) {
  4971. // $baseDuration = 5;
  4972. // } elseif ($adjustedLength <= 80) {
  4973. // $baseDuration = 6;
  4974. // } elseif ($adjustedLength <= 100) {
  4975. // $baseDuration = 7;
  4976. // } elseif ($adjustedLength <= 120) {
  4977. // $baseDuration = 8;
  4978. // } else {
  4979. // $baseDuration = 9;
  4980. // }
  4981. // 根据内容复杂度调整时长
  4982. $finalDuration = $baseDuration + $complexityScore;
  4983. // 确保时长在2-12秒范围内
  4984. return max(4, min(12, $finalDuration));
  4985. }
  4986. /**
  4987. * 分析内容复杂度,返回时长调整值
  4988. *
  4989. * @param string $text 文本内容
  4990. * @return int 调整值(-2到+3)
  4991. */
  4992. private function analyzeContentComplexity($text) {
  4993. $score = 0;
  4994. // 动作关键词(需要更长时间展现)
  4995. $actionKeywords = [
  4996. '跑步', '奔跑', '飞行', '跳跃', '战斗', '打斗', '追逐', '逃跑', '舞蹈', '表演',
  4997. '变化', '变身', '爆炸', '崩塌', '建造', '制作', '烹饪', '绘画', '写字',
  4998. '移动', '旋转', '翻滚', '攀爬', '游泳', '潜水', '滑行', '飞翔'
  4999. ];
  5000. // 静态关键词(可以用较短时间)
  5001. $staticKeywords = [
  5002. '站立', '坐着', '躺着', '静止', '凝视', '思考', '沉思', '观察', '等待',
  5003. '睡觉', '休息', '静坐', '冥想', '阅读', '听音乐'
  5004. ];
  5005. // 复杂场景关键词(需要更长时间)
  5006. $complexSceneKeywords = [
  5007. '人群', '聚会', '会议', '战争', '庆典', '仪式', '表演', '比赛', '竞技',
  5008. '多人', '群体', '团队', '合作', '互动', '对话', '争论', '讨论'
  5009. ];
  5010. // 情感关键词(需要适中时间表现)
  5011. $emotionKeywords = [
  5012. '哭泣', '笑容', '愤怒', '惊讶', '恐惧', '悲伤', '喜悦', '兴奋', '紧张',
  5013. '感动', '震惊', '困惑', '失望', '希望', '绝望', '温柔', '严肃'
  5014. ];
  5015. // 检查动作关键词
  5016. foreach ($actionKeywords as $keyword) {
  5017. if (strpos($text, $keyword) !== false) {
  5018. $score += 1;
  5019. break; // 避免重复加分
  5020. }
  5021. }
  5022. // 检查静态关键词
  5023. foreach ($staticKeywords as $keyword) {
  5024. if (strpos($text, $keyword) !== false) {
  5025. $score -= 1;
  5026. break;
  5027. }
  5028. }
  5029. // 检查复杂场景关键词
  5030. foreach ($complexSceneKeywords as $keyword) {
  5031. if (strpos($text, $keyword) !== false) {
  5032. $score += 1;
  5033. break;
  5034. }
  5035. }
  5036. // 检查情感关键词
  5037. foreach ($emotionKeywords as $keyword) {
  5038. if (strpos($text, $keyword) !== false) {
  5039. $score += 1;
  5040. break;
  5041. }
  5042. }
  5043. // 检查时间相关词汇
  5044. if (preg_match('/缓慢|慢慢|渐渐|逐渐|慢动作/', $text)) {
  5045. $score += 1;
  5046. }
  5047. if (preg_match('/快速|迅速|急速|瞬间|立刻|马上/', $text)) {
  5048. $score -= 1;
  5049. }
  5050. // 检查转场词汇
  5051. if (preg_match('/然后|接着|随后|紧接着|同时|与此同时/', $text)) {
  5052. $score += 1;
  5053. }
  5054. // 检查环境描述(复杂环境需要更多时间)
  5055. if (preg_match('/风景|景色|环境|背景|氛围|光线|阴影|色彩|细节/', $text)) {
  5056. $score += 1;
  5057. }
  5058. // 检查对话内容(对话需要更多时间)
  5059. if (preg_match('/说|讲|告诉|回答|询问|问|对话|交谈/', $text)) {
  5060. $score += 1;
  5061. }
  5062. // 限制调整范围
  5063. return max(-1, min(4, $score));
  5064. }
  5065. /**
  5066. * 创建完整视频合成任务
  5067. *
  5068. * @param array $data
  5069. * @return array
  5070. */
  5071. public function createCompleteVideoTask($data)
  5072. {
  5073. $animeId = getProp($data, 'anime_id');
  5074. $episodeId = getProp($data, 'episode_id');
  5075. // 验证参数
  5076. if (!$animeId || !$episodeId) {
  5077. Utils::throwError('20003:anime_id 和 episode_id 不能为空');
  5078. }
  5079. // 检查是否已存在处理中的任务
  5080. $existingTask = DB::table('mp_complete_video_tasks')
  5081. ->where('anime_id', $animeId)
  5082. ->where('episode_id', $episodeId)
  5083. ->whereIn('generate_status', ['执行中'])
  5084. ->first();
  5085. if ($existingTask) {
  5086. Utils::throwError('20003:该剧集已有正在处理的视频合成任务');
  5087. }
  5088. // 获取全能模式状态
  5089. $ace_mode = DB::table('mp_animes')->where('id', $animeId)->value('ace_mode');
  5090. if ((int)$ace_mode === 1) {
  5091. // 获取所有片段的配音视频,按 act_number 排序
  5092. $segments = DB::table('mp_episode_segments')
  5093. ->where('anime_id', $animeId)
  5094. ->where('episode_id', $episodeId)
  5095. ->orderBy('segment_number')
  5096. ->select('id as act_id', 'act_number', 'video_url', 'audio_url', 'video_time_point_start', 'video_time_point_end')
  5097. ->get();
  5098. // 检查是否所有片段都有视频
  5099. $missingVideos = $segments->filter(function($segment) {
  5100. return empty($segment->video_url);
  5101. });
  5102. if ($missingVideos->isNotEmpty()) {
  5103. Utils::throwError('20003:存在未完成视频的片段,请确保所有片段都已完成配音');
  5104. }
  5105. }else {
  5106. // 获取所有分镜的配音视频,按 segment_number 排序
  5107. $segments = DB::table('mp_episode_segments')
  5108. ->where('anime_id', $animeId)
  5109. ->where('episode_id', $episodeId)
  5110. ->orderBy('segment_number')
  5111. ->select('segment_id', 'segment_number', 'video_url', 'audio_url', 'video_time_point_start', 'video_time_point_end')
  5112. ->get();
  5113. // 检查是否所有分镜都有配音和视频
  5114. $missingVideos = $segments->filter(function($segment) {
  5115. return empty($segment->audio_url) || empty($segment->video_url);
  5116. });
  5117. if ($missingVideos->isNotEmpty()) {
  5118. Utils::throwError('20003:存在未完成配音或视频的分镜,请确保所有分镜都已完成配音或视频');
  5119. }
  5120. }
  5121. if ($segments->isEmpty()) {
  5122. Utils::throwError('20003:未找到该剧集的分镜数据');
  5123. }
  5124. // 获取当前完整视频url
  5125. $completeVideoUrl = DB::table('mp_anime_episodes')
  5126. ->where('anime_id', $animeId)
  5127. ->where('id', $episodeId)
  5128. ->value('complete_video_url');
  5129. // 构建 generate_json
  5130. $generateJson = [];
  5131. $sequence = 1;
  5132. foreach ($segments as $segment) {
  5133. if ((int)$ace_mode === 1) {
  5134. $generateJson[] = [
  5135. 'sequence' => $sequence++,
  5136. 'video_url' => $segment->video_url,
  5137. 'video_time_point_start' => $segment->video_time_point_start,
  5138. 'video_time_point_end' => $segment->video_time_point_end
  5139. ];
  5140. }else {
  5141. $generateJson[] = [
  5142. 'sequence' => $sequence++,
  5143. 'video_url' => $segment->video_url,
  5144. 'audio_url' => $segment->audio_url,
  5145. 'video_time_point_start' => $segment->video_time_point_start,
  5146. 'video_time_point_end' => $segment->video_time_point_end
  5147. ];
  5148. }
  5149. }
  5150. // 创建任务
  5151. $now = date('Y-m-d H:i:s');
  5152. $taskId = DB::table('mp_complete_video_tasks')->insertGetId([
  5153. 'anime_id' => $animeId,
  5154. 'episode_id' => $episodeId,
  5155. 'generate_json' => json_encode($generateJson, 256),
  5156. 'generate_status' => '执行中',
  5157. 'complete_video_url' => '',
  5158. 'created_at' => $now,
  5159. 'updated_at' => $now
  5160. ]);
  5161. if (!$taskId) {
  5162. Utils::throwError('20003:创建任务失败');
  5163. }
  5164. // 更新剧集表的任务ID和状态
  5165. $boolen = DB::table('mp_anime_episodes')
  5166. ->where('anime_id', $animeId)
  5167. ->where('id', $episodeId)
  5168. ->update([
  5169. 'complete_video_task_id' => $taskId,
  5170. 'complete_video_task_status' => '执行中',
  5171. 'updated_at' => $now
  5172. ]);
  5173. if (!$boolen) {
  5174. Utils::throwError('20003:更新剧集表失败');
  5175. }
  5176. dLog('anime')->info('创建完整视频合成任务', [
  5177. 'task_id' => $taskId,
  5178. 'anime_id' => $animeId,
  5179. 'episode_id' => $episodeId,
  5180. 'segment_count' => count($generateJson)
  5181. ]);
  5182. // 请求远程服务器执行生成
  5183. $client = new Client(['timeout' => 600, 'verify' => false]);
  5184. try {
  5185. $result = $client->get("http://122.9.129.83:5000/api/anime/genVideo?taskId={$taskId}");
  5186. $response = $result->getBody()->getContents();
  5187. $response_arr = json_decode($response, true);
  5188. if (!isset($response_arr['code']) || (int)$response_arr['code'] !== 0) {
  5189. $error_msg = isset($response_arr['msg']) ? $response_arr['msg'] : '未知错误';
  5190. dLog('anime')->error('火山合成完整视频失败', ['error' => $error_msg, 'task_id' => $taskId]);
  5191. // // 更新任务状态为失败
  5192. // DB::table('mp_complete_video_tasks')
  5193. // ->where('id', $taskId)
  5194. // ->update([
  5195. // 'generate_status' => '执行失败',
  5196. // 'error_message' => $error_msg,
  5197. // 'updated_at' => date('Y-m-d H:i:s')
  5198. // ]);
  5199. // // 同步更新剧集表状态
  5200. // DB::table('mp_anime_episodes')
  5201. // ->where('complete_video_task_id', $taskId)
  5202. // ->update([
  5203. // 'complete_video_task_status' => '执行失败',
  5204. // 'updated_at' => date('Y-m-d H:i:s')
  5205. // ]);
  5206. Utils::throwError('20003:火山合成完整视频失败: ' . $error_msg);
  5207. }
  5208. } catch (\Exception $e) {
  5209. dLog('anime')->error('调用远程服务器失败', ['error' => $e->getMessage(), 'task_id' => $taskId]);
  5210. // 更新任务状态为失败
  5211. DB::table('mp_complete_video_tasks')
  5212. ->where('id', $taskId)
  5213. ->update([
  5214. 'generate_status' => '执行失败',
  5215. 'error_message' => $e->getMessage(),
  5216. 'updated_at' => date('Y-m-d H:i:s')
  5217. ]);
  5218. // 同步更新剧集表状态
  5219. DB::table('mp_anime_episodes')
  5220. ->where('complete_video_task_id', $taskId)
  5221. ->update([
  5222. 'complete_video_task_status' => '执行失败',
  5223. 'updated_at' => date('Y-m-d H:i:s')
  5224. ]);
  5225. Utils::throwError('20003:调用远程服务器失败: ' . $e->getMessage());
  5226. }
  5227. // 开始轮询任务状态
  5228. $maxAttempts = 60; // 5分钟 = 60次 * 5秒
  5229. $pollInterval = 5; // 每5秒轮询一次
  5230. $attempt = 0;
  5231. dLog('anime')->info('开始轮询任务状态', ['task_id' => $taskId]);
  5232. while ($attempt < $maxAttempts) {
  5233. sleep($pollInterval);
  5234. $attempt++;
  5235. // 查询任务状态
  5236. $task = DB::table('mp_complete_video_tasks')
  5237. ->where('id', $taskId)
  5238. ->first();
  5239. if (!$task) {
  5240. dLog('anime')->error('任务不存在', ['task_id' => $taskId]);
  5241. Utils::throwError('20003:任务不存在');
  5242. }
  5243. dLog('anime')->info('轮询任务状态', [
  5244. 'task_id' => $taskId,
  5245. 'attempt' => $attempt,
  5246. 'status' => $task->generate_status
  5247. ]);
  5248. // 检查任务是否完成
  5249. if ($task->generate_status === '执行成功') {
  5250. // 同步更新剧集表状态
  5251. $boolen3 = DB::table('mp_anime_episodes')
  5252. ->where('anime_id', $animeId)
  5253. ->where('id', $episodeId)
  5254. ->update([
  5255. 'complete_video_url' => $task->complete_video_url,
  5256. 'complete_video_task_status' => '执行成功',
  5257. 'updated_at' => date('Y-m-d H:i:s')
  5258. ]);
  5259. dLog('anime')->info('视频合成任务完成', [
  5260. 'task_id' => $taskId,
  5261. 'video_url' => $task->complete_video_url,
  5262. 'attempts' => $attempt
  5263. ]);
  5264. // 如果更新成功则远程删除之前的文件
  5265. if ($boolen3 && $completeVideoUrl) {
  5266. $encode_url = urlencode($completeVideoUrl);
  5267. $client = new Client(['timeout' => 300, 'verify' => false]);
  5268. // 根据ID通过API通知合成音频
  5269. // $result = $client->get("http://47.240.171.155:5000/api/fileDelete?url={$encode_url}");
  5270. $result = $client->get("http://122.9.129.83:5000/api/fileDelete?url={$encode_url}");
  5271. $response = $result->getBody()->getContents();
  5272. $response_arr = json_decode($response, true);
  5273. Log::info('火山删除音频返回: '.$response);
  5274. if (!isset($response_arr['status']) || (int)$response_arr['status'] !== 0) {
  5275. $error_msg = isset($response_arr['msg']) ? $response_arr['msg'] : '未知错误';
  5276. Log::info('火山删除音频失败: '.$error_msg);
  5277. // Utils::throwError('20003:火山删除音频失败');
  5278. }
  5279. }
  5280. return [
  5281. 'task_id' => $taskId,
  5282. 'anime_id' => $animeId,
  5283. 'episode_id' => $episodeId,
  5284. 'segment_count' => count($generateJson),
  5285. 'generate_status' => '执行成功',
  5286. 'complete_video_url' => $task->complete_video_url,
  5287. ];
  5288. }
  5289. // 检查任务是否失败
  5290. if ($task->generate_status === '执行失败') {
  5291. // 同步更新剧集表状态
  5292. DB::table('mp_anime_episodes')
  5293. ->where('anime_id', $animeId)
  5294. ->where('id', $episodeId)
  5295. ->update([
  5296. 'complete_video_task_status' => '执行失败',
  5297. 'updated_at' => date('Y-m-d H:i:s')
  5298. ]);
  5299. $errorMessage = $task->error_message ?? '未知错误';
  5300. dLog('anime')->error('视频合成任务失败', [
  5301. 'task_id' => $taskId,
  5302. 'error' => $errorMessage,
  5303. 'attempts' => $attempt
  5304. ]);
  5305. return [
  5306. 'task_id' => $taskId,
  5307. 'anime_id' => $animeId,
  5308. 'episode_id' => $episodeId,
  5309. 'segment_count' => count($generateJson),
  5310. 'generate_status' => '执行失败',
  5311. 'error_message' => $errorMessage
  5312. ];
  5313. }
  5314. }
  5315. // 超时处理
  5316. dLog('anime')->warning('视频合成任务超时', [
  5317. 'task_id' => $taskId,
  5318. 'max_attempts' => $maxAttempts,
  5319. 'timeout_seconds' => $maxAttempts * $pollInterval
  5320. ]);
  5321. // 更新任务状态为超时
  5322. DB::table('mp_complete_video_tasks')
  5323. ->where('id', $taskId)
  5324. ->update([
  5325. 'generate_status' => '超时',
  5326. 'error_message' => '任务执行超时(5分钟)',
  5327. 'updated_at' => date('Y-m-d H:i:s')
  5328. ]);
  5329. return [
  5330. 'task_id' => $taskId,
  5331. 'anime_id' => $animeId,
  5332. 'episode_id' => $episodeId,
  5333. 'segment_count' => count($generateJson),
  5334. 'generate_status' => '超时',
  5335. 'error_message' => '任务执行超时,请稍后查询任务状态'
  5336. ];
  5337. }
  5338. /**
  5339. * 根据 inner_prompt_type 附加内置提示词
  5340. *
  5341. * @param string $prompt 用户提示词
  5342. * @param int $innerPromptType 内置提示词类型(1=三视图, 2=九宫格)
  5343. * @return string 合并后的提示词
  5344. */
  5345. public static function appendInnerPrompt($prompt, $innerPromptType = 0)
  5346. {
  5347. $innerPromptMap = [
  5348. 1 => '基于参考图生成主体的标准正面、侧面、后面三视图,主体完整。在最左侧添加主体正视图的特写,特写大小为标准一寸照,人物不要带表情。右侧是全身的三视图,其中正面、侧面的三视图给人脸打白色码、不显示五官。主体清晰完整。背景修改成纯白色,整体保持与参考图一致的美术风格和色彩搭配。画面无说明文字。',
  5349. 2 => '基于参考图及提示词内容,生成9张连贯的系列图片:9张图片围绕同一主体展开,保持角色形象、美术风格和色彩搭配完全一致,画面内容依次衔接、情节连贯,整体构成一组完整的系列图。每张图片主体完整清晰,构图合理,画面干净,无文字、无水印、无字幕。',
  5350. ];
  5351. if (!isset($innerPromptMap[$innerPromptType])) {
  5352. return $prompt;
  5353. }
  5354. return trim((string)$prompt) . "\n" . $innerPromptMap[$innerPromptType];
  5355. }
  5356. /**
  5357. * 根据 inner_prompt_type 获取生成图片数量
  5358. *
  5359. * @param int $innerPromptType 内置提示词类型
  5360. * @param int $imageNum 传入的图片张数
  5361. * @return int 图片数量
  5362. */
  5363. public static function getInnerImageNum($innerPromptType = 0, $imageNum)
  5364. {
  5365. return (int)$innerPromptType === 2 ? 9 : $imageNum;
  5366. }
  5367. /**
  5368. * 提取图片生成结果URL
  5369. *
  5370. * @param mixed $resultUrl 任务结果URL(数组、JSON字符串或普通字符串)
  5371. * @param int $innerPromptType 内置提示词类型
  5372. * @return mixed 类型2返回全部URL数组,其它类型返回首个URL
  5373. */
  5374. public static function extractResultUrls($resultUrl, $innerPromptType = 0)
  5375. {
  5376. $resultUrls = is_array($resultUrl) ? $resultUrl : json_decode((string)$resultUrl, true);
  5377. if (is_array($resultUrls) && !empty($resultUrls)) {
  5378. $resultUrls = array_values($resultUrls);
  5379. return (int)$innerPromptType === 2 ? $resultUrls : $resultUrls[0];
  5380. }
  5381. if (!empty($resultUrl)) {
  5382. return (int)$innerPromptType === 2 ? [$resultUrl] : $resultUrl;
  5383. }
  5384. return (int)$innerPromptType === 2 ? [] : '';
  5385. }
  5386. public function generateImg($data, $onTaskCreated = null, $onPoll = null) {
  5387. $prompt = getProp($data, 'prompt');
  5388. $episode_id = getProp($data, 'episode_id');
  5389. $ref_img_urls = getProp($data, 'ref_img_urls');
  5390. $ratio = getProp($data, 'ratio', '9:16');
  5391. $resolution = getProp($data, 'resolution', '2k');
  5392. $inner_prompt_type = getProp($data, 'inner_prompt_type', 0);
  5393. $imageNum = (int)getProp($data, 'image_num', 1);
  5394. // 分辨率档位与尺寸映射统一从 BaseConst 获取
  5395. $sizeMap = BaseConst::IMAGE_RESOLUTION_SIZE_MAP;
  5396. // 参数验证
  5397. $resolution = strtolower($resolution);
  5398. if (!isset($sizeMap[$resolution])) {
  5399. Utils::throwError('20003:分辨率参数错误,仅支持 2k、3k、4k');
  5400. }
  5401. if (!isset($sizeMap[$resolution][$ratio])) {
  5402. Utils::throwError('20003:宽高比参数错误,该分辨率下不支持 ' . $ratio . ' 比例');
  5403. }
  5404. // 根据 ratio 和 resolution 确定宽高
  5405. $width = $sizeMap[$resolution][$ratio]['width'];
  5406. $height = $sizeMap[$resolution][$ratio]['height'];
  5407. if (!is_array($ref_img_urls) && !empty($ref_img_urls)) {
  5408. if (is_json($ref_img_urls)) {
  5409. $ref_img_urls = json_decode($ref_img_urls, true);
  5410. }else {
  5411. $ref_img_urls = explode(',', $ref_img_urls);
  5412. }
  5413. }
  5414. // 处理图片模型
  5415. $model = getProp($data, 'model');
  5416. if (!$model) {
  5417. // 用户没有输入,从episode表获取
  5418. if ($episode_id) {
  5419. $episode = DB::table('mp_anime_episodes')->where('id', $episode_id)->first();
  5420. $model = getProp($episode, 'image_model');
  5421. }
  5422. if (!$model) {
  5423. // episode表也没有,使用默认值
  5424. $model = 'gpt-image-2';
  5425. }
  5426. }
  5427. // 验证模型是否在可用模型表中
  5428. if (!DB::table('mp_image_models')->where('model', $model)->where('is_enabled', 1)->exists()) {
  5429. // $model = 'gpt-image-2';
  5430. Utils::throwError('20003:该模型已不可用,请更换!');
  5431. }
  5432. // 保存到episode表
  5433. if ($episode_id) {
  5434. DB::table('mp_anime_episodes')->where('id', $episode_id)->update([
  5435. 'image_model' => $model,
  5436. 'updated_at' => date('Y-m-d H:i:s')
  5437. ]);
  5438. }
  5439. // 参数验证
  5440. if (!$prompt) Utils::throwError('20003:请提供提示词');
  5441. // 根据 inner_prompt_type 附加内置提示词并确定生成图片数量
  5442. $prompt = self::appendInnerPrompt($prompt, $inner_prompt_type);
  5443. $imageNum = self::getInnerImageNum($inner_prompt_type, $imageNum);
  5444. try {
  5445. // 创建图片生成任务
  5446. $params = [
  5447. 'prompt' => $prompt,
  5448. 'model' => $model,
  5449. 'ref_img_urls' => '',
  5450. 'width' => $width,
  5451. 'height' => $height,
  5452. 'image_num' => $imageNum
  5453. ];
  5454. if ($ref_img_urls) $params['ref_img_urls'] = is_array($ref_img_urls) ? $ref_img_urls : [$ref_img_urls];
  5455. $task = $this->aiImageGenerationService->createImageGenerationTask($params);
  5456. $task_id = $task->id;
  5457. if (!$task_id) {
  5458. Utils::throwError('20003:创建图片生成任务失败');
  5459. }
  5460. // 创建任务中心记录并关联图片任务ID
  5461. $taskCenter = $this->taskCenterService->createTask('image', [
  5462. 'title' => '文生图',
  5463. 'ref_task_id' => $task_id,
  5464. // 'prompt' => $prompt,
  5465. // 'params' => json_encode($data, JSON_UNESCAPED_UNICODE),
  5466. ]);
  5467. $taskCenterId = $taskCenter->id;
  5468. // 组装本次任务信息(用于init消息,类似generateVideo)
  5469. $taskInfo = [
  5470. 'task_id' => $task_id,
  5471. 'status' => getProp($task, 'status', 'processing'),
  5472. 'model' => $model,
  5473. 'ratio' => $ratio,
  5474. 'resolution' => $resolution,
  5475. 'image_num' => $imageNum,
  5476. ];
  5477. // 创建图片任务后立即回调(类似generateVideo的init消息,返回任务中心ID和任务信息)
  5478. if (is_callable($onTaskCreated)) {
  5479. $onTaskCreated($taskCenterId, $taskInfo);
  5480. }
  5481. // 检查任务模型类型(火山模型和GPT模型都支持直接检查任务状态)
  5482. $model = getProp($task, 'model');
  5483. $isVolcModel = in_array($model, \App\Consts\BaseConst::VOLC_PIC_MODELS);
  5484. $isGptModel = in_array($model, \App\Consts\BaseConst::GPT_IMAGE2_MODELS);
  5485. $isSyncModel = $isVolcModel || $isGptModel;
  5486. // 任务需要轮询获取结果(15分钟超时,每3秒查询一次)
  5487. $start_time = time();
  5488. $timeout = 900; // 15分钟
  5489. $img_url = '';
  5490. $img_urls = [];
  5491. $lastQueueMessageTime = $start_time; // 记录上次发送队列消息的时间
  5492. $queueMessageInterval = 60; // 队列消息发送间隔(秒)
  5493. while (time() - $start_time < $timeout) {
  5494. sleep(3);
  5495. // 每分钟发送一次队列状态消息(仅流式模式)
  5496. if (is_callable($onPoll)) {
  5497. $currentTime = time();
  5498. if ($currentTime - $lastQueueMessageTime >= $queueMessageInterval) {
  5499. $onPoll($taskCenterId, $task_id, $currentTime - $start_time);
  5500. $lastQueueMessageTime = $currentTime;
  5501. }
  5502. }
  5503. // 火山API和GPT-Image2 API是同步返回结果的,直接检查任务状态
  5504. if ($isSyncModel) {
  5505. // 刷新任务状态
  5506. $task = MpGeneratePicTask::where('id', $task_id)->first();
  5507. if ($task->status === 'success' && $task->result_url) {
  5508. $resultUrls = is_array($task->result_url) ? $task->result_url : json_decode((string)$task->result_url, true);
  5509. $resultUrls = is_array($resultUrls) ? array_values(array_filter($resultUrls)) : [];
  5510. if (!empty($resultUrls)) {
  5511. $img_urls = $resultUrls;
  5512. $img_url = $resultUrls[0];
  5513. } else {
  5514. $img_url = (string)$task->result_url;
  5515. }
  5516. break;
  5517. } elseif ($task->status === 'failed') {
  5518. $errorMsg = mapErrorMessage($task->error_message ?? '');
  5519. Utils::throwError('20003:图片生成失败,' . $errorMsg);
  5520. }
  5521. // // 如果还在处理中,提示用户稍后查看
  5522. // Utils::throwError('20003:图片生成中,请稍后刷新查看结果');
  5523. }else {
  5524. $task = MpGeneratePicTask::where('id', $task_id)->first();
  5525. $statusInfo = $this->aiImageGenerationService->queryTaskStatus($task);
  5526. if ($statusInfo['status'] === 'success') {
  5527. $task->updateStatus('success', [
  5528. 'result_url' => $statusInfo['result_url'],
  5529. 'result_json' => $statusInfo['result_json'] ?? []
  5530. ]);
  5531. $resultUrls = is_array($statusInfo['result_url']) ? $statusInfo['result_url'] : json_decode((string)$statusInfo['result_url'], true);
  5532. $resultUrls = is_array($resultUrls) ? array_values(array_filter($resultUrls)) : [];
  5533. if (!empty($resultUrls)) {
  5534. $img_urls = $resultUrls;
  5535. $img_url = $resultUrls[0];
  5536. } else {
  5537. $img_url = (string)$statusInfo['result_url'];
  5538. }
  5539. break;
  5540. } elseif ($statusInfo['status'] === 'failed') {
  5541. $task->updateStatus('failed', [
  5542. 'error_message' => $statusInfo['error_message'],
  5543. 'result_json' => $statusInfo['result_json'] ?? []
  5544. ]);
  5545. dLog('anime')->error('图片生成失败,', [
  5546. 'error' => $statusInfo['error_message'] ?? '未知错误'
  5547. ]);
  5548. $errorMsg = mapErrorMessage($statusInfo['error_message'] ?? '');
  5549. Utils::throwError('20003:图片生成失败,' . $errorMsg);
  5550. }
  5551. }
  5552. }
  5553. if (empty($img_url)) {
  5554. Utils::throwError('20003:图片生成超时,请稍后重试');
  5555. }
  5556. // 多张图片返回全部URL数组(配合控制器输出image_urls字段)
  5557. if (count($img_urls) > 1) {
  5558. return [
  5559. 'img_url' => $img_url,
  5560. 'image_urls' => $img_urls,
  5561. 'task_id' => $taskCenterId,
  5562. ];
  5563. }
  5564. return [
  5565. 'img_url' => $img_url,
  5566. 'task_id' => $taskCenterId,
  5567. ];
  5568. } catch (\Exception $e) {
  5569. dLog('anime')->error('更新角色或场景失败', [
  5570. 'error' => $e->getMessage()
  5571. ]);
  5572. logDB('anime', 'error', '更新角色或场景失败', ['error' => $e->getMessage()]);
  5573. Utils::throwError('20003:' . $e->getMessage());
  5574. }
  5575. }
  5576. /**
  5577. * 使用文生文模型解析分镜内容
  5578. */
  5579. private function parseSegmentContentWithAI($segment_content) {
  5580. try {
  5581. // 使用DeepSeek服务的公开方法解析分镜内容
  5582. return $this->DeepSeekService->parseSegmentContent($segment_content);
  5583. } catch (\Exception $e) {
  5584. // 如果AI解析失败,记录日志并返回原内容
  5585. dLog('anime')->error('AI解析分镜内容失败: ' . $e->getMessage());
  5586. return $segment_content;
  5587. }
  5588. }
  5589. /**
  5590. * 处理分集的角色和场景数据(继承全局数据或创建新任务)
  5591. *
  5592. * @param int $episode_id 分集ID
  5593. * @param int $anime_id 动漫ID
  5594. * @param array $roles 分集角色数组(引用传递)
  5595. * @param array $scenes 分集场景数组(引用传递)
  5596. * @param array $episode 分集数据
  5597. */
  5598. private function processEpisodeRolesAndScenes($episode_id, $anime_id, &$roles, &$scenes, $episode) {
  5599. // 获取全局动漫的角色和场景数据
  5600. $anime = DB::table('mp_animes')->where('id', $anime_id)->first();
  5601. if (!$anime) return;
  5602. $art_style_type = getProp($anime, 'art_style_type');
  5603. $character_prefix = '';
  5604. $scene_prefix = '';
  5605. if ($art_style_type) {
  5606. $art_style_arr = $this->DeepSeekService->getArtStyleShortPromptByInput($art_style_type);
  5607. $character_prefix = isset($art_style_arr['character_prefix']) ? $art_style_arr['character_prefix'] : '';
  5608. $scene_prefix = isset($art_style_arr['scene_prefix']) ? $art_style_arr['scene_prefix'] : '';
  5609. }
  5610. $global_roles = json_decode(getProp($anime, 'roles'), true) ?: [];
  5611. $global_scenes = json_decode(getProp($anime, 'scenes'), true) ?: [];
  5612. $roles_updated = false;
  5613. $scenes_updated = false;
  5614. // 处理角色
  5615. foreach ($roles as &$role) {
  5616. $role_name = getProp($role, 'role');
  5617. $role_description = getProp($role, 'description');
  5618. $role_pic_prompt = getProp($role, 'pic_prompt');
  5619. $role_url = getProp($role, 'url');
  5620. $role_task_id = getProp($role, 'task_id');
  5621. // 如果已有URL或已有任务ID,跳过
  5622. if (!empty($role_url) || !empty($role_task_id) || $role_name === '旁白') {
  5623. continue;
  5624. }
  5625. $url_inherited = false;
  5626. // 尝试从全局数据中继承
  5627. foreach ($global_roles as $global_role) {
  5628. $global_role_name = getProp($global_role, 'role');
  5629. $global_role_description = getProp($global_role, 'description');
  5630. $global_role_pic_prompt = getProp($global_role, 'pic_prompt');
  5631. $global_role_url = getProp($global_role, 'url');
  5632. $global_role_task_id = getProp($global_role, 'task_id');
  5633. $global_role_task_status = getProp($global_role, 'task_status');
  5634. // 满足条件:角色名相同、描述相同、pic_prompt相同、全局有URL
  5635. if ($role_name === $global_role_name
  5636. && $role_description === $global_role_description
  5637. && $role_pic_prompt === $global_role_pic_prompt
  5638. && !empty($global_role_url)) {
  5639. // 继承 task_id、task_status 和 url
  5640. $role['task_id'] = $global_role_task_id;
  5641. $role['task_status'] = $global_role_task_status;
  5642. $role['url'] = $global_role_url;
  5643. $roles_updated = true;
  5644. $url_inherited = true;
  5645. dLog('anime')->info("分集ID:{$episode_id} 角色:{$role_name} 继承全局数据");
  5646. break;
  5647. }
  5648. }
  5649. // 如果无法继承且没有任务ID,创建新任务
  5650. if (!$url_inherited && empty($role_task_id)) {
  5651. try {
  5652. $art_style = getProp($episode, 'art_style');
  5653. // 优先使用 pic_prompt,如果没有则使用 description
  5654. $description = !empty($role_pic_prompt) ? trim((string)$role_pic_prompt) : $role_description;
  5655. // if ($art_style) {
  5656. // // $description = "美术风格:\n{$art_style}\n主体描述:{$description}\n图片要求:图片侧重点是人物,不要出现场景或背景,并且只能生成一个人物";
  5657. // $description = "主体描述:{$description}\n图片要求:图片侧重点是人物,不要出现场景或背景,并且只能生成一个人物";
  5658. // }
  5659. $description = "{$character_prefix}。\n主体描述:{$description}\n超高清,高细节,主体突出,构图合理,画面干净,无场景或背景,单人物,无文字,无水印,无字幕,电影级光影,视觉焦点明确";
  5660. $params = [
  5661. 'prompt' => $description,
  5662. 'ref_img_urls' => []
  5663. ];
  5664. $task = $this->aiImageGenerationService->createImageGenerationTask($params);
  5665. $task_id = $task->id;
  5666. if ($task_id) {
  5667. $role['task_id'] = $task_id;
  5668. $role['task_status'] = 'processing';
  5669. $roles_updated = true;
  5670. dLog('anime')->info("分集ID:{$episode_id} 角色:{$role_name} 创建图片生成任务,任务ID:{$task_id}");
  5671. }
  5672. } catch (\Exception $e) {
  5673. dLog('anime')->error("分集ID:{$episode_id} 角色:{$role_name} 创建图片生成任务失败: " . $e->getMessage());
  5674. }
  5675. }
  5676. }
  5677. // 处理场景
  5678. foreach ($scenes as &$scene) {
  5679. $scene_name = getProp($scene, 'scene');
  5680. $scene_description = getProp($scene, 'description');
  5681. $scene_pic_prompt = getProp($scene, 'pic_prompt');
  5682. $scene_url = getProp($scene, 'url');
  5683. $scene_task_id = getProp($scene, 'task_id');
  5684. // 如果已有URL或已有任务ID,跳过
  5685. if (!empty($scene_url) || !empty($scene_task_id)) {
  5686. continue;
  5687. }
  5688. $url_inherited = false;
  5689. // 尝试从全局数据中继承
  5690. foreach ($global_scenes as $global_scene) {
  5691. $global_scene_name = getProp($global_scene, 'scene');
  5692. $global_scene_description = getProp($global_scene, 'description');
  5693. $global_scene_pic_prompt = getProp($global_scene, 'pic_prompt');
  5694. $global_scene_url = getProp($global_scene, 'url');
  5695. $global_scene_task_id = getProp($global_scene, 'task_id');
  5696. $global_scene_task_status = getProp($global_scene, 'task_status');
  5697. // 满足条件:场景名相同、描述相同、pic_prompt相同、全局有URL
  5698. if ($scene_name === $global_scene_name
  5699. && $scene_description === $global_scene_description
  5700. && $scene_pic_prompt === $global_scene_pic_prompt
  5701. && !empty($global_scene_url)) {
  5702. // 继承 task_id、task_status 和 url
  5703. $scene['task_id'] = $global_scene_task_id;
  5704. $scene['task_status'] = $global_scene_task_status;
  5705. $scene['url'] = $global_scene_url;
  5706. $scenes_updated = true;
  5707. $url_inherited = true;
  5708. dLog('anime')->info("分集ID:{$episode_id} 场景:{$scene_name} 继承全局数据");
  5709. break;
  5710. }
  5711. }
  5712. // 如果无法继承且没有任务ID,创建新任务
  5713. if (!$url_inherited && empty($scene_task_id)) {
  5714. try {
  5715. $art_style = getProp($episode, 'art_style');
  5716. // 优先使用 pic_prompt,如果没有则使用 description
  5717. $description = !empty($scene_pic_prompt) ? trim((string)$scene_pic_prompt) : $scene_description;
  5718. // if ($art_style) {
  5719. // // $description = "美术风格:\n{$art_style}\n场景描述:{$description}\n图片要求: 图片侧重点是场景,生成的是场景环境图片,不要出现人物(此为第一优先要求)";
  5720. // $description = "场景描述:{$description}\n图片要求: 图片侧重点是场景,生成的是场景环境图片,不要出现人物(此为第一优先要求)";
  5721. // }
  5722. $description = "{$scene_prefix}。\n场景描述:{$description}\n无人物,超高清,高细节,主体突出,构图合理,画面干净,无文字,无水印,无字幕,电影级光影,视觉焦点明确";
  5723. $params = [
  5724. 'prompt' => $description,
  5725. 'ref_img_urls' => []
  5726. ];
  5727. $task = $this->aiImageGenerationService->createImageGenerationTask($params);
  5728. $task_id = $task->id;
  5729. if ($task_id) {
  5730. $scene['task_id'] = $task_id;
  5731. $scene['task_status'] = 'processing';
  5732. $scenes_updated = true;
  5733. dLog('anime')->info("分集ID:{$episode_id} 场景:{$scene_name} 创建图片生成任务,任务ID:{$task_id}");
  5734. }
  5735. } catch (\Exception $e) {
  5736. dLog('anime')->error("分集ID:{$episode_id} 场景:{$scene_name} 创建图片生成任务失败: " . $e->getMessage());
  5737. }
  5738. }
  5739. }
  5740. // 如果有更新,保存到数据库
  5741. if ($roles_updated || $scenes_updated) {
  5742. $update_data = ['updated_at' => date('Y-m-d H:i:s')];
  5743. if ($roles_updated) {
  5744. $update_data['roles'] = json_encode($roles, JSON_UNESCAPED_UNICODE);
  5745. }
  5746. if ($scenes_updated) {
  5747. $update_data['scenes'] = json_encode($scenes, JSON_UNESCAPED_UNICODE);
  5748. }
  5749. DB::table('mp_anime_episodes')->where('id', $episode_id)->update($update_data);
  5750. dLog('anime')->info("分集ID:{$episode_id} 角色和场景数据已更新");
  5751. }
  5752. }
  5753. /**
  5754. * 根据图片URL使用AI反推图片提示词
  5755. *
  5756. * @param string $img_url 图片URL
  5757. * @return string 反推的提示词
  5758. */
  5759. private function generateImagePromptFromUrl($img_url) {
  5760. try {
  5761. // 获取默认模型
  5762. $model = 'doubao-seed-2-0-mini-260215';
  5763. // 构建messages参数
  5764. $messages = [
  5765. [
  5766. 'role' => 'user',
  5767. 'content' => [
  5768. [
  5769. 'type' => 'text',
  5770. 'text' => '请解析这张参考图,并直接输出一段专业中文反推提示词。提示词用于短剧分镜图片生成,必须聚焦角色和场景本身,可包含姿态、镜头视角、构图、画风、色彩氛围、光线、景深或光圈质感等要素。不要输出解释、标题、列表或无关背景,只输出可直接用于文生图的分镜图片提示词'
  5771. ],
  5772. [
  5773. 'type' => 'image_url',
  5774. 'image_url' => [
  5775. 'url' => $img_url
  5776. ]
  5777. ]
  5778. ]
  5779. ]
  5780. ];
  5781. // 构建请求参数
  5782. $params = [
  5783. 'model' => $model,
  5784. 'messages' => $messages,
  5785. 'stream' => false,
  5786. 'thinking' => ['type' => 'disabled'] // 不使用思考模式
  5787. ];
  5788. // 调用DeepSeek服务的volcEngineChatCompletion方法(非流式)
  5789. $result = $this->DeepSeekService->volcEngineChatCompletion($params);
  5790. // 仅记录 token 使用明细(不扣积分)
  5791. $uid = 0;
  5792. try {
  5793. $uid = (int)Site::getUid();
  5794. } catch (\Throwable $e) {
  5795. // 非请求上下文(如命令行)下可能无法获取用户ID,置为0跳过记录
  5796. }
  5797. $this->pointsService->recordTokenOnlyDetail(
  5798. $uid,
  5799. $this->pointsService->getTokensFromUsage($result['usage'] ?? []),
  5800. [
  5801. 'model' => $model,
  5802. 'img_url' => $img_url,
  5803. 'source' => 'generateImagePromptFromUrl',
  5804. ],
  5805. 'chat',
  5806. $model,
  5807. ''
  5808. );
  5809. // 返回生成的内容
  5810. return getProp($result, 'fullContent', '图片描述生成失败');
  5811. } catch (\Exception $e) {
  5812. dLog('anime')->error('AI反推图片提示词失败: ' . $e->getMessage(), [
  5813. 'img_url' => $img_url
  5814. ]);
  5815. logDB('anime', 'error', 'AI反推图片提示词失败', [
  5816. 'error' => $e->getMessage(),
  5817. 'img_url' => $img_url
  5818. ]);
  5819. return '图片描述生成失败: ' . $e->getMessage();
  5820. }
  5821. }
  5822. /**
  5823. * 音频试听接口
  5824. * 创建音频任务并轮询获取结果
  5825. *
  5826. * @param array $data 参数数组
  5827. * @return array 返回音频URL或错误信息
  5828. */
  5829. public function previewAudio($data) {
  5830. $dialogue = getProp($data, 'dialogue');
  5831. // 必填参数验证
  5832. if (!$dialogue) Utils::throwError('20003:dialogue不能为空');
  5833. // 获取参数,优先使用传入的参数,否则使用分镜中的参数
  5834. $voice_type = getProp($data, 'voice_type');
  5835. $voice_name = getProp($data, 'voice_name');
  5836. $voice_actor = getProp($data, 'voice_actor');
  5837. $emotion_type = getProp($data, 'emotion_type');
  5838. $gender = getProp($data, 'gender', 0);
  5839. $emotion = getProp($data, 'emotion');
  5840. $speed_ratio = getProp($data, 'speed_ratio', 0);
  5841. $loudness_ratio = getProp($data, 'loudness_ratio', 0);
  5842. $emotion_scale = getProp($data, 'emotion_scale', 0);
  5843. $pitch = getProp($data, 'pitch', 0);
  5844. try {
  5845. $now = date('Y-m-d H:i:s');
  5846. // 构建生成参数
  5847. $generate_json = json_encode([
  5848. 'text' => $dialogue,
  5849. 'role' => $voice_actor,
  5850. 'voice_type' => $voice_type,
  5851. 'voice_name' => $voice_name,
  5852. 'emotion' => $emotion,
  5853. 'emotion_type' => $emotion_type,
  5854. 'gender' => $gender,
  5855. 'speed_ratio' => $speed_ratio,
  5856. 'loudness_ratio' => $loudness_ratio,
  5857. 'emotion_scale' => $emotion_scale,
  5858. 'pitch' => $pitch,
  5859. ], 256);
  5860. // 请求远程服务器执行生成
  5861. $client = new Client(['timeout' => 600, 'verify' => false]);
  5862. $result = $client->get("http://122.9.129.83:5000/api/anime/audioPreview?generateJson={$generate_json}");
  5863. $response = $result->getBody()->getContents();
  5864. $response_arr = json_decode($response, true);
  5865. if (!isset($response_arr['code']) || (int)$response_arr['code'] !== 0) {
  5866. $error_msg = isset($response_arr['msg']) ? $response_arr['msg'] : '未知错误';
  5867. dLog('anime')->error('音频试听任务创建失败', ['error' => $error_msg, 'response_arr' => $response_arr]);
  5868. Utils::throwError('20003:音频试听任务创建失败: ' . $error_msg);
  5869. }
  5870. $arr = $response_arr['data'];
  5871. $subtitle_info = $arr['subtitle_info'];
  5872. $audio_duration = json_decode($subtitle_info, true)['duration'];
  5873. if (!isset($arr['url']) || !$audio_duration || !$subtitle_info) Utils::throwError('20003:音频参数生成异常');
  5874. return [
  5875. 'audio_url' => $arr['url'],
  5876. 'subtitle_info' => $subtitle_info,
  5877. 'audio_duration' => round($audio_duration, 2)
  5878. ];
  5879. } catch (\Exception $e) {
  5880. dLog('anime')->error('音频试听失败', ['error' => $e->getMessage()]);
  5881. Utils::throwError('20003:' . $e->getMessage());
  5882. }
  5883. }
  5884. /**
  5885. * 获取角色库列表(支持文件夹递归查询)
  5886. * @param array $data 包含 parent_id(父文件夹ID,默认0表示最外层)、role(搜索关键词)、is_public(筛选类型)
  5887. * @return array 返回当前目录下的所有子目录和角色列表(递归)
  5888. */
  5889. public function globalProducts($data) {
  5890. $uid = Site::getUid();
  5891. $cpid = Site::getCpid();
  5892. $role = Site::getRole();
  5893. $id = getProp($data, 'id', 0);
  5894. $parent_id = getProp($data, 'parent_id', 0);
  5895. $product_name = getProp($data, 'product_name');
  5896. $product = getProp($data, 'product'); // 1.角色 2.场景 3.道具
  5897. $is_public = getProp($data, 'public_type', 2); // 0=仅个人库 1=仅公共库 2=个人库+公共库
  5898. if (!$product) {
  5899. Utils::throwError('20003:请选择产品类型');
  5900. }
  5901. // 根据角色和is_public参数确定查询范围
  5902. // admin角色:获取所有个人库+公共库(忽略is_public参数)
  5903. // user角色:根据is_public参数筛选
  5904. $query_user_ids = [];
  5905. if ($role === 'admin') {
  5906. // admin获取所有个人库和公共库
  5907. $query_user_ids = [$uid, 0];
  5908. } else {
  5909. // user角色根据is_public参数筛选
  5910. if ($is_public == 2) {
  5911. // 个人库+公共库
  5912. $query_user_ids = [$uid, 0];
  5913. } elseif ($is_public == 0) {
  5914. // 仅个人库
  5915. $query_user_ids = [$uid];
  5916. } elseif ($is_public == 1) {
  5917. // 仅公共库
  5918. $query_user_ids = [0];
  5919. }
  5920. }
  5921. // 如果有搜索条件(product_name 或 id),按条件搜索文件夹和产品
  5922. if ($id || $product_name) {
  5923. $query = DB::table('mp_products')
  5924. ->where('cpid', $cpid)
  5925. ->whereIn('user_id', $query_user_ids)
  5926. ->where('is_deleted', 0);
  5927. // 如果指定了 id,按 id 精确查询
  5928. if ($id) {
  5929. $query->where('id', $id);
  5930. }
  5931. // 如果指定了 product_name,按名称模糊查询
  5932. if ($product_name) {
  5933. $query->where('product_name', 'like', "%{$product_name}%");
  5934. }
  5935. // 如果指定了 product,添加筛选条件
  5936. if ($product) {
  5937. $query->where('product', $product);
  5938. }
  5939. $result = $query->select('id', 'type', 'parent_id', 'level', 'product_name', 'url', 'pic_prompt', 'three_view_image_url', 'versions', 'product', 'user_id', 'created_at')
  5940. ->orderByRaw('type DESC, CASE WHEN user_id = '.$uid.' THEN 0 ELSE 1 END ASC, sort_order DESC, created_at DESC')
  5941. ->get()
  5942. ->map(function($value) {
  5943. $value = (array)$value;
  5944. $value['created_at'] = transDate($value['created_at'], 'Y-m-d');
  5945. $value['type'] = (int)$value['type'];
  5946. $value['parent_id'] = (int)$value['parent_id'];
  5947. $value['level'] = (int)$value['level'];
  5948. $value['product'] = (int)($value['product'] ?? 1);
  5949. $value['is_public'] = (int)$value['user_id'] === 0 ? 1 : 0;
  5950. $value['versions'] = json_decode($value['versions'], true) ?: [];
  5951. unset($value['user_id']);
  5952. return $value;
  5953. })
  5954. ->toArray();
  5955. return $result;
  5956. }
  5957. // 递归获取所有子目录和角色
  5958. return $this->getChildrenRecursive($cpid, $parent_id, $product, $query_user_ids, $uid);
  5959. }
  5960. /**
  5961. * 递归获取指定目录下的所有子目录和角色
  5962. * @param int $cpid 公司ID
  5963. * @param int $parent_id 父目录ID
  5964. * @param int|null $product 产品类型筛选 1.角色 2.场景 3.道具
  5965. * @param array $query_user_ids 用户ID数组(支持多个)
  5966. * @param int $current_uid 当前用户ID(用于排序)
  5967. * @return array
  5968. */
  5969. private function getChildrenRecursive($cpid, $parent_id, $product = null, $query_user_ids = [], $current_uid = 0) {
  5970. // 查询当前层级的所有项(文件夹和角色)
  5971. $query = DB::table('mp_products')
  5972. ->where('cpid', $cpid)
  5973. ->where('is_deleted', 0)
  5974. ->where('parent_id', $parent_id);
  5975. // 添加用户ID验证(支持多个user_id)
  5976. if (!empty($query_user_ids)) {
  5977. $query->whereIn('user_id', $query_user_ids);
  5978. }
  5979. // 如果指定了 product,添加筛选条件(文件夹和角色都需要筛选)
  5980. if ($product) {
  5981. $query->where('product', $product);
  5982. }
  5983. // 排序规则:
  5984. // 1. 文件夹在前(type DESC)
  5985. // 2. 个人库在前,公共库在后(CASE WHEN user_id = current_uid)
  5986. // 3. 其他排序规则
  5987. $items = $query->select('id', 'type', 'parent_id', 'level', 'product_name', 'url', 'pic_prompt', 'three_view_image_url', 'versions', 'product', 'user_id', 'created_at')
  5988. ->orderByRaw('type DESC, CASE WHEN user_id = '.$current_uid.' THEN 0 ELSE 1 END ASC, sort_order DESC, created_at DESC')
  5989. ->get();
  5990. $result = [];
  5991. foreach ($items as $item) {
  5992. $itemArray = [
  5993. 'id' => $item->id,
  5994. 'type' => (int)$item->type,
  5995. 'parent_id' => (int)$item->parent_id,
  5996. 'level' => (int)$item->level,
  5997. 'product_name' => $item->product_name,
  5998. 'url' => $item->url,
  5999. 'pic_prompt' => $item->pic_prompt ?? '',
  6000. 'three_view_image_url' => $item->three_view_image_url,
  6001. 'product' => (int)($item->product ?? 1),
  6002. 'is_public' => (int)$item->user_id === 0 ? 1 : 0,
  6003. 'created_at' => transDate($item->created_at, 'Y-m-d')
  6004. ];
  6005. $itemArray['versions'] = json_decode($item->versions, true) ?: [];
  6006. // 如果是文件夹,递归获取其子项
  6007. if ($item->type == 2) {
  6008. $children = $this->getChildrenRecursive($cpid, $item->id, $product, $query_user_ids, $current_uid);
  6009. if (!empty($children)) {
  6010. $itemArray['children'] = $children;
  6011. }
  6012. }
  6013. $result[] = $itemArray;
  6014. }
  6015. return $result;
  6016. }
  6017. /**
  6018. * 创建文件夹
  6019. * @param array $data 包含 parent_id(父文件夹ID)、product_name(文件夹名称)、product(产品类型)
  6020. * @return int 返回新建文件夹ID
  6021. */
  6022. public function createFolder($data) {
  6023. $uid = Site::getUid();
  6024. $cpid = Site::getCpid();
  6025. $role = Site::getRole();
  6026. $parent_id = getProp($data, 'parent_id', 0);
  6027. $folder_name = getProp($data, 'product_name', '新建文件夹');
  6028. $is_public = getProp($data, 'is_public', 0); // 0=个人资产库 1=公共资产库
  6029. // 如果是公共库操作,需要admin权限
  6030. if ($is_public && $role !== 'admin') {
  6031. Utils::throwError('20003:只有管理员才能操作公共资产库');
  6032. }
  6033. // 根据is_public参数确定存储的user_id(公共库user_id=0,cpid保持不变)
  6034. $store_uid = $is_public ? 0 : $uid;
  6035. // 获取 product 字段:1.角色 2.场景 3.道具,默认为1
  6036. $product = getProp($data, 'product');
  6037. if (!in_array($product, [1, 2, 3])) {
  6038. // Utils::throwError('20003:product 参数错误,只能是 1(角色)、2(场景) 或 3(道具)');
  6039. }
  6040. // 验证父文件夹
  6041. $parent_level = 0;
  6042. if ($parent_id > 0) {
  6043. $parent = DB::table('mp_products')
  6044. ->where('id', $parent_id)
  6045. ->where('cpid', $cpid)
  6046. ->where('user_id', $store_uid)
  6047. ->where('type', 2)
  6048. ->where('is_deleted', 0)
  6049. ->first();
  6050. if (!$parent) {
  6051. Utils::throwError('20003:父文件夹不存在');
  6052. }
  6053. // 检查父文件夹的 product 类型是否一致
  6054. if ($parent->product != $product) {
  6055. Utils::throwError('20003:文件夹类型必须与父文件夹一致');
  6056. }
  6057. $parent_level = $parent->level;
  6058. // 检查层级限制(最多3层)
  6059. if ($parent_level >= 3) {
  6060. Utils::throwError('20003:文件夹层级不能超过3层');
  6061. }
  6062. }
  6063. // 检查当前目录下是否已存在空白文件夹
  6064. $empty_folder_exists = DB::table('mp_products')
  6065. ->where('parent_id', $parent_id)
  6066. ->where('cpid', $cpid)
  6067. ->where('user_id', $store_uid)
  6068. ->where('type', 2)
  6069. ->where('product', $product)
  6070. ->where('product_name', '新建文件夹')
  6071. ->where('is_deleted', 0)
  6072. ->exists();
  6073. if ($empty_folder_exists && $folder_name == '新建文件夹') {
  6074. Utils::throwError('20003:不允许创建多个空白文件夹,请先重命名现有文件夹');
  6075. }
  6076. // 创建文件夹
  6077. $folder_id = DB::table('mp_products')->insertGetId([
  6078. 'user_id' => $store_uid,
  6079. 'cpid' => $cpid,
  6080. 'type' => 2,
  6081. 'parent_id' => $parent_id,
  6082. 'level' => $parent_level + 1,
  6083. 'product_name' => $folder_name,
  6084. 'product' => $product,
  6085. 'sort_order' => time(), // 使用时间戳作为排序权重
  6086. 'is_deleted' => 0,
  6087. 'created_at' => date('Y-m-d H:i:s'),
  6088. 'updated_at' => date('Y-m-d H:i:s')
  6089. ]);
  6090. return [
  6091. 'id' => $folder_id,
  6092. 'type' => 2,
  6093. 'parent_id' => $parent_id,
  6094. 'level' => $parent_level + 1,
  6095. 'product_name' => $folder_name,
  6096. 'product' => $product,
  6097. ];
  6098. }
  6099. /**
  6100. * 重命名文件夹或角色
  6101. * @param array $data 包含 id、product_name(新名称)
  6102. * @return bool
  6103. */
  6104. public function renameFolder($data) {
  6105. $uid = Site::getUid();
  6106. $cpid = Site::getCpid();
  6107. $role = Site::getRole();
  6108. $id = getProp($data, 'id');
  6109. $new_name = getProp($data, 'product_name');
  6110. $is_public = getProp($data, 'is_public', 0); // 0=个人资产库 1=公共资产库
  6111. if (!$id || !$new_name) {
  6112. Utils::throwError('20003:参数不完整');
  6113. }
  6114. // 根据is_public参数确定查询的user_id(公共库user_id=0,cpid保持不变)
  6115. $query_uid = $is_public ? 0 : $uid;
  6116. // 如果是公共库操作,需要admin权限
  6117. if ($is_public && $role !== 'admin') {
  6118. Utils::throwError('20003:只有管理员才能操作公共资产库');
  6119. }
  6120. // 检查是否存在
  6121. $item = DB::table('mp_products')
  6122. ->where('id', $id)
  6123. ->where('cpid', $cpid)
  6124. ->where('user_id', $query_uid)
  6125. ->where('is_deleted', 0)
  6126. ->first();
  6127. if (!$item) {
  6128. Utils::throwError('20003:项目不存在');
  6129. }
  6130. return DB::table('mp_products')
  6131. ->where('id', $id)
  6132. ->where('cpid', $cpid)
  6133. ->where('user_id', $query_uid)
  6134. ->update([
  6135. 'product_name' => $new_name,
  6136. 'updated_at' => date('Y-m-d H:i:s')
  6137. ]);
  6138. }
  6139. /**
  6140. * 移动角色或文件夹到指定文件夹
  6141. * @param array $data 包含 id(要移动的项目ID)、target_parent_id(目标父文件夹ID)
  6142. * @return bool
  6143. */
  6144. public function moveProductOrFolder($data) {
  6145. $uid = Site::getUid();
  6146. $cpid = Site::getCpid();
  6147. $role = Site::getRole();
  6148. $id = getProp($data, 'id');
  6149. $target_parent_id = getProp($data, 'target_parent_id', 0);
  6150. $is_public = getProp($data, 'is_public', 0); // 0=个人资产库 1=公共资产库
  6151. if (!$id) {
  6152. Utils::throwError('20003:请选择要移动的项目');
  6153. }
  6154. // 根据is_public参数确定查询的user_id(公共库user_id=0,cpid保持不变)
  6155. $query_uid = $is_public ? 0 : $uid;
  6156. // 如果是公共库操作,需要admin权限
  6157. if ($is_public && $role !== 'admin') {
  6158. Utils::throwError('20003:只有管理员才能操作公共资产库');
  6159. }
  6160. // 检查要移动的项目
  6161. $item = DB::table('mp_products')
  6162. ->where('id', $id)
  6163. ->where('cpid', $cpid)
  6164. ->where('user_id', $query_uid)
  6165. ->where('is_deleted', 0)
  6166. ->first();
  6167. if (!$item) {
  6168. Utils::throwError('20003:项目不存在');
  6169. }
  6170. // 验证目标文件夹
  6171. $target_level = 0;
  6172. $target_product = $item->product; // 默认使用当前项目的 product
  6173. if ($target_parent_id > 0) {
  6174. $target_parent = DB::table('mp_products')
  6175. ->where('id', $target_parent_id)
  6176. ->where('cpid', $cpid)
  6177. ->where('user_id', $query_uid)
  6178. ->where('type', 2)
  6179. ->where('is_deleted', 0)
  6180. ->first();
  6181. if (!$target_parent) {
  6182. Utils::throwError('20003:目标文件夹不存在');
  6183. }
  6184. // 检查 product 类型是否一致
  6185. if ($target_parent->product != $item->product) {
  6186. Utils::throwError('20003:不能移动到不同类型的文件夹下');
  6187. }
  6188. $target_level = $target_parent->level;
  6189. $target_product = $target_parent->product;
  6190. // 如果移动的是文件夹,需要检查层级
  6191. if ($item->type == 2) {
  6192. // 计算移动后的最大层级
  6193. $max_child_level = $this->getMaxChildLevel($id);
  6194. $depth = $max_child_level - $item->level;
  6195. if ($target_level + 1 + $depth > 3) {
  6196. Utils::throwError('20003:移动后文件夹层级将超过3层限制');
  6197. }
  6198. // 不能移动到自己或自己的子文件夹下
  6199. if ($this->isDescendant($target_parent_id, $id)) {
  6200. Utils::throwError('20003:不能移动到自己或子文件夹下');
  6201. }
  6202. }
  6203. }
  6204. // 更新父文件夹和层级
  6205. $new_level = $target_level + 1;
  6206. DB::table('mp_products')
  6207. ->where('id', $id)
  6208. ->update([
  6209. 'parent_id' => $target_parent_id,
  6210. 'level' => $new_level,
  6211. 'updated_at' => date('Y-m-d H:i:s')
  6212. ]);
  6213. // 如果是文件夹,需要递归更新所有子项的层级
  6214. if ($item->type == 2) {
  6215. $this->updateChildrenLevel($id, $new_level);
  6216. }
  6217. return true;
  6218. }
  6219. /**
  6220. * 获取文件夹下最大子层级
  6221. * @param int $folder_id
  6222. * @return int
  6223. */
  6224. private function getMaxChildLevel($folder_id) {
  6225. $max_level = DB::table('mp_products')
  6226. ->where('parent_id', $folder_id)
  6227. ->where('is_deleted', 0)
  6228. ->max('level');
  6229. if (!$max_level) {
  6230. return DB::table('mp_products')->where('id', $folder_id)->value('level');
  6231. }
  6232. // 递归查找子文件夹
  6233. $children = DB::table('mp_products')
  6234. ->where('parent_id', $folder_id)
  6235. ->where('type', 2)
  6236. ->where('is_deleted', 0)
  6237. ->pluck('id');
  6238. foreach ($children as $child_id) {
  6239. $child_max = $this->getMaxChildLevel($child_id);
  6240. if ($child_max > $max_level) {
  6241. $max_level = $child_max;
  6242. }
  6243. }
  6244. return $max_level;
  6245. }
  6246. /**
  6247. * 检查 target_id 是否是 folder_id 的后代
  6248. * @param int $target_id
  6249. * @param int $folder_id
  6250. * @return bool
  6251. */
  6252. private function isDescendant($target_id, $folder_id) {
  6253. if ($target_id == $folder_id) {
  6254. return true;
  6255. }
  6256. $parent = DB::table('mp_products')
  6257. ->where('id', $target_id)
  6258. ->where('is_deleted', 0)
  6259. ->first();
  6260. if (!$parent || $parent->parent_id == 0) {
  6261. return false;
  6262. }
  6263. return $this->isDescendant($parent->parent_id, $folder_id);
  6264. }
  6265. /**
  6266. * 递归更新子项层级
  6267. * @param int $parent_id
  6268. * @param int $parent_level
  6269. */
  6270. private function updateChildrenLevel($parent_id, $parent_level) {
  6271. $children = DB::table('mp_products')
  6272. ->where('parent_id', $parent_id)
  6273. ->where('is_deleted', 0)
  6274. ->get();
  6275. foreach ($children as $child) {
  6276. $new_level = $parent_level + 1;
  6277. DB::table('mp_products')
  6278. ->where('id', $child->id)
  6279. ->update([
  6280. 'level' => $new_level,
  6281. 'updated_at' => date('Y-m-d H:i:s')
  6282. ]);
  6283. // 如果是文件夹,继续递归
  6284. if ($child->type == 2) {
  6285. $this->updateChildrenLevel($child->id, $new_level);
  6286. }
  6287. }
  6288. }
  6289. /**
  6290. * 获取文件夹路径(面包屑导航)
  6291. * @param array $data 包含 folder_id
  6292. * @return array 返回路径数组
  6293. */
  6294. public function getFolderPath($data) {
  6295. $uid = Site::getUid();
  6296. $cpid = Site::getCpid();
  6297. $folder_id = getProp($data, 'id', 0);
  6298. $is_public = getProp($data, 'is_public', 0); // 0=个人资产库 1=公共资产库
  6299. if ($folder_id == 0) {
  6300. return [
  6301. ['id' => 0, 'name' => '根目录']
  6302. ];
  6303. }
  6304. // 根据is_public参数确定查询的user_id(公共库user_id=0,cpid保持不变)
  6305. $query_uid = $is_public ? 0 : $uid;
  6306. $path = [];
  6307. $current_id = $folder_id;
  6308. while ($current_id > 0) {
  6309. $folder = DB::table('mp_products')
  6310. ->where('id', $current_id)
  6311. ->where('cpid', $cpid)
  6312. ->where('user_id', $query_uid)
  6313. ->where('type', 2)
  6314. ->where('is_deleted', 0)
  6315. ->first();
  6316. if (!$folder) {
  6317. break;
  6318. }
  6319. array_unshift($path, [
  6320. 'id' => $folder->id,
  6321. 'name' => $folder->product_name
  6322. ]);
  6323. $current_id = $folder->parent_id;
  6324. }
  6325. // 添加根目录
  6326. array_unshift($path, ['id' => 0, 'name' => '根目录']);
  6327. return $path;
  6328. }
  6329. public function createProduct($data) {
  6330. $uid = Site::getUid();
  6331. $cpid = Site::getCpid();
  6332. $role = Site::getRole();
  6333. $is_public = getProp($data, 'is_public', 0); // 0=个人资产库 1=公共资产库
  6334. // 如果是公共库操作,需要admin权限
  6335. if ($is_public && $role !== 'admin') {
  6336. Utils::throwError('20003:只有管理员才能操作公共资产库');
  6337. }
  6338. // 根据is_public参数确定存储的user_id(公共库user_id=0,cpid保持不变)
  6339. $store_uid = $is_public ? 0 : $uid;
  6340. // 新增参数:剧本ID和剧集序号(支持数组传参,多个序号也可用英文逗号隔开)
  6341. $script_id = (int)getProp($data, 'script_id', 0);
  6342. $episode_numbers = $this->normalizeEpisodeNumbers(getProp($data, 'episode_number', []));
  6343. if ($script_id && empty($episode_numbers)) {
  6344. Utils::throwError('20003:剧集序号不能为空');
  6345. }
  6346. if (!$script_id && !empty($episode_numbers)) {
  6347. Utils::throwError('20003:请提供剧本ID');
  6348. }
  6349. $product_name = trim(getProp($data, 'product_name'));
  6350. if (!$product_name) Utils::throwError('20003:名称不能为空');
  6351. $product_name = preg_replace('/^[\s*\[\]【】[]{}{}\x{3000}]+|[\s*\[\]【】[]{}{}\x{3000}]+$/u', '', $product_name);
  6352. // $exists_id = DB::table('mp_products')->where('cpid', $cpid)->where('type', 1)->where('product_name', $product_name)->where('is_deleted', 0)->value('id');
  6353. // if ($exists_id) Utils::throwError('20003:名称不能重复,请修改');
  6354. $url = trim(getProp($data, 'url'));
  6355. if (!$url) Utils::throwError('20003:图片地址不能为空');
  6356. $versions = getProp($data, 'versions');
  6357. // 检查是否是正确的图片格式
  6358. $allowedExtensions = ['jpg', 'jpeg', 'png', 'gif', 'webp', 'bmp'];
  6359. $urlPath = parse_url($url, PHP_URL_PATH);
  6360. $extension = strtolower(pathinfo($urlPath, PATHINFO_EXTENSION));
  6361. if (!in_array($extension, $allowedExtensions)) {
  6362. Utils::throwError('20003:图片格式不正确,仅支持 jpg、jpeg、png、gif、webp、bmp 格式');
  6363. }
  6364. // 选填三视图图片地址,格式校验与 url 一致
  6365. $three_view_image_url = trim(getProp($data, 'three_view_image_url', ''));
  6366. if ($three_view_image_url) {
  6367. $threeViewPath = parse_url($three_view_image_url, PHP_URL_PATH);
  6368. $threeViewExtension = strtolower(pathinfo($threeViewPath, PATHINFO_EXTENSION));
  6369. if (!in_array($threeViewExtension, $allowedExtensions)) {
  6370. Utils::throwError('20003:三视图图片格式不正确,仅支持 jpg、jpeg、png、gif、webp、bmp 格式');
  6371. }
  6372. }
  6373. $pic_prompt = trim(getProp($data, 'pic_prompt'));
  6374. if (!$pic_prompt) Utils::throwError('20003:提示词不能为空');
  6375. // 获取 product 字段:1.角色 2.场景 3.道具,默认为1
  6376. $product = getProp($data, 'product');
  6377. if (!in_array($product, [1, 2, 3])) {
  6378. // Utils::throwError('20003:产品类型只能是 1(角色)、2(场景) 或 3(道具)');
  6379. }
  6380. // 获取父文件夹ID和层级
  6381. $parent_id = getProp($data, 'parent_id', 0);
  6382. $parent_level = 0;
  6383. if ($parent_id > 0) {
  6384. $parent = DB::table('mp_products')
  6385. ->where('id', $parent_id)
  6386. ->where('cpid', $cpid)
  6387. ->where('user_id', $store_uid)
  6388. ->where('type', 2)
  6389. ->where('is_deleted', 0)
  6390. ->first();
  6391. if (!$parent) {
  6392. Utils::throwError('20003:父文件夹不存在');
  6393. }
  6394. $parent_level = $parent->level;
  6395. }
  6396. // 创建资产并保存剧本资产关联关系(同一事务)
  6397. DB::beginTransaction();
  6398. try {
  6399. $id = DB::table('mp_products')->insertGetId([
  6400. 'user_id' => $store_uid,
  6401. 'cpid' => $cpid,
  6402. 'type' => 1, // 1=角色图片
  6403. 'parent_id' => $parent_id,
  6404. 'level' => $parent_level + 1,
  6405. 'product_name' => $product_name,
  6406. 'url' => $url,
  6407. 'three_view_image_url' => $three_view_image_url,
  6408. 'pic_prompt' => $pic_prompt,
  6409. 'product' => $product,
  6410. 'versions' => json_encode($versions, 256),
  6411. 'sort_order' => time(), // 使用时间戳作为排序权重
  6412. 'created_at' => date('Y-m-d H:i:s'),
  6413. 'updated_at' => date('Y-m-d H:i:s')
  6414. ]);
  6415. if (!$id) Utils::throwError('20003:创建失败');
  6416. // 保存剧本资产关联关系
  6417. if ($script_id) {
  6418. $this->saveProductScriptMapping($id, $script_id, $episode_numbers);
  6419. }
  6420. DB::commit();
  6421. } catch (\Exception $e) {
  6422. DB::rollback();
  6423. throw $e;
  6424. }
  6425. return [
  6426. 'id' => $id,
  6427. 'type' => 1,
  6428. 'parent_id' => $parent_id,
  6429. 'level' => $parent_level + 1,
  6430. 'product_name' => $product_name,
  6431. 'url' => $url,
  6432. 'three_view_image_url' => $three_view_image_url,
  6433. 'pic_prompt' => $pic_prompt,
  6434. 'product' => $product,
  6435. 'versions' => $versions
  6436. ];
  6437. }
  6438. public function editProduct($data) {
  6439. $uid = Site::getUid();
  6440. $cpid = Site::getCpid();
  6441. $role = Site::getRole();
  6442. $id = getProp($data, 'id');
  6443. if (!$id) Utils::throwError('20003:ID不能为空');
  6444. $versions = getProp($data, 'versions');
  6445. $is_public = getProp($data, 'is_public', 0); // 0=个人资产库 1=公共资产库
  6446. // 新增参数:剧本ID和剧集序号(支持数组传参,多个序号也可用英文逗号隔开)
  6447. $script_id = (int)getProp($data, 'script_id', 0);
  6448. $episode_numbers = $this->normalizeEpisodeNumbers(getProp($data, 'episode_number', []));
  6449. if ($script_id && empty($episode_numbers)) {
  6450. Utils::throwError('20003:剧集序号不能为空');
  6451. }
  6452. if (!$script_id && !empty($episode_numbers)) {
  6453. Utils::throwError('20003:请提供剧本ID');
  6454. }
  6455. // 根据is_public参数确定查询的user_id(公共库user_id=0,cpid保持不变)
  6456. $query_uid = $is_public ? 0 : $uid;
  6457. // 如果是公共库操作,需要admin权限
  6458. if ($is_public && $role !== 'admin') {
  6459. Utils::throwError('20003:只有管理员才能操作公共资产库');
  6460. }
  6461. // 检查是否存在且属于当前用户或公共库
  6462. $role = DB::table('mp_products')
  6463. ->where('id', $id)
  6464. ->where('cpid', $cpid)
  6465. ->where('user_id', $query_uid)
  6466. ->where('type', 1)->first();
  6467. if (!$role) Utils::throwError('20003:记录不存在');
  6468. $updateData = [];
  6469. // $needVersionRecord = false; // 是否需要记录版本
  6470. // 名称
  6471. $product_name = trim(getProp($data, 'product_name'));
  6472. if ($product_name) {
  6473. $product_name = preg_replace('/^[\s*\[\]【】[]{}{}\x{3000}]+|[\s*\[\]【】[]{}{}\x{3000}]+$/u', '', $product_name);
  6474. $updateData['product_name'] = $product_name;
  6475. }
  6476. // $exists_id = DB::table('mp_products')->where('cpid', $cpid)->where('type', 1)->where('product_name', $product_name)->where('is_deleted', 0)->value('id');
  6477. // if ($exists_id && $exists_id != $id) Utils::throwError('20003:名称不能重复,请修改');
  6478. // 图片地址
  6479. $allowedExtensions = ['jpg', 'jpeg', 'png', 'gif', 'webp', 'bmp'];
  6480. $url = trim(getProp($data, 'url'));
  6481. if ($url) {
  6482. // 检查是否是正确的图片格式
  6483. $urlPath = parse_url($url, PHP_URL_PATH);
  6484. $extension = strtolower(pathinfo($urlPath, PATHINFO_EXTENSION));
  6485. if (!in_array($extension, $allowedExtensions)) {
  6486. Utils::throwError('20003:图片格式不正确,仅支持 jpg、jpeg、png、gif、webp、bmp 格式');
  6487. }
  6488. // // 如果 url 有变更,记录版本
  6489. // if ($url !== $role->url) {
  6490. // $needVersionRecord = true;
  6491. // }
  6492. $updateData['url'] = $url;
  6493. }
  6494. // 三视图图片地址(选填),格式校验与 url 一致
  6495. $three_view_image_url = trim(getProp($data, 'three_view_image_url', ''));
  6496. if ($three_view_image_url) {
  6497. $threeViewPath = parse_url($three_view_image_url, PHP_URL_PATH);
  6498. $threeViewExtension = strtolower(pathinfo($threeViewPath, PATHINFO_EXTENSION));
  6499. if (!in_array($threeViewExtension, $allowedExtensions)) {
  6500. Utils::throwError('20003:三视图图片格式不正确,仅支持 jpg、jpeg、png、gif、webp、bmp 格式');
  6501. }
  6502. $updateData['three_view_image_url'] = $three_view_image_url;
  6503. }
  6504. // 提示词
  6505. $pic_prompt = trim(getProp($data, 'pic_prompt'));
  6506. if ($pic_prompt) {
  6507. // // 如果 pic_prompt 有变更,记录版本
  6508. // if ($pic_prompt !== $role->pic_prompt) {
  6509. // $needVersionRecord = true;
  6510. // }
  6511. $updateData['pic_prompt'] = $pic_prompt;
  6512. }
  6513. if (empty($updateData) && !$script_id) {
  6514. Utils::throwError('20003:没有需要更新的数据');
  6515. }
  6516. // // 如果需要记录版本,将数据添加到 versions 数组
  6517. // if ($needVersionRecord) {
  6518. // // 获取现有的 versions 数据
  6519. // $versions = json_decode($role->versions, true) ?: [];
  6520. // $isFirstVersion = empty($versions); // 判断是否是第一次记录版本
  6521. // // 如果是第一次记录版本,先添加旧版本(变更前)
  6522. // if ($isFirstVersion) {
  6523. // $oldVersion = [
  6524. // 'url' => $role->url,
  6525. // 'description' => $role->pic_prompt,
  6526. // ];
  6527. // // 旧版本添加到数组末尾
  6528. // $versions[] = $oldVersion;
  6529. // }
  6530. // // 构建新版本(变更后)
  6531. // $newVersion = [
  6532. // 'url' => isset($updateData['url']) ? $updateData['url'] : $role->url,
  6533. // 'description' => isset($updateData['pic_prompt']) ? $updateData['pic_prompt'] : $role->pic_prompt,
  6534. // ];
  6535. // // 检查新版本是否已存在于历史版本中
  6536. // $existingIndex = -1;
  6537. // foreach ($versions as $index => $version) {
  6538. // if ($version['url'] === $newVersion['url'] && $version['description'] === $newVersion['description']) {
  6539. // $existingIndex = $index;
  6540. // break;
  6541. // }
  6542. // }
  6543. // if ($existingIndex !== -1) {
  6544. // // 如果已存在,移除旧的位置
  6545. // array_splice($versions, $existingIndex, 1);
  6546. // }
  6547. // // 新版本添加到数组开头(最新的在前)
  6548. // array_unshift($versions, $newVersion);
  6549. // // // 限制版本数量(可选,例如只保留最近10个版本)
  6550. // // if (count($versions) > 10) {
  6551. // // $versions = array_slice($versions, 0, 10);
  6552. // // }
  6553. // $updateData['versions'] = json_encode($versions, 256);
  6554. // }
  6555. if ($versions) {
  6556. $updateData['versions'] = json_encode($versions, 256);
  6557. }
  6558. if (!empty($updateData)) {
  6559. $updateData['updated_at'] = date('Y-m-d H:i:s');
  6560. }
  6561. // 更新资产并保存剧本资产关联关系(同一事务)
  6562. DB::beginTransaction();
  6563. try {
  6564. $updated = true;
  6565. if (!empty($updateData)) {
  6566. $updated = DB::table('mp_products')
  6567. ->where('cpid', $cpid)
  6568. ->where('id', $id)
  6569. ->update($updateData);
  6570. }
  6571. // 保存剧本资产关联关系
  6572. if ($script_id) {
  6573. $this->saveProductScriptMapping($id, $script_id, $episode_numbers);
  6574. }
  6575. DB::commit();
  6576. } catch (\Exception $e) {
  6577. DB::rollback();
  6578. throw $e;
  6579. }
  6580. return $updated;
  6581. }
  6582. /**
  6583. * 保存单一资产与剧本剧集的关联关系
  6584. *
  6585. * @param int $product_id 资产ID
  6586. * @param int $script_id 剧本ID
  6587. * @param array $episode_numbers 剧集序号数组(序号从1开始)
  6588. * @return int 新增关联数量
  6589. */
  6590. private function saveProductScriptMapping($product_id, $script_id, $episode_numbers) {
  6591. $uid = Site::getUid();
  6592. // 验证剧本是否存在
  6593. $script = DB::table('mp_scripts')
  6594. ->where('id', $script_id)
  6595. ->where('is_deleted', 0)
  6596. ->first();
  6597. if (!$script) {
  6598. Utils::throwError('20003:剧本不存在');
  6599. }
  6600. // 验证剧本归属:只能关联自己的剧本
  6601. if ((int)$script->user_id !== (int)$uid) {
  6602. Utils::throwError('20003:只能添加到自己的剧本');
  6603. }
  6604. // 使用 splitContent 拆分剧本内容获取总集数
  6605. $totalEpisodes = $this->getScriptTotalEpisodeCount($script);
  6606. // 解析剧集序号(数组)
  6607. $episodes = [];
  6608. foreach ($episode_numbers as $item) {
  6609. if (is_array($item)) {
  6610. continue;
  6611. }
  6612. $item = trim((string)$item);
  6613. if ($item === '' || !is_numeric($item)) {
  6614. Utils::throwError('20003:剧集序号格式不正确,仅支持数字数组或英文逗号分隔的数字');
  6615. }
  6616. $episodes[] = (int)$item;
  6617. }
  6618. // 去重并校验序号范围(序号从1开始)
  6619. $episodes = array_values(array_unique($episodes));
  6620. if (empty($episodes)) {
  6621. Utils::throwError('20003:剧集序号不能为空');
  6622. }
  6623. foreach ($episodes as $episode) {
  6624. if ($episode < 1 || $episode > $totalEpisodes) {
  6625. Utils::throwError('20003:剧集序号 ' . $episode . ' 超出范围,剧本共 ' . $totalEpisodes . ' 集(序号从1开始)');
  6626. }
  6627. }
  6628. $now = now();
  6629. // 过滤已存在的关联,避免重复
  6630. $existingEpisodes = DB::table('mp_script_product_mappings')
  6631. ->where('script_id', $script_id)
  6632. ->where('product_id', $product_id)
  6633. ->whereIn('episode_number', $episodes)
  6634. ->pluck('episode_number')
  6635. ->all();
  6636. $mappingRecords = [];
  6637. foreach ($episodes as $episode) {
  6638. if (in_array($episode, $existingEpisodes)) {
  6639. continue;
  6640. }
  6641. $mappingRecords[] = [
  6642. 'script_id' => $script_id,
  6643. 'product_id' => $product_id,
  6644. 'episode_number' => $episode,
  6645. 'created_at' => $now,
  6646. 'updated_at' => $now,
  6647. ];
  6648. }
  6649. $insertedCount = 0;
  6650. if (!empty($mappingRecords)) {
  6651. $insertedCount = DB::table('mp_script_product_mappings')->insert($mappingRecords) ? count($mappingRecords) : 0;
  6652. }
  6653. return $insertedCount;
  6654. }
  6655. /**
  6656. * 规范化剧集序号参数,统一为数组
  6657. * 兼容传入数组(如 [1, 3, 5])、逗号分隔字符串(如 "1,3,5")以及字符串数组(如 ["1,3", 5])
  6658. *
  6659. * @param mixed $episode_number 剧集序号参数
  6660. * @return array
  6661. */
  6662. private function normalizeEpisodeNumbers($episode_number) {
  6663. if (!is_array($episode_number)) {
  6664. $episode_number = explode(',', (string)$episode_number);
  6665. }
  6666. $items = [];
  6667. foreach ($episode_number as $item) {
  6668. if (is_array($item)) {
  6669. continue;
  6670. }
  6671. foreach (explode(',', (string)$item) as $part) {
  6672. $part = trim($part);
  6673. if ($part !== '') {
  6674. $items[] = $part;
  6675. }
  6676. }
  6677. }
  6678. return $items;
  6679. }
  6680. /**
  6681. * 获取剧本总集数(通过 splitContent 拆分剧本内容)
  6682. *
  6683. * @param object $script 剧本记录
  6684. * @return int 总集数
  6685. */
  6686. private function getScriptTotalEpisodeCount($script) {
  6687. if (empty($script->content)) {
  6688. Utils::throwError('20003:剧本内容为空,无法确定剧集数量');
  6689. }
  6690. $totalEpisodes = count(splitContent($script->content));
  6691. if ($totalEpisodes < 1) {
  6692. Utils::throwError('20003:剧本内容无法拆分出剧集');
  6693. }
  6694. return $totalEpisodes;
  6695. }
  6696. /**
  6697. * 获取剧本总集数
  6698. *
  6699. * @param array $data 包含 script_id(剧本ID)
  6700. * @return array
  6701. */
  6702. public function getScriptTotalEpisodes($data) {
  6703. $script_id = (int)getProp($data, 'script_id', 0);
  6704. if (!$script_id) {
  6705. Utils::throwError('20003:请提供剧本ID');
  6706. }
  6707. // 验证剧本是否存在
  6708. $script = DB::table('mp_scripts')
  6709. ->where('id', $script_id)
  6710. ->where('is_deleted', 0)
  6711. ->first();
  6712. if (!$script) {
  6713. Utils::throwError('20003:剧本不存在');
  6714. }
  6715. return [
  6716. 'script_id' => $script_id,
  6717. 'script_name' => $script->script_name ?? 'script_' . $script_id,
  6718. 'episode_num' => $this->getScriptTotalEpisodeCount($script),
  6719. ];
  6720. }
  6721. /**
  6722. * 获取角色版本历史
  6723. * @param array $data 包含 id(角色ID)
  6724. * @return array 返回版本历史列表
  6725. */
  6726. public function getProductVersions($data) {
  6727. $cpid = Site::getCpid();
  6728. $id = getProp($data, 'id');
  6729. if (!$id) Utils::throwError('20003:角色ID不能为空');
  6730. $role = DB::table('mp_products')
  6731. ->where('id', $id)
  6732. ->where('cpid', $cpid)
  6733. ->where('type', 1)
  6734. ->first();
  6735. if (!$role) Utils::throwError('20003:角色不存在');
  6736. // 获取版本历史
  6737. $versions = json_decode($role->versions, true) ?: [];
  6738. // 添加当前版本作为最新版本
  6739. $currentVersion = [
  6740. 'version' => 0, // 0 表示当前版本
  6741. 'url' => $role->url,
  6742. 'pic_prompt' => $role->pic_prompt,
  6743. 'updated_at' => $role->updated_at,
  6744. 'is_current' => true
  6745. ];
  6746. array_unshift($versions, $currentVersion);
  6747. return $versions;
  6748. }
  6749. /**
  6750. * 恢复到指定版本
  6751. * @param array $data 包含 id(角色ID)、version(版本号)
  6752. * @return bool
  6753. */
  6754. public function restoreProductVersion($data) {
  6755. $uid = Site::getUid();
  6756. $cpid = Site::getCpid();
  6757. $id = getProp($data, 'id');
  6758. $version = getProp($data, 'version');
  6759. if (!$id) Utils::throwError('20003:角色ID不能为空');
  6760. if (!$version) Utils::throwError('20003:版本号不能为空');
  6761. $role = DB::table('mp_products')
  6762. ->where('id', $id)
  6763. ->where('cpid', $cpid)
  6764. ->where('type', 1)
  6765. ->first();
  6766. if (!$role) Utils::throwError('20003:角色不存在');
  6767. // 获取版本历史
  6768. $versions = json_decode($role->versions, true) ?: [];
  6769. // 查找指定版本
  6770. $targetVersion = null;
  6771. foreach ($versions as $v) {
  6772. if ($v['version'] == $version) {
  6773. $targetVersion = $v;
  6774. break;
  6775. }
  6776. }
  6777. if (!$targetVersion) Utils::throwError('20003:版本不存在');
  6778. // 先将当前版本保存到历史
  6779. $newVersion = [
  6780. 'version' => count($versions) + 1,
  6781. 'url' => $role->url,
  6782. 'pic_prompt' => $role->pic_prompt,
  6783. 'updated_at' => date('Y-m-d H:i:s'),
  6784. 'updated_by' => $uid
  6785. ];
  6786. array_unshift($versions, $newVersion);
  6787. // 限制版本数量
  6788. if (count($versions) > 10) {
  6789. $versions = array_slice($versions, 0, 10);
  6790. }
  6791. // 恢复到指定版本
  6792. return DB::table('mp_products')
  6793. ->where('id', $id)
  6794. ->where('cpid', $cpid)
  6795. ->update([
  6796. 'url' => $targetVersion['url'],
  6797. 'pic_prompt' => $targetVersion['pic_prompt'],
  6798. 'versions' => json_encode($versions, JSON_UNESCAPED_UNICODE),
  6799. 'updated_at' => date('Y-m-d H:i:s')
  6800. ]);
  6801. }
  6802. public function deleteProduct($data) {
  6803. $uid = Site::getUid();
  6804. $cpid = Site::getCpid();
  6805. $role = Site::getRole();
  6806. $id = getProp($data, 'id');
  6807. if (!$id) Utils::throwError('20003:ID不能为空');
  6808. $ids = explode(',', $id);
  6809. $is_public = getProp($data, 'is_public', 0); // 0=个人资产库 1=公共资产库
  6810. // 根据is_public参数确定查询的user_id(公共库user_id=0,cpid保持不变)
  6811. $query_uid = $is_public ? 0 : $uid;
  6812. // 如果是公共库操作,需要admin权限
  6813. if ($is_public && $role !== 'admin') {
  6814. Utils::throwError('20003:只有管理员才能操作公共资产库');
  6815. }
  6816. // 检查是否存在且属于当前用户或公共库
  6817. $role = DB::table('mp_products')
  6818. ->whereIn('id', $ids)
  6819. ->where('cpid', $cpid)
  6820. ->where('user_id', $query_uid)
  6821. ->get();
  6822. if (!$role) Utils::throwError('20003:记录不存在');
  6823. return DB::table('mp_products')
  6824. ->where('cpid', $cpid)
  6825. ->where('user_id', $query_uid)
  6826. ->whereIn('id', $ids)
  6827. ->update([
  6828. 'is_deleted' => 1,
  6829. 'updated_at' => date('Y-m-d H:i:s')
  6830. ]);
  6831. }
  6832. public function generateThreeView($data) {
  6833. $uid = Site::getUid();
  6834. $cpid = Site::getCpid();
  6835. $role = Site::getRole();
  6836. $id = getProp($data, 'id');
  6837. if (!$id) Utils::throwError('20003:ID不能为空');
  6838. $is_public = getProp($data, 'is_public', 0); // 0=个人资产库 1=公共资产库
  6839. // 根据is_public参数确定查询的user_id(公共库user_id=0,cpid保持不变)
  6840. $query_uid = $is_public ? 0 : $uid;
  6841. // 如果是公共库操作,需要admin权限
  6842. if ($is_public && $role !== 'admin') {
  6843. Utils::throwError('20003:只有管理员才能操作公共资产库');
  6844. }
  6845. // 检查是否存在且属于当前用户或公共库
  6846. $product = DB::table('mp_products')
  6847. ->where('id', $id)
  6848. ->where('cpid', $cpid)
  6849. ->where('user_id', $query_uid)
  6850. ->where('type', 1)->first();
  6851. if (!$product) Utils::throwError('20003:资产不存在');
  6852. $prompt = trim(getProp($data, 'prompt', '基于参考图生成主体的标准正面、侧面、后面三视图,主体完整。在最左侧添加主体正视图的特写,特写大小为标准一寸照,人物不要带表情。右侧是全身的三视图,其中正面、侧面的三视图给人脸打白色码、不显示五官。主体清晰完整。背景修改成纯白色,整体保持与参考图一致的美术风格和色彩搭配。画面无说明文字。'));
  6853. $ref_img_url = trim(getProp($data, 'ref_img_url'));
  6854. if (!$ref_img_url) {
  6855. // 如果没有传入参考图,使用角色表中的图片
  6856. $ref_img_url = $product->url ?? '';
  6857. if (!$ref_img_url) {
  6858. Utils::throwError('20003:参考图不能为空');
  6859. }
  6860. }
  6861. $pic_prompt = getProp($product, 'pic_prompt');
  6862. if ($pic_prompt) {
  6863. $prompt .= '\n参考图原始提示词: '.$pic_prompt;
  6864. }
  6865. // 检查参考图是否是正确的图片格式
  6866. $allowedExtensions = ['jpg', 'jpeg', 'png', 'gif', 'webp', 'bmp'];
  6867. $urlPath = parse_url($ref_img_url, PHP_URL_PATH);
  6868. $extension = strtolower(pathinfo($urlPath, PATHINFO_EXTENSION));
  6869. if (!in_array($extension, $allowedExtensions)) {
  6870. Utils::throwError('20003:参考图格式不正确,仅支持 jpg、jpeg、png、gif、webp、bmp 格式');
  6871. }
  6872. // 处理图片模型
  6873. $model = getProp($data, 'model');
  6874. if (!$model) {
  6875. // 使用默认模型
  6876. $model = 'gpt-image-2';
  6877. }
  6878. // 验证模型是否在可用模型表中
  6879. if (!DB::table('mp_image_models')->where('model', $model)->where('is_enabled', 1)->exists()) {
  6880. Utils::throwError('20003:该模型已不可用,请更换!');
  6881. }
  6882. $ratio = getProp($data, 'ratio', '16:9');
  6883. $resolution = getProp($data, 'resolution', '2k');
  6884. // 分辨率档位与尺寸映射统一从 BaseConst 获取
  6885. $sizeMap = BaseConst::IMAGE_RESOLUTION_SIZE_MAP;
  6886. // 参数验证
  6887. $resolution = strtolower($resolution);
  6888. if (!isset($sizeMap[$resolution])) {
  6889. Utils::throwError('20003:分辨率参数错误,仅支持 2k、3k、4k');
  6890. }
  6891. if (!isset($sizeMap[$resolution][$ratio])) {
  6892. Utils::throwError('20003:宽高比参数错误,该分辨率下不支持 ' . $ratio . ' 比例');
  6893. }
  6894. // 根据 ratio 和 resolution 确定宽高
  6895. $width = $sizeMap[$resolution][$ratio]['width'];
  6896. $height = $sizeMap[$resolution][$ratio]['height'];
  6897. try {
  6898. // 创建图片生成任务
  6899. $params = [
  6900. 'prompt' => $prompt,
  6901. 'model' => $model,
  6902. 'ref_img_urls' => [$ref_img_url],
  6903. 'width' => $width,
  6904. 'height' => $height
  6905. ];
  6906. $task = $this->aiImageGenerationService->createImageGenerationTask($params);
  6907. $task_id = $task->id;
  6908. if (!$task_id) {
  6909. Utils::throwError('20003:创建图片生成任务失败');
  6910. }
  6911. // 轮询获取结果
  6912. // 只查询数据库,不调用API,不更新任务表
  6913. $start_time = time();
  6914. $timeout = 1800;
  6915. $img_url = '';
  6916. while (time() - $start_time < $timeout) {
  6917. sleep(5);
  6918. // 只查询数据库中的任务状态,不调用API,不更新任务表
  6919. $task = DB::table('mp_generate_pic_tasks')
  6920. ->where('id', $task_id)
  6921. ->first();
  6922. if (!$task) {
  6923. Utils::throwError('20003:任务不存在');
  6924. }
  6925. if ($task->status === 'success' && $task->result_url) {
  6926. $result_urls = is_string($task->result_url)
  6927. ? json_decode($task->result_url, true)
  6928. : $task->result_url;
  6929. $img_url = is_array($result_urls) ? $result_urls[0] : $task->result_url;
  6930. break;
  6931. } elseif ($task->status === 'failed') {
  6932. Utils::throwError('20003:三视图生成失败,' . ($task->error_message ?? '未知错误'));
  6933. }
  6934. // 其他状态继续轮询
  6935. }
  6936. if (empty($img_url)) {
  6937. Utils::throwError('20003:三视图生成超时,请稍后重试');
  6938. }
  6939. // 更新 mp_products 表(不是任务表)
  6940. DB::table('mp_products')
  6941. ->where('id', $id)
  6942. ->where('cpid', $cpid)
  6943. ->update([
  6944. 'three_view_image_url' => $img_url,
  6945. 'updated_at' => date('Y-m-d H:i:s')
  6946. ]);
  6947. return ['three_view_image_url' => $img_url];
  6948. } catch (\Exception $e) {
  6949. dLog('anime')->error('生成三视图失败', [
  6950. 'error' => $e->getMessage()
  6951. ]);
  6952. logDB('anime', 'error', '生成三视图失败', ['error' => $e->getMessage()]);
  6953. Utils::throwError('20003:' . $e->getMessage());
  6954. }
  6955. }
  6956. /**
  6957. * 推送(复制)资产或文件夹到目标位置
  6958. * @param array $data 包含 product_id(要推送的资产或文件夹ID)、target_parent_id(目标父文件夹ID,0表示根目录)
  6959. * @return array 返回推送结果
  6960. */
  6961. public function pushProductOrFolder($data) {
  6962. $uid = Site::getUid();
  6963. $cpid = Site::getCpid();
  6964. $role = Site::getRole();
  6965. $product_id = getProp($data, 'product_id');
  6966. $target_parent_id = getProp($data, 'target_parent_id', 0);
  6967. $target_product = getProp($data, 'product'); // 目标 product 类型,用于跨类型推送
  6968. if (!$product_id) {
  6969. Utils::throwError('20003:请选择要推送的项目');
  6970. }
  6971. // 查询源项目(只通过cpid查询,不限制user_id)
  6972. $sourceItem = DB::table('mp_products')
  6973. ->where('id', $product_id)
  6974. ->where('cpid', $cpid)
  6975. ->where('is_deleted', 0)
  6976. ->first();
  6977. if (!$sourceItem) {
  6978. Utils::throwError('20003:要推送的项目不存在');
  6979. }
  6980. // 通过user_id判断源是公共库还是个人库
  6981. $source_uid = $sourceItem->user_id;
  6982. $source_is_public = ($source_uid == 0) ? 1 : 0;
  6983. // 验证目标文件夹并确定目标是公共库还是个人库
  6984. $target_level = 0;
  6985. $target_uid = $uid; // 默认推送到个人库
  6986. $target_is_public = 0;
  6987. $final_product_type = $sourceItem->product; // 默认使用源的 product 类型
  6988. if ($target_parent_id > 0) {
  6989. // 查询目标文件夹(只通过cpid查询,不限制user_id)
  6990. $targetParent = DB::table('mp_products')
  6991. ->where('id', $target_parent_id)
  6992. ->where('cpid', $cpid)
  6993. ->where('type', 2)
  6994. ->where('is_deleted', 0)
  6995. ->first();
  6996. if (!$targetParent) {
  6997. Utils::throwError('20003:目标文件夹不存在');
  6998. }
  6999. // 通过user_id判断目标是公共库还是个人库
  7000. $target_level = $targetParent->level;
  7001. $target_uid = $targetParent->user_id;
  7002. $target_is_public = ($target_uid == 0) ? 1 : 0;
  7003. // 使用目标文件夹的 product 类型
  7004. $final_product_type = $targetParent->product;
  7005. }
  7006. // 如果 target_parent_id = 0(推送到根目录),需要通过参数判断推送到个人库还是公共库
  7007. else {
  7008. $push_to_public = getProp($data, 'push_to_public');
  7009. if ($push_to_public === '') {
  7010. Utils::throwError('20003:请选择是否推送到公共库');
  7011. }
  7012. if ($push_to_public) {
  7013. $target_uid = 0;
  7014. $target_is_public = 1;
  7015. }
  7016. // 推送到根目录时,必须指定 product 类型
  7017. if ($target_product === null || $target_product === '') {
  7018. Utils::throwError('20003:推送到根目录时必须指定目标类型(product)');
  7019. }
  7020. $final_product_type = $target_product;
  7021. }
  7022. // 如果目标是公共库,需要admin权限
  7023. if ($target_is_public && $role !== 'admin') {
  7024. Utils::throwError('20003:只有管理员才能推送到公共资产库');
  7025. }
  7026. // 权限验证:验证是否符合允许的推送规则
  7027. $this->validatePushPermission($source_uid, $target_uid, $uid);
  7028. try {
  7029. DB::beginTransaction();
  7030. // 如果是资产,直接复制(支持跨类型推送,更新 product 字段)
  7031. if ($sourceItem->type == 1) {
  7032. $newId = $this->copyProduct($sourceItem, $target_parent_id, $target_level + 1, $cpid, $target_uid, $final_product_type);
  7033. DB::commit();
  7034. return [
  7035. 'product_id' => $newId,
  7036. ];
  7037. }
  7038. // 如果是文件夹,递归复制(支持跨类型推送)
  7039. $newFolderId = $this->copyFolderRecursive($sourceItem, $target_parent_id, $target_level + 1, $cpid, $target_uid, $source_uid, $final_product_type);
  7040. DB::commit();
  7041. return [
  7042. 'product_id' => $newFolderId,
  7043. ];
  7044. } catch (\Exception $e) {
  7045. DB::rollBack();
  7046. dLog('anime')->error('推送失败', [
  7047. 'error' => $e->getMessage(),
  7048. 'product_id' => $product_id
  7049. ]);
  7050. Utils::throwError('20003:' . $e->getMessage());
  7051. }
  7052. }
  7053. /**
  7054. * 验证推送权限
  7055. * 允许的推送规则:
  7056. * 1. 自己推送给自己的个人库(个人库 → 个人库,同一用户)
  7057. * 2. 公共库推送给自己的个人库(公共库 → 个人库)
  7058. * 3. 公共库推送给公共库(公共库 → 公共库)
  7059. *
  7060. * @param int $source_uid 源的user_id
  7061. * @param int $target_uid 目标的user_id
  7062. * @param int $current_uid 当前用户ID
  7063. * @throws \Exception
  7064. */
  7065. private function validatePushPermission($source_uid, $target_uid, $current_uid) {
  7066. // 规则1:自己推送给自己的个人库(个人库 → 个人库,同一用户)
  7067. if ($source_uid == $current_uid && $target_uid == $current_uid) {
  7068. return; // 允许
  7069. }
  7070. // 规则2:公共库推送给自己的个人库(公共库 → 个人库)
  7071. if ($source_uid == 0 && $target_uid == $current_uid) {
  7072. return; // 允许
  7073. }
  7074. // 规则3:公共库推送给公共库(公共库 → 公共库)
  7075. if ($source_uid == 0 && $target_uid == 0) {
  7076. return; // 允许
  7077. }
  7078. // 其他情况都不允许
  7079. if ($source_uid != 0 && $source_uid != $current_uid) {
  7080. // 源是别人的个人库
  7081. Utils::throwError('20003:无权限访问该资产');
  7082. } elseif ($source_uid == $current_uid && $target_uid == 0) {
  7083. // 个人库推送给公共库(不允许)
  7084. Utils::throwError('20003:不允许将个人资产推送到公共库');
  7085. } elseif ($source_uid != 0 && $target_uid != 0 && $source_uid != $target_uid) {
  7086. // 不同用户的个人库之间推送(不允许)
  7087. Utils::throwError('20003:不允许推送到其他用户的个人库');
  7088. } else {
  7089. // 其他未知情况
  7090. Utils::throwError('20003:不允许的推送操作');
  7091. }
  7092. }
  7093. /**
  7094. * 复制单个资产
  7095. * @param object $sourceProduct 源资产对象
  7096. * @param int $targetParentId 目标父文件夹ID
  7097. * @param int $targetLevel 目标层级
  7098. * @param int $cpid 公司ID
  7099. * @param int $targetUid 目标用户ID
  7100. * @return int 返回新资产ID
  7101. */
  7102. private function copyProduct($sourceProduct, $targetParentId, $targetLevel, $cpid, $targetUid, $productType = null) {
  7103. // 如果指定了 productType,使用指定的;否则使用源的 product 类型
  7104. $finalProductType = ($productType !== null) ? $productType : $sourceProduct->product;
  7105. $newProductData = [
  7106. 'user_id' => $targetUid,
  7107. 'cpid' => $cpid,
  7108. 'type' => 1,
  7109. 'parent_id' => $targetParentId,
  7110. 'level' => $targetLevel,
  7111. 'product_name' => $sourceProduct->product_name,
  7112. 'url' => $sourceProduct->url,
  7113. 'pic_prompt' => $sourceProduct->pic_prompt ?? '',
  7114. 'three_view_image_url' => $sourceProduct->three_view_image_url ?? '',
  7115. 'product' => $finalProductType,
  7116. 'versions' => $sourceProduct->versions ?? '',
  7117. 'sort_order' => time(),
  7118. 'is_deleted' => 0,
  7119. 'created_at' => date('Y-m-d H:i:s'),
  7120. 'updated_at' => date('Y-m-d H:i:s')
  7121. ];
  7122. return DB::table('mp_products')->insertGetId($newProductData);
  7123. }
  7124. /**
  7125. * 递归复制文件夹及其子项
  7126. * @param object $sourceFolder 源文件夹对象
  7127. * @param int $targetParentId 目标父文件夹ID
  7128. * @param int $targetLevel 目标层级
  7129. * @param int $cpid 公司ID
  7130. * @param int $targetUid 目标用户ID
  7131. * @param int $sourceUid 源用户ID
  7132. * @return int 返回新文件夹ID
  7133. */
  7134. private function copyFolderRecursive($sourceFolder, $targetParentId, $targetLevel, $cpid, $targetUid, $sourceUid, $productType = null) {
  7135. // 如果指定了 productType,使用指定的;否则使用源的 product 类型
  7136. $finalProductType = ($productType !== null) ? $productType : $sourceFolder->product;
  7137. // 创建新文件夹
  7138. $newFolderData = [
  7139. 'user_id' => $targetUid,
  7140. 'cpid' => $cpid,
  7141. 'type' => 2,
  7142. 'parent_id' => $targetParentId,
  7143. 'level' => $targetLevel,
  7144. 'product_name' => $sourceFolder->product_name,
  7145. 'product' => $finalProductType,
  7146. 'sort_order' => time(),
  7147. 'is_deleted' => 0,
  7148. 'created_at' => date('Y-m-d H:i:s'),
  7149. 'updated_at' => date('Y-m-d H:i:s')
  7150. ];
  7151. $newFolderId = DB::table('mp_products')->insertGetId($newFolderData);
  7152. // 获取源文件夹下的所有子项
  7153. $children = DB::table('mp_products')
  7154. ->where('parent_id', $sourceFolder->id)
  7155. ->where('cpid', $cpid)
  7156. ->where('user_id', $sourceUid)
  7157. ->where('is_deleted', 0)
  7158. ->orderByRaw('type DESC, sort_order DESC, created_at DESC')
  7159. ->get();
  7160. // 递归复制子项(子项继承目标文件夹的 product 类型)
  7161. foreach ($children as $child) {
  7162. if ($child->type == 1) {
  7163. // 资产
  7164. $this->copyProduct($child, $newFolderId, $targetLevel + 1, $cpid, $targetUid, $finalProductType);
  7165. } else {
  7166. // 文件夹
  7167. $this->copyFolderRecursive($child, $newFolderId, $targetLevel + 1, $cpid, $targetUid, $sourceUid, $finalProductType);
  7168. }
  7169. }
  7170. return $newFolderId;
  7171. }
  7172. /**
  7173. * 转让剧本归属(剧本及其关联资产)
  7174. *
  7175. * 仅调整 mp_scripts.user_id 与 mp_products.user_id,其他表保持不变。
  7176. * 权限:仅 admin / superadmin 可操作;目标用户必须是同组(cpid 相同)且角色为 user(组员)的用户,禁止跨组转让。
  7177. * 多个剧本逐个独立事务处理,单个剧本失败不影响其他剧本;
  7178. * 单个剧本内的剧本记录与关联资产必须全部更新成功,否则整体回滚。
  7179. *
  7180. * @param array $data 请求参数:script_ids(数组或英文逗号分隔,兼容单个 script_id)、target_user_id
  7181. * @return array
  7182. */
  7183. public function transferScriptOwner($data) {
  7184. $operatorRole = Site::getRole();
  7185. $operatorCpid = Site::getCpid();
  7186. // 1.权限校验:仅管理员和超管可操作
  7187. if (!in_array($operatorRole, ['admin', 'superadmin'], true)) {
  7188. Utils::throwError(ErrorConst::NOT_ACCESS);
  7189. }
  7190. // 2.目标用户校验:必须存在且角色为 user(组员)
  7191. $targetUserId = (int)getProp($data, 'target_user_id', 0);
  7192. if ($targetUserId < 1) {
  7193. Utils::throwError('1002:请选择转让的目标用户');
  7194. }
  7195. $targetUser = DB::table('mp_manage_users')
  7196. ->where('id', $targetUserId)
  7197. ->where('is_deleted', 0)
  7198. ->first();
  7199. if (!$targetUser) {
  7200. Utils::throwError('20003:目标用户不存在');
  7201. }
  7202. if ((string)getProp($targetUser, 'role') !== 'user') {
  7203. Utils::throwError('20003:只能转让给角色为组员(user)的用户');
  7204. }
  7205. $targetCpid = (int)getProp($targetUser, 'cpid');
  7206. // 3.规范化剧本ID列表(兼容数组、逗号分隔字符串、script_id 单值)
  7207. $rawScriptIds = getProp($data, 'script_ids');
  7208. if (empty($rawScriptIds)) {
  7209. $rawScriptIds = getProp($data, 'script_id');
  7210. }
  7211. $scriptIds = $this->normalizeIdList($rawScriptIds);
  7212. if (empty($scriptIds)) {
  7213. Utils::throwError('20003:请提供剧本ID');
  7214. }
  7215. // 预取剧本名称,便于失败结果中回显
  7216. $scriptNameMap = DB::table('mp_scripts')
  7217. ->whereIn('id', $scriptIds)
  7218. ->pluck('script_name', 'id')
  7219. ->all();
  7220. $successList = [];
  7221. $failedList = [];
  7222. // 4.逐个剧本独立事务处理,单个失败不影响其他剧本
  7223. foreach ($scriptIds as $scriptId) {
  7224. DB::beginTransaction();
  7225. try {
  7226. $successList[] = $this->transferSingleScriptOwner(
  7227. $scriptId,
  7228. $targetUserId,
  7229. $targetCpid,
  7230. $operatorRole,
  7231. $operatorCpid,
  7232. Site::getUid()
  7233. );
  7234. DB::commit();
  7235. } catch (\Throwable $e) {
  7236. DB::rollBack();
  7237. $failedList[] = [
  7238. 'script_id' => (int)$scriptId,
  7239. 'script_name' => (string)($scriptNameMap[$scriptId] ?? ''),
  7240. 'reason' => $e->getMessage() !== '' ? $e->getMessage() : '转让失败',
  7241. ];
  7242. dLog('anime')->error('剧本归属转让失败', [
  7243. 'script_id' => $scriptId,
  7244. 'target_user_id' => $targetUserId,
  7245. 'operator_uid' => Site::getUid(),
  7246. 'error' => $e->getMessage(),
  7247. ]);
  7248. }
  7249. }
  7250. return [
  7251. 'target_user_id' => $targetUserId,
  7252. 'success_count' => count($successList),
  7253. 'failed_count' => count($failedList),
  7254. 'success_list' => $successList,
  7255. 'failed_list' => $failedList,
  7256. ];
  7257. }
  7258. /**
  7259. * 单个剧本的归属转让(需在事务中调用)
  7260. *
  7261. * @param int $scriptId 剧本ID
  7262. * @param int $targetUserId 目标用户ID
  7263. * @param int $targetCpid 目标用户所属公司ID
  7264. * @param string $operatorRole 操作人角色
  7265. * @param int $operatorCpid 操作人所属公司ID
  7266. * @param int $operatorUid 操作人用户ID
  7267. * @return array
  7268. */
  7269. private function transferSingleScriptOwner($scriptId, $targetUserId, $targetCpid, $operatorRole, $operatorCpid, $operatorUid) {
  7270. $script = DB::table('mp_scripts')
  7271. ->where('id', $scriptId)
  7272. ->where('is_deleted', 0)
  7273. ->first();
  7274. if (!$script) {
  7275. Utils::throwError('20003:剧本不存在');
  7276. }
  7277. $scriptCpid = (int)getProp($script, 'cpid');
  7278. $fromUserId = (int)getProp($script, 'user_id');
  7279. // 管理员仅可操作本组剧本
  7280. if ($operatorRole !== 'superadmin' && $scriptCpid !== $operatorCpid) {
  7281. Utils::throwError(ErrorConst::NOT_ACCESS);
  7282. }
  7283. // 管理员仅可转让自己创建的剧本(超管不做此验证)
  7284. if ($operatorRole !== 'superadmin' && $fromUserId !== (int)$operatorUid) {
  7285. Utils::throwError('20003:管理员仅能转让自己创建的剧本和资产');
  7286. }
  7287. // 禁止跨组转让:目标用户必须与剧本同组
  7288. if ($targetCpid !== $scriptCpid) {
  7289. Utils::throwError('20003:不能跨组转让,目标用户与剧本不在同一组');
  7290. }
  7291. // 关联资产ID(同一资产可能关联多个剧集序号,需去重)
  7292. $productIds = $this->normalizeIdList(
  7293. DB::table('mp_script_product_mappings')
  7294. ->where('script_id', $scriptId)
  7295. ->pluck('product_id')
  7296. ->all()
  7297. );
  7298. $folderIds = [];
  7299. if (!empty($productIds)) {
  7300. $products = DB::table('mp_products')
  7301. ->whereIn('id', $productIds)
  7302. ->select('id', 'cpid', 'parent_id', 'user_id')
  7303. ->get();
  7304. // 关联资产必须全部存在,否则视为数据异常,不提交
  7305. if ($products->count() !== count($productIds)) {
  7306. Utils::throwError('20003:剧本存在已丢失的关联资产,无法完成转让');
  7307. }
  7308. foreach ($products as $product) {
  7309. // 关联资产必须与剧本同组,避免误转让跨组资产
  7310. if ((int)getProp($product, 'cpid') !== $scriptCpid) {
  7311. Utils::throwError('20003:剧本存在跨组关联资产,无法完成转让');
  7312. }
  7313. $parentId = (int)getProp($product, 'parent_id', 0);
  7314. if ($parentId > 0 && !in_array($parentId, $folderIds, true)) {
  7315. $folderIds[] = $parentId;
  7316. }
  7317. }
  7318. // 仅转让归属于原剧本所有者的资产
  7319. $folderIds = DB::table('mp_products')
  7320. ->whereIn('id', $folderIds)
  7321. ->where('type', 2)
  7322. ->where('cpid', $scriptCpid)
  7323. ->where('user_id', $fromUserId)
  7324. ->pluck('id')
  7325. ->map('intval')
  7326. ->all();
  7327. // 管理员仅可转让自己创建的资产及其所属文件夹(超管不做此验证)
  7328. if ($operatorRole !== 'superadmin') {
  7329. foreach ($products as $product) {
  7330. if ((int)getProp($product, 'user_id') !== (int)$operatorUid) {
  7331. Utils::throwError('20003:管理员仅能转让自己创建的剧本和资产');
  7332. }
  7333. }
  7334. foreach ($products as $product) {
  7335. $parentId = (int)getProp($product, 'parent_id', 0);
  7336. if ($parentId > 0 && !in_array($parentId, $folderIds, true)) {
  7337. Utils::throwError('20003:管理员仅能转让自己创建的剧本和资产');
  7338. }
  7339. }
  7340. }
  7341. }
  7342. $now = now();
  7343. // 5.更新剧本归属
  7344. DB::table('mp_scripts')
  7345. ->where('id', $scriptId)
  7346. ->update([
  7347. 'user_id' => $targetUserId,
  7348. 'updated_at' => $now,
  7349. ]);
  7350. // 6.更新关联资产归属
  7351. if (!empty($productIds)) {
  7352. DB::table('mp_products')
  7353. ->whereIn('id', $productIds)
  7354. ->update([
  7355. 'user_id' => $targetUserId,
  7356. 'updated_at' => $now,
  7357. ]);
  7358. }
  7359. // 7.更新资产所属的类型根文件夹归属(文件夹属于 mp_products,随资产一并转让)
  7360. if (!empty($folderIds)) {
  7361. DB::table('mp_products')
  7362. ->whereIn('id', $folderIds)
  7363. ->update([
  7364. 'user_id' => $targetUserId,
  7365. 'updated_at' => $now,
  7366. ]);
  7367. }
  7368. // 8.校验剧本与资产是否全部更新成功,任一未成功则回滚
  7369. $scriptOwner = (int)DB::table('mp_scripts')->where('id', $scriptId)->value('user_id');
  7370. if ($scriptOwner !== $targetUserId) {
  7371. Utils::throwError('20003:剧本归属更新失败');
  7372. }
  7373. if (!empty($productIds)) {
  7374. $updatedProductCount = DB::table('mp_products')
  7375. ->whereIn('id', $productIds)
  7376. ->where('user_id', $targetUserId)
  7377. ->count();
  7378. if ($updatedProductCount !== count($productIds)) {
  7379. Utils::throwError('20003:部分剧本资产转让失败,已回滚');
  7380. }
  7381. }
  7382. if (!empty($folderIds)) {
  7383. $updatedFolderCount = DB::table('mp_products')
  7384. ->whereIn('id', $folderIds)
  7385. ->where('user_id', $targetUserId)
  7386. ->count();
  7387. if ($updatedFolderCount !== count($folderIds)) {
  7388. Utils::throwError('20003:部分资产文件夹转让失败,已回滚');
  7389. }
  7390. }
  7391. return [
  7392. 'script_id' => (int)$scriptId,
  7393. 'script_name' => (string)getProp($script, 'script_name', ''),
  7394. 'from_user_id' => $fromUserId,
  7395. 'to_user_id' => $targetUserId,
  7396. 'product_count' => count($productIds),
  7397. 'folder_count' => count($folderIds),
  7398. ];
  7399. }
  7400. /**
  7401. * 规范化ID列表,兼容数组、逗号分隔字符串以及字符串数组
  7402. *
  7403. * @param mixed $ids 待处理的ID集合
  7404. * @return array 去重后的正整数ID数组
  7405. */
  7406. private function normalizeIdList($ids) {
  7407. if (!is_array($ids)) {
  7408. $ids = explode(',', (string)$ids);
  7409. }
  7410. $result = [];
  7411. foreach ($ids as $item) {
  7412. if (is_array($item)) {
  7413. continue;
  7414. }
  7415. foreach (explode(',', (string)$item) as $part) {
  7416. $part = trim($part);
  7417. if ($part !== '' && is_numeric($part) && (int)$part > 0) {
  7418. $result[] = (int)$part;
  7419. }
  7420. }
  7421. }
  7422. return array_values(array_unique($result));
  7423. }
  7424. /**
  7425. * 通过 Excel 批量导入剧本资产(独立实现,不依赖 saveScriptProducts)
  7426. *
  7427. * 流程:
  7428. * 1. 校验剧本存在且属于当前用户
  7429. * 2. 解析 Excel 并校验强制列与数据完整性(资产类型/资产名称/使用范围/参考提示词)
  7430. * 3. 名称去重(与 Excel 内及该剧本已有关联资产比对)
  7431. * 4. 事务内创建类型文件夹、资产与剧本映射
  7432. * 5. 为没有图片的资产创建图片生成任务,生成中返回 SSE 轮询
  7433. *
  7434. * @param array $data 请求参数
  7435. * @param \Illuminate\Http\UploadedFile $file 上传的 Excel 文件
  7436. * @return array|\Generator
  7437. */
  7438. public function importScriptProductsByExcel($data, $file) {
  7439. $uid = Site::getUid();
  7440. $cpid = Site::getCpid();
  7441. $script_id = (int)getProp($data, 'script_id', 0);
  7442. if (!$script_id) {
  7443. Utils::throwError('20003:请提供剧本ID');
  7444. }
  7445. // 验证剧本是否存在,且只能导入自己创建的剧本
  7446. $script = DB::table('mp_scripts')
  7447. ->where('id', $script_id)
  7448. ->where('is_deleted', 0)
  7449. ->where('user_id', $uid)
  7450. ->first();
  7451. if (!$script) {
  7452. Utils::throwError('20003:剧本不存在或无权限操作');
  7453. }
  7454. $script_name = $script->script_name ?? 'script_' . $script_id;
  7455. // 校验上传文件
  7456. if (!$file) {
  7457. Utils::throwError('20003:请上传Excel文件');
  7458. }
  7459. $extension = strtolower($file->getClientOriginalExtension());
  7460. if (!in_array($extension, ['xlsx', 'xls'])) {
  7461. Utils::throwError('20003:文件格式错误,仅支持 xlsx、xls 格式');
  7462. }
  7463. if ($file->getSize() > 10 * 1024 * 1024) {
  7464. Utils::throwError('20003:文件大小不能超过10M');
  7465. }
  7466. // 解析 Excel(第一行为表头)
  7467. $rows = $this->readImportExcelRows($file);
  7468. if (empty($rows)) {
  7469. Utils::throwError('20003:Excel内容为空');
  7470. }
  7471. $headers = array_shift($rows);
  7472. // 定位强制列
  7473. $typeColumnIndex = $this->findImportExcelColumnIndex($headers, ['资产类型'], ['资产类型', '类型']);
  7474. $nameColumnIndex = $this->findImportExcelColumnIndex($headers, ['资产名称'], ['资产名称', '名称']);
  7475. $rangeColumnIndex = $this->findImportExcelColumnIndex($headers, ['使用范围'], ['使用范围', '范围']);
  7476. $promptColumnIndex = $this->findImportExcelColumnIndex($headers, ['参考提示词', '提示词'], ['提示词']);
  7477. $missingColumns = [];
  7478. if ($typeColumnIndex < 0) {
  7479. $missingColumns[] = '资产类型';
  7480. }
  7481. if ($nameColumnIndex < 0) {
  7482. $missingColumns[] = '资产名称';
  7483. }
  7484. if ($rangeColumnIndex < 0) {
  7485. $missingColumns[] = '使用范围';
  7486. }
  7487. if ($promptColumnIndex < 0) {
  7488. $missingColumns[] = '参考提示词';
  7489. }
  7490. if (!empty($missingColumns)) {
  7491. Utils::throwError('20003:Excel缺少必填列:' . implode('、', $missingColumns));
  7492. }
  7493. // 先整体校验 Excel 数据,所有异常行一次性返回
  7494. $validation = $this->validateImportExcelRows(
  7495. $rows,
  7496. $typeColumnIndex,
  7497. $nameColumnIndex,
  7498. $rangeColumnIndex,
  7499. $promptColumnIndex
  7500. );
  7501. $errors = $validation['errors'];
  7502. $checkedRows = $validation['checked_rows'];
  7503. if (empty($checkedRows)) {
  7504. $errors[] = 'Excel中没有有效的数据行';
  7505. }
  7506. if (!empty($errors)) {
  7507. Utils::throwError('20003:Excel数据校验失败:' . implode(';', $errors));
  7508. }
  7509. // 名称去重:Excel 内部 + 该剧本已关联资产(按 createProduct 的名称判断逻辑)
  7510. $existingNames = $this->getScriptProductNames($script_id, $cpid);
  7511. $dedupResult = $this->deduplicateImportRows($checkedRows, $existingNames);
  7512. $validRows = $dedupResult['valid_rows'];
  7513. $skipped = $dedupResult['skipped'];
  7514. // 图片生成参数(与 saveScriptProducts 保持一致的校验规则)
  7515. $model = getProp($data, 'model');
  7516. if (!$model) {
  7517. $model = 'gpt-image-2';
  7518. }
  7519. if (!DB::table('mp_image_models')->where('model', $model)->where('is_enabled', 1)->exists()) {
  7520. Utils::throwError('20003:该模型已不可用,请更换!');
  7521. }
  7522. $ratio = getProp($data, 'ratio', '9:16');
  7523. $resolution = strtolower(getProp($data, 'resolution', '2k'));
  7524. $sizeMap = BaseConst::IMAGE_RESOLUTION_SIZE_MAP;
  7525. if (!isset($sizeMap[$resolution])) {
  7526. Utils::throwError('20003:分辨率参数错误,仅支持 2k、3k、4k');
  7527. }
  7528. if (!isset($sizeMap[$resolution][$ratio])) {
  7529. Utils::throwError('20003:宽高比参数错误,该分辨率下不支持 ' . $ratio . ' 比例');
  7530. }
  7531. $width = $sizeMap[$resolution][$ratio]['width'];
  7532. $height = $sizeMap[$resolution][$ratio]['height'];
  7533. $autoRaw = getProp($data, 'auto_generate_images', true);
  7534. $auto_generate_images = !in_array($autoRaw, [false, 0, '0', 'false', 'False'], true);
  7535. // 创建/复用任务中心记录(md5 验重,避免重复任务)
  7536. $taskCenterId = $this->createScriptProductTaskCenter(
  7537. $uid,
  7538. $cpid,
  7539. $script_id,
  7540. $validRows,
  7541. $model,
  7542. $ratio,
  7543. $resolution,
  7544. $auto_generate_images
  7545. );
  7546. // 全部为重复项:参照 saveScriptProducts,检查已存在资产的图片状态,缺图的补建任务
  7547. if (empty($validRows)) {
  7548. $existingTaskInfo = $this->prepareExistingScriptProductTasks(
  7549. $script_id,
  7550. $model,
  7551. $width,
  7552. $height,
  7553. $auto_generate_images
  7554. );
  7555. $productTaskMap = $existingTaskInfo['product_task_map'];
  7556. $typeFolderIds = $existingTaskInfo['type_folder_ids'];
  7557. if (!empty($productTaskMap)) {
  7558. $message = 'Excel中的资产均已存在,正在为缺少图片的资产生成图片';
  7559. } elseif (!$existingTaskInfo['has_all_tasks']) {
  7560. $message = 'Excel中的资产均已存在,部分资产没有参考提示词,无法生成图片';
  7561. } else {
  7562. $message = 'Excel中的资产均已存在,且图片已全部生成完成';
  7563. }
  7564. $resultData = [
  7565. 'success' => true,
  7566. 'message' => $message,
  7567. 'script_id' => $script_id,
  7568. 'script_name' => $script_name,
  7569. 'imported_count' => 0,
  7570. 'existing_products' => $existingTaskInfo['product_count'],
  7571. 'skipped_count' => count($skipped),
  7572. 'skipped' => $skipped,
  7573. 'created_products' => [],
  7574. 'type_folder_ids' => $typeFolderIds,
  7575. 'pending_tasks_count' => count($productTaskMap),
  7576. 'image_tasks_created' => $existingTaskInfo['created_count'],
  7577. 'task_center_id' => $taskCenterId,
  7578. ];
  7579. // 有需要轮询的任务(已有任务或本次补建):走 SSE 轮询
  7580. if (!empty($productTaskMap)) {
  7581. return $this->pollProductImageTasks(
  7582. $script_id,
  7583. $script_name,
  7584. $productTaskMap,
  7585. $typeFolderIds,
  7586. $taskCenterId,
  7587. ['import_result' => $resultData],
  7588. ['import_result' => $resultData]
  7589. );
  7590. }
  7591. // 没有需要轮询的任务:直接通过 complete 事件返回导入结果
  7592. return $this->streamImportComplete($script_id, $script_name, $resultData, $typeFolderIds, $taskCenterId);
  7593. }
  7594. // 事务内创建资产、类型文件夹与剧本映射
  7595. $typeFolderIds = [];
  7596. $createdProducts = [];
  7597. $mappingRecords = [];
  7598. $now = now();
  7599. DB::beginTransaction();
  7600. try {
  7601. foreach ($validRows as $row) {
  7602. $type = $row['type'];
  7603. if (!isset($typeFolderIds[$type])) {
  7604. // 与 createProduct 一致:先查找该剧本已存在的类型文件夹,没有则创建
  7605. $folder = DB::table('mp_products')
  7606. ->where('cpid', $cpid)
  7607. ->where('type', 2)
  7608. ->where('product', $type)
  7609. ->where('product_name', $script_name)
  7610. ->where('parent_id', 0)
  7611. ->where('is_deleted', 0)
  7612. ->first();
  7613. if ($folder) {
  7614. $typeFolderIds[$type] = $folder->id;
  7615. } else {
  7616. $typeFolderIds[$type] = DB::table('mp_products')->insertGetId([
  7617. 'user_id' => $uid,
  7618. 'cpid' => $cpid,
  7619. 'type' => 2, // 文件夹
  7620. 'product' => $type, // 1=角色 2=场景 3=道具
  7621. 'parent_id' => 0,
  7622. 'level' => 1,
  7623. 'product_name' => $script_name,
  7624. 'sort_order' => time() + $type,
  7625. 'is_deleted' => 0,
  7626. 'created_at' => $now,
  7627. 'updated_at' => $now,
  7628. ]);
  7629. }
  7630. }
  7631. $folder_id = $typeFolderIds[$type];
  7632. $product_id = DB::table('mp_products')->insertGetId([
  7633. 'user_id' => $uid,
  7634. 'cpid' => $cpid,
  7635. 'type' => 1, // 资产
  7636. 'product' => $type,
  7637. 'parent_id' => $folder_id,
  7638. 'level' => 2,
  7639. 'product_name' => $row['product_name'],
  7640. 'pic_prompt' => $row['pic_prompt'],
  7641. 'sort_order' => time(),
  7642. 'is_deleted' => 0,
  7643. 'created_at' => $now,
  7644. 'updated_at' => $now,
  7645. ]);
  7646. $createdProducts[] = [
  7647. 'id' => $product_id,
  7648. 'type' => $type,
  7649. 'product_name' => $row['product_name'],
  7650. 'pic_prompt' => $row['pic_prompt'],
  7651. ];
  7652. // 为每个使用范围(集数)创建映射记录
  7653. foreach ($row['episode_numbers'] as $episodeNumber) {
  7654. $mappingRecords[] = [
  7655. 'script_id' => $script_id,
  7656. 'product_id' => $product_id,
  7657. 'episode_number' => $episodeNumber,
  7658. 'created_at' => $now,
  7659. 'updated_at' => $now,
  7660. ];
  7661. }
  7662. }
  7663. // 批量插入映射数据(使用 insertOrIgnore 避免重复插入)
  7664. DB::table('mp_script_product_mappings')->insertOrIgnore($mappingRecords);
  7665. // 剧本已有资产,同步更新is_products标记
  7666. DB::table('mp_scripts')->where('id', $script_id)->update([
  7667. 'is_products' => 1,
  7668. 'updated_at' => $now,
  7669. ]);
  7670. DB::commit();
  7671. } catch (\Exception $e) {
  7672. DB::rollback();
  7673. if ($taskCenterId) {
  7674. $this->taskCenterService->updateTask($taskCenterId, [
  7675. 'status' => MpTaskCenter::STATUS_FAILED,
  7676. 'error_message' => $e->getMessage(),
  7677. ]);
  7678. }
  7679. dLog('anime')->error('Excel导入剧本资产失败: ' . $e->getMessage(), [
  7680. 'script_id' => $script_id,
  7681. 'error' => $e->getMessage(),
  7682. 'trace' => $e->getTraceAsString(),
  7683. ]);
  7684. Utils::throwError('20003:Excel导入剧本资产失败:' . $e->getMessage());
  7685. }
  7686. // 参照 saveScriptProducts:为新建资产以及已存在但缺图的资产统一补建图片生成任务
  7687. $existingTaskInfo = $this->prepareExistingScriptProductTasks(
  7688. $script_id,
  7689. $model,
  7690. $width,
  7691. $height,
  7692. $auto_generate_images
  7693. );
  7694. $productTaskMap = $existingTaskInfo['product_task_map'];
  7695. $resultData = [
  7696. 'success' => true,
  7697. 'message' => '导入完成',
  7698. 'script_id' => $script_id,
  7699. 'script_name' => $script_name,
  7700. 'imported_count' => count($createdProducts),
  7701. 'skipped_count' => count($skipped),
  7702. 'skipped' => $skipped,
  7703. 'created_products' => array_map(function ($item) {
  7704. return [
  7705. 'id' => $item['id'],
  7706. 'type' => $item['type'],
  7707. 'product_name' => $item['product_name'],
  7708. ];
  7709. }, $createdProducts),
  7710. 'type_folder_ids' => $typeFolderIds,
  7711. 'pending_tasks_count' => count($productTaskMap),
  7712. 'image_tasks_created' => $existingTaskInfo['created_count'],
  7713. 'task_center_id' => $taskCenterId,
  7714. ];
  7715. // 有待生成的图片任务:返回 SSE 轮询结果(导入统计在 init 与 complete 事件中)
  7716. if (!empty($productTaskMap)) {
  7717. return $this->pollProductImageTasks(
  7718. $script_id,
  7719. $script_name,
  7720. $productTaskMap,
  7721. $typeFolderIds,
  7722. $taskCenterId,
  7723. ['import_result' => $resultData],
  7724. ['import_result' => $resultData]
  7725. );
  7726. }
  7727. // 没有需要轮询的任务:直接通过 complete 事件返回导入结果
  7728. return $this->streamImportComplete($script_id, $script_name, $resultData, $typeFolderIds, $taskCenterId);
  7729. }
  7730. /**
  7731. * 校验 Excel 数据行(先校验完毕,再进行后续逻辑)
  7732. *
  7733. * @param array $rows
  7734. * @param int $typeColumnIndex
  7735. * @param int $nameColumnIndex
  7736. * @param int $rangeColumnIndex
  7737. * @param int $promptColumnIndex
  7738. * @return array ['errors' => [], 'checked_rows' => []]
  7739. */
  7740. private function validateImportExcelRows(array $rows, $typeColumnIndex, $nameColumnIndex, $rangeColumnIndex, $promptColumnIndex) {
  7741. $errors = [];
  7742. $checkedRows = [];
  7743. foreach ($rows as $rowIndex => $row) {
  7744. // 数据从第2行开始(表头占第1行)
  7745. $excelRowNo = $rowIndex + 2;
  7746. if (!is_array($row) || $this->isImportExcelRowEmpty($row)) {
  7747. continue;
  7748. }
  7749. $typeRaw = trim((string)($row[$typeColumnIndex] ?? ''));
  7750. $nameRaw = trim((string)($row[$nameColumnIndex] ?? ''));
  7751. $rangeRaw = trim((string)($row[$rangeColumnIndex] ?? ''));
  7752. $promptRaw = trim((string)($row[$promptColumnIndex] ?? ''));
  7753. $missingFields = [];
  7754. if ($typeRaw === '') {
  7755. $missingFields[] = '资产类型';
  7756. }
  7757. if ($nameRaw === '') {
  7758. $missingFields[] = '资产名称';
  7759. }
  7760. if ($rangeRaw === '') {
  7761. $missingFields[] = '使用范围';
  7762. }
  7763. if ($promptRaw === '') {
  7764. $missingFields[] = '参考提示词';
  7765. }
  7766. if (!empty($missingFields)) {
  7767. $errors[] = "第{$excelRowNo}行:" . implode('、', $missingFields) . '不能为空';
  7768. continue;
  7769. }
  7770. // 资产类型校验
  7771. $productType = $this->resolveImportProductType($typeRaw);
  7772. if (!$productType) {
  7773. $errors[] = "第{$excelRowNo}行:资产类型「{$typeRaw}」不正确,仅支持 角色/场景/道具";
  7774. continue;
  7775. }
  7776. // 资产名称去除两边特殊符号
  7777. $productName = $this->normalizeImportProductName($nameRaw);
  7778. if ($productName === '') {
  7779. $errors[] = "第{$excelRowNo}行:资产名称「{$nameRaw}」去除特殊符号后为空";
  7780. continue;
  7781. }
  7782. if (mb_strlen($productName, 'UTF-8') > 64) {
  7783. $errors[] = "第{$excelRowNo}行:资产名称「{$productName}」超过64个字符";
  7784. continue;
  7785. }
  7786. // 解析使用范围(逗号分隔的集数)
  7787. $episodeNumbers = $this->parseImportEpisodeNumbers($rangeRaw);
  7788. if (empty($episodeNumbers)) {
  7789. $errors[] = "第{$excelRowNo}行:使用范围「{$rangeRaw}」格式错误,仅支持数字或逗号分隔的数字";
  7790. continue;
  7791. }
  7792. $checkedRows[] = [
  7793. 'row' => $excelRowNo,
  7794. 'type' => $productType,
  7795. 'product_name' => $productName,
  7796. 'episode_numbers' => $episodeNumbers,
  7797. 'pic_prompt' => $promptRaw,
  7798. ];
  7799. }
  7800. return [
  7801. 'errors' => $errors,
  7802. 'checked_rows' => $checkedRows,
  7803. ];
  7804. }
  7805. /**
  7806. * Excel 资产名称去重:Excel 内部 + 剧本已有关联资产
  7807. *
  7808. * @param array $checkedRows
  7809. * @param array $existingNames 剧本已有关联资产名称集合(name => true)
  7810. * @return array ['valid_rows' => [], 'skipped' => []]
  7811. */
  7812. private function deduplicateImportRows(array $checkedRows, array $existingNames) {
  7813. $seenNames = [];
  7814. $validRows = [];
  7815. $skipped = [];
  7816. foreach ($checkedRows as $row) {
  7817. $nameKey = $row['product_name'];
  7818. $typeText = $this->getImportProductTypeText($row['type']);
  7819. if (isset($seenNames[$nameKey])) {
  7820. $skipped[] = [
  7821. 'row' => $row['row'],
  7822. 'type' => $typeText,
  7823. 'product_name' => $row['product_name'],
  7824. 'reason' => 'Excel中资产名称重复',
  7825. ];
  7826. continue;
  7827. }
  7828. if (isset($existingNames[$nameKey])) {
  7829. $skipped[] = [
  7830. 'row' => $row['row'],
  7831. 'type' => $typeText,
  7832. 'product_name' => $row['product_name'],
  7833. 'reason' => '剧本中已存在同名资产',
  7834. ];
  7835. continue;
  7836. }
  7837. $seenNames[$nameKey] = true;
  7838. $validRows[] = $row;
  7839. }
  7840. return [
  7841. 'valid_rows' => $validRows,
  7842. 'skipped' => $skipped,
  7843. ];
  7844. }
  7845. /**
  7846. * 读取 Excel 文件为二维数组(第一行为表头)
  7847. *
  7848. * @param \Illuminate\Http\UploadedFile $file
  7849. * @return array
  7850. */
  7851. private function readImportExcelRows($file) {
  7852. try {
  7853. $reader = IOFactory::createReaderForFile($file->getRealPath());
  7854. $reader->setReadDataOnly(true);
  7855. $spreadsheet = $reader->load($file->getRealPath());
  7856. $sheet = $spreadsheet->getSheet(0);
  7857. $rows = $sheet->toArray(null, true, true, false);
  7858. $spreadsheet->disconnectWorksheets();
  7859. unset($spreadsheet);
  7860. return $rows;
  7861. } catch (\Exception $e) {
  7862. dLog('anime')->error('Excel文件解析失败', [
  7863. 'error' => $e->getMessage(),
  7864. ]);
  7865. Utils::throwError('20003:Excel文件解析失败,请确认文件格式正确');
  7866. }
  7867. }
  7868. /**
  7869. * 查找 Excel 表头列索引(先精确匹配,再模糊匹配)
  7870. *
  7871. * @param array $headers
  7872. * @param array $exactKeywords
  7873. * @param array $fuzzyKeywords
  7874. * @return int
  7875. */
  7876. private function findImportExcelColumnIndex(array $headers, array $exactKeywords, array $fuzzyKeywords) {
  7877. foreach ($headers as $index => $header) {
  7878. $header = trim((string)$header);
  7879. if ($header === '') {
  7880. continue;
  7881. }
  7882. foreach ($exactKeywords as $keyword) {
  7883. if ($header === $keyword) {
  7884. return $index;
  7885. }
  7886. }
  7887. }
  7888. foreach ($headers as $index => $header) {
  7889. $header = trim((string)$header);
  7890. if ($header === '') {
  7891. continue;
  7892. }
  7893. foreach ($fuzzyKeywords as $keyword) {
  7894. if (mb_strpos($header, $keyword) !== false) {
  7895. return $index;
  7896. }
  7897. }
  7898. }
  7899. return -1;
  7900. }
  7901. /**
  7902. * 判断 Excel 行是否为空行
  7903. *
  7904. * @param array $row
  7905. * @return bool
  7906. */
  7907. private function isImportExcelRowEmpty(array $row) {
  7908. foreach ($row as $cell) {
  7909. if (trim((string)$cell) !== '') {
  7910. return false;
  7911. }
  7912. }
  7913. return true;
  7914. }
  7915. /**
  7916. * 资产名称去除两边特殊符号(与 createProduct 保持一致)
  7917. *
  7918. * @param string $name
  7919. * @return string
  7920. */
  7921. private function normalizeImportProductName($name) {
  7922. $name = trim((string)$name);
  7923. $name = preg_replace('/^[\s*\[\]【】[]{}{}\x{3000}]+|[\s*\[\]【】[]{}{}\x{3000}]+$/u', '', $name);
  7924. if (!$name || preg_match('/^[-—_]+$/u', $name)) {
  7925. return '';
  7926. }
  7927. return $name;
  7928. }
  7929. /**
  7930. * 解析 Excel 中的资产类型
  7931. *
  7932. * @param string $value
  7933. * @return int|null 1=角色 2=场景 3=道具
  7934. */
  7935. private function resolveImportProductType($value) {
  7936. $value = trim((string)$value);
  7937. $map = [
  7938. '角色' => 1,
  7939. '主体' => 1,
  7940. '人物' => 1,
  7941. '1' => 1,
  7942. '场景' => 2,
  7943. '2' => 2,
  7944. '道具' => 3,
  7945. '3' => 3,
  7946. ];
  7947. return isset($map[$value]) ? $map[$value] : null;
  7948. }
  7949. /**
  7950. * 资产类型文案
  7951. *
  7952. * @param int $type
  7953. * @return string
  7954. */
  7955. private function getImportProductTypeText($type) {
  7956. $map = [1 => '角色', 2 => '场景', 3 => '道具'];
  7957. return isset($map[$type]) ? $map[$type] : (string)$type;
  7958. }
  7959. /**
  7960. * 解析使用范围(逗号分隔的集数)
  7961. *
  7962. * @param string $value
  7963. * @return array
  7964. */
  7965. private function parseImportEpisodeNumbers($value) {
  7966. $parts = preg_split('/[,,、\s]+/u', trim((string)$value));
  7967. $episodeNumbers = [];
  7968. foreach ($parts as $part) {
  7969. if ($part === '') {
  7970. continue;
  7971. }
  7972. if (!is_numeric($part)) {
  7973. return [];
  7974. }
  7975. $episodeNumbers[] = (int)$part;
  7976. }
  7977. $episodeNumbers = array_values(array_unique($episodeNumbers));
  7978. sort($episodeNumbers);
  7979. return $episodeNumbers;
  7980. }
  7981. /**
  7982. * 获取剧本已关联资产名称集合(按 createProduct 的名称判断逻辑)
  7983. *
  7984. * @param int $script_id
  7985. * @param int $cpid
  7986. * @return array
  7987. */
  7988. private function getScriptProductNames($script_id, $cpid) {
  7989. $products = DB::table('mp_script_product_mappings as m')
  7990. ->join('mp_products as p', 'm.product_id', '=', 'p.id')
  7991. ->where('m.script_id', $script_id)
  7992. ->where('p.cpid', $cpid)
  7993. ->where('p.type', 1)
  7994. ->where('p.is_deleted', 0)
  7995. ->get(['p.product_name']);
  7996. $names = [];
  7997. foreach ($products as $product) {
  7998. $name = $this->normalizeImportProductName($product->product_name);
  7999. if ($name !== '') {
  8000. $names[$name] = true;
  8001. }
  8002. }
  8003. return $names;
  8004. }
  8005. /**
  8006. * 获取剧本已关联的资产名称(仅按剧本判重,不区分资产类型)
  8007. *
  8008. * @param int $script_id
  8009. * @return array ['资产名称' => true]
  8010. */
  8011. private function getScriptAssetNames($script_id) {
  8012. $products = DB::table('mp_script_product_mappings as m')
  8013. ->join('mp_products as p', 'm.product_id', '=', 'p.id')
  8014. ->where('m.script_id', $script_id)
  8015. ->where('p.type', 1)
  8016. ->where('p.is_deleted', 0)
  8017. ->get(['p.product_name']);
  8018. $names = [];
  8019. foreach ($products as $product) {
  8020. $name = $this->normalizeImportProductName($product->product_name);
  8021. if ($name !== '') {
  8022. $names[$name] = true;
  8023. }
  8024. }
  8025. return $names;
  8026. }
  8027. /**
  8028. * 校验并提取本次入参中的新增资产行
  8029. *
  8030. * 规则:
  8031. * - 资产名称为空(或仅剩占位符):跳过
  8032. * - 同一份入参内重名(跨类型):保留最后一条
  8033. * - 与剧本已关联资产同名(跨类型判重,仅限当前剧本):不算新增
  8034. * - 新增行的参考提示词为空:直接报错,不进行任何后续处理
  8035. *
  8036. * @param int $script_id
  8037. * @param mixed $products 入参(数组或 JSON 字符串)
  8038. * @return array [['type' => int, 'product_name' => string, 'pic_prompt' => string, 'episode_numbers' => []]]
  8039. */
  8040. private function extractNewScriptProductRows($script_id, $products) {
  8041. // 兼容 JSON 字符串;无法解析时按"没有新增行"处理,由后续创建逻辑给出原有报错
  8042. if (is_string($products)) {
  8043. $decoded = json_decode($products, true);
  8044. $products = (json_last_error() === JSON_ERROR_NONE) ? $decoded : [];
  8045. }
  8046. if (!is_array($products) || empty($products)) {
  8047. return [];
  8048. }
  8049. $rowMap = [];
  8050. foreach ($products as $productGroup) {
  8051. $type = getProp($productGroup, 'type');
  8052. $content = getProp($productGroup, 'content', []);
  8053. if (!in_array($type, [1, 2, 3]) || empty($content) || count($content) < 2) {
  8054. continue;
  8055. }
  8056. // 获取表头(第一行)并查找关键列的位置
  8057. $headers = $content[0];
  8058. $nameColumnIndex = -1;
  8059. $sequenceColumnIndex = -1;
  8060. $promptColumnIndex = -1;
  8061. $fallbackPromptColumnIndex = -1;
  8062. foreach ($headers as $index => $header) {
  8063. if (strpos($header, '资产名称') !== false || strpos($header, '名称') !== false) {
  8064. $nameColumnIndex = $index;
  8065. }
  8066. if (strpos($header, '使用范围') !== false || strpos($header, '范围') !== false) {
  8067. $sequenceColumnIndex = $index;
  8068. }
  8069. if (strpos($header, '参考') !== false && strpos($header, '提示词') !== false) {
  8070. $promptColumnIndex = $index;
  8071. } elseif (strpos($header, '提示词') !== false && $fallbackPromptColumnIndex === -1) {
  8072. // 与 Excel 导入保持一致:优先"参考提示词",否则兼容"提示词"列
  8073. $fallbackPromptColumnIndex = $index;
  8074. }
  8075. }
  8076. if ($promptColumnIndex === -1) {
  8077. $promptColumnIndex = $fallbackPromptColumnIndex;
  8078. }
  8079. if ($nameColumnIndex === -1) {
  8080. continue;
  8081. }
  8082. for ($i = 1; $i < count($content); $i++) {
  8083. $row = $content[$i];
  8084. if (empty($row) || !isset($row[$nameColumnIndex])) {
  8085. continue;
  8086. }
  8087. // 处理product_name两边的符号;名称为空或仅剩占位符号则跳过
  8088. $product_name = $this->normalizeImportProductName($row[$nameColumnIndex]);
  8089. if ($product_name === '') {
  8090. continue;
  8091. }
  8092. $pic_prompt = '';
  8093. if ($promptColumnIndex >= 0 && isset($row[$promptColumnIndex])) {
  8094. $pic_prompt = trim((string)$row[$promptColumnIndex]);
  8095. }
  8096. // 解析使用范围(逗号分隔的序号),为空时由创建逻辑写入默认映射(序号0)
  8097. $sequences = [];
  8098. $sequence_str = ($sequenceColumnIndex >= 0 && isset($row[$sequenceColumnIndex]))
  8099. ? trim((string)$row[$sequenceColumnIndex])
  8100. : '';
  8101. if ($sequence_str !== '') {
  8102. foreach (array_map('trim', explode(',', $sequence_str)) as $part) {
  8103. if (is_numeric($part)) {
  8104. $sequences[] = (int)$part;
  8105. }
  8106. }
  8107. }
  8108. // 跨类型判重,同一份入参内重名保留最后一条
  8109. $rowMap[$product_name] = [
  8110. 'type' => (int)$type,
  8111. 'product_name' => $product_name,
  8112. 'pic_prompt' => $pic_prompt,
  8113. 'episode_numbers' => $sequences,
  8114. ];
  8115. }
  8116. }
  8117. // 与剧本已关联资产判重(仅限当前剧本,跨类型)
  8118. $existingNames = $this->getScriptAssetNames($script_id);
  8119. $newRows = [];
  8120. $emptyPromptNames = [];
  8121. foreach ($rowMap as $name => $row) {
  8122. if (isset($existingNames[$name])) {
  8123. continue;
  8124. }
  8125. if ($row['pic_prompt'] === '') {
  8126. $emptyPromptNames[] = $name;
  8127. continue;
  8128. }
  8129. $newRows[] = $row;
  8130. }
  8131. // 新增行的参考提示词为空:直接报错,不进行任何后续处理
  8132. if (!empty($emptyPromptNames)) {
  8133. Utils::throwError('20003:以下新增资产的参考提示词不能为空:' . implode('、', $emptyPromptNames));
  8134. }
  8135. return $newRows;
  8136. }
  8137. /**
  8138. * 已有关联资产的图片任务处理(参照 saveScriptProducts 的处理方式)
  8139. *
  8140. * - 已有图片任务的资产:收集任务ID,交给轮询
  8141. * - 已有图片且生成成功的资产:跳过
  8142. * - 没有图片的资产:允许自动生成时补建图片任务(需要提示词)
  8143. *
  8144. * @param int $script_id
  8145. * @param string $model
  8146. * @param int $width
  8147. * @param int $height
  8148. * @param bool $auto_generate_images
  8149. * @return array ['product_task_map' => [], 'type_folder_ids' => [], 'has_all_tasks' => bool, 'product_count' => int, 'created_count' => int]
  8150. */
  8151. private function prepareExistingScriptProductTasks($script_id, $model, $width, $height, $auto_generate_images) {
  8152. $productTaskMap = [];
  8153. $typeFolderIds = [];
  8154. $hasAllTasks = true;
  8155. $createdCount = 0;
  8156. $existingMappings = DB::table('mp_script_product_mappings')
  8157. ->where('script_id', $script_id)
  8158. ->get();
  8159. $productIds = $existingMappings->pluck('product_id')->unique()->toArray();
  8160. $productsWithTasks = DB::table('mp_products')
  8161. ->whereIn('id', $productIds)
  8162. ->where('is_deleted', 0)
  8163. ->get();
  8164. foreach ($productsWithTasks as $product) {
  8165. // 收集类型文件夹ID
  8166. if ($product->parent_id > 0 && !in_array($product->parent_id, $typeFolderIds)) {
  8167. $parentFolder = DB::table('mp_products')
  8168. ->where('id', $product->parent_id)
  8169. ->where('type', 2)
  8170. ->first();
  8171. if ($parentFolder) {
  8172. $typeFolderIds[$parentFolder->product] = $parentFolder->id;
  8173. }
  8174. }
  8175. // 检查是否有图片生成任务
  8176. if (!empty($product->pic_task_id)) {
  8177. $productTaskMap[$product->id] = $product->pic_task_id;
  8178. } elseif ($product->url && $product->pic_task_status == '生成成功') {
  8179. continue;
  8180. } else {
  8181. // 有资产没有图片
  8182. $hasAllTasks = false;
  8183. }
  8184. }
  8185. // 为没有图片的资产补建图片生成任务
  8186. if (!$hasAllTasks && $auto_generate_images && $productsWithTasks->isNotEmpty()) {
  8187. DB::beginTransaction();
  8188. try {
  8189. foreach ($productsWithTasks as $product) {
  8190. // 跳过已有任务的资产
  8191. if (!empty($product->pic_task_id)) {
  8192. continue;
  8193. }
  8194. // 跳过没有提示词的资产
  8195. if (empty($product->pic_prompt)) {
  8196. dLog('anime')->warning('资产没有提示词,跳过图片生成', [
  8197. 'product_id' => $product->id,
  8198. 'product_name' => $product->product_name,
  8199. ]);
  8200. continue;
  8201. }
  8202. try {
  8203. $task = $this->aiImageGenerationService->createImageGenerationTask([
  8204. 'prompt' => $product->pic_prompt,
  8205. 'model' => $model,
  8206. 'ref_img_urls' => [],
  8207. 'width' => $width,
  8208. 'height' => $height,
  8209. ]);
  8210. $task_id = $task->id;
  8211. if ($task_id) {
  8212. $productTaskMap[$product->id] = $task_id;
  8213. $createdCount++;
  8214. DB::table('mp_products')
  8215. ->where('id', $product->id)
  8216. ->update([
  8217. 'pic_task_id' => $task_id,
  8218. 'pic_task_status' => '生成中',
  8219. 'updated_at' => now(),
  8220. ]);
  8221. dLog('anime')->info('为已存在资产创建图片生成任务', [
  8222. 'product_id' => $product->id,
  8223. 'task_id' => $task_id,
  8224. ]);
  8225. }
  8226. } catch (\Exception $e) {
  8227. dLog('anime')->error('创建资产图片生成任务失败', [
  8228. 'product_id' => $product->id,
  8229. 'error' => $e->getMessage(),
  8230. ]);
  8231. DB::table('mp_products')
  8232. ->where('id', $product->id)
  8233. ->update([
  8234. 'pic_task_status' => '生成失败',
  8235. 'updated_at' => now(),
  8236. ]);
  8237. }
  8238. }
  8239. DB::commit();
  8240. } catch (\Exception $e) {
  8241. DB::rollback();
  8242. dLog('anime')->error('为已存在资产创建图片任务失败', [
  8243. 'script_id' => $script_id,
  8244. 'error' => $e->getMessage(),
  8245. ]);
  8246. Utils::throwError('20003:创建图片任务失败:' . $e->getMessage());
  8247. }
  8248. }
  8249. return [
  8250. 'product_task_map' => $productTaskMap,
  8251. 'type_folder_ids' => $typeFolderIds,
  8252. 'has_all_tasks' => $hasAllTasks,
  8253. 'product_count' => count($productIds),
  8254. 'created_count' => $createdCount,
  8255. ];
  8256. }
  8257. /**
  8258. * 保存剧本资产关联关系
  8259. * @param array $data 请求参数
  8260. * @return bool
  8261. */
  8262. public function saveScriptProducts($data) {
  8263. $uid = Site::getUid();
  8264. $cpid = Site::getCpid();
  8265. $script_id = getProp($data, 'script_id');
  8266. $products = getProp($data, 'products', []);
  8267. $auto_generate_images = getProp($data, 'auto_generate_images', true); // 是否自动生成图片,默认true
  8268. if (!$script_id) {
  8269. Utils::throwError('20003:请提供剧本ID');
  8270. }
  8271. // 验证剧本是否存在
  8272. $script = DB::table('mp_scripts')
  8273. ->where('id', $script_id)
  8274. ->where('is_deleted', 0)
  8275. ->first();
  8276. if (!$script) {
  8277. Utils::throwError('20003:剧本不存在');
  8278. }
  8279. // 处理图片模型
  8280. $model = getProp($data, 'model');
  8281. if (!$model) {
  8282. // 使用默认模型
  8283. $model = 'gpt-image-2';
  8284. }
  8285. // 验证模型是否在可用模型表中
  8286. if (!DB::table('mp_image_models')->where('model', $model)->where('is_enabled', 1)->exists()) {
  8287. Utils::throwError('20003:该模型已不可用,请更换!');
  8288. }
  8289. $ratio = getProp($data, 'ratio', '9:16');
  8290. $resolution = getProp($data, 'resolution', '2k');
  8291. // 分辨率档位与尺寸映射统一从 BaseConst 获取
  8292. $sizeMap = BaseConst::IMAGE_RESOLUTION_SIZE_MAP;
  8293. // 参数验证
  8294. $resolution = strtolower($resolution);
  8295. if (!isset($sizeMap[$resolution])) {
  8296. Utils::throwError('20003:分辨率参数错误,仅支持 2k、3k、4k');
  8297. }
  8298. if (!isset($sizeMap[$resolution][$ratio])) {
  8299. Utils::throwError('20003:宽高比参数错误,该分辨率下不支持 ' . $ratio . ' 比例');
  8300. }
  8301. // 根据 ratio 和 resolution 确定宽高
  8302. $width = $sizeMap[$resolution][$ratio]['width'];
  8303. $height = $sizeMap[$resolution][$ratio]['height'];
  8304. $script_name = $script->script_name ?? 'script_' . $script_id;
  8305. // 先校验并提取本次入参中的新增资产行:
  8306. // 新增行的参考提示词为空时直接报错,不写任何数据、不创建任务中心记录
  8307. $newRows = $this->extractNewScriptProductRows($script_id, $products);
  8308. // 根据入参创建/复用任务中心记录(params md5 验重,避免重复任务)
  8309. $taskCenterId = $this->createScriptProductTaskCenter(
  8310. $uid,
  8311. $cpid,
  8312. $script_id,
  8313. $products,
  8314. $model,
  8315. $ratio,
  8316. $resolution,
  8317. $auto_generate_images
  8318. );
  8319. // 检查是否已经有该剧本的资产数据
  8320. $existingMappings = DB::table('mp_script_product_mappings')
  8321. ->where('script_id', $script_id)
  8322. ->get();
  8323. // 已有资产且本次没有新增行时,走原有的"已存在"处理;否则走下方创建逻辑
  8324. if ($existingMappings->isNotEmpty() && empty($newRows)) {
  8325. // 已存在资产映射,检查是否所有资产都有图片生成任务
  8326. $productIds = $existingMappings->pluck('product_id')->unique()->toArray();
  8327. // 查询这些资产的图片生成任务状态
  8328. $productsWithTasks = DB::table('mp_products')
  8329. ->whereIn('id', $productIds)
  8330. ->where('is_deleted', 0)
  8331. ->get();
  8332. $productTaskMap = [];
  8333. $typeFolderIds = [];
  8334. $hasAllTasks = true;
  8335. foreach ($productsWithTasks as $product) {
  8336. // 收集类型文件夹ID
  8337. if ($product->parent_id > 0 && !in_array($product->parent_id, $typeFolderIds)) {
  8338. $parentFolder = DB::table('mp_products')
  8339. ->where('id', $product->parent_id)
  8340. ->where('type', 2)
  8341. ->first();
  8342. if ($parentFolder) {
  8343. $typeFolderIds[$parentFolder->product] = $parentFolder->id;
  8344. }
  8345. }
  8346. // 检查是否有图片生成任务
  8347. if (!empty($product->pic_task_id)) {
  8348. $productTaskMap[$product->id] = $product->pic_task_id;
  8349. } else if($product->url && $product->pic_task_status == '生成成功') {
  8350. continue;
  8351. } else {
  8352. // 有资产没有图片任务
  8353. $hasAllTasks = false;
  8354. }
  8355. }
  8356. // 如果所有资产都有任务ID,直接轮询返回结果
  8357. if ($hasAllTasks && !empty($productTaskMap)) {
  8358. dLog('anime')->info('剧本资产已存在且都有图片任务,直接轮询结果', [
  8359. 'script_id' => $script_id,
  8360. 'script_name' => $script_name,
  8361. 'product_count' => count($productTaskMap)
  8362. ]);
  8363. // 直接返回 SSE 流轮询结果
  8364. return $this->pollProductImageTasks($script_id, $script_name, $productTaskMap, $typeFolderIds, $taskCenterId);
  8365. }
  8366. // 如果部分资产没有任务ID,只为这些资产创建任务
  8367. if (!$hasAllTasks && $auto_generate_images) {
  8368. dLog('anime')->info('剧本资产已存在,但部分资产没有图片任务,为缺失的资产创建任务', [
  8369. 'script_id' => $script_id,
  8370. 'script_name' => $script_name
  8371. ]);
  8372. // 开启事务
  8373. DB::beginTransaction();
  8374. try {
  8375. foreach ($productsWithTasks as $product) {
  8376. // 跳过已有任务的资产
  8377. if (!empty($product->pic_task_id)) {
  8378. continue;
  8379. }
  8380. // 跳过没有提示词的资产
  8381. if (empty($product->pic_prompt)) {
  8382. dLog('anime')->warning('资产没有提示词,跳过图片生成', [
  8383. 'product_id' => $product->id,
  8384. 'product_name' => $product->product_name
  8385. ]);
  8386. continue;
  8387. }
  8388. try {
  8389. // 创建图片生成任务
  8390. $params = [
  8391. 'prompt' => $product->pic_prompt,
  8392. 'model' => $model,
  8393. 'ref_img_urls' => [],
  8394. 'width' => $width,
  8395. 'height' => $height
  8396. ];
  8397. $task = $this->aiImageGenerationService->createImageGenerationTask($params);
  8398. $task_id = $task->id;
  8399. if ($task_id) {
  8400. $productTaskMap[$product->id] = $task_id;
  8401. // 在事务中更新资产表的任务ID和状态
  8402. DB::table('mp_products')
  8403. ->where('id', $product->id)
  8404. ->update([
  8405. 'pic_task_id' => $task_id,
  8406. 'pic_task_status' => '生成中',
  8407. 'updated_at' => now()
  8408. ]);
  8409. dLog('anime')->info('为已存在资产创建图片生成任务', [
  8410. 'product_id' => $product->id,
  8411. 'task_id' => $task_id
  8412. ]);
  8413. }
  8414. } catch (\Exception $e) {
  8415. dLog('anime')->error('创建资产图片生成任务失败', [
  8416. 'product_id' => $product->id,
  8417. 'error' => $e->getMessage()
  8418. ]);
  8419. // 标记为失败(仍在事务中)
  8420. DB::table('mp_products')
  8421. ->where('id', $product->id)
  8422. ->update([
  8423. 'pic_task_status' => '生成失败',
  8424. 'updated_at' => now()
  8425. ]);
  8426. }
  8427. }
  8428. // 提交事务
  8429. DB::commit();
  8430. // 如果有新创建的任务,返回 SSE 流
  8431. if (!empty($productTaskMap)) {
  8432. return $this->pollProductImageTasks($script_id, $script_name, $productTaskMap, $typeFolderIds, $taskCenterId);
  8433. }
  8434. } catch (\Exception $e) {
  8435. // 回滚事务
  8436. DB::rollback();
  8437. dLog('anime')->error('为已存在资产创建图片任务失败', [
  8438. 'script_id' => $script_id,
  8439. 'error' => $e->getMessage()
  8440. ]);
  8441. Utils::throwError('20003:创建图片任务失败:' . $e->getMessage());
  8442. }
  8443. }
  8444. // 如果不需要生成图片,返回已存在的信息
  8445. $resultData = [
  8446. 'success' => true,
  8447. 'message' => '剧本资产已存在',
  8448. 'script_id' => $script_id,
  8449. 'script_name' => $script_name,
  8450. 'type_folder_ids' => $typeFolderIds,
  8451. 'existing_products' => count($productIds),
  8452. 'tasks_count' => count($productTaskMap),
  8453. 'task_center_id' => $taskCenterId
  8454. ];
  8455. // 接口已正常完成,更新任务中心状态和结果
  8456. if ($taskCenterId) {
  8457. $this->taskCenterService->updateTask($taskCenterId, [
  8458. 'status' => MpTaskCenter::STATUS_SUCCESS,
  8459. 'result' => json_encode($resultData, JSON_UNESCAPED_UNICODE),
  8460. 'error_message' => null
  8461. ]);
  8462. }
  8463. return $resultData;
  8464. }
  8465. // 走到这里说明有新行需要创建(或剧本还没有任何资产),保留原有的入参校验报错
  8466. if (empty($newRows)) {
  8467. $decodedProducts = $products;
  8468. if (is_string($decodedProducts)) {
  8469. $decodedProducts = json_decode($decodedProducts, true);
  8470. if (json_last_error() !== JSON_ERROR_NONE) {
  8471. Utils::throwError('20003:产品数据格式错误');
  8472. }
  8473. }
  8474. if (!is_array($decodedProducts) || empty($decodedProducts)) {
  8475. Utils::throwError('20003:产品数据不能为空');
  8476. }
  8477. Utils::throwError('20003:没有有效的产品数据');
  8478. }
  8479. // 仅保留本次新增的资产行,复用下方原有的创建逻辑
  8480. $products = [];
  8481. foreach ($newRows as $newRow) {
  8482. if (!isset($products[$newRow['type']])) {
  8483. $products[$newRow['type']] = [
  8484. 'type' => $newRow['type'],
  8485. 'content' => [['资产名称', '使用范围', '参考提示词']],
  8486. ];
  8487. }
  8488. $products[$newRow['type']]['content'][] = [
  8489. $newRow['product_name'],
  8490. implode(',', $newRow['episode_numbers']),
  8491. $newRow['pic_prompt'],
  8492. ];
  8493. }
  8494. $products = array_values($products);
  8495. // 以下是原有的创建逻辑...
  8496. // 开启事务
  8497. DB::beginTransaction();
  8498. try {
  8499. $now = now();
  8500. $mappingRecords = [];
  8501. $createdProductIds = []; // 记录所有创建的资产ID
  8502. // 获取剧本名称
  8503. $script_name = $script->script_name ?? 'script_' . $script_id;
  8504. // 存储每个类型的根文件夹ID
  8505. $typeFolderIds = [];
  8506. // 遍历每个产品类型(type: 1=角色, 2=场景, 3=道具)
  8507. foreach ($products as $productGroup) {
  8508. $type = getProp($productGroup, 'type');
  8509. $title = getProp($productGroup, 'title', '');
  8510. $content = getProp($productGroup, 'content', []);
  8511. if (!in_array($type, [1, 2, 3]) || empty($content) || count($content) < 2) {
  8512. continue;
  8513. }
  8514. // 为当前类型获取根文件夹:该剧本已存在则复用,避免重复创建根文件夹
  8515. if (!isset($typeFolderIds[$type])) {
  8516. $folder = DB::table('mp_products')
  8517. ->where('cpid', $cpid)
  8518. ->where('type', 2)
  8519. ->where('product', $type)
  8520. ->where('product_name', $script_name)
  8521. ->where('parent_id', 0)
  8522. ->where('is_deleted', 0)
  8523. ->first();
  8524. if ($folder) {
  8525. $typeFolderIds[$type] = $folder->id;
  8526. } else {
  8527. $typeFolderIds[$type] = DB::table('mp_products')->insertGetId([
  8528. 'user_id' => $uid,
  8529. 'cpid' => $cpid,
  8530. 'type' => 2, // 1.资产 2文件夹
  8531. 'product' => $type, // 1.主体 2.场景 3.道具
  8532. 'parent_id' => 0, // 根文件夹,parent_id=0
  8533. 'level' => 1, // 第一层级
  8534. 'product_name' => $script_name,
  8535. 'sort_order' => time() + $type,
  8536. 'is_deleted' => 0,
  8537. 'created_at' => $now,
  8538. 'updated_at' => $now
  8539. ]);
  8540. }
  8541. }
  8542. $folder_id = $typeFolderIds[$type];
  8543. // 获取表头(第一行)并查找关键列的位置
  8544. $headers = $content[0];
  8545. $nameColumnIndex = -1; // 资产名称列索引
  8546. $sequenceColumnIndex = -1; // 使用范围列索引
  8547. $promptColumnIndex = -1; // 参考提示词列索引
  8548. foreach ($headers as $index => $header) {
  8549. // 查找"资产名称"列
  8550. if (strpos($header, '资产名称') !== false || strpos($header, '名称') !== false) {
  8551. $nameColumnIndex = $index;
  8552. }
  8553. // 查找"使用范围"列
  8554. if (strpos($header, '使用范围') !== false || strpos($header, '范围') !== false) {
  8555. $sequenceColumnIndex = $index;
  8556. }
  8557. // 查找"参考提示词"列(可能是"干净参考图提示词"、"参考提示词"等)
  8558. if (strpos($header, '参考') !== false && strpos($header, '提示词') !== false) {
  8559. $promptColumnIndex = $index;
  8560. }
  8561. }
  8562. // 验证必要的列是否都找到了
  8563. if ($nameColumnIndex === -1) {
  8564. dLog('anime')->warning('未找到资产名称列', ['type' => $type, 'headers' => $headers]);
  8565. continue;
  8566. }
  8567. if ($sequenceColumnIndex === -1) {
  8568. dLog('anime')->warning('未找到使用范围列', ['type' => $type, 'headers' => $headers]);
  8569. continue;
  8570. }
  8571. // 跳过表头,解析每一行数据
  8572. for ($i = 1; $i < count($content); $i++) {
  8573. $row = $content[$i];
  8574. // 确保行数据有效
  8575. if (empty($row) || count($row) <= max($nameColumnIndex, $sequenceColumnIndex)) {
  8576. continue;
  8577. }
  8578. // 根据动态查找的列索引提取数据
  8579. $product_name = isset($row[$nameColumnIndex]) ? trim((string)$row[$nameColumnIndex]) : '';
  8580. $sequence_str = isset($row[$sequenceColumnIndex]) ? trim($row[$sequenceColumnIndex]) : '';
  8581. $pic_prompt = '';
  8582. // 提取参考提示词(如果找到了该列)
  8583. if ($promptColumnIndex >= 0 && isset($row[$promptColumnIndex])) {
  8584. $pic_prompt = trim($row[$promptColumnIndex]);
  8585. }
  8586. // 解析使用范围(逗号分隔的序号)
  8587. $sequences = [];
  8588. if (!empty($sequence_str)) {
  8589. $sequenceParts = array_map('trim', explode(',', $sequence_str));
  8590. foreach ($sequenceParts as $part) {
  8591. if (is_numeric($part)) {
  8592. $sequences[] = (int)$part;
  8593. }
  8594. }
  8595. }
  8596. if (empty($product_name)) {
  8597. continue;
  8598. }
  8599. // 处理product_name两边的符号
  8600. $product_name = preg_replace('/^[\s*\[\]【】[]{}{}\x{3000}]+|[\s*\[\]【】[]{}{}\x{3000}]+$/u', '', $product_name);
  8601. // 如果名称不存在或仅剩占位符号,则跳过
  8602. if (!$product_name || preg_match('/^[-—_]+$/u', $product_name)) {
  8603. dLog('anime')->warning('资产名称无效,跳过保存', [
  8604. 'script_id' => $script_id,
  8605. 'type' => $type,
  8606. 'product_name' => $product_name
  8607. ]);
  8608. continue;
  8609. }
  8610. // 直接插入新资产到 mp_products 表(parent_id 指向对应类型的根文件夹)
  8611. $product_id = DB::table('mp_products')->insertGetId([
  8612. 'product_name' => $product_name,
  8613. 'type' => 1, // 1=资产 2.文件夹
  8614. 'product' => $type, // 1=角色, 2=场景, 3=道具
  8615. 'parent_id' => $folder_id, // 父文件夹是该类型的根文件夹
  8616. 'level' => 2, // 第二层级
  8617. 'pic_prompt' => $pic_prompt,
  8618. 'user_id' => $uid,
  8619. 'cpid' => $cpid,
  8620. 'sort_order' => time(),
  8621. 'is_deleted' => 0,
  8622. 'created_at' => $now,
  8623. 'updated_at' => $now,
  8624. ]);
  8625. // 记录创建的资产ID
  8626. $createdProductIds[] = $product_id;
  8627. // 为每个序号创建映射记录
  8628. if (!empty($sequences)) {
  8629. foreach ($sequences as $sequence) {
  8630. $mappingRecords[] = [
  8631. 'script_id' => $script_id,
  8632. 'product_id' => $product_id,
  8633. 'episode_number' => $sequence,
  8634. 'created_at' => $now,
  8635. 'updated_at' => $now,
  8636. ];
  8637. }
  8638. } else {
  8639. // 如果没有指定序号,创建一个默认映射(序号为0)
  8640. $mappingRecords[] = [
  8641. 'script_id' => $script_id,
  8642. 'product_id' => $product_id,
  8643. 'episode_number' => 0,
  8644. 'created_at' => $now,
  8645. 'updated_at' => $now,
  8646. ];
  8647. }
  8648. }
  8649. }
  8650. if (empty($mappingRecords)) {
  8651. Utils::throwError('20003:没有有效的产品数据');
  8652. }
  8653. // 批量插入映射数据(使用 insertOrIgnore 避免重复插入)
  8654. $insertedCount = DB::table('mp_script_product_mappings')->insertOrIgnore($mappingRecords);
  8655. // 剧本已有资产,同步更新is_products标记
  8656. DB::table('mp_scripts')->where('id', $script_id)->update([
  8657. 'is_products' => 1,
  8658. 'updated_at' => $now
  8659. ]);
  8660. // 如果需要自动生成图片,在事务中创建图片生成任务
  8661. $productTaskMap = [];
  8662. if ($auto_generate_images && !empty($createdProductIds)) {
  8663. // 查询所有创建的资产
  8664. $productsToGenerate = DB::table('mp_products')
  8665. ->whereIn('id', $createdProductIds)
  8666. ->where('is_deleted', 0)
  8667. ->get();
  8668. foreach ($productsToGenerate as $product) {
  8669. if (empty($product->pic_prompt)) {
  8670. dLog('anime')->warning('资产没有提示词,跳过图片生成', [
  8671. 'product_id' => $product->id,
  8672. 'product_name' => $product->product_name
  8673. ]);
  8674. continue;
  8675. }
  8676. try {
  8677. // 创建图片生成任务
  8678. $params = [
  8679. 'prompt' => $product->pic_prompt,
  8680. 'model' => $model,
  8681. 'ref_img_urls' => [],
  8682. 'width' => $width,
  8683. 'height' => $height
  8684. ];
  8685. $task = $this->aiImageGenerationService->createImageGenerationTask($params);
  8686. $task_id = $task->id;
  8687. if ($task_id) {
  8688. $productTaskMap[$product->id] = $task_id;
  8689. // 在事务中更新资产表的任务ID和状态
  8690. DB::table('mp_products')
  8691. ->where('id', $product->id)
  8692. ->update([
  8693. 'pic_task_id' => $task_id,
  8694. 'pic_task_status' => '生成中',
  8695. 'updated_at' => now()
  8696. ]);
  8697. dLog('anime')->info('创建资产图片生成任务', [
  8698. 'product_id' => $product->id,
  8699. 'task_id' => $task_id
  8700. ]);
  8701. }
  8702. } catch (\Exception $e) {
  8703. dLog('anime')->error('创建资产图片生成任务失败', [
  8704. 'product_id' => $product->id,
  8705. 'error' => $e->getMessage()
  8706. ]);
  8707. // 标记为失败(仍在事务中)
  8708. DB::table('mp_products')
  8709. ->where('id', $product->id)
  8710. ->update([
  8711. 'pic_task_status' => '生成失败',
  8712. 'updated_at' => now()
  8713. ]);
  8714. }
  8715. }
  8716. }
  8717. // 提交事务
  8718. DB::commit();
  8719. // 本次新增资产创建的图片任务
  8720. $createdTaskMap = $productTaskMap;
  8721. } catch (\Exception $e) {
  8722. // 回滚事务
  8723. DB::rollback();
  8724. // 更新任务中心状态为失败
  8725. if (!empty($taskCenterId)) {
  8726. $this->taskCenterService->updateTask($taskCenterId, [
  8727. 'status' => MpTaskCenter::STATUS_FAILED,
  8728. 'error_message' => $e->getMessage()
  8729. ]);
  8730. }
  8731. // 记录错误日志
  8732. dLog('anime')->error('保存剧本资产失败: ' . $e->getMessage(), [
  8733. 'script_id' => $script_id,
  8734. 'error' => $e->getMessage(),
  8735. 'trace' => $e->getTraceAsString()
  8736. ]);
  8737. // 统一使用 Utils::throwError 抛出错误
  8738. Utils::throwError('20003:保存剧本资产失败:' . $e->getMessage());
  8739. }
  8740. // 落库成功后统一处理图片任务:
  8741. // 1) 本次新增资产的图片任务已在上方事务中创建
  8742. // 2) 剧本内已存在但缺图的资产在此补建,并与新增资产的任务一并收集为待轮询任务
  8743. $existingTaskInfo = $this->prepareExistingScriptProductTasks(
  8744. $script_id,
  8745. $model,
  8746. $width,
  8747. $height,
  8748. $auto_generate_images
  8749. );
  8750. $productTaskMap = $existingTaskInfo['product_task_map'];
  8751. // 创建阶段解析到的类型根文件夹优先
  8752. $typeFolderIds = $typeFolderIds + $existingTaskInfo['type_folder_ids'];
  8753. // 保存结果(SSE 的 init / complete 事件会携带该结构)
  8754. $resultData = [
  8755. 'success' => true,
  8756. 'message' => '保存完成',
  8757. 'script_id' => $script_id,
  8758. 'script_name' => $script_name,
  8759. 'type_folder_ids' => $typeFolderIds,
  8760. 'inserted_count' => $insertedCount,
  8761. 'total_records' => count($mappingRecords),
  8762. 'created_products' => count($createdProductIds),
  8763. 'pending_tasks_count' => count($productTaskMap),
  8764. 'image_tasks_created' => count($createdTaskMap) + $existingTaskInfo['created_count'],
  8765. 'task_center_id' => $taskCenterId,
  8766. ];
  8767. // 有待完成的图片任务:返回 SSE 轮询流(事务外轮询)
  8768. if ($auto_generate_images && !empty($productTaskMap)) {
  8769. return $this->pollProductImageTasks(
  8770. $script_id,
  8771. $script_name,
  8772. $productTaskMap,
  8773. $typeFolderIds,
  8774. $taskCenterId,
  8775. ['import_result' => $resultData],
  8776. ['import_result' => $resultData]
  8777. );
  8778. }
  8779. // 没有需要轮询的任务:通过 SSE complete 事件返回保存结果
  8780. return $this->streamImportComplete($script_id, $script_name, $resultData, $typeFolderIds, $taskCenterId);
  8781. }
  8782. /**
  8783. * 根据入参创建或复用任务中心记录
  8784. *
  8785. * 以规范化入参计算 md5 并保存到任务中心 params 字段中用于验重:
  8786. * 同一用户/企业下,相同入参且任务未结束(pending/processing)时复用已有任务,
  8787. * 避免生成重复任务。
  8788. *
  8789. * @param int|string $uid
  8790. * @param int|string $cpid
  8791. * @param int|string $script_id
  8792. * @param mixed $products
  8793. * @param string $model
  8794. * @param string $ratio
  8795. * @param string $resolution
  8796. * @param mixed $auto_generate_images
  8797. * @return int 任务中心ID
  8798. */
  8799. private function createScriptProductTaskCenter($uid, $cpid, $script_id, $products, $model, $ratio, $resolution, $auto_generate_images) {
  8800. // 规范化 products(兼容 JSON 字符串和数组),保证 md5 稳定
  8801. if (is_string($products)) {
  8802. $decoded = json_decode($products, true);
  8803. if (json_last_error() === JSON_ERROR_NONE) {
  8804. $products = $decoded;
  8805. }
  8806. }
  8807. $params = [
  8808. 'script_id' => (int)$script_id,
  8809. 'products' => $products,
  8810. 'model' => $model,
  8811. 'ratio' => $ratio,
  8812. 'resolution' => $resolution,
  8813. 'auto_generate_images' => (bool)$auto_generate_images,
  8814. ];
  8815. $paramsMd5 = md5(json_encode($params, JSON_UNESCAPED_UNICODE | JSON_UNESCAPED_SLASHES));
  8816. // 验重:相同 md5 且任务未结束(pending/processing)时复用已有任务中心记录
  8817. $existing = DB::table('mp_task_center')
  8818. ->where('uid', (int)$uid)
  8819. ->where('cpid', (int)$cpid)
  8820. ->where('task_type', MpTaskCenter::TYPE_SAVE_SCRIPT_PRODUCTS)
  8821. ->whereIn('status', [MpTaskCenter::STATUS_PENDING, MpTaskCenter::STATUS_PROCESSING])
  8822. ->where('params_md5', $paramsMd5)
  8823. ->orderBy('id', 'desc')
  8824. ->first();
  8825. if ($existing) {
  8826. dLog('anime')->info('复用已有任务中心记录,避免重复任务', [
  8827. 'script_id' => $script_id,
  8828. 'task_center_id' => $existing->id,
  8829. 'params_md5' => $paramsMd5,
  8830. ]);
  8831. return (int)$existing->id;
  8832. }
  8833. // 唯一索引 (uid, cpid, task_type, params_md5) 兜底并发重复,冲突时静默忽略
  8834. $now = date('Y-m-d H:i:s');
  8835. DB::table('mp_task_center')->insertOrIgnore([
  8836. 'uid' => (int)$uid,
  8837. 'cpid' => (int)$cpid,
  8838. 'task_type' => MpTaskCenter::TYPE_SAVE_SCRIPT_PRODUCTS,
  8839. 'title' => '剧本资产图片生成',
  8840. 'ref_task_id' => 0,
  8841. 'status' => MpTaskCenter::STATUS_PROCESSING,
  8842. 'result' => null,
  8843. 'error_message' => null,
  8844. 'prompt' => null,
  8845. 'params' => json_encode($params + ['params_md5' => $paramsMd5], JSON_UNESCAPED_UNICODE | JSON_UNESCAPED_SLASHES),
  8846. 'params_md5' => $paramsMd5,
  8847. 'created_at' => $now,
  8848. 'updated_at' => $now,
  8849. ]);
  8850. // 获取任务中心ID(insertOrIgnore 冲突时复用并发插入的已有记录)
  8851. $taskId = (int)DB::table('mp_task_center')
  8852. ->where('uid', (int)$uid)
  8853. ->where('cpid', (int)$cpid)
  8854. ->where('task_type', MpTaskCenter::TYPE_SAVE_SCRIPT_PRODUCTS)
  8855. ->where('params_md5', $paramsMd5)
  8856. ->orderBy('id', 'desc')
  8857. ->value('id');
  8858. dLog('anime')->info('创建任务中心记录', [
  8859. 'script_id' => $script_id,
  8860. 'task_center_id' => $taskId,
  8861. 'params_md5' => $paramsMd5,
  8862. ]);
  8863. return $taskId;
  8864. }
  8865. /**
  8866. * 任务结束时更新任务中心记录的状态和结果
  8867. *
  8868. * result 字段保存与 saveScriptProducts 接口返回给客户端一致的结果数据
  8869. * (普通数组返回为完整返回数组,SSE 轮询为 complete/timeout 事件载荷)。
  8870. *
  8871. * @param int|null $taskCenterId
  8872. * @param array $resultData 接口返回结果数组
  8873. * @param bool $timeout 是否超时未完成
  8874. */
  8875. private function finishScriptProductTask($taskCenterId, array $resultData, $timeout = false) {
  8876. if (!$taskCenterId) {
  8877. return;
  8878. }
  8879. $stats = $resultData['stats'] ?? [];
  8880. $successCount = (int)array_sum(array_column((array)$stats, 'success'));
  8881. $completedCount = (int)array_sum(array_column((array)$stats, 'completed'));
  8882. $failedCount = $completedCount - $successCount;
  8883. // 与接口返回给客户端的结果保持一致
  8884. $result = json_encode($resultData, JSON_UNESCAPED_UNICODE);
  8885. if ($timeout) {
  8886. $this->taskCenterService->updateTask((int)$taskCenterId, [
  8887. 'status' => MpTaskCenter::STATUS_FAILED,
  8888. 'result' => $result,
  8889. 'error_message' => '部分任务超时,请稍后查看结果',
  8890. ]);
  8891. return;
  8892. }
  8893. $this->taskCenterService->updateTask((int)$taskCenterId, [
  8894. 'status' => $failedCount > 0 ? MpTaskCenter::STATUS_FAILED : MpTaskCenter::STATUS_SUCCESS,
  8895. 'result' => $result,
  8896. 'error_message' => $failedCount > 0 ? ('有 ' . $failedCount . ' 个资产生成失败') : null,
  8897. ]);
  8898. }
  8899. /**
  8900. * 批量为剧本资产生成图片
  8901. *
  8902. * @param array $data 请求参数
  8903. * @return \Generator 返回 SSE 流
  8904. */
  8905. public function batchGenerateProductImages($data) {
  8906. $script_id = getProp($data, 'script_id');
  8907. $type_folder_ids = getProp($data, 'type_folder_ids', []); // {1: 角色文件夹ID, 2: 场景文件夹ID, 3: 道具文件夹ID}
  8908. if (!$script_id) {
  8909. Utils::throwError('20003:请提供剧本ID');
  8910. }
  8911. // 验证剧本是否存在
  8912. $script = DB::table('mp_scripts')
  8913. ->where('id', $script_id)
  8914. ->where('is_deleted', 0)
  8915. ->first();
  8916. if (!$script) {
  8917. Utils::throwError('20003:剧本不存在');
  8918. }
  8919. $script_name = $script->script_name ?? 'script_' . $script_id;
  8920. // 获取需要生成图片的所有资产
  8921. $products = DB::table('mp_products')
  8922. ->whereIn('parent_id', array_values($type_folder_ids))
  8923. ->where('is_deleted', 0)
  8924. ->whereIn('type', [1, 2, 3]) // 只处理资产,不处理文件夹
  8925. ->get();
  8926. if ($products->isEmpty()) {
  8927. Utils::throwError('20003:没有找到需要生成图片的资产');
  8928. }
  8929. // 默认参数
  8930. $model = 'gpt-image-2';
  8931. $width = 1600;
  8932. $height = 2848;
  8933. // 开始为每个资产创建图片生成任务
  8934. $taskIds = [];
  8935. $productTaskMap = []; // 资产ID到任务ID的映射
  8936. foreach ($products as $product) {
  8937. if (empty($product->pic_prompt)) {
  8938. dLog('anime')->warning('资产没有提示词,跳过', ['product_id' => $product->id, 'product_name' => $product->product_name]);
  8939. continue;
  8940. }
  8941. try {
  8942. // 创建图片生成任务
  8943. $params = [
  8944. 'prompt' => $product->pic_prompt,
  8945. 'model' => $model,
  8946. 'ref_img_urls' => [],
  8947. 'width' => $width,
  8948. 'height' => $height
  8949. ];
  8950. $task = $this->aiImageGenerationService->createImageGenerationTask($params);
  8951. $task_id = $task->id;
  8952. if ($task_id) {
  8953. $taskIds[] = $task_id;
  8954. $productTaskMap[$product->id] = $task_id;
  8955. // 更新资产表的任务ID和状态
  8956. DB::table('mp_products')
  8957. ->where('id', $product->id)
  8958. ->update([
  8959. 'pic_task_id' => $task_id,
  8960. 'pic_task_status' => '生成中',
  8961. 'updated_at' => now()
  8962. ]);
  8963. dLog('anime')->info('创建资产图片生成任务', ['product_id' => $product->id, 'task_id' => $task_id]);
  8964. }
  8965. } catch (\Exception $e) {
  8966. dLog('anime')->error('创建资产图片生成任务失败', [
  8967. 'product_id' => $product->id,
  8968. 'error' => $e->getMessage()
  8969. ]);
  8970. // 标记为失败
  8971. DB::table('mp_products')
  8972. ->where('id', $product->id)
  8973. ->update([
  8974. 'pic_task_status' => '生成失败',
  8975. 'updated_at' => now()
  8976. ]);
  8977. }
  8978. }
  8979. if (empty($taskIds)) {
  8980. Utils::throwError('20003:没有成功创建任何图片生成任务');
  8981. }
  8982. // 返回 SSE 流
  8983. return $this->pollProductImageTasks($script_id, $script_name, $productTaskMap, $type_folder_ids);
  8984. }
  8985. /**
  8986. * 无需轮询时的 SSE 返回:直接通过 complete 事件返回导入结果
  8987. *
  8988. * @param int $script_id
  8989. * @param string $script_name
  8990. * @param array $resultData 导入结果(原普通 JSON 的 data 内容)
  8991. * @param array $type_folder_ids
  8992. * @param int|null $taskCenterId
  8993. * @return \Generator
  8994. */
  8995. private function streamImportComplete($script_id, $script_name, array $resultData, $type_folder_ids, $taskCenterId = null) {
  8996. if ($taskCenterId) {
  8997. $initResponse = [
  8998. 'type' => 'init',
  8999. 'script_id' => $script_id,
  9000. 'script_name' => $script_name,
  9001. 'timestamp' => date('Y-m-d H:i:s'),
  9002. 'task_center_id' => (int)$taskCenterId,
  9003. 'import_result' => $resultData,
  9004. ];
  9005. yield "data: " . json_encode($initResponse, JSON_UNESCAPED_UNICODE) . "\n\n";
  9006. }
  9007. $stats = $this->collectScriptProductStats($script_id);
  9008. $response = [
  9009. 'type' => 'complete',
  9010. 'script_id' => $script_id,
  9011. 'script_name' => $script_name,
  9012. 'stats' => $stats,
  9013. 'timestamp' => date('Y-m-d H:i:s'),
  9014. 'import_result' => $resultData,
  9015. ];
  9016. if ($taskCenterId) {
  9017. $response['task_center_id'] = (int)$taskCenterId;
  9018. }
  9019. yield "data: " . json_encode($response, JSON_UNESCAPED_UNICODE) . "\n\n";
  9020. // 更新任务中心状态和结果
  9021. $this->finishScriptProductTask($taskCenterId, $response);
  9022. }
  9023. /**
  9024. * 统计剧本资产的图片生成状态(仅按 mp_products 当前状态统计,不驱动任务)
  9025. *
  9026. * @param int $script_id
  9027. * @return array
  9028. */
  9029. private function collectScriptProductStats($script_id) {
  9030. $stats = [
  9031. 'character' => ['total' => 0, 'success' => 0, 'completed' => 0],
  9032. 'scene' => ['total' => 0, 'success' => 0, 'completed' => 0],
  9033. 'prop' => ['total' => 0, 'success' => 0, 'completed' => 0],
  9034. ];
  9035. $typeNames = [1 => 'roles', 2 => 'scenes', 3 => 'props'];
  9036. $productIds = DB::table('mp_script_product_mappings')
  9037. ->where('script_id', $script_id)
  9038. ->pluck('product_id')
  9039. ->unique()
  9040. ->toArray();
  9041. if (empty($productIds)) {
  9042. return [];
  9043. }
  9044. $products = DB::table('mp_products')
  9045. ->whereIn('id', $productIds)
  9046. ->where('is_deleted', 0)
  9047. ->get();
  9048. foreach ($products as $product) {
  9049. $typeName = $typeNames[$product->product] ?? 'unknown';
  9050. if (!isset($stats[$typeName])) {
  9051. $stats[$typeName] = ['total' => 0, 'success' => 0, 'completed' => 0];
  9052. }
  9053. $stats[$typeName]['total']++;
  9054. if ($product->pic_task_status === '生成成功') {
  9055. $stats[$typeName]['success']++;
  9056. $stats[$typeName]['completed']++;
  9057. } elseif ($product->pic_task_status === '生成失败') {
  9058. $stats[$typeName]['completed']++;
  9059. }
  9060. }
  9061. foreach ($stats as $typeName => $stat) {
  9062. if ($stat['total'] === 0) {
  9063. unset($stats[$typeName]);
  9064. }
  9065. }
  9066. return $stats;
  9067. }
  9068. /**
  9069. * 轮询资产图片生成任务状态(SSE流式返回)
  9070. * 只通过查询数据库获取任务状态,不主动调用API
  9071. *
  9072. * @param int $script_id 剧本ID
  9073. * @param string $script_name 剧本名称
  9074. * @param array $productTaskMap 资产ID到任务ID的映射
  9075. * @param array $type_folder_ids 类型文件夹ID映射
  9076. * @param int|null $taskCenterId 任务中心ID
  9077. * @param array $initExtra 追加到 init 事件中的额外数据
  9078. * @param array $completeExtra 追加到 complete、timeout 事件中的额外数据
  9079. * @return \Generator
  9080. */
  9081. private function pollProductImageTasks($script_id, $script_name, $productTaskMap, $type_folder_ids, $taskCenterId = null, array $initExtra = [], array $completeExtra = []) {
  9082. $startTime = time();
  9083. $timeout = 1800; // 30分钟超时
  9084. $pollInterval = 10; // 10秒轮询一次
  9085. $lastStatus = []; // 记录上次的状态,用于判断是否有变化
  9086. // 流一开始即返回 init 事件(saveScriptProducts 场景下携带任务中心ID)
  9087. if ($taskCenterId) {
  9088. $initResponse = array_merge([
  9089. 'type' => 'init',
  9090. 'script_id' => $script_id,
  9091. 'script_name' => $script_name,
  9092. 'timestamp' => date('Y-m-d H:i:s'),
  9093. 'task_center_id' => (int)$taskCenterId,
  9094. ], $initExtra);
  9095. yield "data: " . json_encode($initResponse, JSON_UNESCAPED_UNICODE) . "\n\n";
  9096. }
  9097. // 定义类型名称映射
  9098. $typeNames = [
  9099. 1 => 'roles', // 角色
  9100. 2 => 'scenes', // 场景
  9101. 3 => 'props' // 道具
  9102. ];
  9103. while (time() - $startTime < $timeout) {
  9104. sleep($pollInterval);
  9105. // 从 mp_script_product_mappings 表获取该剧本的所有资产ID
  9106. $mappings = DB::table('mp_script_product_mappings')
  9107. ->where('script_id', $script_id)
  9108. ->pluck('product_id')
  9109. ->unique()
  9110. ->toArray();
  9111. if (empty($mappings)) {
  9112. dLog('anime')->warning('该剧本没有关联的资产', [
  9113. 'script_id' => $script_id,
  9114. 'script_name' => $script_name
  9115. ]);
  9116. break;
  9117. }
  9118. // 查询所有资产的当前状态
  9119. $products = DB::table('mp_products')
  9120. ->whereIn('id', $mappings)
  9121. ->where('is_deleted', 0)
  9122. ->get();
  9123. // 统计各类型的状态(使用类型名称作为键名)
  9124. $stats = [
  9125. 'character' => ['total' => 0, 'success' => 0, 'completed' => 0], // 角色
  9126. 'scene' => ['total' => 0, 'success' => 0, 'completed' => 0], // 场景
  9127. 'prop' => ['total' => 0, 'success' => 0, 'completed' => 0], // 道具
  9128. ];
  9129. $allCompleted = true;
  9130. $hasStatusChange = false;
  9131. foreach ($products as $product) {
  9132. $type = $product->product;
  9133. $typeName = $typeNames[$type] ?? 'unknown'; // 使用 unknown 作为未知类型
  9134. // 如果类型名称不在 stats 中,初始化
  9135. if (!isset($stats[$typeName])) {
  9136. $stats[$typeName] = ['total' => 0, 'success' => 0, 'completed' => 0];
  9137. }
  9138. $stats[$typeName]['total']++;
  9139. $task_id = $product->pic_task_id;
  9140. $currentStatus = $product->pic_task_status;
  9141. // 检查状态是否有变化
  9142. if (!isset($lastStatus[$product->id]) || $lastStatus[$product->id] !== $currentStatus) {
  9143. $hasStatusChange = true;
  9144. $lastStatus[$product->id] = $currentStatus;
  9145. }
  9146. // 如果是生成中,查询任务表状态
  9147. if ($currentStatus === '生成中' && $task_id) {
  9148. // 只查询数据库,不调用API
  9149. $task = DB::table('mp_generate_pic_tasks')
  9150. ->where('id', $task_id)
  9151. ->first();
  9152. if ($task) {
  9153. // 检查任务状态
  9154. if ($task->status === 'success' && $task->result_url) {
  9155. // 解析图片URL
  9156. $result_urls = $task->result_url;
  9157. if (is_string($result_urls)) {
  9158. $result_urls = json_decode($result_urls, true);
  9159. }
  9160. $img_url = is_array($result_urls) ? $result_urls[0] : $task->result_url;
  9161. // 更新资产表状态
  9162. DB::table('mp_products')
  9163. ->where('id', $product->id)
  9164. ->update([
  9165. 'pic_task_status' => '生成成功',
  9166. 'url' => $img_url,
  9167. 'updated_at' => now()
  9168. ]);
  9169. $stats[$typeName]['success']++;
  9170. $stats[$typeName]['completed']++;
  9171. $hasStatusChange = true;
  9172. dLog('anime')->info('资产图片生成成功', [
  9173. 'product_id' => $product->id,
  9174. 'task_id' => $task_id,
  9175. 'img_url' => $img_url
  9176. ]);
  9177. } elseif ($task->status === 'failed') {
  9178. // 更新资产表状态
  9179. DB::table('mp_products')
  9180. ->where('id', $product->id)
  9181. ->update([
  9182. 'pic_task_status' => '生成失败',
  9183. 'updated_at' => now()
  9184. ]);
  9185. $stats[$typeName]['completed']++;
  9186. $hasStatusChange = true;
  9187. dLog('anime')->warning('资产图片生成失败', [
  9188. 'product_id' => $product->id,
  9189. 'task_id' => $task_id,
  9190. 'error' => $task->error_message ?? '未知错误'
  9191. ]);
  9192. } else {
  9193. // 任务还在处理中
  9194. $allCompleted = false;
  9195. }
  9196. } else {
  9197. // 任务不存在,标记为失败
  9198. DB::table('mp_products')
  9199. ->where('id', $product->id)
  9200. ->update([
  9201. 'pic_task_status' => '生成失败',
  9202. 'updated_at' => now()
  9203. ]);
  9204. $stats[$typeName]['completed']++;
  9205. $hasStatusChange = true;
  9206. dLog('anime')->error('图片生成任务不存在', [
  9207. 'product_id' => $product->id,
  9208. 'task_id' => $task_id
  9209. ]);
  9210. }
  9211. } elseif ($currentStatus === '生成成功') {
  9212. $stats[$typeName]['success']++;
  9213. $stats[$typeName]['completed']++;
  9214. } elseif ($currentStatus === '生成失败') {
  9215. $stats[$typeName]['completed']++;
  9216. } else {
  9217. // 其他状态也认为未完成
  9218. $allCompleted = false;
  9219. }
  9220. }
  9221. // 移除没有数据的类型(total=0)
  9222. foreach ($stats as $typeName => $stat) {
  9223. if ($stat['total'] === 0) {
  9224. unset($stats[$typeName]);
  9225. }
  9226. }
  9227. // 如果有状态变化,发送 SSE 更新
  9228. if ($hasStatusChange) {
  9229. $eventType = $allCompleted ? 'complete' : 'update';
  9230. $response = [
  9231. 'type' => $eventType,
  9232. 'script_id' => $script_id,
  9233. 'script_name' => $script_name,
  9234. 'stats' => $stats,
  9235. 'timestamp' => date('Y-m-d H:i:s')
  9236. ];
  9237. if ($taskCenterId) {
  9238. $response['task_center_id'] = $taskCenterId;
  9239. }
  9240. if ($eventType === 'complete') {
  9241. $response = array_merge($response, $completeExtra);
  9242. }
  9243. yield "data: " . json_encode($response, JSON_UNESCAPED_UNICODE) . "\n\n";
  9244. dLog('anime')->info('SSE更新', [
  9245. 'event_type' => $eventType,
  9246. 'script_id' => $script_id,
  9247. 'script_name' => $script_name,
  9248. 'stats' => $stats
  9249. ]);
  9250. if ($allCompleted) {
  9251. dLog('anime')->info('所有资产图片生成任务已完成', [
  9252. 'script_id' => $script_id,
  9253. 'script_name' => $script_name,
  9254. 'stats' => $stats
  9255. ]);
  9256. // 全部任务完成,更新任务中心状态和结果
  9257. $this->finishScriptProductTask($taskCenterId, $response);
  9258. break;
  9259. }
  9260. }
  9261. }
  9262. // 超时处理
  9263. if (time() - $startTime >= $timeout && !$allCompleted) {
  9264. $response = [
  9265. 'type' => 'timeout',
  9266. 'message' => '部分任务超时,请稍后查看结果',
  9267. 'script_id' => $script_id,
  9268. 'script_name' => $script_name,
  9269. 'timestamp' => date('Y-m-d H:i:s')
  9270. ];
  9271. if ($taskCenterId) {
  9272. $response['task_center_id'] = $taskCenterId;
  9273. }
  9274. $response = array_merge($response, $completeExtra);
  9275. yield "data: " . json_encode($response, JSON_UNESCAPED_UNICODE) . "\n\n";
  9276. dLog('anime')->warning('资产图片生成任务超时', [
  9277. 'script_id' => $script_id,
  9278. 'script_name' => $script_name,
  9279. 'timeout' => $timeout
  9280. ]);
  9281. // 超时未完成,更新任务中心状态和结果
  9282. $this->finishScriptProductTask($taskCenterId, $response, true);
  9283. }
  9284. }
  9285. /**
  9286. * 定时任务:检查产品图片生成任务状态并更新产品记录
  9287. * 扫描 mp_products 中 pic_task_id 非空且 pic_task_status 为生成中的记录,
  9288. * 通过 pic_task_id 查询 mp_generate_pic_tasks 获取生成结果,按结果更新状态
  9289. *
  9290. * @return array ['total' => 总数, 'success' => 成功数, 'failed' => 失败数, 'pending' => 待处理数]
  9291. */
  9292. public function checkProductPicTasks() {
  9293. // 查询所有生成中的产品图片任务
  9294. $products = DB::table('mp_products')
  9295. ->whereNotNull('pic_task_id')
  9296. ->where('pic_task_status', '生成中')
  9297. ->where('is_deleted', 0)
  9298. ->get();
  9299. $stats = [
  9300. 'total' => $products->count(),
  9301. 'success' => 0,
  9302. 'failed' => 0,
  9303. 'pending' => 0,
  9304. ];
  9305. foreach ($products as $product) {
  9306. try {
  9307. $task_id = $product->pic_task_id;
  9308. // 通过 pic_task_id 查询图片生成任务结果
  9309. $task = DB::table('mp_generate_pic_tasks')
  9310. ->where('id', $task_id)
  9311. ->first();
  9312. if ($task) {
  9313. if ($task->status === 'success' && $task->result_url) {
  9314. // 解析图片URL
  9315. $result_urls = $task->result_url;
  9316. if (is_string($result_urls)) {
  9317. $result_urls = json_decode($result_urls, true);
  9318. }
  9319. $img_url = is_array($result_urls) ? ($result_urls[0] ?? $task->result_url) : $task->result_url;
  9320. // 更新资产表状态
  9321. DB::table('mp_products')
  9322. ->where('id', $product->id)
  9323. ->update([
  9324. 'pic_task_status' => '生成成功',
  9325. 'url' => $img_url,
  9326. 'updated_at' => now()
  9327. ]);
  9328. $stats['success']++;
  9329. dLog('anime')->info('资产图片生成成功', [
  9330. 'product_id' => $product->id,
  9331. 'task_id' => $task_id,
  9332. 'img_url' => $img_url
  9333. ]);
  9334. } elseif ($task->status === 'failed') {
  9335. // 更新资产表状态
  9336. DB::table('mp_products')
  9337. ->where('id', $product->id)
  9338. ->update([
  9339. 'pic_task_status' => '生成失败',
  9340. 'updated_at' => now()
  9341. ]);
  9342. $stats['failed']++;
  9343. dLog('anime')->warning('资产图片生成失败', [
  9344. 'product_id' => $product->id,
  9345. 'task_id' => $task_id,
  9346. 'error' => $task->error_message ?? '未知错误'
  9347. ]);
  9348. } else {
  9349. // 任务还在处理中
  9350. $stats['pending']++;
  9351. }
  9352. } else {
  9353. // 任务不存在,标记为失败
  9354. DB::table('mp_products')
  9355. ->where('id', $product->id)
  9356. ->update([
  9357. 'pic_task_status' => '生成失败',
  9358. 'updated_at' => now()
  9359. ]);
  9360. $stats['failed']++;
  9361. dLog('anime')->error('图片生成任务不存在', [
  9362. 'product_id' => $product->id,
  9363. 'task_id' => $task_id
  9364. ]);
  9365. }
  9366. } catch (\Exception $e) {
  9367. dLog('anime')->error('检查产品图片生成任务异常', [
  9368. 'product_id' => $product->id,
  9369. 'task_id' => $product->pic_task_id ?? null,
  9370. 'error' => $e->getMessage()
  9371. ]);
  9372. }
  9373. }
  9374. return $stats;
  9375. }
  9376. /**
  9377. * 定时任务:检查任务中心中 saveScriptProducts 类型的任务是否已完成
  9378. *
  9379. * 当保存剧本资产的 SSE 连接中断等原因导致任务中心记录未及时更新时,
  9380. * 通过关联资产的图片生成状态兜底判断任务是否全部完成;
  9381. * 全部完成后更新任务中心的状态和结果(result 与 saveScriptProducts 接口返回保持一致)。
  9382. *
  9383. * @return int 更新的任务中心记录数
  9384. */
  9385. public function checkSaveScriptProductTaskCenters() {
  9386. $updated = 0;
  9387. // 只扫描尚未结束的 saveScriptProducts 任务
  9388. $tasks = DB::table('mp_task_center')
  9389. ->where('task_type', MpTaskCenter::TYPE_SAVE_SCRIPT_PRODUCTS)
  9390. ->whereIn('status', [MpTaskCenter::STATUS_PENDING, MpTaskCenter::STATUS_PROCESSING])
  9391. ->orderBy('id', 'desc')
  9392. ->limit(500)
  9393. ->get();
  9394. // 与 pollProductImageTasks 保持一致的类型名称映射
  9395. $typeNames = [
  9396. 1 => 'roles', // 角色
  9397. 2 => 'scenes', // 场景
  9398. 3 => 'props', // 道具
  9399. ];
  9400. foreach ($tasks as $task) {
  9401. try {
  9402. $taskParams = json_decode((string)$task->params, true);
  9403. $script_id = is_array($taskParams) ? (int)($taskParams['script_id'] ?? 0) : 0;
  9404. if (!$script_id) {
  9405. dLog('command')->warning('saveScriptProducts任务缺少script_id,跳过', [
  9406. 'task_center_id' => $task->id,
  9407. ]);
  9408. continue;
  9409. }
  9410. // 获取该剧本关联的全部资产ID
  9411. $productIds = DB::table('mp_script_product_mappings')
  9412. ->where('script_id', $script_id)
  9413. ->pluck('product_id')
  9414. ->unique()
  9415. ->toArray();
  9416. if (empty($productIds)) {
  9417. // 剧本没有关联资产,不视为完成,等待下一次检查
  9418. continue;
  9419. }
  9420. $products = DB::table('mp_products')
  9421. ->whereIn('id', $productIds)
  9422. ->where('is_deleted', 0)
  9423. ->get();
  9424. $stats = [];
  9425. $allCompleted = true;
  9426. foreach ($products as $product) {
  9427. $typeName = $typeNames[$product->product] ?? 'unknown';
  9428. if (!isset($stats[$typeName])) {
  9429. $stats[$typeName] = ['total' => 0, 'success' => 0, 'completed' => 0];
  9430. }
  9431. $stats[$typeName]['total']++;
  9432. if ($product->pic_task_status === '生成成功') {
  9433. $stats[$typeName]['success']++;
  9434. $stats[$typeName]['completed']++;
  9435. } elseif ($product->pic_task_status === '生成失败') {
  9436. $stats[$typeName]['completed']++;
  9437. } else {
  9438. // 仍有资产在生成中或未生成,任务未完成
  9439. $allCompleted = false;
  9440. }
  9441. }
  9442. if (!$allCompleted) {
  9443. continue;
  9444. }
  9445. // 全部完成,更新任务中心状态和结果(与接口返回结果保持一致)
  9446. $script = DB::table('mp_scripts')
  9447. ->where('id', $script_id)
  9448. ->where('is_deleted', 0)
  9449. ->first();
  9450. $script_name = $script->script_name ?? 'script_' . $script_id;
  9451. $this->finishScriptProductTask($task->id, [
  9452. 'type' => 'complete',
  9453. 'script_id' => $script_id,
  9454. 'script_name' => $script_name,
  9455. 'stats' => $stats,
  9456. 'timestamp' => date('Y-m-d H:i:s'),
  9457. 'task_center_id' => (int)$task->id,
  9458. ]);
  9459. $updated++;
  9460. dLog('command')->info('saveScriptProducts任务已完成,更新任务中心', [
  9461. 'task_center_id' => $task->id,
  9462. 'script_id' => $script_id,
  9463. 'stats' => $stats,
  9464. ]);
  9465. } catch (\Exception $e) {
  9466. dLog('command')->error('检查saveScriptProducts任务中心状态异常', [
  9467. 'task_center_id' => $task->id,
  9468. 'error' => $e->getMessage(),
  9469. ]);
  9470. }
  9471. }
  9472. return $updated;
  9473. }
  9474. /**
  9475. * 获取剧本关联的资产列表
  9476. * @param array $data 请求参数
  9477. * @return array
  9478. */
  9479. public function getScriptProducts($data) {
  9480. $uid = Site::getUid();
  9481. $cpid = Site::getCpid();
  9482. $script_id = getProp($data, 'script_id');
  9483. $episode_number = getProp($data, 'episode_number');
  9484. if (!$script_id) {
  9485. Utils::throwError('20003:请提供剧本ID');
  9486. }
  9487. // 验证剧本是否存在
  9488. $script = DB::table('mp_scripts')
  9489. ->where('id', $script_id)
  9490. ->where('is_deleted', 0)
  9491. ->first();
  9492. if (!$script) {
  9493. Utils::throwError('20003:剧本不存在');
  9494. }
  9495. // 联表查询资产信息
  9496. $query = DB::table('mp_script_product_mappings as mapping')
  9497. ->join('mp_products as product', 'mapping.product_id', '=', 'product.id')
  9498. ->where('mapping.script_id', $script_id)
  9499. ->where('product.cpid', $cpid)
  9500. ->where('product.is_deleted', 0);
  9501. // 如果提供了 episode_number,则过滤指定集数
  9502. if ($episode_number !== null && $episode_number !== '') {
  9503. $query->where('mapping.episode_number', $episode_number);
  9504. }
  9505. $mappings = $query->select(
  9506. 'mapping.script_id',
  9507. 'mapping.product_id',
  9508. 'mapping.episode_number',
  9509. 'product.product_name',
  9510. 'product.type',
  9511. 'product.product',
  9512. 'product.pic_prompt',
  9513. 'product.url',
  9514. 'product.pic_task_id',
  9515. 'product.pic_task_status',
  9516. 'product.three_view_image_url',
  9517. 'mapping.created_at'
  9518. )
  9519. ->orderBy('mapping.product_id', 'asc')
  9520. ->orderBy('mapping.episode_number', 'asc')
  9521. ->get();
  9522. // 按 product_id 分组,合并 episode_number
  9523. $productMap = [];
  9524. foreach ($mappings as $item) {
  9525. $product_id = $item->product_id;
  9526. if (!isset($productMap[$product_id])) {
  9527. $productMap[$product_id] = [
  9528. 'product_id' => $product_id,
  9529. 'product_name' => $item->product_name,
  9530. 'type' => (int)$item->type,
  9531. 'product' => (int)$item->product,
  9532. 'pic_prompt' => $item->pic_prompt,
  9533. 'url' => $item->url,
  9534. 'pic_task_id' => $item->pic_task_id,
  9535. 'pic_task_status' => $item->pic_task_status,
  9536. 'episode_numbers' => [],
  9537. 'created_at' => $item->created_at,
  9538. ];
  9539. }
  9540. // 添加 episode_number(去重)
  9541. if (!in_array($item->episode_number, $productMap[$product_id]['episode_numbers'])) {
  9542. $productMap[$product_id]['episode_numbers'][] = $item->episode_number;
  9543. }
  9544. }
  9545. // 按类型分组
  9546. $roles = []; // type=1 角色/主体
  9547. $scenes = []; // type=2 场景
  9548. $props = []; // type=3 道具
  9549. foreach ($productMap as $product) {
  9550. // 将 episode_numbers 数组转换为逗号分隔的字符串
  9551. $episodeNumbersStr = implode(',', $product['episode_numbers']);
  9552. // 构造返回数据
  9553. $productData = [
  9554. 'product_id' => $product['product_id'],
  9555. 'product_name' => $product['product_name'],
  9556. 'product' => $product['product'],
  9557. 'pic_prompt' => $product['pic_prompt'],
  9558. 'url' => $product['url'],
  9559. 'pic_task_id' => $product['pic_task_id'],
  9560. 'pic_task_status' => $product['pic_task_status'],
  9561. 'episode_numbers' => $episodeNumbersStr,
  9562. 'created_at' => $product['created_at'],
  9563. ];
  9564. // 根据 type 分类(注意:type 字段表示资产类型,不是文件夹)
  9565. // 根据 product 字段分类(1=角色, 2=场景, 3=道具)
  9566. switch ($product['product']) {
  9567. case 1:
  9568. $roles[] = $productData;
  9569. break;
  9570. case 2:
  9571. $scenes[] = $productData;
  9572. break;
  9573. case 3:
  9574. $props[] = $productData;
  9575. break;
  9576. }
  9577. }
  9578. return [
  9579. 'script_id' => $script_id,
  9580. 'script_name' => $script->script_name ?? '',
  9581. 'roles' => $roles, // 主体
  9582. 'scenes' => $scenes, // 场景
  9583. 'props' => $props, // 道具
  9584. ];
  9585. }
  9586. /**
  9587. * 处理act_content中的{}标记,替换为product_name(图+序号)格式,并收集参考图片
  9588. * @param string $actContent 原始内容
  9589. * @param array $products 产品数组(包含product_name和url)
  9590. * @return array ['content' => 处理后的内容, 'reference_images' => 参考图片数组]
  9591. */
  9592. public function processActContentWithProducts($actContent, $products) {
  9593. if (empty($actContent) || empty($products)) {
  9594. return [
  9595. 'content' => $actContent,
  9596. 'reference_images' => []
  9597. ];
  9598. }
  9599. // 构建产品名称到产品信息的映射
  9600. $product_dict = [];
  9601. foreach ($products as $product) {
  9602. $product_name = getProp($product, 'product_name');
  9603. if ($product_name) {
  9604. $product_dict[$product_name] = [
  9605. // 优先使用三视图图片作为素材/参考图,否则使用原图 url
  9606. 'url' => getProp($product, 'three_view_image_url') ?: getProp($product, 'url'),
  9607. 'voice_prompt' => getProp($product, 'voice_prompt')
  9608. ];
  9609. }
  9610. }
  9611. // 第一步:查找内容中所有 {产品名称} 格式的标记(按出现顺序,去重)
  9612. preg_match_all('/\{([^}]+)\}/u', $actContent, $matches);
  9613. $reference_images = [];
  9614. $product_index_map = []; // 产品名称 => 图片序号的映射
  9615. $voice_prompts = []; // 存储需要添加到开头的voice_prompt信息
  9616. $narrator_voice_prompt = ''; // 单独存储旁白的voice_prompt
  9617. $current_index = 1;
  9618. if (!empty($matches[1])) {
  9619. // 按照在内容中第一次出现的顺序,为每个产品分配序号
  9620. $seen_products = []; // 用于去重
  9621. foreach ($matches[1] as $product_name) {
  9622. // 跳过已处理的产品
  9623. if (isset($seen_products[$product_name])) {
  9624. continue;
  9625. }
  9626. $seen_products[$product_name] = true;
  9627. // 检查产品是否在字典中
  9628. if (isset($product_dict[$product_name])) {
  9629. $url = $product_dict[$product_name]['url'];
  9630. $voice_prompt = $product_dict[$product_name]['voice_prompt'];
  9631. // 处理voice_prompt(旁白不在这里处理,旁白是公共的在后面单独处理)
  9632. if (!empty($voice_prompt) && $product_name !== '旁白') {
  9633. $voice_prompts[] = $product_name . ':' . $voice_prompt . "\n";
  9634. }
  9635. // 只有URL非空才分配序号和添加到参考图片
  9636. if (!empty($url)) {
  9637. // 检查URL是否已经在reference_images中(去重)
  9638. if (!in_array($url, $reference_images)) {
  9639. $reference_images[] = $url;
  9640. $product_index_map[$product_name] = $current_index;
  9641. $current_index++;
  9642. } else {
  9643. // URL重复,找到已有的序号
  9644. $existing_index = array_search($url, $reference_images) + 1;
  9645. $product_index_map[$product_name] = $existing_index;
  9646. }
  9647. } else {
  9648. // URL为空,不分配序号(后续直接去掉{})
  9649. $product_index_map[$product_name] = 0;
  9650. }
  9651. } else {
  9652. // 产品不在字典中,不分配序号
  9653. $product_index_map[$product_name] = 0;
  9654. }
  9655. }
  9656. }
  9657. // 第二步:替换内容中的 {产品名称}
  9658. $processedContent = $actContent;
  9659. foreach ($product_index_map as $product_name => $index) {
  9660. $escaped_name = preg_quote($product_name, '/');
  9661. if ($index > 0) {
  9662. // 有图片,替换为:产品名称(图X)
  9663. $replacement = $product_name . '<图片' . $index . '>';
  9664. } else {
  9665. // 无图片,只保留产品名称
  9666. $replacement = $product_name;
  9667. }
  9668. // 替换所有 {产品名称} 为处理后的格式
  9669. $processedContent = preg_replace('/\{' . $escaped_name . '\}/u', $replacement, $processedContent);
  9670. }
  9671. // 第三步:单独处理旁白的voice_prompt(旁白是公共的,不依赖product_dict)
  9672. foreach ($products as $product) {
  9673. $product_name = getProp($product, 'product_name');
  9674. $voice_prompt = getProp($product, 'voice_prompt');
  9675. if ($product_name === '旁白' && !empty($voice_prompt)) {
  9676. $narrator_voice_prompt = $product_name . ':' . $voice_prompt . "\n";
  9677. break; // 找到旁白后退出循环
  9678. }
  9679. }
  9680. // 第四步:将voice_prompt信息添加到内容最前面
  9681. $voice_prompt_prefix = '';
  9682. if (!empty($voice_prompts)) {
  9683. $voice_prompt_prefix .= implode('', $voice_prompts);
  9684. }
  9685. // 旁白的voice_prompt放在最后
  9686. if (!empty($narrator_voice_prompt)) {
  9687. $voice_prompt_prefix .= $narrator_voice_prompt;
  9688. }
  9689. // 如果有voice_prompt信息,添加到内容开头
  9690. if (!empty($voice_prompt_prefix)) {
  9691. $processedContent = "人物音色:\n" . $voice_prompt_prefix . "\n" . $processedContent;
  9692. }
  9693. return [
  9694. 'content' => $processedContent,
  9695. 'reference_images' => $reference_images
  9696. ];
  9697. }
  9698. public function saveActVideoGenerateParams($data) {
  9699. $episode_id = getProp($data, 'episode_id');
  9700. $model = getProp($data, 'video_model');
  9701. $valid_models = DB::table('mp_video_models')->where('ace_mode', 1)->select('model')->pluck('model')->toArray();
  9702. if (!in_array($model, $valid_models)) {
  9703. Utils::throwError('20003:该模型不可用');
  9704. }
  9705. // 验证模型是否在可用模型表中
  9706. if (!DB::table('mp_video_models')->where('model', $model)->where('is_enabled', 1)->exists()) {
  9707. Utils::throwError('20003:该模型已不可用,请更换!');
  9708. }
  9709. $video_resolution = getProp($data, 'video_resolution', '720p');
  9710. $ratio = getProp($data, 'ratio');
  9711. if (!$ratio) $ratio = '9:16';
  9712. $episode = DB::table('mp_anime_episodes')->where('id', $episode_id)->first(['anime_id']);
  9713. if (!$episode) {
  9714. Utils::throwError('20003:分集不存在');
  9715. }
  9716. dLog('anime')->info('保存分集视频参数', $data);
  9717. try {
  9718. DB::beginTransaction();
  9719. $result = DB::table('mp_anime_episodes')->where('id', $episode_id)->update([
  9720. 'video_model' => $model,
  9721. 'video_resolution' => $video_resolution,
  9722. 'ratio' => $ratio,
  9723. 'updated_at' => date('Y-m-d H:i:s')
  9724. ]);
  9725. if ($result === false) {
  9726. Utils::throwError('20003:分集视频参数保存失败');
  9727. }
  9728. // 同步更新mp_animes表
  9729. $anime_result = DB::table('mp_animes')->where('id', $episode->anime_id)->update([
  9730. 'video_model' => $model,
  9731. 'video_resolution' => $video_resolution,
  9732. 'video_ratio' => $ratio,
  9733. 'updated_at' => date('Y-m-d H:i:s')
  9734. ]);
  9735. if ($anime_result === false) {
  9736. Utils::throwError('20003:动漫视频参数保存失败');
  9737. }
  9738. } catch (\Exception $e) {
  9739. DB::rollBack();
  9740. Utils::throwError('20003:'.$e->getMessage());
  9741. }
  9742. DB::commit();
  9743. return $result;
  9744. }
  9745. public function confirmActs($data) {
  9746. $episode_id = getProp($data, 'episode_id');
  9747. $episode = DB::table('mp_anime_episodes')->where('id', $episode_id)->first();
  9748. if (!$episode) {
  9749. Utils::throwError('20003:分集不存在');
  9750. }
  9751. $roles = json_decode(getProp($episode, 'roles'), true) ?: [];
  9752. $scenes = json_decode(getProp($episode, 'scenes'), true) ?: [];
  9753. $props = json_decode(getProp($episode, 'props'), true) ?: [];
  9754. // 确认前校验并等待角色、场景、道具图片全部生成(参照 episodePicsInfo 更新与监控逻辑),未全部生成不得继续后续逻辑
  9755. $this->waitForEpisodeAssetsImagesReady($episode_id, $roles, $scenes, $props);
  9756. // 获取所有片段数据
  9757. $acts = DB::table('mp_episode_segments')->where('episode_id', $episode_id)->orderBy('act_number')->get();
  9758. // 先构建完整的 products(角色、场景、道具、extra_products,并用资产库映射覆盖),
  9759. // 再处理每个片段的 act_content,避免 extra_products 等资产名未被格式化为 {资产名}
  9760. // 合并角色、场景、道具和extra_products作为products,统一字段名为product_name
  9761. // extra_products优先级更高,会覆盖同名的roles、scenes和props
  9762. $products = [];
  9763. // 先处理角色数组
  9764. foreach ($roles as $role) {
  9765. $product = $role;
  9766. // 将role字段重命名为product_name
  9767. if (isset($product['role'])) {
  9768. $product['product_name'] = $product['role'];
  9769. unset($product['role']);
  9770. $product['product'] = 1; // 标记类型为角色
  9771. $products[$product['product_name']] = $product; // 使用product_name作为key便于后续覆盖
  9772. }
  9773. }
  9774. // 处理场景数组
  9775. foreach ($scenes as $scene) {
  9776. $product = $scene;
  9777. // 将scene字段重命名为product_name
  9778. if (isset($product['scene'])) {
  9779. $product['product_name'] = $product['scene'];
  9780. unset($product['scene']);
  9781. $product['product'] = 2; // 标记类型为场景
  9782. $products[$product['product_name']] = $product; // 使用product_name作为key便于后续覆盖
  9783. }
  9784. }
  9785. // 处理道具数组(逻辑与场景一致)
  9786. foreach ($props as $prop) {
  9787. $product = $prop;
  9788. // 将prop字段重命名为product_name
  9789. if (isset($product['prop'])) {
  9790. $product['product_name'] = $product['prop'];
  9791. unset($product['prop']);
  9792. $product['product'] = 3; // 标记类型为道具
  9793. $products[$product['product_name']] = $product; // 使用product_name作为key便于后续覆盖
  9794. }
  9795. }
  9796. // extra_products优先级更高,直接覆盖同名的roles和scenes
  9797. $extra_products = json_decode(getProp($episode, 'extra_products', '[]'), true) ?: [];
  9798. foreach ($extra_products as $extra_product) {
  9799. $product_name = getProp($extra_product, 'product_name');
  9800. if ($product_name) {
  9801. $products[$product_name] = $extra_product; // 覆盖同名数据
  9802. }
  9803. }
  9804. // mp_script_product_mappings 信息优先级更高:
  9805. // 获取当前剧集所属动漫剧本下、与本集资产同名的资产库最新数据(url/三视图/提示词等),
  9806. // 覆盖分集 JSON 中保存的同名旧快照;分集内独有的 description、voice_prompt 等字段保留
  9807. $anime = DB::table('mp_animes')->where('id', getProp($episode, 'anime_id'))->first();
  9808. $script_id = $anime ? (int)getProp($anime, 'script_id', 0) : 0;
  9809. if ($script_id && !empty($products)) {
  9810. $currentProductNames = array_keys($products);
  9811. $normalizeName = function($name) {
  9812. return trim(preg_replace(
  9813. '/^[\s*\[\]【】[]{}{}\x{3000}]+|[\s*\[\]【】[]{}{}\x{3000}]+$/u',
  9814. '',
  9815. trim((string)$name)
  9816. ));
  9817. };
  9818. $mappingItems = DB::table('mp_script_product_mappings as mapping')
  9819. ->join('mp_products as product', 'mapping.product_id', '=', 'product.id')
  9820. ->where('mapping.script_id', $script_id)
  9821. ->where('product.is_deleted', 0)
  9822. ->whereIn('product.product_name', $currentProductNames)
  9823. ->select(
  9824. 'mapping.product_id',
  9825. 'product.product_name',
  9826. 'product.product',
  9827. 'product.pic_prompt',
  9828. 'product.url',
  9829. 'product.three_view_image_url',
  9830. )
  9831. ->get();
  9832. $mappingByName = [];
  9833. foreach ($mappingItems as $mappingItem) {
  9834. $normalizedName = $normalizeName($mappingItem->product_name);
  9835. if (!$normalizedName) continue;
  9836. $mappingByName[$normalizedName] = [
  9837. 'product_id' => (int)$mappingItem->product_id,
  9838. 'product_name' => $mappingItem->product_name,
  9839. 'product' => (int)$mappingItem->product,
  9840. 'pic_prompt' => $mappingItem->pic_prompt ?? '',
  9841. 'url' => $mappingItem->url ?? '',
  9842. 'three_view_image_url' => $mappingItem->three_view_image_url ?? '',
  9843. ];
  9844. }
  9845. foreach ($products as $key => &$product) {
  9846. $normalizedKey = $normalizeName($key);
  9847. if ($normalizedKey && isset($mappingByName[$normalizedKey])) {
  9848. $product = array_merge($product, $mappingByName[$normalizedKey]);
  9849. }
  9850. }
  9851. unset($product);
  9852. }
  9853. // 兼容返回 three_view_image_url 字段(旧数据可能没有该键,统一补空值)
  9854. foreach ($products as &$product) {
  9855. if (!isset($product['three_view_image_url'])) {
  9856. $product['three_view_image_url'] = '';
  9857. }
  9858. }
  9859. unset($product);
  9860. // 重新索引数组(去除key)
  9861. $products = array_values($products);
  9862. // 基于构建完成的 products 收集所有资产名称(含 extra_products 中的资产)
  9863. $product_names = [];
  9864. foreach ($products as $product) {
  9865. $product_name = getProp($product, 'product_name');
  9866. if ($product_name && $product_name !== '旁白') {
  9867. $product_names[] = $product_name;
  9868. }
  9869. }
  9870. // 去重并按长度降序排序(避免短名称先匹配到长名称的一部分)
  9871. $product_names = array_unique($product_names);
  9872. usort($product_names, function($a, $b) {
  9873. return mb_strlen($b) - mb_strlen($a);
  9874. });
  9875. try {
  9876. DB::beginTransaction();
  9877. // 处理每个片段
  9878. foreach ($acts as $act) {
  9879. $act_content = getProp($act, 'act_content');
  9880. if (!$act_content) continue;
  9881. $processed_content = $act_content;
  9882. // 统一替换所有资产名称为 {资产名} 格式
  9883. // 使用占位符避免嵌套替换问题
  9884. $placeholder_map = [];
  9885. $placeholder_index = 0;
  9886. foreach ($product_names as $product_name) {
  9887. // 转义特殊字符
  9888. $escaped_product = preg_quote($product_name, '/');
  9889. // 检查是否匹配且未被 {} 包裹
  9890. $processed_content = preg_replace_callback(
  9891. '/(?<![{])(' . $escaped_product . ')(?![}])/u',
  9892. function($matches) use (&$placeholder_map, &$placeholder_index) {
  9893. // 使用唯一占位符
  9894. $placeholder = '<<<PLACEHOLDER_' . $placeholder_index . '>>>';
  9895. $placeholder_map[$placeholder] = '{' . $matches[1] . '}';
  9896. $placeholder_index++;
  9897. return $placeholder;
  9898. },
  9899. $processed_content
  9900. );
  9901. }
  9902. // 将所有占位符替换回实际内容
  9903. foreach ($placeholder_map as $placeholder => $replacement) {
  9904. $processed_content = str_replace($placeholder, $replacement, $processed_content);
  9905. }
  9906. // 处理【镜头X】或【分镜X】重新编号为从1开始的连续整数【镜头X】
  9907. $shot_counter = 0;
  9908. $processed_content = preg_replace_callback(
  9909. '/【(?:镜头|分镜)(\d+)】/u',
  9910. function($matches) use (&$shot_counter) {
  9911. $shot_counter++;
  9912. return '【镜头' . $shot_counter . '】';
  9913. },
  9914. $processed_content
  9915. );
  9916. // 更新数据库
  9917. $boolen = DB::table('mp_episode_segments')
  9918. ->where('id', $act->id)
  9919. ->update([
  9920. 'act_show_content' => $processed_content,
  9921. 'updated_at' => date('Y-m-d H:i:s')
  9922. ]);
  9923. if (!$boolen) {
  9924. Utils::throwError('20003:片段处理失败');
  9925. }
  9926. }
  9927. }catch (\Exception $e) {
  9928. DB::rollBack();
  9929. Utils::throwError('20003:'.$e->getMessage());
  9930. }
  9931. $boolen1 = DB::table('mp_anime_episodes')->where('id', $episode_id)->update([
  9932. 'is_generated' => 1,
  9933. 'updated_at' => date('Y-m-d H:i:s')
  9934. ]);
  9935. if (!$boolen1) {
  9936. DB::rollBack();
  9937. Utils::throwError('20003:分集处理失败!');
  9938. }
  9939. DB::commit();
  9940. // 重新查询更新后的片段数据
  9941. $acts = DB::table('mp_episode_segments')->where('episode_id', $episode_id)->orderBy('act_number')->get();
  9942. // 构建返回的acts数组
  9943. $return_acts = [];
  9944. foreach ($acts as $act) {
  9945. $return_acts[] = [
  9946. 'act_id' => getProp($act, 'id'),
  9947. 'act_number' => getProp($act, 'act_number'),
  9948. 'act_duration' => getProp($act, 'video_duration') ? getProp($act, 'video_duration') : getProp($act, 'act_duration'),
  9949. 'act_show_content' => getProp($act, 'act_show_content'),
  9950. 'video_url' => getProp($act, 'video_url'),
  9951. 'video_duration' => getProp($act, 'video_duration'),
  9952. 'video_time_point_start' => getProp($act, 'video_time_point_start'),
  9953. 'video_time_point_end' => getProp($act, 'video_time_point_end'),
  9954. ];
  9955. }
  9956. return [
  9957. 'anime_id' => getProp($episode, 'anime_id'),
  9958. 'episode_id' => $episode_id,
  9959. 'title' => getProp($episode, 'title'),
  9960. 'episode_number' => getProp($episode, 'episode_number'),
  9961. 'is_generated' => getProp($episode, 'is_generated'),
  9962. 'video_params' => [
  9963. 'video_model' => getProp($episode, 'video_model'),
  9964. 'video_resolution' => getProp($episode, 'video_resolution'),
  9965. 'ratio' => getProp($episode, 'ratio'),
  9966. ],
  9967. 'products' => $products,
  9968. 'acts' => $return_acts
  9969. ];
  9970. }
  9971. /**
  9972. * 参照 episodePicsInfo 的更新与监控逻辑:
  9973. * 每5秒查询一次角色/场景/道具的图片任务状态,任务成功后将图片URL回填到对应资产并写回分集表。
  9974. * 所有需要图片的资产均已生成(url 非空)才返回;最多等待1分钟,仍有图片未生成则直接报错。
  9975. */
  9976. private function waitForEpisodeAssetsImagesReady($episode_id, &$roles, &$scenes, &$props) {
  9977. $pollInterval = 5; // 每5秒查询一次
  9978. $maxWaitSeconds = 60; // 最多持续1分钟
  9979. $startTime = time();
  9980. while (true) {
  9981. // 从数据库读取最新数据,兼容后台 Anime:checkImgUrl 等任务对角色/场景/道具图片URL的更新
  9982. $episode = DB::table('mp_anime_episodes')->where('id', $episode_id)->first();
  9983. if (!$episode) {
  9984. Utils::throwError('20003:分集不存在');
  9985. }
  9986. $roles = json_decode(getProp($episode, 'roles'), true) ?: [];
  9987. $scenes = json_decode(getProp($episode, 'scenes'), true) ?: [];
  9988. $props = json_decode(getProp($episode, 'props'), true) ?: [];
  9989. $updated = false;
  9990. $waitingAssets = []; // 任务仍在处理中,可等待后续轮询
  9991. $missingAssets = []; // 无任务或任务已失败/不存在,无法通过等待自动恢复
  9992. $this->refreshEpisodeAssetsImageTasks($roles, 'role', '旁白', $waitingAssets, $missingAssets, $updated);
  9993. $this->refreshEpisodeAssetsImageTasks($scenes, 'scene', '', $waitingAssets, $missingAssets, $updated);
  9994. $this->refreshEpisodeAssetsImageTasks($props, 'prop', '', $waitingAssets, $missingAssets, $updated);
  9995. // 有图片任务结果更新时写回分集表
  9996. if ($updated) {
  9997. DB::table('mp_anime_episodes')->where('id', $episode_id)->update([
  9998. 'roles' => json_encode($roles, JSON_UNESCAPED_UNICODE),
  9999. 'scenes' => json_encode($scenes, JSON_UNESCAPED_UNICODE),
  10000. 'props' => json_encode($props, JSON_UNESCAPED_UNICODE),
  10001. 'updated_at' => date('Y-m-d H:i:s')
  10002. ]);
  10003. }
  10004. // 所有需要图片的资产都已生成,允许继续 confirmActs 后续逻辑
  10005. if (empty($waitingAssets) && empty($missingAssets)) {
  10006. return;
  10007. }
  10008. // 其他任务都已处理完毕,仍有角色、场景或道具图片未生成,统一报错阻止后续逻辑
  10009. if (empty($waitingAssets)) {
  10010. Utils::throwError('20003:还有主体、场景或道具图片未生成,请等待图片生成后重试');
  10011. }
  10012. // 超过1分钟仍未生成完毕,阻止 confirmActs 后续逻辑
  10013. if (time() - $startTime >= $maxWaitSeconds) {
  10014. Utils::throwError('20003:还有主体、场景或道具图片未生成,请等待图片生成后重试');
  10015. }
  10016. sleep($pollInterval);
  10017. }
  10018. }
  10019. /**
  10020. * 参照 episodePicsInfo:遍历单个资产列表,对有图片任务但还没有图片URL的资产查询图片任务结果并回填。
  10021. * 无任务、任务不存在或生成失败的资产记录为缺失项,不在此处直接报错;
  10022. * 仍在处理中的任务记录为等待项,由外层统一等待所有任务完成后,再对缺失资产统一报错。
  10023. */
  10024. private function refreshEpisodeAssetsImageTasks(&$assets, $nameKey, $skipName, &$waitingAssets, &$missingAssets, &$updated) {
  10025. foreach ($assets as &$asset) {
  10026. $assetName = getProp($asset, $nameKey);
  10027. if ($assetName === '' || ($skipName !== '' && $assetName === $skipName)) {
  10028. continue;
  10029. }
  10030. // 已有图片URL的资产视为已生成
  10031. if (getProp($asset, 'url')) {
  10032. continue;
  10033. }
  10034. $task_id = getProp($asset, 'task_id');
  10035. // 没有图片任务且没有图片URL:记录为缺失项,继续遍历其他资产,待其他任务都完成后再统一报错
  10036. if (!$task_id) {
  10037. $missingAssets[] = $assetName;
  10038. continue;
  10039. }
  10040. $task = DB::table('mp_generate_pic_tasks')
  10041. ->where('id', $task_id)
  10042. ->select('status', 'result_url')
  10043. ->first();
  10044. // 任务不存在:同样记录为缺失项,不在此处直接报错
  10045. if (!$task) {
  10046. $missingAssets[] = $assetName;
  10047. continue;
  10048. }
  10049. if ($task->status === 'success') {
  10050. $result_url = getProp($task, 'result_url');
  10051. if ($result_url) {
  10052. $result_urls = is_json($result_url) ? json_decode($result_url, true) : [$result_url];
  10053. if (is_array($result_urls) && !empty($result_urls[0])) {
  10054. $asset['url'] = $result_urls[0];
  10055. $asset['task_status'] = 'success';
  10056. $updated = true;
  10057. continue;
  10058. }
  10059. }
  10060. // 任务成功但没有可用的结果URL,仍视为未生成,继续等待后续轮询结果
  10061. $waitingAssets[] = $assetName;
  10062. } elseif ($task->status === 'failed') {
  10063. // 生成失败:记录为缺失项,待其他任务处理完后统一报错
  10064. $missingAssets[] = $assetName;
  10065. } else {
  10066. // 任务仍在生成中,等待下一次轮询
  10067. $waitingAssets[] = $assetName;
  10068. }
  10069. }
  10070. unset($asset);
  10071. }
  10072. /**
  10073. * 导出动漫剧本为PDF(参照示例PDF版式)
  10074. * @param int $animeId 动漫ID
  10075. * @param int $episodeCount 导出集数,默认8,传-1表示全部
  10076. * @param string|null $savePath 指定保存路径(为空则直接下载输出)
  10077. * @return string|null
  10078. */
  10079. public function exportAnimeScriptAsPdf($animeId, $episodeCount = 8, $savePath = null) {
  10080. // 图片下载与转换可能占用较多内存
  10081. ini_set('memory_limit', '512M');
  10082. $anime = DB::table('mp_animes')->where('id', $animeId)->where('is_deleted', 0)->first();
  10083. if (!$anime) Utils::throwError('20003:该动漫不存在!');
  10084. $anime = (array)$anime;
  10085. // 剧本名去掉末尾"_数字"标识后缀,只保留剧名本身
  10086. $anime['anime_name'] = trim((string)preg_replace('/_\d+$/u', '', getProp($anime, 'anime_name', '')));
  10087. // 获取分集(默认展示版本,按集数升序)
  10088. $episodeQuery = DB::table('mp_anime_episodes')
  10089. ->where('anime_id', $animeId)
  10090. ->where('is_default', 1)
  10091. ->orderBy('episode_number')
  10092. ->orderBy('id');
  10093. if ($episodeCount > 0) {
  10094. $episodeQuery->limit($episodeCount);
  10095. }
  10096. $episodes = $episodeQuery->get()->map(function ($value) {
  10097. return (array)$value;
  10098. })->toArray();
  10099. if (!$episodes) Utils::throwError('20003:该动漫暂无分集数据');
  10100. // 聚合主体/场景/道具列表(前N集内容,按名称去重)
  10101. $roles = $this->mergeEpisodeItems($episodes, 'role');
  10102. $scenes = $this->mergeEpisodeItems($episodes, 'scene');
  10103. $props = $this->mergeEpisodeItems($episodes, 'prop');
  10104. // 组装分集剧本数据
  10105. $episodeScripts = [];
  10106. foreach ($episodes as $episode) {
  10107. $segments = DB::table('mp_episode_segments')
  10108. ->where('anime_id', $animeId)
  10109. ->where('episode_id', $episode['id'])
  10110. ->get();
  10111. // 按act_number分组,同一片段多版本时取最新一条(id最大)
  10112. $acts = [];
  10113. foreach ($segments as $segment) {
  10114. $segment = (array)$segment;
  10115. $actNumber = (int)getProp($segment, 'act_number', 0);
  10116. if ($actNumber <= 0) continue;
  10117. if (!isset($acts[$actNumber]) || (int)$segment['id'] > (int)$acts[$actNumber]['id']) {
  10118. $acts[$actNumber] = [
  10119. 'id' => (int)$segment['id'],
  10120. 'act_number' => $actNumber,
  10121. 'duration' => getProp($segment, 'act_duration', ''),
  10122. 'content' => getProp($segment, 'act_content', ''),
  10123. ];
  10124. }
  10125. }
  10126. ksort($acts);
  10127. // 分镜序号按出现先后重新编号(整集范围内保持连续,兼容【镜头N】/【分镜N】两种格式)
  10128. $segmentCounter = 0;
  10129. foreach ($acts as &$act) {
  10130. $act['content'] = $this->renumberSegmentBlocks($act['content'], $segmentCounter);
  10131. }
  10132. unset($act);
  10133. // 旁白音色:优先取分集roles中"旁白"的voice_prompt,否则从片段内容解析
  10134. $narratorVoice = '';
  10135. $episodeRoles = json_decode(getProp($episode, 'roles', ''), true) ?: [];
  10136. foreach ($episodeRoles as $role) {
  10137. if (getProp($role, 'role') === '旁白') {
  10138. $narratorVoice = trim((string)getProp($role, 'voice_prompt', ''));
  10139. break;
  10140. }
  10141. }
  10142. if ($narratorVoice === '') {
  10143. foreach ($acts as $act) {
  10144. if (preg_match('/旁白音色[::]\s*([^\n]+)/u', $act['content'], $match)) {
  10145. $narratorVoice = trim($match[1]);
  10146. break;
  10147. }
  10148. }
  10149. }
  10150. $episodeScripts[] = [
  10151. 'episode_number' => getProp($episode, 'episode_number'),
  10152. 'title' => getProp($episode, 'title', ''),
  10153. 'act_count' => count($acts),
  10154. 'narrator_voice' => $narratorVoice,
  10155. 'acts' => array_values($acts),
  10156. ];
  10157. }
  10158. // 并发下载列表图片(主体/场景/道具),url => 临时文件
  10159. $imageCache = $this->downloadImagesConcurrently(array_merge($roles, $scenes, $props));
  10160. // 构建PDF
  10161. $pdf = $this->buildAnimeScriptPdf($anime, $roles, $scenes, $props, $episodeScripts, $imageCache);
  10162. // 图片已嵌入PDF,清理临时文件
  10163. foreach ($imageCache as $imgFile) {
  10164. @unlink($imgFile);
  10165. }
  10166. $filename = $anime['anime_name'] . '_' . date('YmdHis');
  10167. if ($savePath) {
  10168. $pdf->Output($savePath, 'F');
  10169. return $savePath;
  10170. }
  10171. // 直接下载输出
  10172. header('Content-Type: application/pdf');
  10173. header("Content-Disposition: attachment; filename*=UTF-8''" . rawurlencode($filename . '.pdf'));
  10174. $pdf->Output($filename . '.pdf', 'D');
  10175. exit();
  10176. }
  10177. /**
  10178. * 聚合分集的主体/场景/道具列表,按名称去重(保留首次出现)
  10179. * @param array $episodes 分集数据
  10180. * @param string $nameKey role|scene|prop
  10181. * @return array
  10182. */
  10183. private function mergeEpisodeItems(array $episodes, $nameKey) {
  10184. $fieldMap = [
  10185. 'role' => 'roles',
  10186. 'scene' => 'scenes',
  10187. 'prop' => 'props',
  10188. ];
  10189. $field = isset($fieldMap[$nameKey]) ? $fieldMap[$nameKey] : $nameKey;
  10190. $items = [];
  10191. foreach ($episodes as $episode) {
  10192. $list = json_decode(getProp($episode, $field, ''), true) ?: [];
  10193. foreach ($list as $item) {
  10194. if (!is_array($item)) continue;
  10195. $name = trim((string)getProp($item, $nameKey, ''));
  10196. if ($name === '') continue;
  10197. // 旁白不进入主体列表(仅作为旁白音色来源)
  10198. if ($nameKey === 'role' && $name === '旁白') continue;
  10199. if (!isset($items[$name])) {
  10200. $items[$name] = $item;
  10201. }
  10202. }
  10203. }
  10204. return array_values($items);
  10205. }
  10206. /**
  10207. * 构建动漫剧本PDF
  10208. * @param array $anime 动漫信息
  10209. * @param array $roles 主体列表
  10210. * @param array $scenes 场景列表
  10211. * @param array $props 道具列表
  10212. * @param array $episodeScripts 分集剧本数据
  10213. * @param array $imageCache 图片缓存(url => 临时文件路径)
  10214. * @return \TCPDF
  10215. */
  10216. private function buildAnimeScriptPdf($anime, $roles, $scenes, $props, $episodeScripts, $imageCache = []) {
  10217. $pdf = new \TCPDF('P', 'mm', 'A4', true, 'UTF-8', false);
  10218. $pdf->SetCreator('动漫剧本导出系统');
  10219. $pdf->SetAuthor('系统');
  10220. $pdf->SetTitle(getProp($anime, 'anime_name', '动漫剧本'));
  10221. $pdf->SetSubject('动漫剧本导出');
  10222. $pdf->SetMargins(15, 15, 15);
  10223. $pdf->SetAutoPageBreak(true, 15);
  10224. // 剧本名
  10225. $pdf->AddPage();
  10226. $pdf->SetFont('simsun', 'B', 20);
  10227. $pdf->Cell(0, 15, getProp($anime, 'anime_name', ''), 0, 1, 'C');
  10228. $pdf->Ln(5);
  10229. // 故事梗概
  10230. $intro = trim((string)getProp($anime, 'intro', ''));
  10231. if ($intro !== '') {
  10232. $this->pdfSectionTitle($pdf, '故事梗概');
  10233. $this->pdfBody($pdf, $intro);
  10234. }
  10235. // 美术风格
  10236. $artStyle = trim((string)getProp($anime, 'art_style', ''));
  10237. if ($artStyle !== '') {
  10238. $this->pdfSectionTitle($pdf, '美术风格');
  10239. $this->pdfBody($pdf, $artStyle);
  10240. }
  10241. // 主体列表(文字+图片)
  10242. $this->pdfSectionTitle($pdf, '主体列表');
  10243. foreach ($roles as $index => $role) {
  10244. $this->pdfBody($pdf, ($index + 1) . '. ' . getProp($role, 'role', '') . ':' . getProp($role, 'description', ''));
  10245. }
  10246. $this->pdfItemImages($pdf, $roles, 'role', $imageCache);
  10247. // 场景列表(文字+图片)
  10248. $this->pdfSectionTitle($pdf, '场景列表');
  10249. foreach ($scenes as $index => $scene) {
  10250. $this->pdfBody($pdf, ($index + 1) . '. ' . getProp($scene, 'scene', '') . ':' . getProp($scene, 'description', ''));
  10251. }
  10252. $this->pdfItemImages($pdf, $scenes, 'scene', $imageCache);
  10253. // 道具列表(文字+图片)
  10254. $this->pdfSectionTitle($pdf, '道具列表');
  10255. foreach ($props as $index => $prop) {
  10256. $this->pdfBody($pdf, ($index + 1) . '. ' . getProp($prop, 'prop', '') . ':' . getProp($prop, 'description', ''));
  10257. }
  10258. $this->pdfItemImages($pdf, $props, 'prop', $imageCache);
  10259. // 分镜剧本
  10260. $this->pdfSectionTitle($pdf, '分镜剧本');
  10261. foreach ($episodeScripts as $episodeScript) {
  10262. $episodeTitle = '第' . getProp($episodeScript, 'episode_number') . '集';
  10263. $episodeTitleRaw = trim((string)getProp($episodeScript, 'title', ''));
  10264. if ($episodeTitleRaw !== '') {
  10265. // title 字段可能已带"第N集"前缀,避免重复
  10266. if (preg_match('/^第\d+集[::\s]/u', $episodeTitleRaw)) {
  10267. $episodeTitle = $episodeTitleRaw;
  10268. } else {
  10269. $episodeTitle .= ':' . $episodeTitleRaw;
  10270. }
  10271. }
  10272. $this->pdfSubTitle($pdf, $episodeTitle, 13);
  10273. $this->pdfBody($pdf, '片段数量:' . getProp($episodeScript, 'act_count', 0));
  10274. if (getProp($episodeScript, 'narrator_voice') !== '') {
  10275. $this->pdfBody($pdf, '旁白音色:' . getProp($episodeScript, 'narrator_voice'));
  10276. }
  10277. foreach (getProp($episodeScript, 'acts', []) as $act) {
  10278. $actTitle = '片段' . getProp($act, 'act_number');
  10279. if (getProp($act, 'duration') !== '' && getProp($act, 'duration') !== null) {
  10280. $actTitle .= ' 时长 ' . getProp($act, 'duration') . 's';
  10281. }
  10282. $this->pdfSubTitle($pdf, $actTitle, 12);
  10283. if (getProp($act, 'content') !== '') {
  10284. $this->pdfBody($pdf, getProp($act, 'content'));
  10285. }
  10286. }
  10287. }
  10288. return $pdf;
  10289. }
  10290. /**
  10291. * PDF章节标题(带分隔线)
  10292. */
  10293. private function pdfSectionTitle($pdf, $title) {
  10294. if ($pdf->GetY() > 230) {
  10295. $pdf->AddPage();
  10296. }
  10297. $pdf->SetFont('simsun', 'B', 15);
  10298. $pdf->Cell(0, 10, $title, 0, 1, 'L');
  10299. $y = $pdf->GetY();
  10300. $pdf->SetLineWidth(0.4);
  10301. $pdf->Line(15, $y, 195, $y);
  10302. $pdf->Ln(4);
  10303. }
  10304. /**
  10305. * PDF子标题(集数/片段标题)
  10306. */
  10307. private function pdfSubTitle($pdf, $title, $size = 13) {
  10308. if ($pdf->GetY() > 240) {
  10309. $pdf->AddPage();
  10310. }
  10311. $pdf->SetFont('simsun', 'B', $size);
  10312. $pdf->Cell(0, 8, $title, 0, 1, 'L');
  10313. $pdf->Ln(1);
  10314. }
  10315. /**
  10316. * PDF正文段落
  10317. */
  10318. private function pdfBody($pdf, $text) {
  10319. $pdf->SetFont('simsun', '', 11);
  10320. $pdf->MultiCell(0, 6, $text, 0, 'L');
  10321. $pdf->Ln(2);
  10322. }
  10323. /**
  10324. * 输出列表项图片(每张图单独一页,图下标注名称)
  10325. * @param \TCPDF $pdf
  10326. * @param array $items 列表项
  10327. * @param string $nameKey role|scene|prop
  10328. * @param array $imageCache 图片缓存(url => 临时文件路径)
  10329. */
  10330. private function pdfItemImages($pdf, array $items, $nameKey, array $imageCache) {
  10331. foreach ($items as $item) {
  10332. $url = trim((string)getProp($item, 'url', ''));
  10333. $name = trim((string)getProp($item, $nameKey, ''));
  10334. if ($url === '' || !isset($imageCache[$url])) continue;
  10335. $imgPath = $imageCache[$url];
  10336. $size = @getimagesize($imgPath);
  10337. if (!$size || $size[0] <= 0 || $size[1] <= 0) {
  10338. continue;
  10339. }
  10340. $pdf->AddPage();
  10341. // 图片按比例缩放,居中偏上,为底部名称标注预留空间
  10342. $maxW = 160;
  10343. $maxH = 170;
  10344. $ratio = min($maxW / $size[0], $maxH / $size[1], 1);
  10345. $drawW = $size[0] * $ratio;
  10346. $drawH = $size[1] * $ratio;
  10347. $x = (210 - $drawW) / 2;
  10348. $y = max(15, (297 - $drawH) / 2 - 10);
  10349. $pdf->Image($imgPath, $x, $y, $drawW, $drawH, '', '', '', false, 300, '', false, false, 0, false, false, false);
  10350. // 图下标注名称
  10351. $pdf->SetFont('simsun', 'B', 13);
  10352. $pdf->SetY(297 - 28);
  10353. $pdf->Cell(0, 8, $name, 0, 1, 'C');
  10354. }
  10355. }
  10356. /**
  10357. * 并发下载远程图片到临时文件,并统一缩放转为JPEG
  10358. * @param array $items 包含url字段的列表项
  10359. * @return array url => 临时文件路径
  10360. */
  10361. private function downloadImagesConcurrently(array $items) {
  10362. // 收集唯一的图片URL
  10363. $urls = [];
  10364. foreach ($items as $item) {
  10365. $url = trim((string)getProp($item, 'url', ''));
  10366. if ($url !== '') $urls[$url] = true;
  10367. }
  10368. if (!$urls) return [];
  10369. $urls = array_keys($urls);
  10370. $tmpDir = sys_get_temp_dir();
  10371. $rawFiles = [];
  10372. foreach ($urls as $url) {
  10373. $rawFile = $tmpDir . '/anime_pdf_raw_' . md5($url) . '.img';
  10374. $rawFiles[$url] = $rawFile;
  10375. }
  10376. $client = new Client(['timeout' => 180, 'verify' => false]);
  10377. // 低并发下载,sink写入文件避免大图占用内存
  10378. $generator = (function () use ($urls, $client, $rawFiles) {
  10379. foreach ($urls as $url) {
  10380. yield $url => $client->getAsync($url, ['sink' => $rawFiles[$url]]);
  10381. }
  10382. })();
  10383. $errors = [];
  10384. $each = new \GuzzleHttp\Promise\EachPromise($generator, [
  10385. 'concurrency' => 4,
  10386. 'rejected' => function ($reason, $url) use (&$errors) {
  10387. $errors[$url] = $reason ? $reason->getMessage() : 'unknown';
  10388. },
  10389. ]);
  10390. $each->promise()->wait();
  10391. // 失败的图片串行重试一次(独占带宽,提高成功率)
  10392. foreach ($urls as $url) {
  10393. if (!isset($errors[$url])) continue;
  10394. try {
  10395. $client->get($url, ['sink' => $rawFiles[$url], 'timeout' => 300]);
  10396. unset($errors[$url]);
  10397. } catch (\Throwable $e) {
  10398. // 重试仍失败
  10399. }
  10400. }
  10401. $cache = [];
  10402. foreach ($urls as $url) {
  10403. $rawFile = $rawFiles[$url];
  10404. if (isset($errors[$url])) {
  10405. dLog('anime')->error('导出PDF图片下载失败', [
  10406. 'url' => $url,
  10407. 'error' => $errors[$url],
  10408. ]);
  10409. @unlink($rawFile);
  10410. continue;
  10411. }
  10412. $converted = $this->convertImageFile($rawFile, $url);
  10413. if ($converted !== null) {
  10414. $cache[$url] = $converted;
  10415. } else {
  10416. @unlink($rawFile);
  10417. }
  10418. }
  10419. return $cache;
  10420. }
  10421. /**
  10422. * 将已下载的图片文件缩放并转为JPEG
  10423. * @param string $rawFile 原始图片临时文件
  10424. * @param string $url 图片地址(用于命名)
  10425. * @return string|null 转换后的文件路径,转换失败返回null
  10426. */
  10427. private function convertImageFile($rawFile, $url) {
  10428. $content = @file_get_contents($rawFile);
  10429. if ($content === false || $content === '') return null;
  10430. if (!function_exists('imagecreatefromstring')) return null;
  10431. $image = @imagecreatefromstring($content);
  10432. if ($image === false) return null;
  10433. $jpeg = $this->compressImageForPdf($image, $rawFile, $url);
  10434. imagedestroy($image);
  10435. if ($jpeg !== null) {
  10436. @unlink($rawFile);
  10437. }
  10438. return $jpeg;
  10439. }
  10440. /**
  10441. * 图片压缩:白底合成后转JPEG,分级缩小尺寸与降低质量,保证每张不超过2MB
  10442. * @param resource $srcImage GD图片资源
  10443. * @param string $rawFile 原始图片临时文件
  10444. * @param string $url 图片地址(用于命名)
  10445. * @return string|null 压缩后的JPEG文件路径
  10446. */
  10447. private function compressImageForPdf($srcImage, $rawFile, $url) {
  10448. $maxBytes = 2 * 1024 * 1024; // 2MB
  10449. $sizes = [2048, 1600, 1280, 1024, 800];
  10450. $qualities = [85, 70, 55, 40];
  10451. $jpeg = dirname($rawFile) . '/anime_pdf_img_' . md5($url) . '.jpg';
  10452. foreach ($sizes as $size) {
  10453. $resized = $this->copyAndResize($srcImage, $size);
  10454. $flat = $this->flattenToWhite($resized);
  10455. imagedestroy($resized);
  10456. foreach ($qualities as $quality) {
  10457. ob_start();
  10458. $saved = imagejpeg($flat, null, $quality);
  10459. $data = ob_get_clean();
  10460. if ($saved && $data !== false && $data !== '' && strlen($data) <= $maxBytes) {
  10461. file_put_contents($jpeg, $data);
  10462. imagedestroy($flat);
  10463. dLog('anime')->info('导出PDF图片压缩完成', [
  10464. 'url' => $url,
  10465. 'size' => filesize($jpeg),
  10466. 'edge' => $size,
  10467. 'quality' => $quality,
  10468. ]);
  10469. return $jpeg;
  10470. }
  10471. }
  10472. imagedestroy($flat);
  10473. }
  10474. // 兜底:最小尺寸、最低质量强制输出
  10475. $resized = $this->copyAndResize($srcImage, 800);
  10476. $flat = $this->flattenToWhite($resized);
  10477. imagedestroy($resized);
  10478. $saved = imagejpeg($flat, $jpeg, 30);
  10479. imagedestroy($flat);
  10480. if (!$saved) return null;
  10481. dLog('anime')->info('导出PDF图片压缩完成(兜底)', [
  10482. 'url' => $url,
  10483. 'size' => filesize($jpeg),
  10484. ]);
  10485. return $jpeg;
  10486. }
  10487. /**
  10488. * 等比缩放图片副本(不销毁原图)
  10489. * @param resource $srcImage GD图片资源
  10490. * @param int $maxEdge 最大边长
  10491. * @return resource
  10492. */
  10493. private function copyAndResize($srcImage, $maxEdge) {
  10494. $width = imagesx($srcImage);
  10495. $height = imagesy($srcImage);
  10496. $max = max($width, $height);
  10497. if ($max <= $maxEdge) {
  10498. $copy = imagecreatetruecolor($width, $height);
  10499. imagecopy($copy, $srcImage, 0, 0, 0, 0, $width, $height);
  10500. return $copy;
  10501. }
  10502. $ratio = $maxEdge / $max;
  10503. $newWidth = max(1, (int)round($width * $ratio));
  10504. $newHeight = max(1, (int)round($height * $ratio));
  10505. $resized = imagecreatetruecolor($newWidth, $newHeight);
  10506. imagealphablending($resized, false);
  10507. imagesavealpha($resized, true);
  10508. imagecopyresampled($resized, $srcImage, 0, 0, 0, 0, $newWidth, $newHeight, $width, $height);
  10509. return $resized;
  10510. }
  10511. /**
  10512. * 将GD图片合成到白色背景上(处理透明通道,输出RGB)
  10513. * @param resource $image GD图片资源
  10514. * @return resource
  10515. */
  10516. private function flattenToWhite($image) {
  10517. $width = imagesx($image);
  10518. $height = imagesy($image);
  10519. $flat = imagecreatetruecolor($width, $height);
  10520. $white = imagecolorallocate($flat, 255, 255, 255);
  10521. imagefill($flat, 0, 0, $white);
  10522. imagecopy($flat, $image, 0, 0, 0, 0, $width, $height);
  10523. return $flat;
  10524. }
  10525. /**
  10526. * 将片段内容中的分镜序号按出现先后重新编号(保证整集连续)
  10527. * @param string $content 片段内容
  10528. * @param int $counter 当前已编号数量(引用传递,整集累计)
  10529. * @return string
  10530. */
  10531. private function renumberSegmentBlocks($content, &$counter) {
  10532. return preg_replace_callback('/^【(分镜|镜头)\d+】/mu', function ($match) use (&$counter) {
  10533. $counter++;
  10534. return '【' . $match[1] . $counter . '】';
  10535. }, $content);
  10536. }
  10537. }