AnimeService.php 525 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695705715725735745755765775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206216226236246256266276286296306316326336346356366376386396406416426436446456466476486496506516526536546556566576586596606616626636646656666676686696706716726736746756766776786796806816826836846856866876886896906916926936946956966976986997007017027037047057067077087097107117127137147157167177187197207217227237247257267277287297307317327337347357367377387397407417427437447457467477487497507517527537547557567577587597607617627637647657667677687697707717727737747757767777787797807817827837847857867877887897907917927937947957967977987998008018028038048058068078088098108118128138148158168178188198208218228238248258268278288298308318328338348358368378388398408418428438448458468478488498508518528538548558568578588598608618628638648658668678688698708718728738748758768778788798808818828838848858868878888898908918928938948958968978988999009019029039049059069079089099109119129139149159169179189199209219229239249259269279289299309319329339349359369379389399409419429439449459469479489499509519529539549559569579589599609619629639649659669679689699709719729739749759769779789799809819829839849859869879889899909919929939949959969979989991000100110021003100410051006100710081009101010111012101310141015101610171018101910201021102210231024102510261027102810291030103110321033103410351036103710381039104010411042104310441045104610471048104910501051105210531054105510561057105810591060106110621063106410651066106710681069107010711072107310741075107610771078107910801081108210831084108510861087108810891090109110921093109410951096109710981099110011011102110311041105110611071108110911101111111211131114111511161117111811191120112111221123112411251126112711281129113011311132113311341135113611371138113911401141114211431144114511461147114811491150115111521153115411551156115711581159116011611162116311641165116611671168116911701171117211731174117511761177117811791180118111821183118411851186118711881189119011911192119311941195119611971198119912001201120212031204120512061207120812091210121112121213121412151216121712181219122012211222122312241225122612271228122912301231123212331234123512361237123812391240124112421243124412451246124712481249125012511252125312541255125612571258125912601261126212631264126512661267126812691270127112721273127412751276127712781279128012811282128312841285128612871288128912901291129212931294129512961297129812991300130113021303130413051306130713081309131013111312131313141315131613171318131913201321132213231324132513261327132813291330133113321333133413351336133713381339134013411342134313441345134613471348134913501351135213531354135513561357135813591360136113621363136413651366136713681369137013711372137313741375137613771378137913801381138213831384138513861387138813891390139113921393139413951396139713981399140014011402140314041405140614071408140914101411141214131414141514161417141814191420142114221423142414251426142714281429143014311432143314341435143614371438143914401441144214431444144514461447144814491450145114521453145414551456145714581459146014611462146314641465146614671468146914701471147214731474147514761477147814791480148114821483148414851486148714881489149014911492149314941495149614971498149915001501150215031504150515061507150815091510151115121513151415151516151715181519152015211522152315241525152615271528152915301531153215331534153515361537153815391540154115421543154415451546154715481549155015511552155315541555155615571558155915601561156215631564156515661567156815691570157115721573157415751576157715781579158015811582158315841585158615871588158915901591159215931594159515961597159815991600160116021603160416051606160716081609161016111612161316141615161616171618161916201621162216231624162516261627162816291630163116321633163416351636163716381639164016411642164316441645164616471648164916501651165216531654165516561657165816591660166116621663166416651666166716681669167016711672167316741675167616771678167916801681168216831684168516861687168816891690169116921693169416951696169716981699170017011702170317041705170617071708170917101711171217131714171517161717171817191720172117221723172417251726172717281729173017311732173317341735173617371738173917401741174217431744174517461747174817491750175117521753175417551756175717581759176017611762176317641765176617671768176917701771177217731774177517761777177817791780178117821783178417851786178717881789179017911792179317941795179617971798179918001801180218031804180518061807180818091810181118121813181418151816181718181819182018211822182318241825182618271828182918301831183218331834183518361837183818391840184118421843184418451846184718481849185018511852185318541855185618571858185918601861186218631864186518661867186818691870187118721873187418751876187718781879188018811882188318841885188618871888188918901891189218931894189518961897189818991900190119021903190419051906190719081909191019111912191319141915191619171918191919201921192219231924192519261927192819291930193119321933193419351936193719381939194019411942194319441945194619471948194919501951195219531954195519561957195819591960196119621963196419651966196719681969197019711972197319741975197619771978197919801981198219831984198519861987198819891990199119921993199419951996199719981999200020012002200320042005200620072008200920102011201220132014201520162017201820192020202120222023202420252026202720282029203020312032203320342035203620372038203920402041204220432044204520462047204820492050205120522053205420552056205720582059206020612062206320642065206620672068206920702071207220732074207520762077207820792080208120822083208420852086208720882089209020912092209320942095209620972098209921002101210221032104210521062107210821092110211121122113211421152116211721182119212021212122212321242125212621272128212921302131213221332134213521362137213821392140214121422143214421452146214721482149215021512152215321542155215621572158215921602161216221632164216521662167216821692170217121722173217421752176217721782179218021812182218321842185218621872188218921902191219221932194219521962197219821992200220122022203220422052206220722082209221022112212221322142215221622172218221922202221222222232224222522262227222822292230223122322233223422352236223722382239224022412242224322442245224622472248224922502251225222532254225522562257225822592260226122622263226422652266226722682269227022712272227322742275227622772278227922802281228222832284228522862287228822892290229122922293229422952296229722982299230023012302230323042305230623072308230923102311231223132314231523162317231823192320232123222323232423252326232723282329233023312332233323342335233623372338233923402341234223432344234523462347234823492350235123522353235423552356235723582359236023612362236323642365236623672368236923702371237223732374237523762377237823792380238123822383238423852386238723882389239023912392239323942395239623972398239924002401240224032404240524062407240824092410241124122413241424152416241724182419242024212422242324242425242624272428242924302431243224332434243524362437243824392440244124422443244424452446244724482449245024512452245324542455245624572458245924602461246224632464246524662467246824692470247124722473247424752476247724782479248024812482248324842485248624872488248924902491249224932494249524962497249824992500250125022503250425052506250725082509251025112512251325142515251625172518251925202521252225232524252525262527252825292530253125322533253425352536253725382539254025412542254325442545254625472548254925502551255225532554255525562557255825592560256125622563256425652566256725682569257025712572257325742575257625772578257925802581258225832584258525862587258825892590259125922593259425952596259725982599260026012602260326042605260626072608260926102611261226132614261526162617261826192620262126222623262426252626262726282629263026312632263326342635263626372638263926402641264226432644264526462647264826492650265126522653265426552656265726582659266026612662266326642665266626672668266926702671267226732674267526762677267826792680268126822683268426852686268726882689269026912692269326942695269626972698269927002701270227032704270527062707270827092710271127122713271427152716271727182719272027212722272327242725272627272728272927302731273227332734273527362737273827392740274127422743274427452746274727482749275027512752275327542755275627572758275927602761276227632764276527662767276827692770277127722773277427752776277727782779278027812782278327842785278627872788278927902791279227932794279527962797279827992800280128022803280428052806280728082809281028112812281328142815281628172818281928202821282228232824282528262827282828292830283128322833283428352836283728382839284028412842284328442845284628472848284928502851285228532854285528562857285828592860286128622863286428652866286728682869287028712872287328742875287628772878287928802881288228832884288528862887288828892890289128922893289428952896289728982899290029012902290329042905290629072908290929102911291229132914291529162917291829192920292129222923292429252926292729282929293029312932293329342935293629372938293929402941294229432944294529462947294829492950295129522953295429552956295729582959296029612962296329642965296629672968296929702971297229732974297529762977297829792980298129822983298429852986298729882989299029912992299329942995299629972998299930003001300230033004300530063007300830093010301130123013301430153016301730183019302030213022302330243025302630273028302930303031303230333034303530363037303830393040304130423043304430453046304730483049305030513052305330543055305630573058305930603061306230633064306530663067306830693070307130723073307430753076307730783079308030813082308330843085308630873088308930903091309230933094309530963097309830993100310131023103310431053106310731083109311031113112311331143115311631173118311931203121312231233124312531263127312831293130313131323133313431353136313731383139314031413142314331443145314631473148314931503151315231533154315531563157315831593160316131623163316431653166316731683169317031713172317331743175317631773178317931803181318231833184318531863187318831893190319131923193319431953196319731983199320032013202320332043205320632073208320932103211321232133214321532163217321832193220322132223223322432253226322732283229323032313232323332343235323632373238323932403241324232433244324532463247324832493250325132523253325432553256325732583259326032613262326332643265326632673268326932703271327232733274327532763277327832793280328132823283328432853286328732883289329032913292329332943295329632973298329933003301330233033304330533063307330833093310331133123313331433153316331733183319332033213322332333243325332633273328332933303331333233333334333533363337333833393340334133423343334433453346334733483349335033513352335333543355335633573358335933603361336233633364336533663367336833693370337133723373337433753376337733783379338033813382338333843385338633873388338933903391339233933394339533963397339833993400340134023403340434053406340734083409341034113412341334143415341634173418341934203421342234233424342534263427342834293430343134323433343434353436343734383439344034413442344334443445344634473448344934503451345234533454345534563457345834593460346134623463346434653466346734683469347034713472347334743475347634773478347934803481348234833484348534863487348834893490349134923493349434953496349734983499350035013502350335043505350635073508350935103511351235133514351535163517351835193520352135223523352435253526352735283529353035313532353335343535353635373538353935403541354235433544354535463547354835493550355135523553355435553556355735583559356035613562356335643565356635673568356935703571357235733574357535763577357835793580358135823583358435853586358735883589359035913592359335943595359635973598359936003601360236033604360536063607360836093610361136123613361436153616361736183619362036213622362336243625362636273628362936303631363236333634363536363637363836393640364136423643364436453646364736483649365036513652365336543655365636573658365936603661366236633664366536663667366836693670367136723673367436753676367736783679368036813682368336843685368636873688368936903691369236933694369536963697369836993700370137023703370437053706370737083709371037113712371337143715371637173718371937203721372237233724372537263727372837293730373137323733373437353736373737383739374037413742374337443745374637473748374937503751375237533754375537563757375837593760376137623763376437653766376737683769377037713772377337743775377637773778377937803781378237833784378537863787378837893790379137923793379437953796379737983799380038013802380338043805380638073808380938103811381238133814381538163817381838193820382138223823382438253826382738283829383038313832383338343835383638373838383938403841384238433844384538463847384838493850385138523853385438553856385738583859386038613862386338643865386638673868386938703871387238733874387538763877387838793880388138823883388438853886388738883889389038913892389338943895389638973898389939003901390239033904390539063907390839093910391139123913391439153916391739183919392039213922392339243925392639273928392939303931393239333934393539363937393839393940394139423943394439453946394739483949395039513952395339543955395639573958395939603961396239633964396539663967396839693970397139723973397439753976397739783979398039813982398339843985398639873988398939903991399239933994399539963997399839994000400140024003400440054006400740084009401040114012401340144015401640174018401940204021402240234024402540264027402840294030403140324033403440354036403740384039404040414042404340444045404640474048404940504051405240534054405540564057405840594060406140624063406440654066406740684069407040714072407340744075407640774078407940804081408240834084408540864087408840894090409140924093409440954096409740984099410041014102410341044105410641074108410941104111411241134114411541164117411841194120412141224123412441254126412741284129413041314132413341344135413641374138413941404141414241434144414541464147414841494150415141524153415441554156415741584159416041614162416341644165416641674168416941704171417241734174417541764177417841794180418141824183418441854186418741884189419041914192419341944195419641974198419942004201420242034204420542064207420842094210421142124213421442154216421742184219422042214222422342244225422642274228422942304231423242334234423542364237423842394240424142424243424442454246424742484249425042514252425342544255425642574258425942604261426242634264426542664267426842694270427142724273427442754276427742784279428042814282428342844285428642874288428942904291429242934294429542964297429842994300430143024303430443054306430743084309431043114312431343144315431643174318431943204321432243234324432543264327432843294330433143324333433443354336433743384339434043414342434343444345434643474348434943504351435243534354435543564357435843594360436143624363436443654366436743684369437043714372437343744375437643774378437943804381438243834384438543864387438843894390439143924393439443954396439743984399440044014402440344044405440644074408440944104411441244134414441544164417441844194420442144224423442444254426442744284429443044314432443344344435443644374438443944404441444244434444444544464447444844494450445144524453445444554456445744584459446044614462446344644465446644674468446944704471447244734474447544764477447844794480448144824483448444854486448744884489449044914492449344944495449644974498449945004501450245034504450545064507450845094510451145124513451445154516451745184519452045214522452345244525452645274528452945304531453245334534453545364537453845394540454145424543454445454546454745484549455045514552455345544555455645574558455945604561456245634564456545664567456845694570457145724573457445754576457745784579458045814582458345844585458645874588458945904591459245934594459545964597459845994600460146024603460446054606460746084609461046114612461346144615461646174618461946204621462246234624462546264627462846294630463146324633463446354636463746384639464046414642464346444645464646474648464946504651465246534654465546564657465846594660466146624663466446654666466746684669467046714672467346744675467646774678467946804681468246834684468546864687468846894690469146924693469446954696469746984699470047014702470347044705470647074708470947104711471247134714471547164717471847194720472147224723472447254726472747284729473047314732473347344735473647374738473947404741474247434744474547464747474847494750475147524753475447554756475747584759476047614762476347644765476647674768476947704771477247734774477547764777477847794780478147824783478447854786478747884789479047914792479347944795479647974798479948004801480248034804480548064807480848094810481148124813481448154816481748184819482048214822482348244825482648274828482948304831483248334834483548364837483848394840484148424843484448454846484748484849485048514852485348544855485648574858485948604861486248634864486548664867486848694870487148724873487448754876487748784879488048814882488348844885488648874888488948904891489248934894489548964897489848994900490149024903490449054906490749084909491049114912491349144915491649174918491949204921492249234924492549264927492849294930493149324933493449354936493749384939494049414942494349444945494649474948494949504951495249534954495549564957495849594960496149624963496449654966496749684969497049714972497349744975497649774978497949804981498249834984498549864987498849894990499149924993499449954996499749984999500050015002500350045005500650075008500950105011501250135014501550165017501850195020502150225023502450255026502750285029503050315032503350345035503650375038503950405041504250435044504550465047504850495050505150525053505450555056505750585059506050615062506350645065506650675068506950705071507250735074507550765077507850795080508150825083508450855086508750885089509050915092509350945095509650975098509951005101510251035104510551065107510851095110511151125113511451155116511751185119512051215122512351245125512651275128512951305131513251335134513551365137513851395140514151425143514451455146514751485149515051515152515351545155515651575158515951605161516251635164516551665167516851695170517151725173517451755176517751785179518051815182518351845185518651875188518951905191519251935194519551965197519851995200520152025203520452055206520752085209521052115212521352145215521652175218521952205221522252235224522552265227522852295230523152325233523452355236523752385239524052415242524352445245524652475248524952505251525252535254525552565257525852595260526152625263526452655266526752685269527052715272527352745275527652775278527952805281528252835284528552865287528852895290529152925293529452955296529752985299530053015302530353045305530653075308530953105311531253135314531553165317531853195320532153225323532453255326532753285329533053315332533353345335533653375338533953405341534253435344534553465347534853495350535153525353535453555356535753585359536053615362536353645365536653675368536953705371537253735374537553765377537853795380538153825383538453855386538753885389539053915392539353945395539653975398539954005401540254035404540554065407540854095410541154125413541454155416541754185419542054215422542354245425542654275428542954305431543254335434543554365437543854395440544154425443544454455446544754485449545054515452545354545455545654575458545954605461546254635464546554665467546854695470547154725473547454755476547754785479548054815482548354845485548654875488548954905491549254935494549554965497549854995500550155025503550455055506550755085509551055115512551355145515551655175518551955205521552255235524552555265527552855295530553155325533553455355536553755385539554055415542554355445545554655475548554955505551555255535554555555565557555855595560556155625563556455655566556755685569557055715572557355745575557655775578557955805581558255835584558555865587558855895590559155925593559455955596559755985599560056015602560356045605560656075608560956105611561256135614561556165617561856195620562156225623562456255626562756285629563056315632563356345635563656375638563956405641564256435644564556465647564856495650565156525653565456555656565756585659566056615662566356645665566656675668566956705671567256735674567556765677567856795680568156825683568456855686568756885689569056915692569356945695569656975698569957005701570257035704570557065707570857095710571157125713571457155716571757185719572057215722572357245725572657275728572957305731573257335734573557365737573857395740574157425743574457455746574757485749575057515752575357545755575657575758575957605761576257635764576557665767576857695770577157725773577457755776577757785779578057815782578357845785578657875788578957905791579257935794579557965797579857995800580158025803580458055806580758085809581058115812581358145815581658175818581958205821582258235824582558265827582858295830583158325833583458355836583758385839584058415842584358445845584658475848584958505851585258535854585558565857585858595860586158625863586458655866586758685869587058715872587358745875587658775878587958805881588258835884588558865887588858895890589158925893589458955896589758985899590059015902590359045905590659075908590959105911591259135914591559165917591859195920592159225923592459255926592759285929593059315932593359345935593659375938593959405941594259435944594559465947594859495950595159525953595459555956595759585959596059615962596359645965596659675968596959705971597259735974597559765977597859795980598159825983598459855986598759885989599059915992599359945995599659975998599960006001600260036004600560066007600860096010601160126013601460156016601760186019602060216022602360246025602660276028602960306031603260336034603560366037603860396040604160426043604460456046604760486049605060516052605360546055605660576058605960606061606260636064606560666067606860696070607160726073607460756076607760786079608060816082608360846085608660876088608960906091609260936094609560966097609860996100610161026103610461056106610761086109611061116112611361146115611661176118611961206121612261236124612561266127612861296130613161326133613461356136613761386139614061416142614361446145614661476148614961506151615261536154615561566157615861596160616161626163616461656166616761686169617061716172617361746175617661776178617961806181618261836184618561866187618861896190619161926193619461956196619761986199620062016202620362046205620662076208620962106211621262136214621562166217621862196220622162226223622462256226622762286229623062316232623362346235623662376238623962406241624262436244624562466247624862496250625162526253625462556256625762586259626062616262626362646265626662676268626962706271627262736274627562766277627862796280628162826283628462856286628762886289629062916292629362946295629662976298629963006301630263036304630563066307630863096310631163126313631463156316631763186319632063216322632363246325632663276328632963306331633263336334633563366337633863396340634163426343634463456346634763486349635063516352635363546355635663576358635963606361636263636364636563666367636863696370637163726373637463756376637763786379638063816382638363846385638663876388638963906391639263936394639563966397639863996400640164026403640464056406640764086409641064116412641364146415641664176418641964206421642264236424642564266427642864296430643164326433643464356436643764386439644064416442644364446445644664476448644964506451645264536454645564566457645864596460646164626463646464656466646764686469647064716472647364746475647664776478647964806481648264836484648564866487648864896490649164926493649464956496649764986499650065016502650365046505650665076508650965106511651265136514651565166517651865196520652165226523652465256526652765286529653065316532653365346535653665376538653965406541654265436544654565466547654865496550655165526553655465556556655765586559656065616562656365646565656665676568656965706571657265736574657565766577657865796580658165826583658465856586658765886589659065916592659365946595659665976598659966006601660266036604660566066607660866096610661166126613661466156616661766186619662066216622662366246625662666276628662966306631663266336634663566366637663866396640664166426643664466456646664766486649665066516652665366546655665666576658665966606661666266636664666566666667666866696670667166726673667466756676667766786679668066816682668366846685668666876688668966906691669266936694669566966697669866996700670167026703670467056706670767086709671067116712671367146715671667176718671967206721672267236724672567266727672867296730673167326733673467356736673767386739674067416742674367446745674667476748674967506751675267536754675567566757675867596760676167626763676467656766676767686769677067716772677367746775677667776778677967806781678267836784678567866787678867896790679167926793679467956796679767986799680068016802680368046805680668076808680968106811681268136814681568166817681868196820682168226823682468256826682768286829683068316832683368346835683668376838683968406841684268436844684568466847684868496850685168526853685468556856685768586859686068616862686368646865686668676868686968706871687268736874687568766877687868796880688168826883688468856886688768886889689068916892689368946895689668976898689969006901690269036904690569066907690869096910691169126913691469156916691769186919692069216922692369246925692669276928692969306931693269336934693569366937693869396940694169426943694469456946694769486949695069516952695369546955695669576958695969606961696269636964696569666967696869696970697169726973697469756976697769786979698069816982698369846985698669876988698969906991699269936994699569966997699869997000700170027003700470057006700770087009701070117012701370147015701670177018701970207021702270237024702570267027702870297030703170327033703470357036703770387039704070417042704370447045704670477048704970507051705270537054705570567057705870597060706170627063706470657066706770687069707070717072707370747075707670777078707970807081708270837084708570867087708870897090709170927093709470957096709770987099710071017102710371047105710671077108710971107111711271137114711571167117711871197120712171227123712471257126712771287129713071317132713371347135713671377138713971407141714271437144714571467147714871497150715171527153715471557156715771587159716071617162716371647165716671677168716971707171717271737174717571767177717871797180718171827183718471857186718771887189719071917192719371947195719671977198719972007201720272037204720572067207720872097210721172127213721472157216721772187219722072217222722372247225722672277228722972307231723272337234723572367237723872397240724172427243724472457246724772487249725072517252725372547255725672577258725972607261726272637264726572667267726872697270727172727273727472757276727772787279728072817282728372847285728672877288728972907291729272937294729572967297729872997300730173027303730473057306730773087309731073117312731373147315731673177318731973207321732273237324732573267327732873297330733173327333733473357336733773387339734073417342734373447345734673477348734973507351735273537354735573567357735873597360736173627363736473657366736773687369737073717372737373747375737673777378737973807381738273837384738573867387738873897390739173927393739473957396739773987399740074017402740374047405740674077408740974107411741274137414741574167417741874197420742174227423742474257426742774287429743074317432743374347435743674377438743974407441744274437444744574467447744874497450745174527453745474557456745774587459746074617462746374647465746674677468746974707471747274737474747574767477747874797480748174827483748474857486748774887489749074917492749374947495749674977498749975007501750275037504750575067507750875097510751175127513751475157516751775187519752075217522752375247525752675277528752975307531753275337534753575367537753875397540754175427543754475457546754775487549755075517552755375547555755675577558755975607561756275637564756575667567756875697570757175727573757475757576757775787579758075817582758375847585758675877588758975907591759275937594759575967597759875997600760176027603760476057606760776087609761076117612761376147615761676177618761976207621762276237624762576267627762876297630763176327633763476357636763776387639764076417642764376447645764676477648764976507651765276537654765576567657765876597660766176627663766476657666766776687669767076717672767376747675767676777678767976807681768276837684768576867687768876897690769176927693769476957696769776987699770077017702770377047705770677077708770977107711771277137714771577167717771877197720772177227723772477257726772777287729773077317732773377347735773677377738773977407741774277437744774577467747774877497750775177527753775477557756775777587759776077617762776377647765776677677768776977707771777277737774777577767777777877797780778177827783778477857786778777887789779077917792779377947795779677977798779978007801780278037804780578067807780878097810781178127813781478157816781778187819782078217822782378247825782678277828782978307831783278337834783578367837783878397840784178427843784478457846784778487849785078517852785378547855785678577858785978607861786278637864786578667867786878697870787178727873787478757876787778787879788078817882788378847885788678877888788978907891789278937894789578967897789878997900790179027903790479057906790779087909791079117912791379147915791679177918791979207921792279237924792579267927792879297930793179327933793479357936793779387939794079417942794379447945794679477948794979507951795279537954795579567957795879597960796179627963796479657966796779687969797079717972797379747975797679777978797979807981798279837984798579867987798879897990799179927993799479957996799779987999800080018002800380048005800680078008800980108011801280138014801580168017801880198020802180228023802480258026802780288029803080318032803380348035803680378038803980408041804280438044804580468047804880498050805180528053805480558056805780588059806080618062806380648065806680678068806980708071807280738074807580768077807880798080808180828083808480858086808780888089809080918092809380948095809680978098809981008101810281038104810581068107810881098110811181128113811481158116811781188119812081218122812381248125812681278128812981308131813281338134813581368137813881398140814181428143814481458146814781488149815081518152815381548155815681578158815981608161816281638164816581668167816881698170817181728173817481758176817781788179818081818182818381848185818681878188818981908191819281938194819581968197819881998200820182028203820482058206820782088209821082118212821382148215821682178218821982208221822282238224822582268227822882298230823182328233823482358236823782388239824082418242824382448245824682478248824982508251825282538254825582568257825882598260826182628263826482658266826782688269827082718272827382748275827682778278827982808281828282838284828582868287828882898290829182928293829482958296829782988299830083018302830383048305830683078308830983108311831283138314831583168317831883198320832183228323832483258326832783288329833083318332833383348335833683378338833983408341834283438344834583468347834883498350835183528353835483558356835783588359836083618362836383648365836683678368836983708371837283738374837583768377837883798380838183828383838483858386838783888389839083918392839383948395839683978398839984008401840284038404840584068407840884098410841184128413841484158416841784188419842084218422842384248425842684278428842984308431843284338434843584368437843884398440844184428443844484458446844784488449845084518452845384548455845684578458845984608461846284638464846584668467846884698470847184728473847484758476847784788479848084818482848384848485848684878488848984908491849284938494849584968497849884998500850185028503850485058506850785088509851085118512851385148515851685178518851985208521852285238524852585268527852885298530853185328533853485358536853785388539854085418542854385448545854685478548854985508551855285538554855585568557855885598560856185628563856485658566856785688569857085718572857385748575857685778578857985808581858285838584858585868587858885898590859185928593859485958596859785988599860086018602860386048605860686078608860986108611861286138614861586168617861886198620862186228623862486258626862786288629863086318632863386348635863686378638863986408641864286438644864586468647864886498650865186528653865486558656865786588659866086618662866386648665866686678668866986708671867286738674867586768677867886798680868186828683868486858686868786888689869086918692869386948695869686978698869987008701870287038704870587068707870887098710871187128713871487158716871787188719872087218722872387248725872687278728872987308731873287338734873587368737873887398740874187428743874487458746874787488749875087518752875387548755875687578758875987608761876287638764876587668767876887698770877187728773877487758776877787788779878087818782878387848785878687878788878987908791879287938794879587968797879887998800880188028803880488058806880788088809881088118812881388148815881688178818881988208821882288238824882588268827882888298830883188328833883488358836883788388839884088418842884388448845884688478848884988508851885288538854885588568857885888598860886188628863886488658866886788688869887088718872887388748875887688778878887988808881888288838884888588868887888888898890889188928893889488958896889788988899890089018902890389048905890689078908890989108911891289138914891589168917891889198920892189228923892489258926892789288929893089318932893389348935893689378938893989408941894289438944894589468947894889498950895189528953895489558956895789588959896089618962896389648965896689678968896989708971897289738974897589768977897889798980898189828983898489858986898789888989899089918992899389948995899689978998899990009001900290039004900590069007900890099010901190129013901490159016901790189019902090219022902390249025902690279028902990309031903290339034903590369037903890399040904190429043904490459046904790489049905090519052905390549055905690579058905990609061906290639064906590669067906890699070907190729073907490759076907790789079908090819082908390849085908690879088908990909091909290939094909590969097909890999100910191029103910491059106910791089109911091119112911391149115911691179118911991209121912291239124912591269127912891299130913191329133913491359136913791389139914091419142914391449145914691479148914991509151915291539154915591569157915891599160916191629163916491659166916791689169917091719172917391749175917691779178917991809181918291839184918591869187918891899190919191929193919491959196919791989199920092019202920392049205920692079208920992109211921292139214921592169217921892199220922192229223922492259226922792289229923092319232923392349235923692379238923992409241924292439244924592469247924892499250925192529253925492559256925792589259926092619262926392649265926692679268926992709271927292739274927592769277927892799280928192829283928492859286928792889289929092919292929392949295929692979298929993009301930293039304930593069307930893099310931193129313931493159316931793189319932093219322932393249325932693279328932993309331933293339334933593369337933893399340934193429343934493459346934793489349935093519352935393549355935693579358935993609361936293639364936593669367936893699370937193729373937493759376937793789379938093819382938393849385938693879388938993909391939293939394939593969397939893999400940194029403940494059406940794089409941094119412941394149415941694179418941994209421942294239424942594269427942894299430943194329433943494359436943794389439944094419442944394449445944694479448944994509451945294539454945594569457945894599460946194629463946494659466946794689469947094719472947394749475947694779478947994809481948294839484948594869487948894899490949194929493949494959496949794989499950095019502950395049505950695079508950995109511951295139514951595169517951895199520952195229523952495259526952795289529953095319532953395349535953695379538953995409541954295439544954595469547954895499550955195529553955495559556955795589559956095619562956395649565956695679568956995709571957295739574957595769577957895799580958195829583958495859586958795889589959095919592959395949595959695979598959996009601960296039604960596069607960896099610961196129613961496159616961796189619962096219622962396249625962696279628962996309631963296339634963596369637963896399640964196429643964496459646964796489649965096519652965396549655965696579658965996609661966296639664966596669667966896699670967196729673967496759676967796789679968096819682968396849685968696879688968996909691969296939694969596969697969896999700970197029703970497059706970797089709971097119712971397149715971697179718971997209721972297239724972597269727972897299730973197329733973497359736973797389739974097419742974397449745974697479748974997509751975297539754975597569757975897599760976197629763976497659766976797689769977097719772977397749775977697779778977997809781978297839784978597869787978897899790979197929793979497959796979797989799980098019802980398049805980698079808980998109811981298139814981598169817981898199820982198229823982498259826982798289829983098319832983398349835983698379838983998409841984298439844984598469847984898499850985198529853985498559856985798589859986098619862986398649865986698679868986998709871987298739874987598769877987898799880988198829883988498859886988798889889989098919892989398949895989698979898989999009901990299039904990599069907990899099910991199129913991499159916991799189919992099219922992399249925992699279928992999309931993299339934993599369937993899399940994199429943994499459946994799489949995099519952995399549955995699579958995999609961996299639964996599669967996899699970997199729973997499759976997799789979998099819982998399849985998699879988998999909991999299939994999599969997999899991000010001100021000310004100051000610007100081000910010100111001210013100141001510016100171001810019100201002110022100231002410025100261002710028100291003010031100321003310034100351003610037100381003910040100411004210043100441004510046100471004810049100501005110052100531005410055100561005710058100591006010061100621006310064100651006610067100681006910070100711007210073100741007510076100771007810079100801008110082100831008410085100861008710088100891009010091100921009310094100951009610097100981009910100101011010210103101041010510106101071010810109101101011110112101131011410115101161011710118101191012010121101221012310124101251012610127101281012910130101311013210133101341013510136101371013810139101401014110142101431014410145101461014710148101491015010151101521015310154101551015610157101581015910160101611016210163101641016510166101671016810169101701017110172101731017410175101761017710178101791018010181101821018310184101851018610187101881018910190101911019210193101941019510196101971019810199102001020110202102031020410205102061020710208102091021010211102121021310214102151021610217102181021910220102211022210223102241022510226102271022810229102301023110232102331023410235102361023710238102391024010241102421024310244102451024610247102481024910250102511025210253102541025510256102571025810259102601026110262102631026410265102661026710268102691027010271102721027310274102751027610277102781027910280102811028210283102841028510286102871028810289102901029110292102931029410295102961029710298102991030010301103021030310304103051030610307103081030910310103111031210313103141031510316103171031810319103201032110322103231032410325103261032710328103291033010331103321033310334103351033610337103381033910340103411034210343103441034510346103471034810349103501035110352103531035410355103561035710358103591036010361103621036310364103651036610367103681036910370103711037210373103741037510376103771037810379103801038110382103831038410385103861038710388103891039010391103921039310394103951039610397103981039910400104011040210403104041040510406104071040810409104101041110412104131041410415104161041710418104191042010421104221042310424104251042610427104281042910430104311043210433104341043510436104371043810439104401044110442104431044410445104461044710448104491045010451104521045310454104551045610457104581045910460104611046210463104641046510466104671046810469104701047110472104731047410475104761047710478104791048010481104821048310484104851048610487104881048910490104911049210493104941049510496104971049810499105001050110502105031050410505105061050710508105091051010511105121051310514105151051610517105181051910520105211052210523105241052510526105271052810529105301053110532105331053410535105361053710538105391054010541105421054310544105451054610547105481054910550105511055210553105541055510556105571055810559105601056110562105631056410565105661056710568105691057010571105721057310574105751057610577105781057910580105811058210583105841058510586105871058810589105901059110592105931059410595105961059710598105991060010601106021060310604106051060610607106081060910610106111061210613106141061510616106171061810619106201062110622106231062410625106261062710628106291063010631106321063310634106351063610637106381063910640106411064210643106441064510646106471064810649106501065110652106531065410655106561065710658106591066010661106621066310664106651066610667106681066910670106711067210673106741067510676106771067810679106801068110682106831068410685106861068710688106891069010691106921069310694106951069610697106981069910700107011070210703107041070510706107071070810709107101071110712107131071410715107161071710718107191072010721107221072310724107251072610727107281072910730107311073210733107341073510736107371073810739107401074110742107431074410745107461074710748107491075010751107521075310754107551075610757107581075910760107611076210763107641076510766107671076810769107701077110772107731077410775107761077710778107791078010781107821078310784107851078610787107881078910790107911079210793107941079510796107971079810799108001080110802108031080410805108061080710808108091081010811108121081310814108151081610817108181081910820108211082210823108241082510826108271082810829108301083110832108331083410835108361083710838108391084010841108421084310844108451084610847108481084910850108511085210853108541085510856108571085810859108601086110862108631086410865108661086710868108691087010871108721087310874108751087610877108781087910880108811088210883108841088510886108871088810889108901089110892108931089410895108961089710898108991090010901109021090310904109051090610907109081090910910109111091210913109141091510916109171091810919109201092110922109231092410925109261092710928109291093010931109321093310934109351093610937109381093910940109411094210943109441094510946109471094810949109501095110952109531095410955109561095710958109591096010961109621096310964109651096610967109681096910970109711097210973109741097510976109771097810979109801098110982109831098410985109861098710988109891099010991109921099310994109951099610997109981099911000110011100211003110041100511006110071100811009110101101111012110131101411015110161101711018110191102011021110221102311024110251102611027110281102911030110311103211033110341103511036110371103811039110401104111042110431104411045110461104711048110491105011051110521105311054110551105611057110581105911060110611106211063110641106511066110671106811069110701107111072110731107411075110761107711078110791108011081110821108311084110851108611087110881108911090110911109211093110941109511096110971109811099111001110111102111031110411105111061110711108111091111011111111121111311114111151111611117111181111911120111211112211123111241112511126111271112811129111301113111132111331113411135111361113711138111391114011141111421114311144111451114611147111481114911150111511115211153111541115511156111571115811159111601116111162111631116411165111661116711168111691117011171111721117311174111751117611177111781117911180111811118211183111841118511186111871118811189111901119111192111931119411195111961119711198111991120011201112021120311204112051120611207112081120911210112111121211213112141121511216112171121811219112201122111222112231122411225112261122711228112291123011231112321123311234112351123611237112381123911240112411124211243112441124511246112471124811249112501125111252112531125411255112561125711258112591126011261112621126311264112651126611267112681126911270112711127211273112741127511276112771127811279112801128111282112831128411285112861128711288112891129011291112921129311294112951129611297112981129911300113011130211303113041130511306113071130811309113101131111312113131131411315113161131711318113191132011321113221132311324113251132611327113281132911330113311133211333113341133511336113371133811339113401134111342113431134411345113461134711348113491135011351113521135311354113551135611357113581135911360113611136211363113641136511366113671136811369113701137111372113731137411375113761137711378113791138011381113821138311384113851138611387113881138911390113911139211393113941139511396113971139811399114001140111402114031140411405114061140711408114091141011411114121141311414114151141611417114181141911420114211142211423114241142511426114271142811429114301143111432114331143411435114361143711438114391144011441114421144311444114451144611447114481144911450114511145211453114541145511456114571145811459114601146111462114631146411465114661146711468114691147011471114721147311474114751147611477114781147911480114811148211483114841148511486114871148811489114901149111492114931149411495114961149711498114991150011501115021150311504115051150611507115081150911510115111151211513115141151511516115171151811519115201152111522115231152411525115261152711528115291153011531115321153311534115351153611537115381153911540115411154211543115441154511546115471154811549115501155111552115531155411555115561155711558115591156011561115621156311564115651156611567115681156911570115711157211573115741157511576115771157811579115801158111582115831158411585115861158711588115891159011591115921159311594115951159611597115981159911600116011160211603116041160511606116071160811609116101161111612116131161411615116161161711618116191162011621116221162311624116251162611627116281162911630116311163211633116341163511636116371163811639116401164111642116431164411645116461164711648116491165011651116521165311654116551165611657116581165911660116611166211663116641166511666116671166811669116701167111672116731167411675116761167711678116791168011681116821168311684116851168611687116881168911690116911169211693116941169511696116971169811699117001170111702117031170411705117061170711708117091171011711117121171311714117151171611717117181171911720117211172211723117241172511726117271172811729117301173111732117331173411735117361173711738117391174011741117421174311744117451174611747117481174911750117511175211753117541175511756117571175811759117601176111762117631176411765117661176711768117691177011771117721177311774117751177611777117781177911780117811178211783117841178511786117871178811789117901179111792117931179411795117961179711798117991180011801118021180311804118051180611807118081180911810118111181211813118141181511816118171181811819118201182111822118231182411825118261182711828118291183011831118321183311834118351183611837118381183911840118411184211843118441184511846118471184811849118501185111852118531185411855118561185711858118591186011861118621186311864118651186611867118681186911870118711187211873118741187511876118771187811879118801188111882118831188411885118861188711888118891189011891118921189311894118951189611897118981189911900119011190211903119041190511906119071190811909119101191111912119131191411915119161191711918119191192011921119221192311924119251192611927119281192911930119311193211933119341193511936119371193811939119401194111942119431194411945119461194711948119491195011951119521195311954119551195611957119581195911960119611196211963119641196511966119671196811969119701197111972119731197411975119761197711978119791198011981119821198311984119851198611987119881198911990119911199211993119941199511996119971199811999120001200112002120031200412005120061200712008120091201012011120121201312014120151201612017120181201912020120211202212023120241202512026120271202812029120301203112032120331203412035120361203712038120391204012041120421204312044120451204612047120481204912050120511205212053120541205512056120571205812059120601206112062120631206412065120661206712068120691207012071120721207312074120751207612077120781207912080120811208212083120841208512086120871208812089120901209112092120931209412095120961209712098120991210012101121021210312104121051210612107121081210912110121111211212113121141211512116121171211812119121201212112122121231212412125121261212712128121291213012131121321213312134121351213612137121381213912140121411214212143121441214512146121471214812149121501215112152121531215412155121561215712158121591216012161121621216312164121651216612167121681216912170121711217212173121741217512176121771217812179121801218112182121831218412185121861218712188121891219012191121921219312194121951219612197121981219912200122011220212203122041220512206122071220812209122101221112212122131221412215122161221712218122191222012221122221222312224122251222612227122281222912230122311223212233122341223512236122371223812239122401224112242122431224412245122461224712248122491225012251122521225312254122551225612257122581225912260122611226212263122641226512266122671226812269122701227112272122731227412275122761227712278122791228012281122821228312284122851228612287122881228912290122911229212293122941229512296122971229812299123001230112302123031230412305123061230712308123091231012311123121231312314123151231612317123181231912320123211232212323123241232512326123271232812329123301233112332
  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. 'anime_id' => $anime_id,
  310. 'episode_id' => $episode_id,
  311. 'episode_number' => getProp($episode, 'episode_number'),
  312. ];
  313. $task = $this->aiImageGenerationService->createImageGenerationTask($params);
  314. $task_id = $task->id;
  315. if (!$task_id) {
  316. Utils::throwError("20003:角色({$role_name})生成图片失败");
  317. }
  318. $role['task_id'] = $task_id;
  319. $role['task_status'] = 'processing';
  320. } catch (\Exception $e) {
  321. logDB('anime', 'error', "角色({$role_name})生成图片失败", ['error' => $e->getMessage()]);
  322. Utils::throwError("20003:" . $e->getMessage());
  323. }
  324. }
  325. // 保存角色信息
  326. $boolen = DB::table('mp_anime_episodes')->where('id', $episode_id)->update([
  327. 'roles' => json_encode($roles, 256),
  328. 'generate_status' => '执行中',
  329. 'generate_at' => date('Y-m-d H:i:s'),
  330. 'updated_at' => date('Y-m-d H:i:s')
  331. ]);
  332. if (!$boolen) {
  333. Utils::throwError('20003:保存角色信息失败');
  334. }
  335. return $boolen;
  336. }
  337. public function batchSetSceneImg($data) {
  338. $episode_id = getProp($data, 'episode_id');
  339. if (!$episode_id) Utils::throwError('1002:请选择分集');
  340. $episode = DB::table('mp_anime_episodes')->where('id', $episode_id)->first();
  341. $scenes = json_decode(getProp($episode, 'scenes'), true);
  342. $art_style = getProp($episode, 'art_style');
  343. $target_scene = getProp($data, 'target_scene');
  344. $anime_id = getProp($episode, 'anime_id');
  345. $anime = DB::table('mp_animes')->where('id', $anime_id)->first();
  346. $art_style_type = getProp($anime, 'art_style_type');
  347. $character_prefix = '';
  348. $scene_prefix = '';
  349. if ($art_style_type) {
  350. $art_style_arr = $this->DeepSeekService->getArtStyleShortPromptByInput($art_style_type);
  351. $character_prefix = isset($art_style_arr['character_prefix']) ? $art_style_arr['character_prefix'] : '';
  352. $scene_prefix = isset($art_style_arr['scene_prefix']) ? $art_style_arr['scene_prefix'] : '';
  353. }
  354. foreach ($scenes as &$scene) {
  355. $scene_name = getProp($scene, 'scene');
  356. if ($scene_name != $target_scene) continue;
  357. // 优先使用 pic_prompt,如果没有则使用 description
  358. $pic_prompt = getProp($scene, 'pic_prompt');
  359. $description = !empty($pic_prompt) ? trim((string)$pic_prompt) : getProp($scene, 'description');
  360. // if ($art_style) $description = "美术风格:\n{$art_style}\n\n场景描述:{$description}\n图片要求: 图片侧重点是场景,生成的是场景环境图片,不要出现人物(此为第一优先要求)";
  361. $description = "{$scene_prefix}。\n场景描述:{$description}\n无人物,超高清,高细节,主体突出,构图合理,画面干净,无文字,无水印,无字幕,电影级光影,视觉焦点明确";
  362. // 参考图地址
  363. $ref_img_url = getProp($scene, 'url');
  364. if ($ref_img_url) continue; // 已有图片则跳过
  365. // 此处调用AIImageGenerationService的生成图片任务接口: createImageGenerationTask(注意使用默认参数,prompt使用角色描述),并返回任务id
  366. try {
  367. $params = [
  368. 'prompt' => $description,
  369. 'ref_img_urls' => !empty($ref_img_url) ? [$ref_img_url] : [],
  370. // 计费锚点(动漫/剧集/剧本),用于积分明细归属统计
  371. 'anime_id' => $anime_id,
  372. 'episode_id' => $episode_id,
  373. 'episode_number' => getProp($episode, 'episode_number'),
  374. ];
  375. $task = $this->aiImageGenerationService->createImageGenerationTask($params);
  376. $task_id = $task->id;
  377. if (!$task_id) {
  378. Utils::throwError("20003:场景({$scene_name})生成图片失败");
  379. }
  380. $scene['task_id'] = $task_id;
  381. $scene['task_status'] = 'processing';
  382. } catch (\Exception $e) {
  383. logDB('anime', 'error', "场景({$scene_name})生成图片失败", ['error' => $e->getMessage()]);
  384. Utils::throwError("20003:" . $e->getMessage());
  385. }
  386. }
  387. // 保存场景信息
  388. $boolen = DB::table('mp_anime_episodes')->where('id', $episode_id)->update([
  389. 'scenes' => json_encode($scenes, 256),
  390. 'generate_status' => '执行中',
  391. 'generate_at' => date('Y-m-d H:i:s'),
  392. 'updated_at' => date('Y-m-d H:i:s')
  393. ]);
  394. if (!$boolen) {
  395. Utils::throwError('20003:保存角色信息失败');
  396. }
  397. return $boolen;
  398. }
  399. public function editAnime($data) {
  400. $anime_id = getProp($data, 'anime_id');
  401. $anime_name = trim(getProp($data, 'anime_name'));
  402. // 确认对话名称唯一性
  403. if ($id = DB::table('mp_animes')->where('anime_name', $anime_name)->value('id')) {
  404. if ($id != $anime_id) $anime_name = $anime_name . '_' . date('YmdHis');
  405. }
  406. if (!$anime_id || !$anime_name) {
  407. Utils::throwError('20003:参数异常');
  408. }
  409. return DB::table('mp_animes')->where('id', $anime_id)->update([
  410. 'anime_name' => $anime_name,
  411. 'updated_at' => date('Y-m-d H:i:s')
  412. ]);
  413. // $script_arr =getProp($data, 'script', []);
  414. // if (!$script_arr) Utils::throwError('20003:剧本内容不能为空');
  415. // $start_episode_sequence = getProp($data, 'start_episode_sequence', 1);
  416. // $anime_id = getProp($data, 'anime_id');
  417. // try {
  418. // DB::beginTransaction();
  419. // $table_data = [
  420. // 'intro' => isset($script_arr['intro']) ? $script_arr['intro'] : '',
  421. // 'highlights' => isset($script_arr['highlights']) ? $script_arr['highlights'] : '',
  422. // 'role_relationship' => isset($script_arr['role_relationship']) ? $script_arr['role_relationship'] : '',
  423. // 'core_contradiction' => isset($script_arr['core_contradiction']) ? $script_arr['core_contradiction'] : '',
  424. // 'roles' => isset($script_arr['roles']) ? json_encode($script_arr['roles'], 256) : '',
  425. // 'art_style' => isset($script_arr['art_style']) ? $script_arr['art_style'] : '',
  426. // 'scenes' => isset($script_arr['scenes']) ? json_encode($script_arr['scenes'], 256) : '',
  427. // 'status' => 3,
  428. // 'start_episode_sequence' => $start_episode_sequence,
  429. // 'end_episode_sequence' => $start_episode_sequence + count($script_arr['episodes']) - 1,
  430. // 'episode_num' => count($script_arr['episodes']),
  431. // 'updated_at' => date('Y-m-d H:i:s')
  432. // ];
  433. // // 保存剧本内容
  434. // if (!empty($anime_id)) {
  435. // $boolen = DB::table('mp_animes')->where('id', $anime_id)->update($table_data);
  436. // if (!$boolen) {
  437. // dLog('anime')->info('对话保存失败', $table_data);
  438. // Utils::throwError('20003:对话保存失败');
  439. // }
  440. // }else {
  441. // $table['created_at'] = $table_data['updated_at'];
  442. // $anime_id = DB::table('mp_animes')->insertGetId($table_data);
  443. // if (!$anime_id) {
  444. // dLog('anime')->info('对话保存失败', $table_data);
  445. // Utils::throwError('20003:对话保存失败');
  446. // }
  447. // }
  448. // // 保存分集内容
  449. // // 删除历史分集内容
  450. // $boolen1 = DB::table('mp_anime_episodes')->where('anime_id', $anime_id)->delete();
  451. // $episodes = [];
  452. // $sequence = 1;
  453. // foreach ($script_arr['episodes'] as $episode) {
  454. // $segment_number = 1;
  455. // foreach($episode['segments'] as $segment) {
  456. // $episodes[] = [
  457. // 'anime_id' => $anime_id,
  458. // 'episode_number' => $episode['episode_number'],
  459. // 'title' => $episode['title'],
  460. // // 'content' => $episode['content'],
  461. // 'content' => '',
  462. // 'segment_number' => $segment_number,
  463. // 'segment_content' => $segment['segment_content'],
  464. // 'sequence' => $sequence,
  465. // 'created_at' => date('Y-m-d H:i:s'),
  466. // 'updated_at' => date('Y-m-d H:i:s')
  467. // ];
  468. // $sequence++;
  469. // $segment_number++;
  470. // }
  471. // }
  472. // $boolen2 = DB::table('mp_anime_episodes')->insert($episodes);
  473. // if (!$boolen2) {
  474. // dLog('deepseek')->info('分集内容保存失败', $episodes);
  475. // logDB('deepseek', 'error', '分集内容保存失败', ['episodes_count' => count($episodes)]);
  476. // Utils::throwError('20003:分集内容保存失败');
  477. // }
  478. // } catch (\Exception $e) {
  479. // DB::rollBack();
  480. // Utils::throwError('20003:'.$e->getMessage());
  481. // }
  482. // DB::commit();
  483. // return true;
  484. }
  485. public function delAnime($data) {
  486. $anime_id = getProp($data, 'anime_id');
  487. if (!$anime_id) {
  488. Utils::throwError('20003:请选择剧本');
  489. }
  490. return DB::table('mp_animes')->where('id', $anime_id)->update([
  491. 'is_deleted' => 1,
  492. 'updated_at' => date('Y-m-d H:i:s')
  493. ]);
  494. }
  495. public function animeDetail($data) {
  496. $uid = Site::getUid();
  497. $anime_id = getProp($data, 'anime_id');
  498. $anime = DB::table('mp_animes')->where('id', $anime_id)->where('is_deleted', 0)->where('user_id', $uid)
  499. ->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();
  500. if (!$anime) Utils::throwError('20003:权限不足');
  501. $anime = (array)$anime;
  502. $anime['roles'] = json_decode($anime['roles']);
  503. $anime['scenes'] = json_decode($anime['scenes']);
  504. // 获取分集信息
  505. $episodes = DB::table('mp_anime_episodes')->where('anime_id', $anime_id)->where('is_default', 1)
  506. ->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"))
  507. ->orderBy('episode_number')->get()->map(function ($value) {
  508. return (array)$value;
  509. })->toArray();
  510. $anime['episodes'] = $episodes;
  511. // 获取当前仍在批量生成中的剧集任务(只展示 episodes 中尚未出现的剧集序号)
  512. $episodeNumbers = array_map('intval', array_column($episodes, 'episode_number'));
  513. $episodeTasks = DB::table('mp_batch_episode_generation_details')
  514. ->where('anime_id', $anime_id)
  515. ->whereIn('status', ['pending', 'processing', 'failed']) // 只获取待生成/生成中任务,已完成或失败的不显示
  516. ->orderBy('episode_number')
  517. ->get()
  518. ->map(function ($task) use ($episodeNumbers) {
  519. if (in_array((int)$task->episode_number, $episodeNumbers, true)) {
  520. return null;
  521. }
  522. return [
  523. 'episode_number' => (int)$task->episode_number,
  524. 'status' => $task->status,
  525. 'error_message' => $task->status == 'failed' ? $task->error_message : '',
  526. ];
  527. })
  528. ->filter()
  529. ->values()
  530. ->toArray();
  531. $anime['episode_tasks'] = $episodeTasks;
  532. return $anime;
  533. }
  534. public function episodeInfo($data) {
  535. $uid = Site::getUid();
  536. $anime_id = getProp($data, 'anime_id');
  537. $episode_id = getProp($data, 'episode_id');
  538. if (!$anime_id || !$episode_id) {
  539. Utils::throwError('1002:请选择剧集');
  540. }
  541. // 验证用户权限
  542. $anime = DB::table('mp_animes')->where('id', $anime_id)->where('user_id', $uid)->where('is_deleted', 0)->first();
  543. if (!$anime) Utils::throwError('20003:权限不足');
  544. $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();
  545. if (!$episode) Utils::throwError('20003:该剧集不存在!');
  546. $episode = (array)$episode;
  547. $episode['roles'] = json_decode($episode['roles'], true);
  548. // foreach($episode['roles'] as &$item) {
  549. // if (isset($item['pic_prompt']) && mb_substr($item['pic_prompt'], 0, 11) != '写实。全景,正面拍摄。') $item['pic_prompt'] = '写实。全景,正面拍摄。'.$item['pic_prompt'];
  550. // }
  551. $episode['scenes'] = json_decode($episode['scenes'], true);
  552. // foreach($episode['scenes'] as &$item) {
  553. // if (isset($item['pic_prompt']) && mb_substr($item['pic_prompt'], 0, 3) != '写实。') $item['pic_prompt'] = '写实。'.$item['pic_prompt'];
  554. // }
  555. // 获取分镜信息
  556. $segments = DB::table('mp_episode_segments')->where('anime_id', $anime_id)->where('episode_id', getProp($episode, 'episode_id'))->orderBy('segment_number')
  557. ->select('*')->get()->map(function ($value) {
  558. return (array)$value;
  559. })->toArray();
  560. // 使用公共方法构建分镜结构
  561. $segmentsStructure = $this->buildEpisodeSegmentsStructure($segments);
  562. $episode['acts'] = $segmentsStructure['acts'];
  563. $episode['total_duration'] = $segmentsStructure['total_duration'];
  564. return $episode;
  565. }
  566. public function episodeInfoForAce($data) {
  567. $anime_id = getProp($data, 'anime_id');
  568. $episode_id = getProp($data, 'episode_id');
  569. if (!$anime_id || !$episode_id) {
  570. Utils::throwError('1002:请选择剧集');
  571. }
  572. $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();
  573. if (!$episode) Utils::throwError('20003:该剧集不存在!');
  574. $episode = (array)$episode;
  575. $episode['roles'] = json_decode($episode['roles'], true);
  576. // foreach($episode['roles'] as &$item) {
  577. // if (isset($item['pic_prompt']) && mb_substr($item['pic_prompt'], 0, 11) != '写实。全景,正面拍摄。') $item['pic_prompt'] = '写实。全景,正面拍摄。'.$item['pic_prompt'];
  578. // }
  579. $episode['scenes'] = json_decode($episode['scenes'], true);
  580. // foreach($episode['scenes'] as &$item) {
  581. // if (isset($item['pic_prompt']) && mb_substr($item['pic_prompt'], 0, 3) != '写实。') $item['pic_prompt'] = '写实。'.$item['pic_prompt'];
  582. // }
  583. $episode['props'] = $episode['props'] ? json_decode($episode['props'], true) : [];
  584. // 获取分镜信息
  585. $segments = DB::table('mp_episode_segments')->where('anime_id', $anime_id)->where('episode_id', getProp($episode, 'episode_id'))->orderBy('act_number')
  586. ->select('*')->get()->map(function ($value) {
  587. return (array)$value;
  588. })->toArray();
  589. $segmentsStructure = $this->buildEpisodeActsStructureForAce($segments);
  590. $episode['acts'] = $segmentsStructure['acts'];
  591. $episode['total_duration'] = $segmentsStructure['total_duration'];
  592. // 获取mp_animes表中的视频参数
  593. $anime = DB::table('mp_animes')->where('id', $anime_id)->first(['video_model', 'video_resolution', 'video_ratio']);
  594. $episode['video_params'] = [
  595. 'video_model' => getProp($anime, 'video_model'),
  596. 'video_resolution' => getProp($anime, 'video_resolution'),
  597. 'ratio' => getProp($anime, 'video_ratio'),
  598. ];
  599. return $episode;
  600. }
  601. public function segmentInfo($data) {
  602. $uid = Site::getUid();
  603. $segment_id = getProp($data, 'segment_id');
  604. if (!$segment_id) {
  605. Utils::throwError('1002:请选择分镜');
  606. }
  607. // 获取分镜信息
  608. $segment = DB::table('mp_episode_segments')->where('segment_id', $segment_id)->first();
  609. // 验证用户权限
  610. if ($segment) {
  611. $anime = DB::table('mp_animes')->where('id', getProp($segment, 'anime_id'))->where('user_id', $uid)->where('is_deleted', 0)->first();
  612. if (!$anime) Utils::throwError('20003:权限不足');
  613. }
  614. $result = [
  615. 'segment_id' => getProp($segment, 'segment_id'),
  616. 'segment_number' => getProp($segment, 'segment_number'),
  617. 'segment_content' => getProp($segment, 'segment_content'),
  618. 'description' => getProp($segment, 'description'),
  619. 'composition' => getProp($segment, 'composition'),
  620. 'camera_movement' => getProp($segment, 'camera_movement'),
  621. 'voice_actor' => getProp($segment, 'voice_actor'),
  622. 'dialogue' => getProp($segment, 'dialogue'),
  623. 'frame_type' => getProp($segment, 'frame_type'),
  624. 'scene' => getProp($segment, 'scene'),
  625. 'characters' => getProp($segment, 'characters'),
  626. 'tail_frame' => getProp($segment, 'tail_frame'),
  627. 'emotion' => getProp($segment, 'emotion'),
  628. 'emotion_type' => getProp($segment, 'emotion_type'),
  629. 'gender' => getProp($segment, 'gender'),
  630. 'speed_ratio' => getProp($segment, 'speed_ratio'),
  631. 'loudness_ratio' => getProp($segment, 'loudness_ratio'),
  632. 'emotion_scale' => getProp($segment, 'emotion_scale'),
  633. 'pitch' => getProp($segment, 'pitch'),
  634. 'voice_name' => getProp($segment, 'voice_name'),
  635. 'voice_type' => getProp($segment, 'voice_type'),
  636. 'voice_audio_url' => getProp($segment, 'voice_audio_url'),
  637. 'img_url' => getProp($segment, 'img_url'),
  638. 'video_url' => getProp($segment, 'video_url'),
  639. 'last_frame_url' => getProp($segment, 'last_frame_url'),
  640. ];
  641. return $result;
  642. }
  643. public function copyEpisodeVersion($data) {
  644. $episode_id = getProp($data, 'episode_id');
  645. $uid = Site::getUid();
  646. $cpid = Site::getCpid();
  647. $episode = DB::table('mp_anime_episodes')->where('id', $episode_id)->first();
  648. if (!$episode) Utils::throwError('20003:该剧集不存在');
  649. $episode = (array)$episode;
  650. $anime_id = $episode['anime_id'];
  651. $episode_number = $episode['episode_number'];
  652. $count = DB::table('mp_anime_episodes')->where('anime_id', $anime_id)->where('episode_number', $episode_number)->count('id');
  653. $sequence = $count + 1;
  654. unset($episode['id']);
  655. $now = date('Y-m-d H:i:s');
  656. $episode['created_at'] = $now;
  657. $episode['updated_at'] = $now;
  658. $episode['is_default'] = 1;
  659. // 获取版本中含有"(副本"字样的个数
  660. $copy_count = DB::table('mp_anime_episodes')->where('anime_id', $anime_id)->where('episode_number', $episode_number)->where('title', 'like', '%(副本%')->count('id');
  661. $episode['title'] = $copy_count > 0 ? $episode['title']."(副本{$copy_count})" : $episode['title']."(副本)"; // 生成带(副本)字样的标题
  662. $episode['sequence'] = $sequence;
  663. $episode['is_generated'] = 0;
  664. $episode['cpid'] = $cpid;
  665. // 获取ace_mode
  666. $ace_mode = DB::table('mp_animes')->where('id', $anime_id)->value('ace_mode');
  667. try {
  668. DB::beginTransaction();
  669. DB::table('mp_anime_episodes')->where('anime_id', $anime_id)->where('episode_number', $episode_number)->update(['is_default' => 0, 'updated_at'=>$now]);
  670. // 新增副本
  671. $new_episode_id = DB::table('mp_anime_episodes')->insertGetId($episode);
  672. if (!$new_episode_id) {
  673. Utils::throwError('20003:创建副本失败!');
  674. }
  675. // 获取分镜数据并准备插入
  676. $segments_for_insert = DB::table('mp_episode_segments')
  677. ->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')
  678. ->where('episode_id', $episode_id)->orderBy('segment_number')->get()->map(function($item) use ($new_episode_id,$ace_mode) {
  679. $item = (array)$item;
  680. $item['episode_id'] = $new_episode_id;
  681. if ((int)$ace_mode !== 1) $item['segment_id'] = date('YmdHis').mt_rand(1000,9999).str_pad($item['segment_number'], 3, "0", STR_PAD_LEFT);
  682. $item['created_at'] = $item['updated_at'] = date('Y-m-d H:i:s');
  683. return $item;
  684. })->toArray();
  685. // 写入分镜数据
  686. $boolen2 = DB::table('mp_episode_segments')->insert($segments_for_insert);
  687. if (!$boolen2) {
  688. Utils::throwError('20003:写入分镜数据失败!');
  689. }
  690. // 写入对话历史
  691. $records = [
  692. [
  693. 'uid' => $uid,
  694. 'anime_id' => $anime_id,
  695. 'role' => 'user',
  696. 'content' => '创建副本',
  697. 'sequence' => $episode_number,
  698. 'episode_id' => $new_episode_id,
  699. 'created_at' => $now,
  700. 'updated_at' => $now
  701. ],
  702. [
  703. 'uid' => $uid,
  704. 'anime_id' => $anime_id,
  705. 'role' => 'assistant',
  706. 'content' => '好的,已为您创建副本',
  707. 'sequence' => $episode_number,
  708. 'episode_id' => $new_episode_id,
  709. 'created_at' => $now,
  710. 'updated_at' => $now
  711. ]
  712. ];
  713. $boolen3 = DB::table('mp_anime_records')->insert($records);
  714. if (!$boolen3) {
  715. Utils::throwError('20003:对话记录保存失败');
  716. }
  717. }catch (\Exception $e) {
  718. DB::rollBack();
  719. Utils::throwError('20003:'.$e->getMessage());
  720. }
  721. DB::commit();
  722. // 构建与 episodeInfo 方法一致的返回数据结构
  723. $result = [
  724. 'episode_id' => $new_episode_id,
  725. 'anime_id' => $anime_id,
  726. 'episode_number' => $episode_number,
  727. 'title' => $episode['title'],
  728. 'intro' => $episode['intro'],
  729. 'art_style' => $episode['art_style'],
  730. 'roles' => json_decode($episode['roles'], true),
  731. 'scenes' => json_decode($episode['scenes'], true),
  732. 'is_generated' => (int)$episode['is_generated']
  733. ];
  734. if ((int)$ace_mode === 1) {
  735. // 获取分镜信息
  736. $segments = DB::table('mp_episode_segments')->where('anime_id', $anime_id)->where('episode_id', $new_episode_id)->orderBy('act_number')
  737. ->select('*')->get()->map(function ($value) {
  738. return (array)$value;
  739. })->toArray();
  740. $segmentsStructure = $this->buildEpisodeActsStructureForAce($segments);
  741. }else {
  742. // 复用已有的分镜数据,按 act 分组(避免重复查询数据库)
  743. $segmentsStructure = $this->buildEpisodeSegmentsStructure($segments_for_insert);
  744. }
  745. $result['acts'] = $segmentsStructure['acts'];
  746. $result['total_duration'] = $segmentsStructure['total_duration'];
  747. return $result;
  748. }
  749. public function episodeVersions($data) {
  750. $anime_id = getProp($data, 'anime_id');
  751. $episode_id = getProp($data, 'episode_id');
  752. if (!$anime_id || !$episode_id) {
  753. Utils::throwError('1002:请选择剧集');
  754. }
  755. $episode_number = DB::table('mp_anime_episodes')->where('anime_id', $anime_id)->where('id', $episode_id)->value('episode_number');
  756. $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) {
  757. return (array)$value;
  758. })->toArray();
  759. if (!$episodes) Utils::throwError('20003:该剧集不存在!');
  760. foreach($episodes as &$episode) {
  761. $episode['version'] = 'V'.$episode['sequence'];
  762. $episode['roles'] = json_decode($episode['roles'], true);
  763. $episode['scenes'] = json_decode($episode['scenes'], true);
  764. // 获取分镜信息
  765. $segments = DB::table('mp_episode_segments')->where('anime_id', $anime_id)->where('episode_id', getProp($episode, 'episode_id'))->orderBy('segment_number')
  766. ->select('*')->get()->map(function ($value) {
  767. return (array)$value;
  768. })->toArray();
  769. // 使用公共方法构建分镜结构
  770. $segmentsStructure = $this->buildEpisodeSegmentsStructure($segments);
  771. $episode['acts'] = $segmentsStructure['acts'];
  772. $episode['total_duration'] = $segmentsStructure['total_duration'];
  773. }
  774. return $episodes;
  775. }
  776. public function bindEpisodeVersion($data) {
  777. $episode_id = getProp($data, 'episode_id');
  778. $episode = DB::table('mp_anime_episodes')->where('id', $episode_id)->first();
  779. if (!$episode) Utils::throwError('20003:该剧集不存在');
  780. $episode = (array)$episode;
  781. if ((int)$episode['is_default'] === 1) return true;
  782. try {
  783. DB::beginTransaction();
  784. // 移除is_default标志
  785. $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')]);
  786. if (!$boolen) {
  787. Utils::throwError('20003:更新失败!');
  788. }
  789. // 绑定副本
  790. $boolen2 = DB::table('mp_anime_episodes')->where('id', $episode_id)->update(['is_default' => 1, 'updated_at'=>date('Y-m-d H:i:s')]);
  791. if (!$boolen2) {
  792. Utils::throwError('20003:绑定失败!');
  793. }
  794. }catch (\Exception $e) {
  795. DB::rollBack();
  796. Utils::throwError('20003:'.$e->getMessage());
  797. }
  798. DB::commit();
  799. return true;
  800. }
  801. public function chatChangeImg($data) {
  802. $segment_id = getProp($data, 'segment_id');
  803. $type = getProp($data, 'type', 1); // 类型: 1.对话改图 2.图片生成
  804. $prompt = getProp($data, 'prompt');
  805. if (!$prompt || !$segment_id) {
  806. Utils::throwError('1002:请输入提示词,并且选择分镜');
  807. }
  808. $segment = DB::table("mp_episode_segments")->where('segment_id', $segment_id)->first();
  809. if (!$segment) Utils::throwError('20003:该分镜不存在!');
  810. if ((int)$type === 1) $ref_img_url = getProp($segment, 'img_url');
  811. else $ref_img_url = '';
  812. // $ref_img_url = '';
  813. if (empty($prompt)) {
  814. if (empty($ref_img_url)) {
  815. $prompt = getProp($segment, 'segment_content');
  816. }else {
  817. $prompt = '请根据图片生成';
  818. }
  819. }
  820. $anime_id = getProp($segment, 'anime_id');
  821. $episode_id = getProp($segment, 'episode_id');
  822. $episode_number = getProp($segment, 'episode_number');
  823. $episode = DB::table('mp_anime_episodes')->where('id', $episode_id)->first();
  824. $ratio = getProp($data, 'ratio');
  825. if (!$ratio) {
  826. $ratio = getProp($episode, 'ratio');
  827. if (!$ratio) $ratio = '9:16';
  828. }
  829. $art_style = getProp($episode, 'art_style');
  830. if ($art_style) {
  831. $prompt = "美术风格:{$art_style}\n{$prompt}";
  832. }
  833. $dimensions = $this->getRatioDimensions($ratio);
  834. $width = $dimensions['width'];
  835. $height = $dimensions['height'];
  836. try {
  837. $params = [
  838. 'alias_segment_id' => $segment_id,
  839. 'prompt' => $prompt,
  840. 'ref_img_urls' => !empty($ref_img_url) ? [$ref_img_url] : [],
  841. 'width' => $width,
  842. 'height' => $height
  843. ];
  844. // 优化提示词(不要生成字幕)
  845. $params['prompt'] = "前置要求:图片中不要带有任何对话台词或字幕信息\n".$params['prompt'];
  846. $task = $this->aiImageGenerationService->createImageGenerationTask($params);
  847. $task_id = $task->id;
  848. if (!$task_id) {
  849. Utils::throwError("20003:生成图片失败");
  850. }
  851. // 更新任务ID
  852. $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')]);
  853. if (!$boolen) Utils::throwError('20003:更新任务ID失败');
  854. } catch (\Exception $e) {
  855. Utils::throwError("20003:" . $e->getMessage());
  856. }
  857. // 创建任务之后先暂停10s等待异步任务完成
  858. sleep(10);
  859. $img_url = $this->loopGetPicTaskResult($task_id);
  860. if (!$img_url) Utils::throwError('20003:图片生成中,请稍后刷新');
  861. // 图片生成后新增对话记录
  862. try {
  863. $uid = Site::getUid();
  864. $now = date('Y-m-d H:i:s');
  865. // 使用AI反推图片提示词
  866. $pic_prompt = $this->generateImagePromptFromUrl($img_url);
  867. // 保存对话记录
  868. $records = [
  869. [
  870. 'uid' => $uid,
  871. 'anime_id' => $anime_id,
  872. 'sequence' => $episode_number,
  873. 'role' => 'user',
  874. 'content' => $prompt,
  875. 'segment_id' => $segment_id,
  876. 'pic_task_id' => $task_id,
  877. 'image_url' => '',
  878. 'created_at' => $now,
  879. 'updated_at' => $now
  880. ],
  881. [
  882. 'uid' => $uid,
  883. 'anime_id' => $anime_id,
  884. 'sequence' => $episode_number,
  885. 'role' => 'assistant',
  886. 'content' => $pic_prompt,
  887. 'segment_id' => $segment_id,
  888. 'pic_task_id' => $task_id,
  889. 'image_url' => $img_url,
  890. 'created_at' => $now,
  891. 'updated_at' => $now
  892. ]
  893. ];
  894. DB::table('mp_anime_records')->insert($records);
  895. } catch (\Exception $e) {
  896. // 记录日志但不影响主流程
  897. dLog('anime')->error('保存对话记录失败: ' . $e->getMessage(), [
  898. 'segment_id' => $segment_id,
  899. 'img_url' => $img_url
  900. ]);
  901. logDB('anime', 'error', '保存对话记录失败', [
  902. 'segment_id' => $segment_id,
  903. 'img_url' => $img_url,
  904. 'error' => $e->getMessage()
  905. ]);
  906. }
  907. return $img_url;
  908. }
  909. public function segmentChatHistory($data) {
  910. $segment_id = getProp($data, 'segment_id');
  911. if (!$segment_id) Utils::throwError('20003:请选择分镜!');
  912. $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');
  913. $chat = $query->orderBy('id')->get()->map(function ($value) {
  914. $value = (array)$value;
  915. $value['created_at'] = transDate($value['created_at']);
  916. return $value;
  917. })->toArray();
  918. // 获取历史图片
  919. $url = [];
  920. $pic_history = DB::table('mp_generate_pic_tasks')->where('alias_segment_id', $segment_id)->where('status', 'success')->orderBy('created_at', 'desc')->get();
  921. foreach($pic_history as $task) {
  922. $result_url = getProp($task, 'result_url');
  923. if (is_json($result_url)) {
  924. $url = array_merge($url, json_decode($result_url, true));
  925. }else {
  926. $url[] = $result_url;
  927. }
  928. }
  929. // 获取历史视频
  930. $video_history = DB::table('mp_generate_video_tasks')->where('alias_segment_id', $segment_id)->where('status', 'success')->orderBy('created_at', 'desc')->get();
  931. foreach($video_history as $task) {
  932. $result_url = getProp($task, 'compressed_url');
  933. if (is_json($result_url)) {
  934. $url = array_merge($url, json_decode($result_url, true));
  935. }else {
  936. $url[] = $result_url;
  937. }
  938. }
  939. return compact('chat', 'url');
  940. }
  941. public function changeEpisodeRoles($data) {
  942. $anime_id = getProp($data, 'anime_id');
  943. $episode_id = getProp($data, 'episode_id');
  944. $target_roles = getProp($data, 'roles');
  945. // 删除标志优先取最外层入参 is_deleted,兼容角色对象内部(roles.is_deleted)的传参
  946. $is_deleted = getProp($data, 'is_deleted', getProp($target_roles, 'is_deleted', 0));
  947. // 控制字段不随角色内容写入分集roles存储
  948. if (is_array($target_roles)) {
  949. unset($target_roles['is_deleted']);
  950. }
  951. // 参数验证
  952. if (!$anime_id) Utils::throwError('20003:请提供动漫ID');
  953. if (!$episode_id) Utils::throwError('20003:请提供剧集ID');
  954. if (!$target_roles) Utils::throwError('20003:请提供角色信息');
  955. // 验证剧集是否存在
  956. $episode = DB::table('mp_anime_episodes')
  957. ->where('anime_id', $anime_id)
  958. ->where('id', $episode_id)
  959. ->first();
  960. if (!$episode) Utils::throwError('20003:该剧集不存在');
  961. $roles = json_decode(getProp($episode, 'roles'), true);
  962. // 获取anime信息,检查是否有关联的script_id
  963. $anime = DB::table('mp_animes')->where('id', $anime_id)->first();
  964. if (!$anime) Utils::throwError('20003:动漫不存在');
  965. $script_id = getProp($anime, 'script_id');
  966. $episode_number = getProp($episode, 'episode_number', 1);
  967. $uid = Site::getUid();
  968. $cpid = Site::getCpid();
  969. try {
  970. $target_role_name = getProp($target_roles, 'role');
  971. if (empty($target_role_name)) {
  972. Utils::throwError('20003:角色名称不能为空');
  973. }
  974. // 如果是删除操作
  975. if ($is_deleted == 1) {
  976. // 从角色列表中移除该角色
  977. $roles = array_values(array_filter($roles, function($role) use ($target_role_name) {
  978. return getProp($role, 'role') !== $target_role_name;
  979. }));
  980. // 更新角色列表
  981. $result = DB::table('mp_anime_episodes')
  982. ->where('anime_id', $anime_id)
  983. ->where('id', $episode_id)
  984. ->update([
  985. 'roles' => json_encode($roles, 256),
  986. 'updated_at' => date('Y-m-d H:i:s')
  987. ]);
  988. if ($result === false) {
  989. Utils::throwError('20003:删除角色失败');
  990. }
  991. } else {
  992. // 新增或更新操作
  993. $role_found = false;
  994. $is_new_role = false;
  995. // 查找并更新已存在的角色
  996. foreach($roles as &$role) {
  997. if (getProp($role, 'role') === $target_role_name) {
  998. $role = $target_roles;
  999. $role_found = true;
  1000. break;
  1001. }
  1002. }
  1003. // 如果角色不存在,则新增
  1004. if (!$role_found) {
  1005. $roles[] = $target_roles;
  1006. $is_new_role = true;
  1007. }
  1008. // 更新角色列表
  1009. $result = DB::table('mp_anime_episodes')
  1010. ->where('anime_id', $anime_id)
  1011. ->where('id', $episode_id)
  1012. ->update([
  1013. 'roles' => json_encode($roles, 256),
  1014. 'updated_at' => date('Y-m-d H:i:s')
  1015. ]);
  1016. if ($result === false) {
  1017. Utils::throwError('20003:更新角色列表失败');
  1018. }
  1019. // 同步更新分镜表中对应主体的音色信息
  1020. $voice_name = getProp($target_roles, 'voice_name');
  1021. $voice_type = getProp($target_roles, 'voice_type');
  1022. $voice_audio_url = getProp($target_roles, 'voice_audio_url');
  1023. DB::table('mp_episode_segments')
  1024. ->where('anime_id', $anime_id)
  1025. ->where('episode_id', $episode_id)
  1026. ->where('voice_actor', $target_role_name)
  1027. ->update([
  1028. 'voice_name' => $voice_name,
  1029. 'voice_type' => $voice_type,
  1030. 'voice_audio_url' => $voice_audio_url,
  1031. 'updated_at' => date('Y-m-d H:i:s')
  1032. ]);
  1033. // 如果有关联的script_id,则同步到mp_products表
  1034. if ($script_id) {
  1035. // 查询剧本信息(仅同步属于当前用户的剧本,不属于则跳过后续资产同步)
  1036. $script = DB::table('mp_scripts')
  1037. ->where('id', $script_id)
  1038. ->where('user_id', $uid)
  1039. ->where('is_deleted', 0)
  1040. ->first();
  1041. if ($script) {
  1042. $script_name = $script->script_name ?? 'script_' . $script_id;
  1043. $product_name = getProp($target_roles, 'role');
  1044. $pic_prompt = getProp($target_roles, 'pic_prompt', '');
  1045. $url = getProp($target_roles, 'url', '');
  1046. $three_view_image_url = trim(getProp($target_roles, 'three_view_image_url', ''));
  1047. // 兼容 versions 传入数组或 JSON 字符串
  1048. $versions = getProp($target_roles, 'versions', null);
  1049. if (is_string($versions) && $versions !== '') {
  1050. $decoded_versions = json_decode($versions, true);
  1051. if (is_array($decoded_versions)) {
  1052. $versions = $decoded_versions;
  1053. }
  1054. }
  1055. $product_type = 1; // 1=角色
  1056. // 查找或创建以script_name命名的文件夹
  1057. $folder = DB::table('mp_products')
  1058. ->where('cpid', $cpid)
  1059. ->where('type', 2) // 文件夹类型
  1060. ->where('product', $product_type) // 角色类型
  1061. ->where('product_name', $script_name)
  1062. ->where('parent_id', 0)
  1063. ->where('is_deleted', 0)
  1064. ->first();
  1065. if (!$folder) {
  1066. // 创建文件夹
  1067. $folder_id = DB::table('mp_products')->insertGetId([
  1068. 'user_id' => $uid,
  1069. 'cpid' => $cpid,
  1070. 'type' => 2, // 文件夹
  1071. 'product' => $product_type, // 角色类型
  1072. 'parent_id' => 0,
  1073. 'level' => 1,
  1074. 'product_name' => $script_name,
  1075. 'sort_order' => time(),
  1076. 'is_deleted' => 0,
  1077. 'created_at' => date('Y-m-d H:i:s'),
  1078. 'updated_at' => date('Y-m-d H:i:s')
  1079. ]);
  1080. } else {
  1081. $folder_id = $folder->id;
  1082. }
  1083. // 查找该文件夹下是否已存在同名资产
  1084. $existing_product = DB::table('mp_products')
  1085. ->where('cpid', $cpid)
  1086. ->where('type', 1) // 资产类型
  1087. ->where('product', $product_type)
  1088. ->where('parent_id', $folder_id)
  1089. ->where('product_name', $product_name)
  1090. ->where('is_deleted', 0)
  1091. ->first();
  1092. if ($existing_product) {
  1093. // 更新已存在的资产
  1094. $updateData = [
  1095. 'pic_task_status' => '生成成功',
  1096. ];
  1097. if ($pic_prompt) $updateData['pic_prompt'] = $pic_prompt;
  1098. if ($url) $updateData['url'] = $url;
  1099. // 显式传入三视图(含空值)时同步写入,空值表示当前版本没有三视图
  1100. if (is_array($target_roles) && array_key_exists('three_view_image_url', $target_roles)) {
  1101. $updateData['three_view_image_url'] = trim(getProp($target_roles, 'three_view_image_url', ''));
  1102. }
  1103. // 处理versions字段,显式传入数组(含空数组)时覆盖
  1104. if (is_array($versions)) {
  1105. $updateData['versions'] = json_encode($versions, 256);
  1106. }
  1107. $updateData['updated_at'] = date('Y-m-d H:i:s');
  1108. DB::table('mp_products')
  1109. ->where('id', $existing_product->id)
  1110. ->update($updateData);
  1111. $product_id = $existing_product->id;
  1112. } else {
  1113. // 创建新资产
  1114. $product_id = DB::table('mp_products')->insertGetId([
  1115. 'user_id' => $uid,
  1116. 'cpid' => $cpid,
  1117. 'type' => 1, // 资产
  1118. 'product' => $product_type, // 角色
  1119. 'parent_id' => $folder_id,
  1120. 'level' => 2,
  1121. 'product_name' => $product_name,
  1122. 'url' => $url,
  1123. 'three_view_image_url' => $three_view_image_url,
  1124. 'pic_prompt' => $pic_prompt,
  1125. 'versions' => is_array($versions) ? json_encode($versions, 256) : '[]',
  1126. 'sort_order' => time(),
  1127. 'is_deleted' => 0,
  1128. 'pic_task_status' => '生成成功',
  1129. 'created_at' => date('Y-m-d H:i:s'),
  1130. 'updated_at' => date('Y-m-d H:i:s')
  1131. ]);
  1132. }
  1133. // 建立或更新绑定关系
  1134. $existing_mapping = DB::table('mp_script_product_mappings')
  1135. ->where('script_id', $script_id)
  1136. ->where('product_id', $product_id)
  1137. ->where('episode_number', $episode_number)
  1138. ->first();
  1139. if (!$existing_mapping) {
  1140. // 创建绑定关系
  1141. DB::table('mp_script_product_mappings')->insert([
  1142. 'script_id' => $script_id,
  1143. 'product_id' => $product_id,
  1144. 'episode_number' => $episode_number,
  1145. 'created_at' => date('Y-m-d H:i:s'),
  1146. 'updated_at' => date('Y-m-d H:i:s')
  1147. ]);
  1148. }
  1149. }
  1150. }
  1151. }
  1152. } catch (\Exception $e) {
  1153. dLog('anime')->error('更新剧集角色失败', [
  1154. 'anime_id' => $anime_id,
  1155. 'episode_id' => $episode_id,
  1156. 'error' => $e->getMessage()
  1157. ]);
  1158. Utils::throwError('20003:更新角色列表失败 ' . $e->getMessage());
  1159. }
  1160. return true;
  1161. }
  1162. public function changeEpisodeScenes($data) {
  1163. $anime_id = getProp($data, 'anime_id');
  1164. $episode_id = getProp($data, 'episode_id');
  1165. $target_scenes = getProp($data, 'scenes');
  1166. // 删除标志优先取最外层入参 is_deleted,兼容场景对象内部(scenes.is_deleted)的传参
  1167. $is_deleted = getProp($data, 'is_deleted', getProp($target_scenes, 'is_deleted', 0));
  1168. // 控制字段不随场景内容写入分集scenes存储
  1169. if (is_array($target_scenes)) {
  1170. unset($target_scenes['is_deleted']);
  1171. }
  1172. // 参数验证
  1173. if (!$anime_id) Utils::throwError('20003:请提供动漫ID');
  1174. if (!$episode_id) Utils::throwError('20003:请提供剧集ID');
  1175. if (!$target_scenes) Utils::throwError('20003:请提供场景信息');
  1176. // 验证剧集是否存在
  1177. $episode = DB::table('mp_anime_episodes')
  1178. ->where('anime_id', $anime_id)
  1179. ->where('id', $episode_id)
  1180. ->first();
  1181. if (!$episode) Utils::throwError('20003:该剧集不存在');
  1182. $scenes = json_decode(getProp($episode, 'scenes'), true);
  1183. // 获取anime信息,检查是否有关联的script_id
  1184. $anime = DB::table('mp_animes')->where('id', $anime_id)->first();
  1185. if (!$anime) Utils::throwError('20003:动漫不存在');
  1186. $script_id = getProp($anime, 'script_id');
  1187. $episode_number = getProp($episode, 'episode_number', 1);
  1188. $uid = Site::getUid();
  1189. $cpid = Site::getCpid();
  1190. try {
  1191. $target_scene_name = getProp($target_scenes, 'scene');
  1192. if (empty($target_scene_name)) {
  1193. Utils::throwError('20003:场景名称不能为空');
  1194. }
  1195. // 如果是删除操作
  1196. if ($is_deleted == 1) {
  1197. // 从场景列表中移除该场景
  1198. $scenes = array_values(array_filter($scenes, function($scene) use ($target_scene_name) {
  1199. return getProp($scene, 'scene') !== $target_scene_name;
  1200. }));
  1201. // 更新场景列表
  1202. $result = DB::table('mp_anime_episodes')
  1203. ->where('anime_id', $anime_id)
  1204. ->where('id', $episode_id)
  1205. ->update([
  1206. 'scenes' => json_encode($scenes, 256),
  1207. 'updated_at' => date('Y-m-d H:i:s')
  1208. ]);
  1209. if ($result === false) {
  1210. Utils::throwError('20003:删除场景失败');
  1211. }
  1212. } else {
  1213. // 新增或更新操作
  1214. $scene_found = false;
  1215. $is_new_scene = false;
  1216. // 查找并更新已存在的场景
  1217. foreach($scenes as &$scene) {
  1218. if (getProp($scene, 'scene') === $target_scene_name) {
  1219. $scene = $target_scenes;
  1220. $scene_found = true;
  1221. break;
  1222. }
  1223. }
  1224. // 如果场景不存在,则新增
  1225. if (!$scene_found) {
  1226. $scenes[] = $target_scenes;
  1227. $is_new_scene = true;
  1228. }
  1229. // 更新场景列表
  1230. $result = DB::table('mp_anime_episodes')
  1231. ->where('anime_id', $anime_id)
  1232. ->where('id', $episode_id)
  1233. ->update([
  1234. 'scenes' => json_encode($scenes, 256),
  1235. 'updated_at' => date('Y-m-d H:i:s')
  1236. ]);
  1237. if ($result === false) {
  1238. Utils::throwError('20003:更新场景列表失败');
  1239. }
  1240. // 如果有关联的script_id,则同步到mp_products表
  1241. if ($script_id) {
  1242. // 查询剧本信息(仅同步属于当前用户的剧本,不属于则跳过后续资产同步)
  1243. $script = DB::table('mp_scripts')
  1244. ->where('id', $script_id)
  1245. ->where('user_id', $uid)
  1246. ->where('is_deleted', 0)
  1247. ->first();
  1248. if ($script) {
  1249. $script_name = $script->script_name ?? 'script_' . $script_id;
  1250. $product_name = getProp($target_scenes, 'scene');
  1251. $pic_prompt = getProp($target_scenes, 'pic_prompt', '');
  1252. $url = getProp($target_scenes, 'url', '');
  1253. $three_view_image_url = trim(getProp($target_scenes, 'three_view_image_url', ''));
  1254. // 兼容 versions 传入数组或 JSON 字符串
  1255. $versions = getProp($target_scenes, 'versions', null);
  1256. if (is_string($versions) && $versions !== '') {
  1257. $decoded_versions = json_decode($versions, true);
  1258. if (is_array($decoded_versions)) {
  1259. $versions = $decoded_versions;
  1260. }
  1261. }
  1262. $product_type = 2; // 2=场景
  1263. // 查找或创建以script_name命名的文件夹
  1264. $folder = DB::table('mp_products')
  1265. ->where('cpid', $cpid)
  1266. ->where('type', 2) // 文件夹类型
  1267. ->where('product', $product_type) // 场景类型
  1268. ->where('product_name', $script_name)
  1269. ->where('parent_id', 0)
  1270. ->where('is_deleted', 0)
  1271. ->first();
  1272. if (!$folder) {
  1273. // 创建文件夹
  1274. $folder_id = DB::table('mp_products')->insertGetId([
  1275. 'user_id' => $uid,
  1276. 'cpid' => $cpid,
  1277. 'type' => 2, // 文件夹
  1278. 'product' => $product_type, // 场景类型
  1279. 'parent_id' => 0,
  1280. 'level' => 1,
  1281. 'product_name' => $script_name,
  1282. 'sort_order' => time(),
  1283. 'is_deleted' => 0,
  1284. 'created_at' => date('Y-m-d H:i:s'),
  1285. 'updated_at' => date('Y-m-d H:i:s')
  1286. ]);
  1287. } else {
  1288. $folder_id = $folder->id;
  1289. }
  1290. // 查找该文件夹下是否已存在同名资产
  1291. $existing_product = DB::table('mp_products')
  1292. ->where('cpid', $cpid)
  1293. ->where('type', 1) // 资产类型
  1294. ->where('product', $product_type)
  1295. ->where('parent_id', $folder_id)
  1296. ->where('product_name', $product_name)
  1297. ->where('is_deleted', 0)
  1298. ->first();
  1299. if ($existing_product) {
  1300. // 更新已存在的资产
  1301. $updateData = [
  1302. 'pic_task_status' => '生成成功'
  1303. ];
  1304. if ($pic_prompt) $updateData['pic_prompt'] = $pic_prompt;
  1305. if ($url) $updateData['url'] = $url;
  1306. // 显式传入三视图(含空值)时同步写入,空值表示当前版本没有三视图
  1307. if (is_array($target_scenes) && array_key_exists('three_view_image_url', $target_scenes)) {
  1308. $updateData['three_view_image_url'] = trim(getProp($target_scenes, 'three_view_image_url', ''));
  1309. }
  1310. // 处理versions字段,显式传入数组(含空数组)时覆盖
  1311. if (is_array($versions)) {
  1312. $updateData['versions'] = json_encode($versions, 256);
  1313. }
  1314. $updateData['updated_at'] = date('Y-m-d H:i:s');
  1315. DB::table('mp_products')
  1316. ->where('id', $existing_product->id)
  1317. ->update($updateData);
  1318. $product_id = $existing_product->id;
  1319. } else {
  1320. // 创建新资产
  1321. $product_id = DB::table('mp_products')->insertGetId([
  1322. 'user_id' => $uid,
  1323. 'cpid' => $cpid,
  1324. 'type' => 1, // 资产
  1325. 'product' => $product_type, // 场景
  1326. 'parent_id' => $folder_id,
  1327. 'level' => 2,
  1328. 'product_name' => $product_name,
  1329. 'url' => $url,
  1330. 'three_view_image_url' => $three_view_image_url,
  1331. 'pic_prompt' => $pic_prompt,
  1332. 'versions' => is_array($versions) ? json_encode($versions, 256) : '[]',
  1333. 'sort_order' => time(),
  1334. 'is_deleted' => 0,
  1335. 'pic_task_status' => '生成成功',
  1336. 'created_at' => date('Y-m-d H:i:s'),
  1337. 'updated_at' => date('Y-m-d H:i:s')
  1338. ]);
  1339. }
  1340. // 建立或更新绑定关系
  1341. $existing_mapping = DB::table('mp_script_product_mappings')
  1342. ->where('script_id', $script_id)
  1343. ->where('product_id', $product_id)
  1344. ->where('episode_number', $episode_number)
  1345. ->first();
  1346. if (!$existing_mapping) {
  1347. // 创建绑定关系
  1348. DB::table('mp_script_product_mappings')->insert([
  1349. 'script_id' => $script_id,
  1350. 'product_id' => $product_id,
  1351. 'episode_number' => $episode_number,
  1352. 'created_at' => date('Y-m-d H:i:s'),
  1353. 'updated_at' => date('Y-m-d H:i:s')
  1354. ]);
  1355. }
  1356. }
  1357. }
  1358. }
  1359. } catch (\Exception $e) {
  1360. dLog('anime')->error('更新剧集场景失败', [
  1361. 'anime_id' => $anime_id,
  1362. 'episode_id' => $episode_id,
  1363. 'error' => $e->getMessage()
  1364. ]);
  1365. Utils::throwError('20003:更新场景列表失败 ' . $e->getMessage());
  1366. }
  1367. return true;
  1368. }
  1369. public function changeEpisodeProps($data) {
  1370. $anime_id = getProp($data, 'anime_id');
  1371. $episode_id = getProp($data, 'episode_id');
  1372. $target_props = getProp($data, 'props');
  1373. // 删除标志优先取最外层入参 is_deleted,兼容道具对象内部(props.is_deleted)的传参
  1374. $is_deleted = getProp($data, 'is_deleted', getProp($target_props, 'is_deleted', 0));
  1375. // 控制字段不随道具内容写入分集props存储
  1376. if (is_array($target_props)) {
  1377. unset($target_props['is_deleted']);
  1378. }
  1379. // 参数验证
  1380. if (!$anime_id) Utils::throwError('20003:请提供动漫ID');
  1381. if (!$episode_id) Utils::throwError('20003:请提供剧集ID');
  1382. if (!$target_props) Utils::throwError('20003:请提供道具信息');
  1383. // 验证剧集是否存在
  1384. $episode = DB::table('mp_anime_episodes')
  1385. ->where('anime_id', $anime_id)
  1386. ->where('id', $episode_id)
  1387. ->first();
  1388. if (!$episode) Utils::throwError('20003:该剧集不存在');
  1389. $props = json_decode(getProp($episode, 'props'), true);
  1390. // 获取anime信息,检查是否有关联的script_id
  1391. $anime = DB::table('mp_animes')->where('id', $anime_id)->first();
  1392. if (!$anime) Utils::throwError('20003:动漫不存在');
  1393. $script_id = getProp($anime, 'script_id');
  1394. $episode_number = getProp($episode, 'episode_number', 1);
  1395. $uid = Site::getUid();
  1396. $cpid = Site::getCpid();
  1397. try {
  1398. $target_prop_name = getProp($target_props, 'prop');
  1399. if (empty($target_prop_name)) {
  1400. Utils::throwError('20003:道具名称不能为空');
  1401. }
  1402. // 如果是删除操作
  1403. if ($is_deleted == 1) {
  1404. // 从道具列表中移除该道具
  1405. $props = array_values(array_filter($props, function($prop) use ($target_prop_name) {
  1406. return getProp($prop, 'prop') !== $target_prop_name;
  1407. }));
  1408. // 更新道具列表
  1409. $result = DB::table('mp_anime_episodes')
  1410. ->where('anime_id', $anime_id)
  1411. ->where('id', $episode_id)
  1412. ->update([
  1413. 'props' => json_encode($props, 256),
  1414. 'updated_at' => date('Y-m-d H:i:s')
  1415. ]);
  1416. if ($result === false) {
  1417. Utils::throwError('20003:删除道具失败');
  1418. }
  1419. } else {
  1420. // 新增或更新操作
  1421. $prop_found = false;
  1422. $is_new_prop = false;
  1423. // 查找并更新已存在的道具
  1424. foreach($props as &$prop) {
  1425. if (getProp($prop, 'prop') === $target_prop_name) {
  1426. $prop = $target_props;
  1427. $prop_found = true;
  1428. break;
  1429. }
  1430. }
  1431. // 如果道具不存在,则新增
  1432. if (!$prop_found) {
  1433. $props[] = $target_props;
  1434. $is_new_prop = true;
  1435. }
  1436. // 更新道具列表
  1437. $result = DB::table('mp_anime_episodes')
  1438. ->where('anime_id', $anime_id)
  1439. ->where('id', $episode_id)
  1440. ->update([
  1441. 'props' => json_encode($props, 256),
  1442. 'updated_at' => date('Y-m-d H:i:s')
  1443. ]);
  1444. if ($result === false) {
  1445. Utils::throwError('20003:更新道具列表失败');
  1446. }
  1447. // 如果有关联的script_id,则同步到mp_products表
  1448. if ($script_id) {
  1449. // 查询剧本信息(仅同步属于当前用户的剧本,不属于则跳过后续资产同步)
  1450. $script = DB::table('mp_scripts')
  1451. ->where('id', $script_id)
  1452. ->where('user_id', $uid)
  1453. ->where('is_deleted', 0)
  1454. ->first();
  1455. if ($script) {
  1456. $script_name = $script->script_name ?? 'script_' . $script_id;
  1457. $product_name = getProp($target_props, 'prop');
  1458. $pic_prompt = getProp($target_props, 'pic_prompt', '');
  1459. $url = getProp($target_props, 'url', '');
  1460. $three_view_image_url = trim(getProp($target_props, 'three_view_image_url', ''));
  1461. // 兼容 versions 传入数组或 JSON 字符串
  1462. $versions = getProp($target_props, 'versions', null);
  1463. if (is_string($versions) && $versions !== '') {
  1464. $decoded_versions = json_decode($versions, true);
  1465. if (is_array($decoded_versions)) {
  1466. $versions = $decoded_versions;
  1467. }
  1468. }
  1469. $product_type = 3; // 3=道具
  1470. // 查找或创建以script_name命名的文件夹
  1471. $folder = DB::table('mp_products')
  1472. ->where('cpid', $cpid)
  1473. ->where('type', 2) // 文件夹类型
  1474. ->where('product', $product_type) // 道具类型
  1475. ->where('product_name', $script_name)
  1476. ->where('parent_id', 0)
  1477. ->where('is_deleted', 0)
  1478. ->first();
  1479. if (!$folder) {
  1480. // 创建文件夹
  1481. $folder_id = DB::table('mp_products')->insertGetId([
  1482. 'user_id' => $uid,
  1483. 'cpid' => $cpid,
  1484. 'type' => 2, // 文件夹
  1485. 'product' => $product_type, // 道具类型
  1486. 'parent_id' => 0,
  1487. 'level' => 1,
  1488. 'product_name' => $script_name,
  1489. 'sort_order' => time(),
  1490. 'is_deleted' => 0,
  1491. 'created_at' => date('Y-m-d H:i:s'),
  1492. 'updated_at' => date('Y-m-d H:i:s')
  1493. ]);
  1494. } else {
  1495. $folder_id = $folder->id;
  1496. }
  1497. // 查找该文件夹下是否已存在同名资产
  1498. $existing_product = DB::table('mp_products')
  1499. ->where('cpid', $cpid)
  1500. ->where('type', 1) // 资产类型
  1501. ->where('product', $product_type)
  1502. ->where('parent_id', $folder_id)
  1503. ->where('product_name', $product_name)
  1504. ->where('is_deleted', 0)
  1505. ->first();
  1506. if ($existing_product) {
  1507. // 更新已存在的资产
  1508. $updateData = [
  1509. 'pic_task_status' => '生成成功'
  1510. ];
  1511. if ($pic_prompt) $updateData['pic_prompt'] = $pic_prompt;
  1512. if ($url) $updateData['url'] = $url;
  1513. // 显式传入三视图(含空值)时同步写入,空值表示当前版本没有三视图
  1514. if (is_array($target_props) && array_key_exists('three_view_image_url', $target_props)) {
  1515. $updateData['three_view_image_url'] = trim(getProp($target_props, 'three_view_image_url', ''));
  1516. }
  1517. // 处理versions字段,显式传入数组(含空数组)时覆盖
  1518. if (is_array($versions)) {
  1519. $updateData['versions'] = json_encode($versions, 256);
  1520. }
  1521. $updateData['updated_at'] = date('Y-m-d H:i:s');
  1522. DB::table('mp_products')
  1523. ->where('id', $existing_product->id)
  1524. ->update($updateData);
  1525. $product_id = $existing_product->id;
  1526. } else {
  1527. // 创建新资产
  1528. $product_id = DB::table('mp_products')->insertGetId([
  1529. 'user_id' => $uid,
  1530. 'cpid' => $cpid,
  1531. 'type' => 1, // 资产
  1532. 'product' => $product_type, // 道具
  1533. 'parent_id' => $folder_id,
  1534. 'level' => 2,
  1535. 'product_name' => $product_name,
  1536. 'url' => $url,
  1537. 'three_view_image_url' => $three_view_image_url,
  1538. 'pic_prompt' => $pic_prompt,
  1539. 'versions' => is_array($versions) ? json_encode($versions, 256) : '[]',
  1540. 'sort_order' => time(),
  1541. 'is_deleted' => 0,
  1542. 'pic_task_status' => '生成成功',
  1543. 'created_at' => date('Y-m-d H:i:s'),
  1544. 'updated_at' => date('Y-m-d H:i:s')
  1545. ]);
  1546. }
  1547. // 建立或更新绑定关系
  1548. $existing_mapping = DB::table('mp_script_product_mappings')
  1549. ->where('script_id', $script_id)
  1550. ->where('product_id', $product_id)
  1551. ->where('episode_number', $episode_number)
  1552. ->first();
  1553. if (!$existing_mapping) {
  1554. // 创建绑定关系
  1555. DB::table('mp_script_product_mappings')->insert([
  1556. 'script_id' => $script_id,
  1557. 'product_id' => $product_id,
  1558. 'episode_number' => $episode_number,
  1559. 'created_at' => date('Y-m-d H:i:s'),
  1560. 'updated_at' => date('Y-m-d H:i:s')
  1561. ]);
  1562. }
  1563. }
  1564. }
  1565. }
  1566. } catch (\Exception $e) {
  1567. dLog('anime')->error('更新剧集道具失败', [
  1568. 'anime_id' => $anime_id,
  1569. 'episode_id' => $episode_id,
  1570. 'error' => $e->getMessage()
  1571. ]);
  1572. Utils::throwError('20003:更新道具列表失败 ' . $e->getMessage());
  1573. }
  1574. return true;
  1575. }
  1576. public function editSegment($data) {
  1577. $segment_id = getProp($data, 'segment_id');
  1578. $segment_content = getProp($data, 'segment_content');
  1579. $image_url = getProp($data, 'image_url');
  1580. $video_url = getProp($data, 'video_url');
  1581. // 参数验证
  1582. if (!$segment_id) Utils::throwError('20003:请提供分镜ID');
  1583. // 验证分镜是否存在
  1584. $segment = DB::table('mp_episode_segments')
  1585. ->where('segment_id', $segment_id)
  1586. ->first();
  1587. if (!$segment) Utils::throwError('20003:该分镜不存在');
  1588. $dubTaskId = 0;
  1589. try {
  1590. DB::beginTransaction();
  1591. // 准备更新数据
  1592. $update_data = [
  1593. 'updated_at' => date('Y-m-d H:i:s')
  1594. ];
  1595. if ($segment_content) {
  1596. // 先将segment_content赋值到update_data
  1597. $update_data['segment_content'] = $segment_content;
  1598. // 使用现有方法分析segment_content,提取各个字段
  1599. $this->handleSegmentContent($update_data);
  1600. // 如果有对话内容,创建视频配音合成任务
  1601. $dialogue = getProp($update_data, 'dialogue');
  1602. if (!empty($dialogue)) {
  1603. $now = date('Y-m-d H:i:s');
  1604. $generate_json = [
  1605. 'text' => $dialogue,
  1606. 'role' => getProp($update_data, 'voice_actor'),
  1607. 'voice_type' => getProp($update_data, 'voice_type'),
  1608. 'voice_name' => getProp($update_data, 'voice_name'),
  1609. 'emotion' => getProp($update_data, 'emotion'),
  1610. 'emotion_type' => getProp($update_data, 'emotion_type'),
  1611. 'gender' => getProp($update_data, 'gender'),
  1612. 'speed_ratio' => getProp($update_data, 'speed_ratio', 0),
  1613. 'loudness_ratio' => getProp($update_data, 'loudness_ratio', 0),
  1614. 'emotion_scale' => getProp($update_data, 'emotion_scale', 0),
  1615. 'pitch' => getProp($update_data, 'pitch', 0),
  1616. ];
  1617. // 插入视频配音合成任务
  1618. $dubTaskId = DB::table('mp_dub_video_tasks')->insertGetId([
  1619. 'alias_segment_id' => $segment_id,
  1620. 'generate_status' => '执行中',
  1621. 'audio_url' => '',
  1622. 'generate_json' => json_encode($generate_json, 256),
  1623. 'created_at' => $now,
  1624. 'updated_at' => $now,
  1625. ]);
  1626. if (!$dubTaskId) {
  1627. Utils::throwError('20003:创建配音任务失败!');
  1628. }
  1629. $update_data['audio_url'] = '';
  1630. } else {
  1631. // dialogue为空时,直接写入默认音频信息
  1632. $update_data['audio_url'] = 'https://zw-audiobook.tos-cn-beijing.volces.com/effects/ellipses_2s.mp3';
  1633. $update_data['audio_duration'] = 2.0;
  1634. $update_data['subtitle_info'] = json_encode(['duration' => 2.0, 'words' => []], 256);
  1635. }
  1636. }
  1637. if ($image_url) {
  1638. $update_data['img_url'] = $image_url;
  1639. // 同时写入一个简单的图片生成任务
  1640. $pic_task = [
  1641. 'alias_segment_id' => $segment_id,
  1642. 'ref_img_url' => json_encode([]),
  1643. 'status' => 'success',
  1644. 'result_url' => json_encode([$image_url], 256),
  1645. 'model' => '',
  1646. 'created_at' => date('Y-m-d H:i:s'),
  1647. 'updated_at' => date('Y-m-d H:i:s'),
  1648. ];
  1649. DB::table('mp_generate_pic_tasks')->insert($pic_task);
  1650. }
  1651. if ($video_url) {
  1652. $update_data['origin_video_url'] = $video_url;
  1653. $compressed_video_url = compressVideo($video_url);
  1654. $update_data['current_type'] = 2;
  1655. $update_data['video_url'] = $compressed_video_url ?: $video_url;
  1656. // 同时写入一个简单的视频生成任务
  1657. $video_task = [
  1658. 'alias_segment_id' => $segment_id,
  1659. 'status' => 'success',
  1660. 'result_url' => $update_data['origin_video_url'],
  1661. 'compressed_url' => $update_data['video_url'],
  1662. 'created_at' => date('Y-m-d H:i:s'),
  1663. 'updated_at' => date('Y-m-d H:i:s'),
  1664. ];
  1665. DB::table('mp_generate_video_tasks')->insert($video_task);
  1666. }
  1667. // 更新分镜信息
  1668. $result = DB::table('mp_episode_segments')
  1669. ->where('segment_id', $segment_id)
  1670. ->update($update_data);
  1671. if ($result === false) {
  1672. Utils::throwError('20003:更新分镜剧本失败');
  1673. }
  1674. DB::commit();
  1675. // 如果有创建音频生成任务则调用API
  1676. if ($dubTaskId) {
  1677. // 请求远程服务器执行生成
  1678. $client = new Client(['timeout' => 300, 'verify' => false]);
  1679. $result = $client->get("http://122.9.129.83:5000/api/anime/genAudio?taskId={$dubTaskId}");
  1680. $response = $result->getBody()->getContents();
  1681. $response_arr = json_decode($response, true);
  1682. if (!isset($response_arr['code']) || (int)$response_arr['code'] !== 0) {
  1683. $error_msg = isset($response_arr['msg']) ? $response_arr['msg'] : '未知错误';
  1684. dLog('anime')->error('火山生成音频失败', ['error' => $error_msg, 'task_id' => $dubTaskId, 'segment_id'=>$segment_id]);
  1685. logDB('anime', 'error', '火山生成音频失败', ['error' => $error_msg, 'task_id' => $dubTaskId, 'segment_id'=>$segment_id]);
  1686. Utils::throwError('20003:火山生成音频失败');
  1687. }
  1688. }
  1689. return true;
  1690. } catch (\Exception $e) {
  1691. DB::rollBack();
  1692. dLog('anime')->error('更新分镜剧本失败', [
  1693. 'segment_id' => $segment_id,
  1694. 'error' => $e->getMessage()
  1695. ]);
  1696. Utils::throwError('20003:更新分镜剧本失败 ' . $e->getMessage());
  1697. }
  1698. }
  1699. public function batchSetSegmentPics($data) {
  1700. $anime_id = getProp($data, 'anime_id');
  1701. $episode_id = getProp($data, 'episode_id');
  1702. $ratio = getProp($data, 'ratio');
  1703. $dimensions = $this->getRatioDimensions($ratio);
  1704. $width = $dimensions['width'];
  1705. $height = $dimensions['height'];
  1706. if (!$anime_id || !$episode_id) {
  1707. Utils::throwError('1002:请选择剧集');
  1708. }
  1709. // 获取剧集信息
  1710. $episode = DB::table('mp_anime_episodes')
  1711. ->where('anime_id', $anime_id)
  1712. ->where('id', $episode_id)
  1713. ->where('is_default', 1)
  1714. ->select('id as episode_id', 'anime_id', 'episode_number', 'roles', 'scenes', 'image_model')
  1715. ->first();
  1716. if (!$episode) {
  1717. Utils::throwError('20003:该剧集不存在');
  1718. }
  1719. $model = getProp($data, 'model');
  1720. if (!$model) {
  1721. $model = getProp($episode, 'image_model');
  1722. if (!$model) {
  1723. // episode表也没有,使用默认值
  1724. $model = 'gpt-image-2';
  1725. }
  1726. }
  1727. // 验证模型是否在可用模型表中
  1728. if (!DB::table('mp_image_models')->where('model', $model)->where('is_enabled', 1)->exists()) {
  1729. $model = 'gpt-image-2';
  1730. }
  1731. $roles = json_decode(getProp($episode, 'roles'), true);
  1732. if (!$roles) {
  1733. Utils::throwError('20003:角色信息格式错误');
  1734. }
  1735. // 构建角色名称到参考图的映射
  1736. $role_map = [];
  1737. foreach ($roles as $role) {
  1738. $role_name = getProp($role, 'role');
  1739. $role_url = getProp($role, 'url');
  1740. if (!empty($role_name) && !empty($role_url)) {
  1741. // // 处理角色名称,去除装扮后缀(如:许芸-校服装 -> 许芸)- 修复中文乱码问题(弃用,容易产生重复图片)
  1742. // $base_name = preg_replace('/[--].*$/u', '', $role_name);
  1743. // $role_map[$base_name] = $role_url;
  1744. // 同时保存完整名称的映射
  1745. $role_map[$role_name] = $role_url;
  1746. }
  1747. }
  1748. $scenes = json_decode(getProp($episode, 'roles'), true);
  1749. if (!$scenes) {
  1750. Utils::throwError('20003:场景信息格式错误');
  1751. }
  1752. // 构建角色名称到参考图的映射
  1753. $scene_map = [];
  1754. foreach ($scenes as $scene) {
  1755. $scene_name = getProp($scene, 'scene');
  1756. $scene_url = getProp($scene, 'url');
  1757. if (!empty($scene_name) && !empty($scene_url)) {
  1758. $scene_map[$scene_name] = $scene_url;
  1759. }
  1760. }
  1761. // 获取所有分镜信息
  1762. $segments = DB::table('mp_episode_segments')
  1763. ->where('anime_id', $anime_id)
  1764. ->where('episode_id', $episode_id)
  1765. ->whereNotIn('pic_task_status', ['已完成', '生成中'])
  1766. ->orderBy('segment_number')
  1767. ->get()
  1768. ->toArray();
  1769. if (empty($segments)) {
  1770. Utils::throwError('20003:所有分镜图片已完成或正在生成中');
  1771. }
  1772. // 保存图片比例
  1773. DB::table('mp_anime_episodes')->where('id', $episode_id)->update(['ratio' => $ratio, 'updated_at' => date('Y-m-d H:i:s')]);
  1774. $updated_segments = [];
  1775. $failed_segments = [];
  1776. // 批量为每个分镜生成图片任务
  1777. foreach ($segments as $segment) {
  1778. $segment_id = $segment->segment_id;
  1779. $segment_content = $segment->segment_content;
  1780. if (empty($segment_content)) {
  1781. $failed_segments[] = [
  1782. 'segment_id' => $segment_id,
  1783. 'error' => '分镜内容为空'
  1784. ];
  1785. continue;
  1786. }
  1787. try {
  1788. $dubTaskId = 0;
  1789. // 解析分镜内容,提取画面描述作为主要提示词
  1790. $prompt = $segment_content;
  1791. $ref_img_urls = [];
  1792. // 分镜场景
  1793. $scene = getProp($segment, 'scene');
  1794. $matched_scene = '';
  1795. if (isset($scene_map[$scene])) {
  1796. $img_index = count($ref_img_urls) + 1;
  1797. $prompt = "场景:$scene(图$img_index)\n$prompt";
  1798. $ref_img_urls[] = $scene_map[$scene];
  1799. $matched_scene = $scene;
  1800. }
  1801. // 分镜角色
  1802. $characters = getProp($segment, 'characters');
  1803. $characters = str_replace(['、', ',', ';'], ',', $characters);
  1804. $roles = explode(',', $characters);
  1805. // 从分镜内容中提取涉及的角色
  1806. $segment_characters = $this->extractCharactersFromSegment($segment_content, array_keys($role_map), $roles);
  1807. // 获取匹配角色的参考图
  1808. foreach ($segment_characters as $character) {
  1809. if (isset($role_map[$character])) {
  1810. // 将$prompt中出现的角色替换成角色(图1、2、3,序号是$ref_img_urls的个数加1)
  1811. $img_index = count($ref_img_urls) + 1;
  1812. $prompt = str_replace($character, $character . '(图' . $img_index . ')', $prompt);
  1813. $ref_img_urls[] = $role_map[$character];
  1814. }
  1815. }
  1816. // 如果没有找到匹配的角色参考图,不使用参考图
  1817. if (empty($ref_img_urls)) {
  1818. $ref_img_urls = [];
  1819. }
  1820. // 准备生成任务参数
  1821. $params = [
  1822. 'model' => $model,
  1823. 'alias_segment_id' => $segment_id,
  1824. 'prompt' => $prompt,
  1825. 'ref_img_urls' => $ref_img_urls,
  1826. 'width' => $width,
  1827. 'height' => $height,
  1828. ];
  1829. // 优化提示词(不要生成字幕)
  1830. $params['prompt'] = "前置要求:图片中不要带有任何对话台词或字幕信息\n".$params['prompt'];
  1831. // $task_id = mt_rand(100000, 999999);
  1832. // 调用AI图片生成服务
  1833. $task = $this->aiImageGenerationService->createImageGenerationTask($params);
  1834. $task_id = $task->id;
  1835. if (!$task_id) {
  1836. $failed_segments[] = [
  1837. 'segment_id' => $segment_id,
  1838. 'error' => '创建生成任务失败'
  1839. ];
  1840. continue;
  1841. }
  1842. $update_data = [
  1843. 'pic_task_id' => $task_id,
  1844. 'pic_task_status' => '生成中',
  1845. 'audio_url' => '',
  1846. 'updated_at' => date('Y-m-d H:i:s')
  1847. ];
  1848. // 如果有对话内容,创建视频配音合成任务
  1849. $dialogue = getProp($segment, 'dialogue');
  1850. if (!empty($dialogue)) {
  1851. $now = date('Y-m-d H:i:s');
  1852. $generate_json = [
  1853. 'text' => $dialogue,
  1854. 'role' => getProp($segment, 'voice_actor'),
  1855. 'voice_type' => getProp($segment, 'voice_type'),
  1856. 'voice_name' => getProp($segment, 'voice_name'),
  1857. 'emotion' => getProp($segment, 'emotion'),
  1858. 'emotion_type' => getProp($segment, 'emotion_type'),
  1859. 'gender' => getProp($segment, 'gender'),
  1860. 'speed_ratio' => getProp($segment, 'speed_ratio', 0),
  1861. 'loudness_ratio' => getProp($segment, 'loudness_ratio', 0),
  1862. 'emotion_scale' => getProp($segment, 'emotion_scale', 0),
  1863. 'pitch' => getProp($segment, 'pitch', 0),
  1864. ];
  1865. // 插入视频配音合成任务
  1866. $dubTaskId = DB::table('mp_dub_video_tasks')->insertGetId([
  1867. 'alias_segment_id' => $segment_id,
  1868. 'generate_status' => '执行中',
  1869. 'audio_url' => '',
  1870. 'generate_json' => json_encode($generate_json, 256),
  1871. 'created_at' => $now,
  1872. 'updated_at' => $now,
  1873. ]);
  1874. if (!$dubTaskId) {
  1875. dLog('anime')->error('火山生成音频失败', ['segment_id' => $segment_id, 'generate_json'=>$generate_json]);
  1876. logDB('anime', 'error', '火山生成音频失败', ['segment_id' => $segment_id, 'generate_json'=>$generate_json]);
  1877. // Utils::throwError('20003:创建配音任务失败!');
  1878. }
  1879. } else {
  1880. // dialogue为空时,直接写入默认音频信息到分镜表
  1881. $update_data['audio_url'] = 'https://zw-audiobook.tos-cn-beijing.volces.com/effects/ellipses_2s.mp3';
  1882. $update_data['audio_duration'] = 2.0;
  1883. $update_data['subtitle_info'] = json_encode(['duration' => 2.0, 'words' => []], 256);
  1884. }
  1885. // 更新分镜的任务信息
  1886. $update_result = DB::table('mp_episode_segments')
  1887. ->where('segment_id', $segment_id)
  1888. ->update($update_data);
  1889. // 如果是第一集的首帧图片,则存入待更新数组
  1890. if ($update_result && (int)getProp($segment, 'episode_number') === 1 && (int)getProp($segment, 'segment_number') === 1) {
  1891. Redis::sadd('anime_first_frame_urls', $segment_id);
  1892. }
  1893. if ($update_result) {
  1894. $updated_segments[] = [
  1895. 'segment_id' => $segment_id,
  1896. 'task_id' => $task_id,
  1897. 'status' => '生成中',
  1898. 'matched_scenes' => $matched_scene,
  1899. 'matched_roles' => $segment_characters,
  1900. 'ref_urls_count' => count($ref_img_urls)
  1901. ];
  1902. } else {
  1903. $failed_segments[] = [
  1904. 'segment_id' => $segment_id,
  1905. 'error' => '更新分镜任务状态失败'
  1906. ];
  1907. }
  1908. if ($dubTaskId) {
  1909. sleep(1);
  1910. // 请求远程服务器执行生成
  1911. $client = new Client(['timeout' => 300, 'verify' => false]);
  1912. $result = $client->get("http://122.9.129.83:5000/api/anime/genAudio?taskId={$dubTaskId}");
  1913. $response = $result->getBody()->getContents();
  1914. $response_arr = json_decode($response, true);
  1915. if (!isset($response_arr['code']) || (int)$response_arr['code'] !== 0) {
  1916. $error_msg = isset($response_arr['msg']) ? $response_arr['msg'] : '未知错误';
  1917. dLog('anime')->error('火山生成音频失败', ['error' => $error_msg, 'task_id' => $dubTaskId, 'segment_id' => $segment_id]);
  1918. logDB('anime', 'error', '火山生成音频失败', ['error' => $error_msg, 'task_id' => $dubTaskId, 'segment_id' => $segment_id]);
  1919. }
  1920. }
  1921. } catch (\Exception $e) {
  1922. $failed_segments[] = [
  1923. 'segment_id' => $segment_id,
  1924. 'error' => $e->getMessage()
  1925. ];
  1926. }
  1927. }
  1928. // 更新剧集生成状态
  1929. if (!empty($updated_segments)) {
  1930. DB::table('mp_anime_episodes')
  1931. ->where('id', $episode_id)
  1932. ->update([
  1933. 'is_generated' => 1,
  1934. 'updated_at' => date('Y-m-d H:i:s')
  1935. ]);
  1936. }
  1937. return [
  1938. 'success_count' => count($updated_segments),
  1939. 'failed_count' => count($failed_segments),
  1940. 'success_segments' => $updated_segments,
  1941. 'failed_segments' => $failed_segments,
  1942. 'total_segments' => count($segments)
  1943. ];
  1944. }
  1945. public function reGenerateSegment($data) {
  1946. $segment_id = getProp($data, 'segment_id');
  1947. $segment = DB::table('mp_episode_segments')->where('segment_id', $segment_id)->first();
  1948. $anime_id = getProp($segment, 'anime_id');
  1949. $episode_id = getProp($segment, 'episode_id');
  1950. $episode_number = getProp($segment, 'episode_number');
  1951. $segment_content = getProp($data, 'segment_content');
  1952. $ratio = getProp($data, 'ratio');
  1953. if (!$ratio) {
  1954. $ratio = DB::table('mp_anime_episodes')->where('id', $episode_id)->value('ratio');
  1955. if (!$ratio) $ratio = '9:16';
  1956. }
  1957. $dimensions = $this->getRatioDimensions($ratio);
  1958. $width = $dimensions['width'];
  1959. $height = $dimensions['height'];
  1960. if (!$anime_id || !$episode_id) {
  1961. Utils::throwError('1002:请选择分镜');
  1962. }
  1963. // 使用文生文模型重新解析segment_content
  1964. if (!empty($segment_content)) {
  1965. $segment_content = $this->parseSegmentContentWithAI($segment_content);
  1966. }
  1967. // 获取动漫的角色信息(包含参考图)
  1968. $anime = DB::table('mp_animes')
  1969. ->where('id', $anime_id)
  1970. ->select('roles', 'scenes')
  1971. ->first();
  1972. if (!$anime || !$anime->roles) {
  1973. Utils::throwError('20003:未找到角色信息');
  1974. }
  1975. $roles = json_decode($anime->roles, true);
  1976. if (!$roles) {
  1977. Utils::throwError('20003:角色信息格式错误');
  1978. }
  1979. // 构建角色名称到参考图的映射
  1980. $role_map = [];
  1981. foreach ($roles as $role) {
  1982. $role_name = getProp($role, 'role');
  1983. $role_url = getProp($role, 'url');
  1984. if (!empty($role_name) && !empty($role_url)) {
  1985. $role_map[$role_name] = $role_url;
  1986. }
  1987. }
  1988. $scenes = json_decode($anime->scenes, true);
  1989. if (!$scenes) {
  1990. Utils::throwError('20003:角色信息格式错误');
  1991. }
  1992. // 构建角色名称到参考图的映射
  1993. $scene_map = [];
  1994. foreach ($scenes as $scene) {
  1995. $scene_name = getProp($scene, 'scene');
  1996. $scene_url = getProp($scene, 'url');
  1997. if (!empty($scene_name) && !empty($scene_url)) {
  1998. $scene_map[$scene_name] = $scene_url;
  1999. }
  2000. }
  2001. $segment_id = $segment->segment_id;
  2002. $original_segment_content = $segment->segment_content;
  2003. // 如果传入了新的segment_content,使用新的内容,否则使用原有内容
  2004. $final_segment_content = !empty($segment_content) ? $segment_content : $original_segment_content;
  2005. if (empty($final_segment_content)) {
  2006. Utils::throwError('20003:分镜内容不存在,请填写内容后重试');
  2007. }
  2008. try {
  2009. $dubTaskId = 0;
  2010. // 分镜剧本数组
  2011. $update_data = [
  2012. 'segment_content' => $final_segment_content,
  2013. 'pic_task_status' => '生成中',
  2014. 'updated_at' => date('Y-m-d H:i:s')
  2015. ];
  2016. // 解析分镜内容,提取画面描述作为主要提示词
  2017. $prompt = $final_segment_content;
  2018. $ref_img_urls = [];
  2019. // 分镜场景
  2020. $scene = getProp($data, 'scene');
  2021. if ($scene) {
  2022. $matched_scene = '';
  2023. if (isset($scene_map[$scene])) {
  2024. $img_index = count($ref_img_urls) + 1;
  2025. $prompt = "场景:$scene(图$img_index)\n$prompt";
  2026. $ref_img_urls[] = $scene_map[$scene];
  2027. $matched_scene = $scene;
  2028. }
  2029. $update_data['scene'] = $scene;
  2030. }
  2031. // 分镜角色
  2032. $characters = getProp($data, 'characters');
  2033. if ($characters) {
  2034. $update_data['characters'] = $characters;
  2035. $characters = str_replace(['、', ',', ';'], ',', $characters);
  2036. $characters = explode(',', $characters);
  2037. // 从分镜内容中提取涉及的角色
  2038. $segment_characters = $this->extractCharactersFromSegment($final_segment_content, array_keys($role_map), $characters);
  2039. // 获取匹配角色的参考图
  2040. foreach ($segment_characters as $character) {
  2041. if (isset($role_map[$character])) {
  2042. // 将$prompt中出现的角色替换成角色(图1、2、3,序号是$ref_img_urls的个数加1)
  2043. $img_index = count($ref_img_urls) + 1;
  2044. $prompt = str_replace($character, $character . '(图' . $img_index . ')', $prompt);
  2045. $ref_img_urls[] = $role_map[$character];
  2046. }
  2047. }
  2048. }
  2049. // 如果没有找到匹配的角色参考图,不使用参考图
  2050. if (empty($ref_img_urls)) {
  2051. $ref_img_urls = [];
  2052. }
  2053. // 准备生成任务参数
  2054. $params = [
  2055. 'alias_segment_id' => $segment_id,
  2056. 'prompt' => $prompt,
  2057. 'ref_img_urls' => $ref_img_urls,
  2058. 'width' => $width,
  2059. 'height' => $height,
  2060. ];
  2061. // 优化提示词(不要生成字幕)
  2062. $params['prompt'] = "前置要求:图片中不要带有任何对话台词或字幕信息\n".$params['prompt'];
  2063. // 调用AI图片生成服务
  2064. $task = $this->aiImageGenerationService->createImageGenerationTask($params);
  2065. $task_id = $task->id;
  2066. if (!$task_id) {
  2067. Utils::throwError('20003:创建生成任务失败!');
  2068. }
  2069. $update_data['pic_task_id'] = $task_id;
  2070. // 更新分镜剧本信息
  2071. $this->handleSegmentContent($update_data);
  2072. // 如果有对话内容,创建视频配音合成任务(有更改分镜内容时创建)
  2073. if ($segment_content) {
  2074. $dialogue = getProp($update_data, 'dialogue');
  2075. if (!empty($dialogue)) {
  2076. $now = date('Y-m-d H:i:s');
  2077. $generate_json = [
  2078. 'text' => $dialogue,
  2079. 'role' => getProp($update_data, 'voice_actor'),
  2080. 'voice_type' => getProp($update_data, 'voice_type'),
  2081. 'voice_name' => getProp($update_data, 'voice_name'),
  2082. 'emotion' => getProp($update_data, 'emotion'),
  2083. 'emotion_type' => getProp($update_data, 'emotion_type'),
  2084. 'gender' => getProp($update_data, 'gender'),
  2085. 'speed_ratio' => getProp($update_data, 'speed_ratio', 0),
  2086. 'loudness_ratio' => getProp($update_data, 'loudness_ratio', 0),
  2087. 'emotion_scale' => getProp($update_data, 'emotion_scale', 0),
  2088. 'pitch' => getProp($update_data, 'pitch', 0),
  2089. ];
  2090. // 插入视频配音合成任务
  2091. $dubTaskId = DB::table('mp_dub_video_tasks')->insertGetId([
  2092. 'alias_segment_id' => $segment_id,
  2093. 'generate_status' => '执行中',
  2094. 'audio_url' => '',
  2095. 'generate_json' => json_encode($generate_json, 256),
  2096. 'created_at' => date('Y-m-d H:i:s'),
  2097. 'updated_at' => date('Y-m-d H:i:s'),
  2098. ]);
  2099. if (!$dubTaskId) {
  2100. Utils::throwError('20003:创建配音任务失败!');
  2101. }
  2102. $update_data['audio_url'] = '';
  2103. } else {
  2104. // dialogue为空时,直接写入默认音频信息
  2105. $update_data['audio_url'] = 'https://zw-audiobook.tos-cn-beijing.volces.com/effects/ellipses_2s.mp3';
  2106. $update_data['audio_duration'] = 2.0;
  2107. $update_data['subtitle_info'] = json_encode(['duration' => 2.0, 'words' => []], 256);
  2108. }
  2109. }
  2110. $boolen = DB::table('mp_episode_segments')
  2111. ->where('segment_id', $segment_id)
  2112. ->update($update_data);
  2113. // 如果是第一集的首帧图片,则存入待更新数组
  2114. if ($boolen && (int)getProp($segment, 'episode_number') === 1 && (int)getProp($segment, 'segment_number') === 1) {
  2115. Redis::sadd('anime_first_frame_urls', $segment_id);
  2116. }
  2117. if ($dubTaskId) {
  2118. // 请求远程服务器执行生成
  2119. $client = new Client(['timeout' => 300, 'verify' => false]);
  2120. $result = $client->get("http://122.9.129.83:5000/api/anime/genAudio?taskId={$dubTaskId}");
  2121. $response = $result->getBody()->getContents();
  2122. $response_arr = json_decode($response, true);
  2123. if (!isset($response_arr['code']) || (int)$response_arr['code'] !== 0) {
  2124. $error_msg = isset($response_arr['msg']) ? $response_arr['msg'] : '未知错误';
  2125. dLog('anime')->error('火山生成音频失败', ['error' => $error_msg, 'task_id' => $dubTaskId]);
  2126. logDB('anime', 'error', '火山生成音频失败', ['error' => $error_msg, 'task_id' => $dubTaskId]);
  2127. Utils::throwError('20003:火山生成音频失败');
  2128. }
  2129. }
  2130. } catch (\Exception $e) {
  2131. $failed_segments[] = [
  2132. 'segment_id' => $segment_id,
  2133. 'error' => $e->getMessage()
  2134. ];
  2135. }
  2136. // 创建任务之后先暂停10s等待异步任务完成
  2137. sleep(10);
  2138. $img_url = $this->loopGetPicTaskResult($task_id);
  2139. if (!$img_url) Utils::throwError('20003:图片生成中,请稍后刷新');
  2140. // 图片生成后新增对话记录
  2141. try {
  2142. $uid = Site::getUid();
  2143. $now = date('Y-m-d H:i:s');
  2144. // 使用AI反推图片提示词
  2145. $pic_prompt = $this->generateImagePromptFromUrl($img_url);
  2146. // 保存对话记录
  2147. $records = [
  2148. [
  2149. 'uid' => $uid,
  2150. 'anime_id' => $anime_id,
  2151. 'sequence' => $episode_number,
  2152. 'role' => 'user',
  2153. 'content' => '重新生成',
  2154. 'segment_id' => $segment_id,
  2155. 'pic_task_id' => $task_id,
  2156. 'image_url' => '',
  2157. 'created_at' => $now,
  2158. 'updated_at' => $now
  2159. ],
  2160. [
  2161. 'uid' => $uid,
  2162. 'anime_id' => $anime_id,
  2163. 'sequence' => $episode_number,
  2164. 'role' => 'assistant',
  2165. 'content' => $pic_prompt,
  2166. 'segment_id' => $segment_id,
  2167. 'pic_task_id' => $task_id,
  2168. 'image_url' => $img_url,
  2169. 'created_at' => $now,
  2170. 'updated_at' => $now
  2171. ]
  2172. ];
  2173. DB::table('mp_anime_records')->insert($records);
  2174. } catch (\Exception $e) {
  2175. // 记录日志但不影响主流程
  2176. dLog('anime')->error('保存对话记录失败: ' . $e->getMessage(), [
  2177. 'segment_id' => $segment_id,
  2178. 'img_url' => $img_url
  2179. ]);
  2180. }
  2181. return $img_url;
  2182. }
  2183. public function addSegment($data) {
  2184. $prev_segment_id = getProp($data, 'prev_segment_id');
  2185. $img_url = getProp($data, 'img_url');
  2186. $video_url = getProp($data, 'video_url');
  2187. $segment = DB::table('mp_episode_segments')->where('segment_id', $prev_segment_id)->first();
  2188. if (!$segment) Utils::throwError('20003:该分镜不存在');
  2189. $anime_id = getProp($segment, 'anime_id');
  2190. $episode_id = getProp($segment, 'episode_id');
  2191. $episode_number = getProp($segment, 'episode_number');
  2192. $segment_number = getProp($segment, 'segment_number');
  2193. $new_segment_number = $segment_number + 1;
  2194. $segment_id = date('YmdHis') . mt_rand(1000, 9999) . str_pad($new_segment_number, 3, "0", STR_PAD_LEFT);
  2195. // 分镜剧本数组
  2196. $insert_data = [
  2197. 'anime_id' => $anime_id,
  2198. 'episode_id' => $episode_id,
  2199. 'episode_number' => $episode_number,
  2200. 'act_number' => getProp($segment, 'act_number'),
  2201. 'act_title' => getProp($segment, 'act_title'),
  2202. 'segment_id' => $segment_id,
  2203. 'segment_number' => $new_segment_number,
  2204. 'segment_content' => '',
  2205. 'img_url' => '',
  2206. 'video_url' => '',
  2207. 'created_at' => date('Y-m-d H:i:s'),
  2208. 'updated_at' => date('Y-m-d H:i:s')
  2209. ];
  2210. if ($img_url) $insert_data['img_url'] = $img_url;
  2211. if ($video_url) {
  2212. $insert_data['origin_video_url'] = $video_url;
  2213. $insert_data['current_type'] = 2;
  2214. $compressed_video_url = compressVideo($video_url);
  2215. $insert_data['video_url'] = $compressed_video_url ?: $video_url;
  2216. }
  2217. try {
  2218. DB::beginTransaction();
  2219. // 先更新序号
  2220. DB::table('mp_episode_segments')->where('anime_id', $anime_id)->where('episode_id', $episode_id)->where('segment_number', '>', $segment_number)->increment('segment_number');
  2221. $id = DB::table('mp_episode_segments')->insertGetId($insert_data);
  2222. if (!$id) {
  2223. Utils::throwError('20003:新增分镜失败!');
  2224. }
  2225. }catch (\Exception $e) {
  2226. DB::rollBack();
  2227. Utils::throwError('20003:'.$e->getMessage());
  2228. }
  2229. DB::commit();
  2230. $segment = DB::table('mp_episode_segments')->where('id', $id)->first();
  2231. $segment = $segment ? (array)$segment : [];
  2232. return $segment;
  2233. // 以下代码暂弃用
  2234. $anime_id = getProp($segment, 'anime_id');
  2235. $episode_id = getProp($segment, 'episode_id');
  2236. $episode_number = getProp($segment, 'episode_number');
  2237. $segment_number = getProp($segment, 'segment_number');
  2238. $segment_content = getProp($data, 'segment_content');
  2239. $img_url = getProp($data, 'img_url');
  2240. $video_url = getProp($data, 'video_url');
  2241. $ratio = getProp($data, 'ratio');
  2242. $dimensions = $this->getRatioDimensions($ratio);
  2243. $width = $dimensions['width'];
  2244. $height = $dimensions['height'];
  2245. if (!$anime_id || !$episode_id) {
  2246. Utils::throwError('1002:请选择分镜');
  2247. }
  2248. // 使用文生文模型重新解析segment_content
  2249. if (!empty($segment_content)) {
  2250. $segment_content = $this->parseSegmentContentWithAI($segment_content);
  2251. }
  2252. // 获取动漫的角色信息(包含参考图)
  2253. $anime = DB::table('mp_animes')
  2254. ->where('id', $anime_id)
  2255. ->select('roles', 'scenes')
  2256. ->first();
  2257. if (!$anime || !$anime->roles) {
  2258. Utils::throwError('20003:未找到角色信息');
  2259. }
  2260. $roles = json_decode($anime->roles, true);
  2261. if (!$roles) {
  2262. Utils::throwError('20003:角色信息格式错误');
  2263. }
  2264. // 构建角色名称到参考图的映射
  2265. $role_map = [];
  2266. foreach ($roles as $role) {
  2267. $role_name = getProp($role, 'role');
  2268. $role_url = getProp($role, 'url');
  2269. if (!empty($role_name) && !empty($role_url)) {
  2270. $role_map[$role_name] = $role_url;
  2271. }
  2272. }
  2273. $scenes = json_decode($anime->scenes, true);
  2274. if (!$scenes) {
  2275. Utils::throwError('20003:角色信息格式错误');
  2276. }
  2277. // 构建角色名称到参考图的映射
  2278. $scene_map = [];
  2279. foreach ($scenes as $scene) {
  2280. $scene_name = getProp($scene, 'scene');
  2281. $scene_url = getProp($scene, 'url');
  2282. if (!empty($scene_name) && !empty($scene_url)) {
  2283. $scene_map[$scene_name] = $scene_url;
  2284. }
  2285. }
  2286. $segment_id = $segment->segment_id;
  2287. $original_segment_content = $segment->segment_content;
  2288. // 如果传入了新的segment_content,使用新的内容,否则使用原有内容
  2289. $final_segment_content = !empty($segment_content) ? $segment_content : $original_segment_content;
  2290. if (empty($final_segment_content)) {
  2291. Utils::throwError('20003:分镜内容不存在,请填写内容后重试');
  2292. }
  2293. try {
  2294. $dubTaskId = 0;
  2295. DB::beginTransaction();
  2296. $new_segment_number = $segment_number + 1;
  2297. $segment_id = date('YmdHis') . mt_rand(1000, 9999) . str_pad($new_segment_number, 3, "0", STR_PAD_LEFT);
  2298. // 分镜剧本数组
  2299. $insert_data = [
  2300. 'anime_id' => $anime_id,
  2301. 'episode_id' => $episode_id,
  2302. 'episode_number' => $episode_number,
  2303. 'act_number' => getProp($segment, 'act_number'),
  2304. 'act_title' => getProp($segment, 'act_title'),
  2305. 'segment_id' => $segment_id,
  2306. 'segment_number' => $new_segment_number,
  2307. 'segment_content' => $final_segment_content,
  2308. 'img_url' => $img_url,
  2309. 'video_url' => $video_url,
  2310. 'created_at' => date('Y-m-d H:i:s'),
  2311. 'updated_at' => date('Y-m-d H:i:s')
  2312. ];
  2313. // 更新分镜剧本信息
  2314. $this->handleSegmentContent($insert_data);
  2315. // 如果有对话内容,创建视频配音合成任务
  2316. $dialogue = getProp($insert_data, 'dialogue');
  2317. if (!empty($dialogue)) {
  2318. $now = date('Y-m-d H:i:s');
  2319. $generate_json = [
  2320. 'text' => $dialogue,
  2321. 'role' => getProp($insert_data, 'voice_actor'),
  2322. 'voice_type' => getProp($insert_data, 'voice_type'),
  2323. 'voice_name' => getProp($insert_data, 'voice_name'),
  2324. 'emotion' => getProp($insert_data, 'emotion'),
  2325. 'emotion_type' => getProp($insert_data, 'emotion_type'),
  2326. 'gender' => getProp($insert_data, 'gender'),
  2327. 'speed_ratio' => getProp($insert_data, 'speed_ratio', 0),
  2328. 'loudness_ratio' => getProp($insert_data, 'loudness_ratio', 0),
  2329. 'emotion_scale' => getProp($insert_data, 'emotion_scale', 0),
  2330. 'pitch' => getProp($insert_data, 'pitch', 0),
  2331. ];
  2332. // 插入视频配音合成任务
  2333. $dubTaskId = DB::table('mp_dub_video_tasks')->insertGetId([
  2334. 'alias_segment_id' => $segment_id,
  2335. 'generate_status' => '执行中',
  2336. 'audio_url' => '',
  2337. 'generate_json' => json_encode($generate_json, 256),
  2338. 'created_at' => $now,
  2339. 'updated_at' => $now,
  2340. ]);
  2341. if (!$dubTaskId) {
  2342. Utils::throwError('20003:创建配音任务失败!');
  2343. }
  2344. $insert_data['audio_url'] = '';
  2345. } else {
  2346. // dialogue为空时,直接写入默认音频信息
  2347. $insert_data['audio_url'] = 'https://zw-audiobook.tos-cn-beijing.volces.com/effects/ellipses_2s.mp3';
  2348. $insert_data['audio_duration'] = 2.0;
  2349. $insert_data['subtitle_info'] = json_encode(['duration' => 2.0, 'words' => []], 256);
  2350. }
  2351. // 如果没有上传图片则使用当前描述进行生成
  2352. if (!$img_url) {
  2353. // 解析分镜内容,提取画面描述作为主要提示词
  2354. $prompt = $final_segment_content;
  2355. $ref_img_urls = [];
  2356. // 分镜场景
  2357. $scene = getProp($insert_data, 'scene');
  2358. if ($scene) {
  2359. $matched_scene = '';
  2360. if (isset($scene_map[$scene])) {
  2361. $img_index = count($ref_img_urls) + 1;
  2362. $prompt = "场景:$scene(图$img_index)\n$prompt";
  2363. $ref_img_urls[] = $scene_map[$scene];
  2364. $matched_scene = $scene;
  2365. }
  2366. $update_data['scene'] = $scene;
  2367. }
  2368. // 分镜角色
  2369. $characters = getProp($insert_data, 'characters');
  2370. if ($characters) {
  2371. $update_data['characters'] = $characters;
  2372. $characters = str_replace(['、', ',', ';'], ',', $characters);
  2373. $characters = explode(',', $characters);
  2374. // 从分镜内容中提取涉及的角色
  2375. $segment_characters = $this->extractCharactersFromSegment($final_segment_content, array_keys($role_map), $characters);
  2376. // 获取匹配角色的参考图
  2377. foreach ($segment_characters as $character) {
  2378. if (isset($role_map[$character])) {
  2379. // 将$prompt中出现的角色替换成角色(图1、2、3,序号是$ref_img_urls的个数加1)
  2380. $img_index = count($ref_img_urls) + 1;
  2381. $prompt = str_replace($character, $character . '(图' . $img_index . ')', $prompt);
  2382. $ref_img_urls[] = $role_map[$character];
  2383. }
  2384. }
  2385. }
  2386. // 如果没有找到匹配的角色参考图,不使用参考图
  2387. if (empty($ref_img_urls)) {
  2388. $ref_img_urls = [];
  2389. }
  2390. // 准备生成任务参数
  2391. $params = [
  2392. 'alias_segment_id' => $segment_id,
  2393. 'prompt' => $prompt,
  2394. 'ref_img_urls' => $ref_img_urls,
  2395. 'width' => $width,
  2396. 'height' => $height,
  2397. ];
  2398. // 调用AI图片生成服务
  2399. $task = $this->aiImageGenerationService->createImageGenerationTask($params);
  2400. $task_id = $task->id;
  2401. // $task_id = 'whatever';
  2402. if (!$task_id) {
  2403. Utils::throwError('20003:创建生成任务失败!');
  2404. }
  2405. $insert_data['pic_task_status'] = '生成中';
  2406. $insert_data['pic_task_id'] = $task_id;
  2407. }
  2408. // 先更新序号
  2409. DB::table('mp_episode_segments')->where('anime_id', $anime_id)->where('episode_id', $episode_id)->where('segment_number', '>', $segment_number)->increment('segment_number');
  2410. $boolen = DB::table('mp_episode_segments')->insert($insert_data);
  2411. if (!$boolen) {
  2412. Utils::throwError('20003:新增分镜失败!');
  2413. }
  2414. // 如果是第一集的首帧图片,则存入待更新数组
  2415. if ($boolen && (int)$episode_number === 1 && (int)$new_segment_number === 1) {
  2416. Redis::sadd('anime_first_frame_urls', $segment_id);
  2417. }
  2418. if ($dubTaskId) {
  2419. // 请求远程服务器执行生成
  2420. $client = new Client(['timeout' => 300, 'verify' => false]);
  2421. $result = $client->get("http://122.9.129.83:5000/api/anime/genAudio?taskId={$dubTaskId}");
  2422. $response = $result->getBody()->getContents();
  2423. $response_arr = json_decode($response, true);
  2424. if (!isset($response_arr['code']) || (int)$response_arr['code'] !== 0) {
  2425. $error_msg = isset($response_arr['msg']) ? $response_arr['msg'] : '未知错误';
  2426. dLog('anime')->error('火山生成音频失败', ['error' => $error_msg, 'task_id' => $dubTaskId]);
  2427. Utils::throwError('20003:火山生成音频失败');
  2428. }
  2429. }
  2430. } catch (\Exception $e) {
  2431. DB::rollBack();
  2432. Utils::throwError('20003:'.$e->getMessage());
  2433. }
  2434. DB::commit();
  2435. // 创建任务之后先暂停10s等待异步任务完成
  2436. sleep(10);
  2437. if (isset($task_id)) $img_url = $this->loopGetPicTaskResult($task_id);
  2438. if (!$img_url) Utils::throwError('20003:图片生成中,请稍后刷新');
  2439. $segment = DB::table('mp_episode_segments')->where('segment_id', $segment_id)->first();
  2440. $segment = $segment ? (array)$segment : [];
  2441. return $segment;
  2442. }
  2443. public function copySegment($data) {
  2444. $segment_id = getProp($data, 'segment_id');
  2445. $segment = DB::table('mp_episode_segments')->where('segment_id', $segment_id)->first();
  2446. if (!$segment) Utils::throwError('20003:请选择分镜');
  2447. $anime_id = getProp($segment, 'anime_id');
  2448. $episode_id = getProp($segment, 'episode_id');
  2449. $episode_number = getProp($segment, 'episode_number');
  2450. $segment_number = getProp($segment, 'segment_number');
  2451. $new_segment_id = 0;
  2452. try {
  2453. DB::beginTransaction();
  2454. $segment = (array)$segment;
  2455. unset($segment['id']);
  2456. $segment['segment_number'] += 1;
  2457. $segment['segment_id'] = date('YmdHis') . mt_rand(1000, 9999) . str_pad($segment['segment_number'], 3, "0", STR_PAD_LEFT);
  2458. // $segment['pic_task_id'] = $segment['pic_task_status'] = $segment['video_task_id'] = $segment['video_task_status'] = '';
  2459. $segment['created_at'] = $segment['updated_at'] = date('Y-m-d H:i:s');
  2460. // 更新其他分镜序号
  2461. DB::table('mp_episode_segments')->where('anime_id', $anime_id)->where('episode_id', $episode_id)->where('segment_number', '>', $segment_number)->increment('segment_number');
  2462. // 复制分镜
  2463. $id = DB::table('mp_episode_segments')->insertGetId($segment);
  2464. if (!$id) {
  2465. Utils::throwError('20003:复制分镜失败');
  2466. }
  2467. }catch (\Exception $e) {
  2468. DB::rollBack();
  2469. Utils::throwError('20003:'.$e->getMessage());
  2470. }
  2471. DB::commit();
  2472. $segment = DB::table('mp_episode_segments')->where('id', $id)->first();
  2473. $segment = $segment ? (array)$segment : [];
  2474. return $segment;
  2475. }
  2476. public function moveSegment($data) {
  2477. $segment_id = getProp($data, 'segment_id');
  2478. $target_segment_id = getProp($data, 'target_segment_id');
  2479. // 获取源分镜信息
  2480. $source_segment = DB::table('mp_episode_segments')->where('segment_id', $segment_id)->first();
  2481. if (!$source_segment) Utils::throwError('20003:请选择分镜');
  2482. // 获取目标分镜信息
  2483. $target_segment = DB::table('mp_episode_segments')->where('segment_id', $target_segment_id)->first();
  2484. if (!$target_segment) Utils::throwError('20003:目标分镜不存在');
  2485. $anime_id = getProp($source_segment, 'anime_id');
  2486. $episode_id = getProp($source_segment, 'episode_id');
  2487. $episode_number = getProp($source_segment, 'episode_number');
  2488. $source_segment_number = getProp($source_segment, 'segment_number');
  2489. $target_segment_number = getProp($target_segment, 'segment_number');
  2490. // 验证源分镜和目标分镜必须属于同一个动漫的同一集
  2491. $target_anime_id = getProp($target_segment, 'anime_id');
  2492. $target_episode_number = getProp($target_segment, 'episode_number');
  2493. if ($anime_id != $target_anime_id || $episode_number != $target_episode_number) {
  2494. Utils::throwError('20003:只能在同一动漫的同一集内移动分镜');
  2495. }
  2496. // 如果源分镜和目标分镜相同,无需移动
  2497. if ($source_segment_number == $target_segment_number) {
  2498. return true;
  2499. }
  2500. try {
  2501. DB::beginTransaction();
  2502. if ($source_segment_number < $target_segment_number) {
  2503. // 向后移动:源分镜移动到目标分镜之后
  2504. // 1. 将源分镜和目标分镜之间的所有分镜序号减1
  2505. DB::table('mp_episode_segments')
  2506. ->where('anime_id', $anime_id)
  2507. ->where('episode_id', $episode_id)
  2508. ->where('segment_number', '>', $source_segment_number)
  2509. ->where('segment_number', '<=', $target_segment_number)
  2510. ->decrement('segment_number');
  2511. // 2. 将源分镜移动到目标分镜之后
  2512. $new_segment_number = $target_segment_number;
  2513. } else {
  2514. // 向前移动:源分镜移动到目标分镜之后
  2515. // 1. 将目标分镜之后到源分镜之前的所有分镜序号加1
  2516. DB::table('mp_episode_segments')
  2517. ->where('anime_id', $anime_id)
  2518. ->where('episode_id', $episode_id)
  2519. ->where('segment_number', '>', $target_segment_number)
  2520. ->where('segment_number', '<', $source_segment_number)
  2521. ->increment('segment_number');
  2522. // 2. 将源分镜移动到目标分镜之后
  2523. $new_segment_number = $target_segment_number + 1;
  2524. }
  2525. // 3. 更新源分镜的序号
  2526. $update_result = DB::table('mp_episode_segments')
  2527. ->where('segment_id', $segment_id)
  2528. ->update([
  2529. 'segment_number' => $new_segment_number,
  2530. 'updated_at' => date('Y-m-d H:i:s')
  2531. ]);
  2532. if (!$update_result) {
  2533. Utils::throwError('20003:更新分镜序号失败');
  2534. }
  2535. DB::commit();
  2536. return true;
  2537. } catch (\Exception $e) {
  2538. DB::rollBack();
  2539. Utils::throwError('20003:' . $e->getMessage());
  2540. }
  2541. }
  2542. public function delSegment($data) {
  2543. $segment_id = getProp($data, 'segment_id');
  2544. $segment = DB::table('mp_episode_segments')->where('segment_id', $segment_id)->first();
  2545. if (!$segment) Utils::throwError('20003:请选择分镜');
  2546. $anime_id = getProp($segment, 'anime_id');
  2547. $episode_id = getProp($segment, 'episode_id');
  2548. $episode_number = getProp($segment, 'episode_number');
  2549. $segment_number = getProp($segment, 'segment_number');
  2550. try {
  2551. DB::beginTransaction();
  2552. // 删除分镜
  2553. $boolen = DB::table('mp_episode_segments')->where('segment_id', $segment_id)->delete();
  2554. if (!$boolen) {
  2555. Utils::throwError('20003:删除分镜失败');
  2556. }
  2557. // 更新其他分镜序号
  2558. DB::table('mp_episode_segments')->where('anime_id', $anime_id)->where('episode_id', $episode_id)->where('segment_number', '>', $segment_number)->decrement('segment_number');
  2559. }catch (\Exception $e) {
  2560. DB::rollBack();
  2561. Utils::throwError('20003:'.$e->getMessage());
  2562. }
  2563. DB::commit();
  2564. return true;
  2565. }
  2566. public function applySegment($data) {
  2567. $segment_id = getProp($data, 'segment_id');
  2568. $url = getProp($data, 'url');
  2569. if (!$segment_id) Utils::throwError('20003:请选择分镜');
  2570. if (!$url) Utils::throwError('20003:URL不能为空');
  2571. // 获取URL的文件扩展名
  2572. $urlPath = parse_url($url, PHP_URL_PATH);
  2573. $extension = strtolower(pathinfo($urlPath, PATHINFO_EXTENSION));
  2574. // 定义图片和视频的扩展名
  2575. $imageExtensions = ['jpg', 'jpeg', 'png', 'gif', 'bmp', 'webp', 'svg'];
  2576. $videoExtensions = ['mp4', 'avi', 'mov', 'wmv', 'flv', 'mkv', 'webm', 'm4v'];
  2577. // 判断是图片还是视频
  2578. $updateData = ['updated_at' => date('Y-m-d H:i:s')];
  2579. if (in_array($extension, $imageExtensions)) {
  2580. // 图片类型
  2581. $updateData['img_url'] = $url;
  2582. $updateData['current_type'] = 1;
  2583. } elseif (in_array($extension, $videoExtensions)) {
  2584. // 视频类型
  2585. $updateData['video_url'] = $url;
  2586. $updateData['current_type'] = 2;
  2587. } else {
  2588. Utils::throwError('20003:不支持的文件类型');
  2589. }
  2590. // 更新分镜表
  2591. $result = DB::table('mp_episode_segments')
  2592. ->where('segment_id', $segment_id)
  2593. ->update($updateData);
  2594. if (!$result) {
  2595. Utils::throwError('20003:更新分镜失败');
  2596. }
  2597. return true;
  2598. }
  2599. public function segmentHistory($data) {
  2600. $segment_id = getProp($data, 'segment_id');
  2601. // 获取历史图片
  2602. $pics = [];
  2603. $pic_history = DB::table('mp_generate_pic_tasks')->where('alias_segment_id', $segment_id)->where('status', 'success')->orderBy('created_at', 'desc')->get();
  2604. foreach($pic_history as $task) {
  2605. $result_url = getProp($task, 'result_url');
  2606. if (is_json($result_url)) {
  2607. $pics = array_merge($pics, json_decode($result_url, true));
  2608. }else {
  2609. $pics[] = $result_url;
  2610. }
  2611. }
  2612. // 获取历史视频
  2613. $videos = [];
  2614. $video_history = DB::table('mp_generate_video_tasks')->where('alias_segment_id', $segment_id)->where('status', 'success')->orderBy('created_at', 'desc')->get();
  2615. foreach($video_history as $task) {
  2616. $result_url = getProp($task, 'result_url');
  2617. if (is_json($result_url)) {
  2618. $videos = array_merge($videos, json_decode($result_url, true));
  2619. }else {
  2620. $videos[] = $result_url;
  2621. }
  2622. }
  2623. return compact('pics', 'videos');
  2624. }
  2625. public function addAct($data) {
  2626. $prev_act_id = getProp($data, 'prev_act_id');
  2627. $act_title = getProp($data, 'act_title', '');
  2628. $act_content = getProp($data, 'act_content', '');
  2629. $act_duration = getProp($data, 'act_duration', 5);
  2630. $video_url = getProp($data, 'video_url');
  2631. // 根据prev_act_id获取记录
  2632. $prev_segment = DB::table('mp_episode_segments')->where('id', $prev_act_id)->first();
  2633. if (!$prev_segment) Utils::throwError('20003:该片段不存在');
  2634. $anime_id = getProp($prev_segment, 'anime_id');
  2635. $episode_id = getProp($prev_segment, 'episode_id');
  2636. $episode_number = getProp($prev_segment, 'episode_number');
  2637. $prev_act_number = getProp($prev_segment, 'act_number');
  2638. // 获取新的act_number
  2639. $new_act_number = $prev_act_number + 1;
  2640. try {
  2641. DB::beginTransaction();
  2642. // 更新后续所有act的act_number(全能模式下每个act只有一条记录)
  2643. DB::table('mp_episode_segments')
  2644. ->where('anime_id', $anime_id)
  2645. ->where('episode_id', $episode_id)
  2646. ->where('act_number', '>', $prev_act_number)
  2647. ->increment('act_number');
  2648. // 插入新片段记录
  2649. $insert_data = [
  2650. 'anime_id' => $anime_id,
  2651. 'episode_id' => $episode_id,
  2652. 'episode_number' => $episode_number,
  2653. 'act_number' => $new_act_number,
  2654. 'created_at' => date('Y-m-d H:i:s'),
  2655. 'updated_at' => date('Y-m-d H:i:s')
  2656. ];
  2657. if ($act_title) {
  2658. $insert_data['act_title'] = $act_title;
  2659. }
  2660. if ($act_content) {
  2661. $insert_data['act_content'] = $act_content;
  2662. }
  2663. if ($act_duration) {
  2664. $insert_data['act_duration'] = $act_duration;
  2665. }
  2666. if ($video_url) {
  2667. $insert_data['origin_video_url'] = $video_url;
  2668. $insert_data['current_type'] = 2;
  2669. $compressed_video_url = compressVideo($video_url);
  2670. $insert_data['video_url'] = $compressed_video_url ?: $video_url;
  2671. }
  2672. $id = DB::table('mp_episode_segments')->insertGetId($insert_data);
  2673. if (!$id) {
  2674. Utils::throwError('20003:新增片段失败!');
  2675. }
  2676. DB::commit();
  2677. }catch (\Exception $e) {
  2678. DB::rollBack();
  2679. Utils::throwError('20003:'.$e->getMessage());
  2680. }
  2681. $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();
  2682. $segment = $segment ? (array)$segment : [];
  2683. return $segment;
  2684. }
  2685. public function editAct($data) {
  2686. $act_id = getProp($data, 'act_id');
  2687. $act_content = getProp($data, 'act_content');
  2688. $act_duration = getProp($data, 'act_duration');
  2689. $act_title = getProp($data, 'act_title');
  2690. $image_url = getProp($data, 'image_url');
  2691. $video_url = getProp($data, 'video_url');
  2692. // 参数验证
  2693. if (!$act_id) Utils::throwError('20003:请提供片段ID');
  2694. // 验证片段是否存在(全能模式下每个act只有一条记录)
  2695. $segment = DB::table('mp_episode_segments')
  2696. ->where('id', $act_id)
  2697. ->first();
  2698. if (!$segment) Utils::throwError('20003:该片段不存在');
  2699. try {
  2700. DB::beginTransaction();
  2701. // 准备更新数据
  2702. $update_data = [
  2703. 'updated_at' => date('Y-m-d H:i:s')
  2704. ];
  2705. // 更新act相关字段
  2706. if (!empty($act_content)) {
  2707. $update_data['act_show_content'] = $act_content;
  2708. $update_data['act_content'] = str_replace(["@", "{", "}"], "", $act_content);
  2709. // 处理【镜头X】或【分镜X】重新编号为从1开始的连续整数【镜头X】
  2710. $shot_counter = 0;
  2711. $update_data['act_show_content'] = preg_replace_callback(
  2712. '/【(?:镜头|分镜)(\d+)】/u',
  2713. function($matches) use (&$shot_counter) {
  2714. $shot_counter++;
  2715. return '【镜头' . $shot_counter . '】';
  2716. },
  2717. $update_data['act_show_content']
  2718. );
  2719. }
  2720. if (!empty($act_duration)) {
  2721. $update_data['act_duration'] = $act_duration;
  2722. }
  2723. if (!empty($act_title)) {
  2724. $update_data['act_title'] = $act_title;
  2725. }
  2726. // 处理图片上传
  2727. if ($image_url) {
  2728. $update_data['img_url'] = $image_url;
  2729. $update_data['current_type'] = 1;
  2730. // 同时写入一个图片生成任务记录
  2731. if ($act_id) {
  2732. $pic_task = [
  2733. 'alias_act_id' => $act_id,
  2734. 'ref_img_url' => json_encode([]),
  2735. 'status' => 'success',
  2736. 'result_url' => json_encode([$image_url], 256),
  2737. 'model' => '',
  2738. 'created_at' => date('Y-m-d H:i:s'),
  2739. 'updated_at' => date('Y-m-d H:i:s'),
  2740. ];
  2741. DB::table('mp_generate_pic_tasks')->insert($pic_task);
  2742. }
  2743. }
  2744. // 处理视频上传
  2745. if ($video_url) {
  2746. $update_data['origin_video_url'] = $video_url;
  2747. $compressed_video_url = compressVideo($video_url);
  2748. $update_data['current_type'] = 2;
  2749. $update_data['video_url'] = $compressed_video_url ?: $video_url;
  2750. // 同时写入一个视频生成任务记录
  2751. if ($act_id) {
  2752. $video_task = [
  2753. 'alias_act_id' => $act_id,
  2754. 'status' => 'success',
  2755. 'result_url' => $update_data['origin_video_url'],
  2756. 'compressed_url' => $update_data['video_url'],
  2757. 'created_at' => date('Y-m-d H:i:s'),
  2758. 'updated_at' => date('Y-m-d H:i:s'),
  2759. ];
  2760. DB::table('mp_generate_video_tasks')->insert($video_task);
  2761. }
  2762. }
  2763. // 更新片段信息
  2764. $result = DB::table('mp_episode_segments')
  2765. ->where('id', $act_id)
  2766. ->update($update_data);
  2767. if ($result === false) {
  2768. Utils::throwError('20003:更新片段失败');
  2769. }
  2770. DB::commit();
  2771. // 返回新复制的记录
  2772. $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();
  2773. $new_segment = (array)$new_segment;
  2774. return $new_segment;
  2775. } catch (\Exception $e) {
  2776. DB::rollBack();
  2777. dLog('anime')->error('更新片段失败', [
  2778. 'act_id' => $act_id,
  2779. 'error' => $e->getMessage()
  2780. ]);
  2781. Utils::throwError('20003:更新片段失败 ' . $e->getMessage());
  2782. }
  2783. }
  2784. public function copyAct($data) {
  2785. $act_id = getProp($data, 'act_id');
  2786. // 根据act_id获取记录(全能模式下每个act只有一条记录)
  2787. $source_segment = DB::table('mp_episode_segments')->where('id', $act_id)->first();
  2788. if (!$source_segment) Utils::throwError('20003:请选择片段');
  2789. $anime_id = getProp($source_segment, 'anime_id');
  2790. $episode_id = getProp($source_segment, 'episode_id');
  2791. $episode_number = getProp($source_segment, 'episode_number');
  2792. $act_number = getProp($source_segment, 'act_number');
  2793. try {
  2794. DB::beginTransaction();
  2795. // 新act的编号
  2796. $new_act_number = $act_number + 1;
  2797. // 更新后续所有act的act_number
  2798. DB::table('mp_episode_segments')
  2799. ->where('anime_id', $anime_id)
  2800. ->where('episode_id', $episode_id)
  2801. ->where('act_number', '>', $act_number)
  2802. ->increment('act_number');
  2803. // 复制该片段记录
  2804. $segment_data = (array)$source_segment;
  2805. unset($segment_data['id']);
  2806. $segment_data['video_url'] = '';
  2807. $segment_data['video_task_id'] = '';
  2808. $segment_data['video_task_status'] = '';
  2809. $segment_data['act_number'] = $new_act_number;
  2810. $segment_data['created_at'] = $segment_data['updated_at'] = date('Y-m-d H:i:s');
  2811. $id = DB::table('mp_episode_segments')->insertGetId($segment_data);
  2812. if (!$id) {
  2813. Utils::throwError('20003:复制片段失败');
  2814. }
  2815. DB::commit();
  2816. }catch (\Exception $e) {
  2817. DB::rollBack();
  2818. Utils::throwError('20003:'.$e->getMessage());
  2819. }
  2820. // 返回新复制的记录
  2821. $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();
  2822. $new_segment = $new_segment ? (array)$new_segment : [];
  2823. $new_segment['act_id'] = $id;
  2824. return $new_segment;
  2825. }
  2826. public function moveAct($data) {
  2827. $act_id = getProp($data, 'act_id');
  2828. $target_act_id = getProp($data, 'target_act_id');
  2829. // 获取源片段信息
  2830. $source_segment = DB::table('mp_episode_segments')->where('id', $act_id)->first();
  2831. if (!$source_segment) Utils::throwError('20003:请选择片段');
  2832. // 获取目标片段信息
  2833. $target_segment = DB::table('mp_episode_segments')->where('id', $target_act_id)->first();
  2834. if (!$target_segment) Utils::throwError('20003:目标片段不存在');
  2835. $anime_id = getProp($source_segment, 'anime_id');
  2836. $episode_id = getProp($source_segment, 'episode_id');
  2837. $source_act_number = getProp($source_segment, 'act_number');
  2838. $target_act_number = getProp($target_segment, 'act_number');
  2839. // 验证源片段和目标片段必须属于同一个动漫的同一集
  2840. $target_anime_id = getProp($target_segment, 'anime_id');
  2841. $target_episode_id = getProp($target_segment, 'episode_id');
  2842. if ($anime_id != $target_anime_id || $episode_id != $target_episode_id) {
  2843. Utils::throwError('20003:只能在同一动漫的同一集内移动片段');
  2844. }
  2845. // 如果源片段和目标片段相同,无需移动
  2846. if ($source_act_number == $target_act_number) {
  2847. return true;
  2848. }
  2849. try {
  2850. DB::beginTransaction();
  2851. if ($source_act_number < $target_act_number) {
  2852. // 向后移动:源片段移动到目标片段之后
  2853. // 1. 将源片段和目标片段之间的所有片段编号减1
  2854. DB::table('mp_episode_segments')
  2855. ->where('anime_id', $anime_id)
  2856. ->where('episode_id', $episode_id)
  2857. ->where('act_number', '>', $source_act_number)
  2858. ->where('act_number', '<=', $target_act_number)
  2859. ->decrement('act_number');
  2860. // 2. 将源片段移动到目标片段之后
  2861. $new_act_number = $target_act_number;
  2862. } else {
  2863. // 向前移动:源片段移动到目标片段之后
  2864. // 1. 将目标片段之后到源片段之前的所有片段编号加1
  2865. DB::table('mp_episode_segments')
  2866. ->where('anime_id', $anime_id)
  2867. ->where('episode_id', $episode_id)
  2868. ->where('act_number', '>', $target_act_number)
  2869. ->where('act_number', '<', $source_act_number)
  2870. ->increment('act_number');
  2871. // 2. 将源片段移动到目标片段之后
  2872. $new_act_number = $target_act_number + 1;
  2873. }
  2874. // 3. 更新源片段的编号
  2875. $update_result = DB::table('mp_episode_segments')
  2876. ->where('id', $act_id)
  2877. ->update([
  2878. 'act_number' => $new_act_number,
  2879. 'updated_at' => date('Y-m-d H:i:s')
  2880. ]);
  2881. if (!$update_result) {
  2882. Utils::throwError('20003:更新片段编号失败');
  2883. }
  2884. DB::commit();
  2885. return true;
  2886. } catch (\Exception $e) {
  2887. DB::rollBack();
  2888. Utils::throwError('20003:' . $e->getMessage());
  2889. }
  2890. }
  2891. public function delAct($data) {
  2892. $act_id = getProp($data, 'act_id');
  2893. // 根据act_id获取记录(全能模式下每个act只有一条记录)
  2894. $segment = DB::table('mp_episode_segments')->where('id', $act_id)->first();
  2895. if (!$segment) Utils::throwError('20003:请选择片段');
  2896. $anime_id = getProp($segment, 'anime_id');
  2897. $episode_id = getProp($segment, 'episode_id');
  2898. $act_number = getProp($segment, 'act_number');
  2899. try {
  2900. DB::beginTransaction();
  2901. // 删除该片段记录
  2902. $deleted = DB::table('mp_episode_segments')->where('id', $act_id)->delete();
  2903. if (!$deleted) {
  2904. Utils::throwError('20003:删除片段失败');
  2905. }
  2906. // 更新后续act的编号
  2907. DB::table('mp_episode_segments')
  2908. ->where('anime_id', $anime_id)
  2909. ->where('episode_id', $episode_id)
  2910. ->where('act_number', '>', $act_number)
  2911. ->decrement('act_number');
  2912. DB::commit();
  2913. }catch (\Exception $e) {
  2914. DB::rollBack();
  2915. Utils::throwError('20003:'.$e->getMessage());
  2916. }
  2917. return true;
  2918. }
  2919. public function applyAct($data) {
  2920. $act_id = getProp($data, 'act_id');
  2921. $url = getProp($data, 'url');
  2922. if (!$act_id) Utils::throwError('20003:请选择片段');
  2923. if (!$url) Utils::throwError('20003:URL不能为空');
  2924. // 获取URL的文件扩展名
  2925. $urlPath = parse_url($url, PHP_URL_PATH);
  2926. $extension = strtolower(pathinfo($urlPath, PATHINFO_EXTENSION));
  2927. // 定义图片和视频的扩展名
  2928. $imageExtensions = ['jpg', 'jpeg', 'png', 'gif', 'bmp', 'webp', 'svg'];
  2929. $videoExtensions = ['mp4', 'avi', 'mov', 'wmv', 'flv', 'mkv', 'webm', 'm4v'];
  2930. // 判断是图片还是视频
  2931. $updateData = ['updated_at' => date('Y-m-d H:i:s')];
  2932. if (in_array($extension, $imageExtensions)) {
  2933. // 图片类型
  2934. $updateData['img_url'] = $url;
  2935. $updateData['current_type'] = 1;
  2936. } elseif (in_array($extension, $videoExtensions)) {
  2937. // 视频类型
  2938. $updateData['video_url'] = $url;
  2939. $updateData['current_type'] = 2;
  2940. } else {
  2941. Utils::throwError('20003:不支持的文件类型');
  2942. }
  2943. // 更新片段记录(全能模式下每个act只有一条记录)
  2944. $result = DB::table('mp_episode_segments')
  2945. ->where('id', $act_id)
  2946. ->update($updateData);
  2947. if (!$result) {
  2948. Utils::throwError('20003:更新片段失败');
  2949. }
  2950. return true;
  2951. }
  2952. public function actChatHistory($data) {
  2953. $act_id = getProp($data, 'act_id');
  2954. if (!$act_id) Utils::throwError('20003:请选择片段!');
  2955. $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');
  2956. $chat = $query->orderBy('id')->get()->map(function ($value) {
  2957. $value = (array)$value;
  2958. $value['created_at'] = transDate($value['created_at']);
  2959. if ($value['reference_images']) $value['reference_images'] = json_decode($value['reference_images'], 256);
  2960. else $value['reference_images'] = [];
  2961. return $value;
  2962. })->toArray();
  2963. // 获取历史图片
  2964. $url = [];
  2965. $pic_history = DB::table('mp_generate_pic_tasks')->where('alias_act_id', $act_id)->where('status', 'success')->orderBy('created_at', 'desc')->get();
  2966. foreach($pic_history as $task) {
  2967. $result_url = getProp($task, 'result_url');
  2968. if (is_json($result_url)) {
  2969. $url = array_merge($url, json_decode($result_url, true));
  2970. }else {
  2971. $url[] = $result_url;
  2972. }
  2973. }
  2974. // 获取历史视频
  2975. $video_history = DB::table('mp_generate_video_tasks')->where('alias_act_id', $act_id)->where('status', 'success')->orderBy('created_at', 'desc')->get();
  2976. foreach($video_history as $task) {
  2977. $result_url = getProp($task, 'result_url');
  2978. if (is_json($result_url)) {
  2979. $url = array_merge($url, json_decode($result_url, true));
  2980. }else {
  2981. $url[] = $result_url;
  2982. }
  2983. }
  2984. // 获取资产库
  2985. $products = [];
  2986. // 通过act_id查询片段信息获取episode_id
  2987. $segment = DB::table('mp_episode_segments')->where('id', $act_id)->first();
  2988. if ($segment) {
  2989. $episode_id = getProp($segment, 'episode_id');
  2990. // 查询剧集信息获取roles、scenes和extra_products
  2991. $episode = DB::table('mp_anime_episodes')->where('id', $episode_id)->first();
  2992. if ($episode) {
  2993. $roles = json_decode(getProp($episode, 'roles', '[]'), true) ?: [];
  2994. $scenes = json_decode(getProp($episode, 'scenes', '[]'), true) ?: [];
  2995. $props = json_decode(getProp($episode, 'props', '[]'), true) ?: [];
  2996. $extra_products = json_decode(getProp($episode, 'extra_products', '[]'), true) ?: [];
  2997. // 先合并roles、scenes和props
  2998. // 处理角色数组
  2999. foreach ($roles as $role) {
  3000. $product = $role;
  3001. // 将role字段重命名为product_name
  3002. if (is_array($product) && !empty($product['role'] ?? null)) {
  3003. $product['product_name'] = $product['role'];
  3004. unset($product['role']);
  3005. $product['product'] = 1; // 标记类型为角色
  3006. $products[$product['product_name']] = $product; // 使用product_name作为key便于后续覆盖
  3007. }
  3008. }
  3009. // 处理场景数组
  3010. foreach ($scenes as $scene) {
  3011. $product = $scene;
  3012. // 将scene字段重命名为product_name
  3013. if (is_array($product) && !empty($product['scene'] ?? null)) {
  3014. $product['product_name'] = $product['scene'];
  3015. unset($product['scene']);
  3016. $product['product'] = 2; // 标记类型为场景
  3017. $products[$product['product_name']] = $product; // 使用product_name作为key便于后续覆盖
  3018. }
  3019. }
  3020. // 处理道具数组
  3021. foreach ($props as $prop) {
  3022. $product = $prop;
  3023. // 将prop字段重命名为product_name
  3024. if (is_array($product) && !empty($product['prop'] ?? null)) {
  3025. $product['product_name'] = $product['prop'];
  3026. unset($product['prop']);
  3027. $product['product'] = 3; // 标记类型为道具
  3028. $products[$product['product_name']] = $product; // 使用product_name作为key便于后续覆盖
  3029. }
  3030. }
  3031. // extra_products优先级更高,直接覆盖同名的roles和scenes
  3032. foreach ($extra_products as $extra_product) {
  3033. $product_name = getProp($extra_product, 'product_name');
  3034. if ($product_name) {
  3035. $products[$product_name] = $extra_product; // 覆盖同名数据
  3036. }
  3037. }
  3038. // 重新索引数组(去除key)
  3039. $products = array_values($products);
  3040. }
  3041. }
  3042. // 获取执行中的任务
  3043. $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) {
  3044. $value = (array)$value;
  3045. if ($value['ref_image_url']) $value['ref_image_url'] = json_decode($value['ref_image_url'], true);
  3046. else $value['ref_image_url'] = [];
  3047. $value['status'] = $value['status'] == 'pending' ? '视频待生成' : '视频生成中';
  3048. // 处理prompt:删除人物音色部分,保留【镜头】开始的内容,并去掉<图片X>标记
  3049. if (!empty($value['prompt'])) {
  3050. $prompt = $value['prompt'];
  3051. // 查找第一个【镜头】的位置
  3052. if (preg_match('/【镜头\d+】/u', $prompt, $matches, PREG_OFFSET_CAPTURE)) {
  3053. // 从【镜头】开始截取
  3054. $prompt = substr($prompt, $matches[0][1]);
  3055. }
  3056. // 去除所有<图片X>格式的标记(X可以是任意数字)
  3057. $prompt = preg_replace('/<图片\d+>/u', '', $prompt);
  3058. $value['prompt'] = $prompt;
  3059. }
  3060. return $value;
  3061. })->toArray();
  3062. return compact('chat', 'url', 'products', 'tasks');
  3063. }
  3064. public function applyAudioData($data) {
  3065. $segment_id = getProp($data, 'segment_id');
  3066. $global_data = getProp($data, 'global_data');
  3067. $segment_data = getProp($data, 'segment_data');
  3068. if (!$segment_id) Utils::throwError('20003:请选择分镜');
  3069. $global_data = is_array($global_data) ? $global_data : [];
  3070. $segment_data = is_array($segment_data) ? $segment_data : [];
  3071. // dialogue只能在segment_data中,如果在global_data中则移到segment_data
  3072. $dialogue_item = null;
  3073. foreach ($global_data as $key => $item) {
  3074. if (trim((string)getProp($item, 'name')) === 'dialogue') {
  3075. $dialogue_item = $item;
  3076. unset($global_data[$key]);
  3077. break;
  3078. }
  3079. }
  3080. if ($dialogue_item) {
  3081. $segment_data[] = $dialogue_item;
  3082. }
  3083. // 特殊参数: audio_url,audio_duration,subtitle_info
  3084. // 这些特殊参数必须同时存在才对当前分镜有效,直接保存但不创建音频任务
  3085. // 如果不是全部存在,则仍需创建音频任务
  3086. $special_fields = ['audio_url', 'audio_duration', 'subtitle_info'];
  3087. $special_update_data = [];
  3088. $has_all_special_params = false;
  3089. // 从segment_data中提取特殊参数
  3090. $filtered_segment_data = [];
  3091. foreach ($segment_data as $item) {
  3092. $field_name = trim((string)getProp($item, 'name'));
  3093. if (in_array($field_name, $special_fields)) {
  3094. $special_update_data[$field_name] = getProp($item, 'value');
  3095. } else {
  3096. // 非特殊参数保留,继续后续处理
  3097. $filtered_segment_data[] = $item;
  3098. }
  3099. }
  3100. // 检查是否三个特殊参数都存在
  3101. if (count($special_update_data) === 3 &&
  3102. isset($special_update_data['audio_url']) &&
  3103. isset($special_update_data['audio_duration']) &&
  3104. isset($special_update_data['subtitle_info'])) {
  3105. $has_all_special_params = true;
  3106. // 立即更新到当前分镜
  3107. $special_update_data['updated_at'] = date('Y-m-d H:i:s');
  3108. DB::table('mp_episode_segments')
  3109. ->where('segment_id', $segment_id)
  3110. ->update($special_update_data);
  3111. }
  3112. // 使用过滤后的segment_data继续处理其他参数
  3113. $segment_data = $filtered_segment_data;
  3114. $allow_fields = ['dialogue', 'voice_type', 'speed_ratio', 'loudness_ratio', 'emotion_scale', 'pitch'];
  3115. $global_update_data = [];
  3116. $segment_update_data = [];
  3117. $global_voice_type = '';
  3118. $target_segment = DB::table('mp_episode_segments')->where('segment_id', $segment_id)->first();
  3119. if (!$target_segment) Utils::throwError('20003:分镜不存在');
  3120. $episode_id = getProp($target_segment, 'episode_id');
  3121. $target_voice_actor = trim((string)getProp($target_segment, 'voice_actor'));
  3122. $episode = DB::table('mp_anime_episodes')->where('id', $episode_id)->first();
  3123. if (!$episode) Utils::throwError('20003:分集不存在');
  3124. foreach ($global_data as $item) {
  3125. $field_name = trim((string)getProp($item, 'name'));
  3126. if (!$field_name || !in_array($field_name, $allow_fields)) {
  3127. continue;
  3128. }
  3129. $global_update_data[$field_name] = getProp($item, 'value');
  3130. if ($field_name === 'voice_type') {
  3131. $global_voice_type = trim((string)getProp($item, 'value'));
  3132. }
  3133. }
  3134. foreach ($segment_data as $item) {
  3135. $field_name = trim((string)getProp($item, 'name'));
  3136. if (!$field_name || !in_array($field_name, $allow_fields)) {
  3137. continue;
  3138. }
  3139. $segment_update_data[$field_name] = getProp($item, 'value');
  3140. }
  3141. if ($global_voice_type) {
  3142. $timbre_info = DB::table('mp_timbres')
  3143. ->where('timbre_type', $global_voice_type)
  3144. ->select('audio_url', 'timbre_name')
  3145. ->first();
  3146. if ($timbre_info) {
  3147. $global_update_data['voice_audio_url'] = getProp($timbre_info, 'audio_url');
  3148. $global_update_data['voice_name'] = str_replace('(多情感)', '', getProp($timbre_info, 'timbre_name'));
  3149. }
  3150. }
  3151. try {
  3152. DB::beginTransaction();
  3153. // 收集需要创建音频合成任务的segment_id和对应的分镜数据
  3154. $segment_ids_to_create_task = [];
  3155. $segments_data = [];
  3156. // 如果有全局更新,获取该角色的所有分镜数据并检查是否有变化
  3157. if (!empty($global_update_data)) {
  3158. // 如果角色不存在,则只更新当前分镜
  3159. if (!$target_voice_actor) {
  3160. // 只处理当前分镜
  3161. $affected_segments = DB::table('mp_episode_segments')
  3162. ->where('segment_id', $segment_id)
  3163. ->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')
  3164. ->get();
  3165. } else {
  3166. // 获取该角色的所有分镜
  3167. $affected_segments = DB::table('mp_episode_segments')
  3168. ->where('episode_id', $episode_id)
  3169. ->where('voice_actor', $target_voice_actor)
  3170. ->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')
  3171. ->get();
  3172. }
  3173. foreach ($affected_segments as $seg) {
  3174. $seg = (array)$seg;
  3175. $sid = getProp($seg, 'segment_id');
  3176. // 检查参数是否发生变化
  3177. $has_changed = false;
  3178. foreach ($global_update_data as $field => $new_value) {
  3179. $old_value = getProp($seg, $field);
  3180. if ($old_value != $new_value) {
  3181. $has_changed = true;
  3182. break;
  3183. }
  3184. }
  3185. if ($has_changed) {
  3186. $segment_ids_to_create_task[] = $sid;
  3187. $segments_data[$sid] = $seg;
  3188. }
  3189. }
  3190. // 只有在有变化的分镜时才更新
  3191. if (!empty($segment_ids_to_create_task)) {
  3192. $global_segment_update_data = $global_update_data;
  3193. $global_segment_update_data['audio_url'] = ''; // 清空音频URL
  3194. $global_segment_update_data['updated_at'] = date('Y-m-d H:i:s');
  3195. DB::table('mp_episode_segments')
  3196. ->where('episode_id', $episode_id)
  3197. ->where('voice_actor', $target_voice_actor)
  3198. ->whereIn('segment_id', $segment_ids_to_create_task)
  3199. ->update($global_segment_update_data);
  3200. }
  3201. if ($global_voice_type) {
  3202. $episode_roles = json_decode((string)getProp($episode, 'roles'), true);
  3203. $episode_roles = is_array($episode_roles) ? $episode_roles : [];
  3204. $roles_updated = false;
  3205. foreach ($episode_roles as &$role) {
  3206. // 通过 role 字段匹配角色名,而不是 voice_name
  3207. if (trim((string)getProp($role, 'role')) !== $target_voice_actor) {
  3208. continue;
  3209. }
  3210. $role['voice_type'] = $global_voice_type;
  3211. $role['voice_audio_url'] = getProp($global_update_data, 'voice_audio_url');
  3212. $role['voice_name'] = getProp($global_update_data, 'voice_name');
  3213. $roles_updated = true;
  3214. }
  3215. unset($role);
  3216. if ($roles_updated) {
  3217. DB::table('mp_anime_episodes')->where('id', $episode_id)->update([
  3218. 'roles' => json_encode($episode_roles, 256),
  3219. 'updated_at' => date('Y-m-d H:i:s'),
  3220. ]);
  3221. }
  3222. }
  3223. }
  3224. // 如果有单个分镜更新,检查是否有变化
  3225. if (!empty($segment_update_data)) {
  3226. // 获取当前分镜数据
  3227. $current_segment = DB::table('mp_episode_segments')
  3228. ->where('segment_id', $segment_id)
  3229. ->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')
  3230. ->first();
  3231. if ($current_segment) {
  3232. $current_segment = (array)$current_segment;
  3233. // 检查参数是否发生变化
  3234. $has_changed = false;
  3235. foreach ($segment_update_data as $field => $new_value) {
  3236. $old_value = getProp($current_segment, $field);
  3237. if ($old_value != $new_value) {
  3238. $has_changed = true;
  3239. break;
  3240. }
  3241. }
  3242. if ($has_changed) {
  3243. // 如果该分镜还未在列表中,添加进去
  3244. if (!in_array($segment_id, $segment_ids_to_create_task)) {
  3245. $segment_ids_to_create_task[] = $segment_id;
  3246. $segments_data[$segment_id] = $current_segment;
  3247. }
  3248. // 更新分镜数据并清空音频URL
  3249. $segment_update_data['audio_url'] = '';
  3250. $segment_update_data['updated_at'] = date('Y-m-d H:i:s');
  3251. DB::table('mp_episode_segments')->where('segment_id', $segment_id)->update($segment_update_data);
  3252. }
  3253. }
  3254. }
  3255. // 为所有有变化的分镜创建音频合成任务
  3256. // 但如果当前分镜同时设置了全部三个特殊参数(audio_url, audio_duration, subtitle_info),则跳过该分镜
  3257. if (!empty($segment_ids_to_create_task)) {
  3258. foreach ($segment_ids_to_create_task as $sid) {
  3259. // 如果当前分镜同时设置了全部三个特殊参数,则跳过音频任务创建
  3260. if ($sid === $segment_id && $has_all_special_params) {
  3261. continue;
  3262. }
  3263. // 重新获取更新后的分镜数据
  3264. $updated_segment = DB::table('mp_episode_segments')
  3265. ->where('segment_id', $sid)
  3266. ->select('voice_actor', 'dialogue', 'voice_type', 'voice_name', 'emotion', 'emotion_type', 'gender', 'speed_ratio', 'loudness_ratio', 'emotion_scale', 'pitch')
  3267. ->first();
  3268. if (!$updated_segment) continue;
  3269. $updated_segment = (array)$updated_segment;
  3270. // 检查dialogue是否为空
  3271. $dialogue = getProp($updated_segment, 'dialogue');
  3272. if (empty($dialogue)) {
  3273. // dialogue为空时,直接写入默认音频信息
  3274. DB::table('mp_episode_segments')->where('segment_id', $sid)->update([
  3275. 'audio_url' => 'https://zw-audiobook.tos-cn-beijing.volces.com/effects/ellipses_2s.mp3',
  3276. 'audio_duration' => 2.0,
  3277. 'subtitle_info' => json_encode(['duration' => 2.0, 'words' => []], 256),
  3278. 'updated_at' => date('Y-m-d H:i:s')
  3279. ]);
  3280. continue;
  3281. }
  3282. $generate_json = [
  3283. 'text' => $dialogue,
  3284. 'role' => getProp($updated_segment, 'voice_actor'),
  3285. 'voice_type' => getProp($updated_segment, 'voice_type'),
  3286. 'voice_name' => getProp($updated_segment, 'voice_name'),
  3287. 'emotion' => getProp($updated_segment, 'emotion'),
  3288. 'emotion_type' => getProp($updated_segment, 'emotion_type'),
  3289. 'gender' => getProp($updated_segment, 'gender'),
  3290. 'speed_ratio' => getProp($updated_segment, 'speed_ratio', 0),
  3291. 'loudness_ratio' => getProp($updated_segment, 'loudness_ratio', 0),
  3292. 'emotion_scale' => getProp($updated_segment, 'emotion_scale', 0),
  3293. 'pitch' => getProp($updated_segment, 'pitch', 0),
  3294. ];
  3295. // 插入视频配音合成任务
  3296. $dubTaskId = DB::table('mp_dub_video_tasks')->insertGetId([
  3297. 'alias_segment_id' => $sid,
  3298. 'generate_status' => '执行中',
  3299. 'audio_url' => '',
  3300. 'generate_json' => json_encode($generate_json, 256),
  3301. 'created_at' => date('Y-m-d H:i:s'),
  3302. 'updated_at' => date('Y-m-d H:i:s'),
  3303. ]);
  3304. if (!$dubTaskId) {
  3305. dLog('anime')->error('创建配音任务失败', ['segment_id' => $sid]);
  3306. continue;
  3307. }
  3308. // 将任务ID添加到Redis列表中
  3309. Redis::lpush('dub_video_task_queue', $dubTaskId);
  3310. // 请求远程服务器执行生成
  3311. try {
  3312. sleep(1);
  3313. $client = new Client(['timeout' => 300, 'verify' => false]);
  3314. $result = $client->get("http://122.9.129.83:5000/api/anime/genAudio?taskId={$dubTaskId}");
  3315. $response = $result->getBody()->getContents();
  3316. $response_arr = json_decode($response, true);
  3317. if (!isset($response_arr['code']) || (int)$response_arr['code'] !== 0) {
  3318. $error_msg = isset($response_arr['msg']) ? $response_arr['msg'] : '未知错误';
  3319. dLog('anime')->error('火山生成音频失败', ['error' => $error_msg, 'task_id' => $dubTaskId, 'segment_id' => $sid]);
  3320. logDB('anime', 'error', '火山生成音频失败', ['error' => $error_msg, 'task_id' => $dubTaskId, 'segment_id' => $sid]);
  3321. }
  3322. } catch (\Exception $e) {
  3323. dLog('anime')->error('调用音频生成API失败', ['error' => $e->getMessage(), 'task_id' => $dubTaskId, 'segment_id' => $sid]);
  3324. logDB('anime', 'error', '调用音频生成API失败', ['error' => $e->getMessage(), 'task_id' => $dubTaskId, 'segment_id' => $sid]);
  3325. }
  3326. }
  3327. }
  3328. DB::commit();
  3329. } catch (\Exception $e) {
  3330. DB::rollBack();
  3331. Utils::throwError('20003:'.$e->getMessage());
  3332. }
  3333. return true;
  3334. }
  3335. public function episodePicsInfo($data) {
  3336. $anime_id = getProp($data, 'anime_id');
  3337. $episode_id = getProp($data, 'episode_id');
  3338. // 参数验证
  3339. if (!$anime_id && !$episode_id) {
  3340. Utils::throwError('20003:请提供动漫ID或分集ID');
  3341. }
  3342. // 根据参数获取数据源
  3343. if ($episode_id) {
  3344. // 从剧集表获取
  3345. $source = DB::table('mp_anime_episodes')->where('id', $episode_id)->first();
  3346. if (!$source) Utils::throwError('20003:该剧集不存在');
  3347. $table_name = 'mp_anime_episodes';
  3348. $id_field = 'id';
  3349. $id_value = $episode_id;
  3350. // 获取剧集的anime_id用于继承全局数据
  3351. $anime_id = getProp($source, 'anime_id');
  3352. } else {
  3353. // 从动漫表获取
  3354. $source = DB::table('mp_animes')->where('id', $anime_id)->where('is_deleted', 0)->first();
  3355. if (!$source) Utils::throwError('20003:该动漫不存在');
  3356. $table_name = 'mp_animes';
  3357. $id_field = 'id';
  3358. $id_value = $anime_id;
  3359. }
  3360. $source = (array)$source;
  3361. $roles = json_decode(getProp($source, 'roles', '[]'), true) ?: [];
  3362. $scenes = json_decode(getProp($source, 'scenes', '[]'), true) ?: [];
  3363. $props = json_decode(getProp($source, 'props', '[]'), true) ?: [];
  3364. // 如果是分集数据,需要处理继承和任务创建逻辑
  3365. if ($episode_id) {
  3366. $this->processEpisodeRolesAndScenes($episode_id, $anime_id, $roles, $scenes, $source);
  3367. }
  3368. // 返回生成器函数,用于 SSE 流式输出
  3369. return function() use ($roles, $scenes, $props, $table_name, $id_field, $id_value) {
  3370. $startTime = time();
  3371. $maxDuration = 600; // 10分钟超时
  3372. $checkInterval = 3; // 每3秒检查一次
  3373. // Redis 缓存键
  3374. $cacheKey = "anime:pics_info:{$table_name}:{$id_value}";
  3375. // 生成当前数据的哈希值用于比较
  3376. $generateHash = function($roles, $scenes, $props) {
  3377. return md5(json_encode(['roles' => $roles, 'scenes' => $scenes, 'props' => $props], JSON_UNESCAPED_UNICODE));
  3378. };
  3379. // 发送初始数据
  3380. $currentHash = $generateHash($roles, $scenes, $props);
  3381. Redis::setex($cacheKey, 600, $currentHash); // 缓存10分钟
  3382. echo "data: " . json_encode([
  3383. 'type' => 'init',
  3384. 'data' => [
  3385. 'roles' => $roles,
  3386. 'scenes' => $scenes,
  3387. 'props' => $props,
  3388. 'start_time' => $startTime
  3389. ]
  3390. ], JSON_UNESCAPED_UNICODE) . "\n\n";
  3391. if (ob_get_level() > 0) {
  3392. ob_flush();
  3393. }
  3394. flush();
  3395. // 持续轮询任务状态
  3396. while (time() - $startTime < $maxDuration) {
  3397. $hasProcessing = false;
  3398. $updated = false;
  3399. // 检查角色任务状态
  3400. foreach ($roles as $index => &$role) {
  3401. $task_id = getProp($role, 'task_id');
  3402. $task_status = getProp($role, 'task_status');
  3403. $existing_url = getProp($role, 'url');
  3404. // 只处理有任务ID且状态为processing的角色,或者状态为processing但没有URL的角色
  3405. if ($task_id && ($task_status === 'processing' || (in_array($task_status, ['success', 'completed']) && empty($existing_url)))) {
  3406. $hasProcessing = ($task_status === 'processing');
  3407. // 查询任务状态
  3408. $task = DB::table('mp_generate_pic_tasks')
  3409. ->where('id', $task_id)
  3410. ->select('id', 'status', 'result_url', 'error_message')
  3411. ->first();
  3412. if ($task) {
  3413. $task = (array)$task;
  3414. $status = getProp($task, 'status');
  3415. // 如果任务完成或失败
  3416. if (in_array($status, ['success', 'failed'])) {
  3417. $role['task_status'] = $status;
  3418. if ($status === 'success') {
  3419. $result_url = getProp($task, 'result_url');
  3420. if ($result_url) {
  3421. $result_urls = is_json($result_url) ? json_decode($result_url, true) : [$result_url];
  3422. if (is_array($result_urls) && !empty($result_urls[0])) {
  3423. $role['url'] = $result_urls[0];
  3424. }
  3425. }
  3426. }
  3427. $updated = true;
  3428. } else if ($status === 'processing') {
  3429. $hasProcessing = true;
  3430. }
  3431. }
  3432. }
  3433. }
  3434. // 检查场景任务状态
  3435. foreach ($scenes as $index => &$scene) {
  3436. $task_id = getProp($scene, 'task_id');
  3437. $task_status = getProp($scene, 'task_status');
  3438. $existing_url = getProp($scene, 'url');
  3439. // 只处理有任务ID且状态为processing的场景,或者状态为success但没有URL的场景
  3440. if ($task_id && ($task_status === 'processing' || (in_array($task_status, ['success', 'completed']) && empty($existing_url)))) {
  3441. $hasProcessing = ($task_status === 'processing');
  3442. // 查询任务状态
  3443. $task = DB::table('mp_generate_pic_tasks')
  3444. ->where('id', $task_id)
  3445. ->select('id', 'status', 'result_url', 'error_message')
  3446. ->first();
  3447. if ($task) {
  3448. $task = (array)$task;
  3449. $status = getProp($task, 'status');
  3450. // 如果任务完成或失败
  3451. if (in_array($status, ['success', 'failed'])) {
  3452. $scene['task_status'] = $status;
  3453. if ($status === 'success') {
  3454. $result_url = getProp($task, 'result_url');
  3455. if ($result_url) {
  3456. $result_urls = is_json($result_url) ? json_decode($result_url, true) : [$result_url];
  3457. if (is_array($result_urls) && !empty($result_urls[0])) {
  3458. $scene['url'] = $result_urls[0];
  3459. }
  3460. }
  3461. }
  3462. $updated = true;
  3463. } else if ($status === 'processing') {
  3464. $hasProcessing = true;
  3465. }
  3466. }
  3467. }
  3468. }
  3469. // 检查道具任务状态
  3470. foreach ($props as $index => &$prop) {
  3471. $task_id = getProp($prop, 'task_id');
  3472. $task_status = getProp($prop, 'task_status');
  3473. $existing_url = getProp($prop, 'url');
  3474. // 只处理有任务ID且状态为processing的道具,或者状态为success但没有URL的道具
  3475. if ($task_id && ($task_status === 'processing' || (in_array($task_status, ['success', 'completed']) && empty($existing_url)))) {
  3476. $hasProcessing = ($task_status === 'processing');
  3477. // 查询任务状态
  3478. $task = DB::table('mp_generate_pic_tasks')
  3479. ->where('id', $task_id)
  3480. ->select('id', 'status', 'result_url', 'error_message')
  3481. ->first();
  3482. if ($task) {
  3483. $task = (array)$task;
  3484. $status = getProp($task, 'status');
  3485. // 如果任务完成或失败
  3486. if (in_array($status, ['success', 'failed'])) {
  3487. $prop['task_status'] = $status;
  3488. if ($status === 'success') {
  3489. $result_url = getProp($task, 'result_url');
  3490. if ($result_url) {
  3491. $result_urls = is_json($result_url) ? json_decode($result_url, true) : [$result_url];
  3492. if (is_array($result_urls) && !empty($result_urls[0])) {
  3493. $prop['url'] = $result_urls[0];
  3494. }
  3495. }
  3496. }
  3497. $updated = true;
  3498. } else if ($status === 'processing') {
  3499. $hasProcessing = true;
  3500. }
  3501. }
  3502. }
  3503. }
  3504. // 如果有更新,检查数据是否真的变化了(通过哈希对比)
  3505. if ($updated) {
  3506. $newHash = $generateHash($roles, $scenes, $props);
  3507. $cachedHash = Redis::get($cacheKey);
  3508. // 只有当数据真正变化时才更新数据库和发送事件
  3509. if ($newHash !== $cachedHash) {
  3510. try {
  3511. // 更新数据库
  3512. DB::table($table_name)->where($id_field, $id_value)->update([
  3513. 'roles' => json_encode($roles, JSON_UNESCAPED_UNICODE),
  3514. 'scenes' => json_encode($scenes, JSON_UNESCAPED_UNICODE),
  3515. 'props' => json_encode($props, JSON_UNESCAPED_UNICODE),
  3516. 'updated_at' => date('Y-m-d H:i:s')
  3517. ]);
  3518. // 更新缓存
  3519. Redis::setex($cacheKey, 600, $newHash);
  3520. // 发送更新事件
  3521. echo "data: " . json_encode([
  3522. 'type' => 'update',
  3523. 'data' => [
  3524. 'roles' => $roles,
  3525. 'scenes' => $scenes,
  3526. 'props' => $props,
  3527. 'elapsed_time' => time() - $startTime
  3528. ]
  3529. ], JSON_UNESCAPED_UNICODE) . "\n\n";
  3530. if (ob_get_level() > 0) {
  3531. ob_flush();
  3532. }
  3533. flush();
  3534. } catch (\Exception $e) {
  3535. dLog('anime')->error('更新角色/场景/道具信息失败: ' . $e->getMessage());
  3536. }
  3537. } else {
  3538. // 即使哈希相同,如果有URL更新也要发送事件
  3539. $hasUrlUpdate = false;
  3540. foreach ($roles as $role) {
  3541. if (!empty(getProp($role, 'url')) && getProp($role, 'task_status') === 'success') {
  3542. $hasUrlUpdate = true;
  3543. break;
  3544. }
  3545. }
  3546. if (!$hasUrlUpdate) {
  3547. foreach ($scenes as $scene) {
  3548. if (!empty(getProp($scene, 'url')) && getProp($scene, 'task_status') === 'success') {
  3549. $hasUrlUpdate = true;
  3550. break;
  3551. }
  3552. }
  3553. }
  3554. if (!$hasUrlUpdate) {
  3555. foreach ($props as $prop) {
  3556. if (!empty(getProp($prop, 'url')) && getProp($prop, 'task_status') === 'success') {
  3557. $hasUrlUpdate = true;
  3558. break;
  3559. }
  3560. }
  3561. }
  3562. if ($hasUrlUpdate) {
  3563. // 强制更新数据库和发送事件
  3564. try {
  3565. DB::table($table_name)->where($id_field, $id_value)->update([
  3566. 'roles' => json_encode($roles, JSON_UNESCAPED_UNICODE),
  3567. 'scenes' => json_encode($scenes, JSON_UNESCAPED_UNICODE),
  3568. 'props' => json_encode($props, JSON_UNESCAPED_UNICODE),
  3569. 'updated_at' => date('Y-m-d H:i:s')
  3570. ]);
  3571. // 更新缓存
  3572. Redis::setex($cacheKey, 600, $newHash);
  3573. // 发送更新事件
  3574. echo "data: " . json_encode([
  3575. 'type' => 'update',
  3576. 'data' => [
  3577. 'roles' => $roles,
  3578. 'scenes' => $scenes,
  3579. 'props' => $props,
  3580. 'elapsed_time' => time() - $startTime
  3581. ]
  3582. ], JSON_UNESCAPED_UNICODE) . "\n\n";
  3583. if (ob_get_level() > 0) {
  3584. ob_flush();
  3585. }
  3586. flush();
  3587. } catch (\Exception $e) {
  3588. dLog('anime')->error('强制更新角色/场景/道具信息失败: ' . $e->getMessage());
  3589. }
  3590. }
  3591. }
  3592. }
  3593. // 如果所有任务都已完成,发送完成事件并退出
  3594. if (!$hasProcessing) {
  3595. // 查询数据库中的最终数据,确保返回最新的完整数据
  3596. try {
  3597. $finalSource = DB::table($table_name)->where($id_field, $id_value)->first();
  3598. if ($finalSource) {
  3599. $finalSource = (array)$finalSource;
  3600. $finalRoles = json_decode(getProp($finalSource, 'roles', '[]'), true) ?: [];
  3601. $finalScenes = json_decode(getProp($finalSource, 'scenes', '[]'), true) ?: [];
  3602. $finalProps = json_decode(getProp($finalSource, 'props', '[]'), true) ?: [];
  3603. // 使用数据库中的最终数据
  3604. $roles = $finalRoles;
  3605. $scenes = $finalScenes;
  3606. $props = $finalProps;
  3607. }
  3608. } catch (\Exception $e) {
  3609. dLog('anime')->error('查询最终数据失败: ' . $e->getMessage());
  3610. // 如果查询失败,继续使用内存中的数据
  3611. }
  3612. // 清理缓存
  3613. Redis::del($cacheKey);
  3614. echo "data: " . json_encode([
  3615. 'type' => 'completed',
  3616. 'data' => [
  3617. 'roles' => $roles,
  3618. 'scenes' => $scenes,
  3619. 'props' => $props,
  3620. 'total_time' => time() - $startTime
  3621. ]
  3622. ], JSON_UNESCAPED_UNICODE) . "\n\n";
  3623. if (ob_get_level() > 0) {
  3624. ob_flush();
  3625. }
  3626. flush();
  3627. break;
  3628. }
  3629. // 等待下次检查
  3630. sleep($checkInterval);
  3631. }
  3632. // 超时处理
  3633. if (time() - $startTime >= $maxDuration) {
  3634. // 查询数据库中的最终数据,即使超时也要返回最新数据
  3635. try {
  3636. $finalSource = DB::table($table_name)->where($id_field, $id_value)->first();
  3637. if ($finalSource) {
  3638. $finalSource = (array)$finalSource;
  3639. $finalRoles = json_decode(getProp($finalSource, 'roles', '[]'), true) ?: [];
  3640. $finalScenes = json_decode(getProp($finalSource, 'scenes', '[]'), true) ?: [];
  3641. $finalProps = json_decode(getProp($finalSource, 'props', '[]'), true) ?: [];
  3642. // 使用数据库中的最终数据
  3643. $roles = $finalRoles;
  3644. $scenes = $finalScenes;
  3645. $props = $finalProps;
  3646. }
  3647. } catch (\Exception $e) {
  3648. dLog('anime')->error('超时时查询最终数据失败: ' . $e->getMessage());
  3649. // 如果查询失败,继续使用内存中的数据
  3650. }
  3651. // 清理缓存
  3652. Redis::del($cacheKey);
  3653. echo "data: " . json_encode([
  3654. 'type' => 'timeout',
  3655. 'message' => '轮询超时,请刷新页面查看最新状态',
  3656. 'data' => [
  3657. 'roles' => $roles,
  3658. 'scenes' => $scenes,
  3659. 'props' => $props
  3660. ]
  3661. ], JSON_UNESCAPED_UNICODE) . "\n\n";
  3662. if (ob_get_level() > 0) {
  3663. ob_flush();
  3664. }
  3665. flush();
  3666. }
  3667. };
  3668. }
  3669. public function clipSegmentVideo($data) {
  3670. $segment_id = getProp($data, 'segment_id');
  3671. $video_time_point_start = getProp($data, 'video_time_point_start');
  3672. $video_time_point_end = getProp($data, 'video_time_point_end');
  3673. if (!$segment_id || !$video_time_point_start || !$video_time_point_end) {
  3674. Utils::throwError('20003:参数异常');
  3675. }
  3676. if (!DB::table('mp_episode_segments')->where('segment_id', $segment_id)->value('video_url')) {
  3677. Utils::throwError('20003:该分镜没有视频,无法裁剪');
  3678. }
  3679. $video_duration = $video_time_point_end - $video_time_point_start;
  3680. if (!$video_duration < 0) Utils::throwError('20003:参数异常');
  3681. return DB::table('mp_episode_segments')->where('segment_id', $segment_id)->update([
  3682. 'video_duration' => $video_duration,
  3683. 'video_time_point_start' => $video_time_point_start,
  3684. 'video_time_point_end' => $video_time_point_end,
  3685. 'updated_at' => date('Y-m-d H:i:s')
  3686. ]);
  3687. }
  3688. // 轮训获取图片任务结果
  3689. private function loopGetPicTaskResult($task_id) {
  3690. $task = MpGeneratePicTask::where('id', $task_id)->first();
  3691. if (!$task) {
  3692. return '';
  3693. }
  3694. // 检查任务模型类型(火山模型和GPT模型都支持直接检查任务状态)
  3695. $model = getProp($task, 'model');
  3696. $isVolcModel = in_array($model, \App\Consts\BaseConst::VOLC_PIC_MODELS);
  3697. $isGptModel = in_array($model, \App\Consts\BaseConst::GPT_IMAGE2_MODELS);
  3698. $isSyncModel = $isVolcModel || $isGptModel;
  3699. // 轮询查询任务状态(火山API和即梦AI都需要轮询)
  3700. $start_count = 0;
  3701. $img_url = '';
  3702. while ($start_count <= 60) { // 循环20次请求,每3s一次
  3703. sleep(3);
  3704. $task = MpGeneratePicTask::where('id', $task_id)->first();
  3705. // 如果任务已经完成,直接返回结果
  3706. if ($task->status === 'success' && $task->result_url) {
  3707. $result_urls = is_array($task->result_url) ? $task->result_url : json_decode($task->result_url, true);
  3708. return is_array($result_urls) ? $result_urls[0] : $task->result_url;
  3709. }
  3710. // 如果任务已失败,返回空
  3711. if ($task->status === 'failed') {
  3712. return '';
  3713. }
  3714. if ($isSyncModel) continue;
  3715. // 查询任务状态
  3716. $statusInfo = $this->aiImageGenerationService->queryTaskStatus($task);
  3717. if ($statusInfo['status'] === 'success') {
  3718. $task->updateStatus('success', [
  3719. 'result_url' => $statusInfo['result_url'],
  3720. 'result_json' => $statusInfo['result_json'] ?? []
  3721. ]);
  3722. // 同步调整分镜图片状态和结果
  3723. if (getProp($task, 'alias_segment_id')) {
  3724. DB::table('mp_episode_segments')->where('segment_id', getProp($task, 'alias_segment_id'))->update([
  3725. 'img_url' => $statusInfo['result_url'][0],
  3726. 'pic_task_status' => '已完成',
  3727. ]);
  3728. }
  3729. $img_url = $statusInfo['result_url'][0];
  3730. break;
  3731. } elseif ($statusInfo['status'] === 'failed') {
  3732. $task->updateStatus('failed', [
  3733. 'error_message' => $statusInfo['error_message'],
  3734. 'result_json' => $statusInfo['result_json'] ?? []
  3735. ]);
  3736. if (getProp($task, 'alias_segment_id')) {
  3737. DB::table('mp_episode_segments')->where('segment_id', getProp($task, 'alias_segment_id'))->update([
  3738. 'pic_task_status' => '失败',
  3739. ]);
  3740. }
  3741. break;
  3742. }
  3743. $start_count++;
  3744. }
  3745. return $img_url;
  3746. }
  3747. /**
  3748. * 从分镜内容中提取涉及的角色
  3749. */
  3750. private function extractCharactersFromSegment($segment_content, $available_characters, $roles) {
  3751. $found_characters = [];
  3752. foreach ($available_characters as $character) {
  3753. // 检查角色名称是否在分镜内容中出现
  3754. if (strpos($segment_content, $character) !== false) {
  3755. $found_characters[] = $character;
  3756. }
  3757. }
  3758. if (!$found_characters) {
  3759. foreach ($roles as $character) {
  3760. // 检查角色名称是否在分镜内容中出现
  3761. if (strpos($segment_content, $character) !== false) {
  3762. $found_characters[] = $character;
  3763. }
  3764. }
  3765. }
  3766. return array_unique($found_characters);
  3767. }
  3768. // 从分镜剧本中提取关键字段
  3769. private function handleSegmentContent(&$data) {
  3770. $segmentContent = getProp($data, 'segment_content');
  3771. // 解析分镜详细信息 - 与 Helpers.php 中 handleEpisodeContent 的 segmentData 结构保持一致
  3772. $segmentData = [
  3773. 'description' => '',
  3774. 'composition' => '',
  3775. 'camera_movement' => '',
  3776. 'voice_actor' => '',
  3777. 'dialogue' => '',
  3778. 'frame_type' => '',
  3779. 'scene' => '', // 场景
  3780. 'characters' => '', // 出镜角色
  3781. 'tail_frame' => '', // 尾帧描述
  3782. 'emotion' => '中性', // 情感
  3783. 'gender' => '0', // 性别(0未知,1男,2女)
  3784. 'speed_ratio' => 0, // 语速
  3785. 'loudness_ratio' => 0, // 音量
  3786. 'emotion_scale' => 4, // 情感强度
  3787. 'pitch' => 0, // 音调
  3788. ];
  3789. // 用于存储需要从 segment_content 中移除的匹配项
  3790. $replaceEmptyArr = [];
  3791. // 提取各个字段 - 兼容中文冒号和英文冒号,支持多种表达方式
  3792. if (preg_match('/(?:画面描述|镜头描述|场景描述)[::]\s*([^\n]+)/u', $segmentContent, $descMatch)) {
  3793. $segmentData['description'] = trim($descMatch[1]);
  3794. $data['description'] = trim($descMatch[1]);
  3795. }
  3796. if (preg_match('/(?:构图设计|构图|镜头构图)[::]\s*([^\n]+)/u', $segmentContent, $compMatch)) {
  3797. $segmentData['composition'] = trim($compMatch[1]);
  3798. $data['composition'] = trim($compMatch[1]);
  3799. }
  3800. if (preg_match('/(?:运镜调度|运镜|镜头运动|摄影机运动)[::]\s*([^\n]+)/u', $segmentContent, $cameraMatch)) {
  3801. $segmentData['camera_movement'] = trim($cameraMatch[1]);
  3802. $data['camera_movement'] = trim($cameraMatch[1]);
  3803. }
  3804. if (preg_match('/(?:配音角色|配音|角色|声优)[::]\s*([^\n]+)/u', $segmentContent, $voiceMatch)) {
  3805. $segmentData['voice_actor'] = trim($voiceMatch[1]);
  3806. $data['voice_actor'] = trim($voiceMatch[1]);
  3807. }
  3808. if (preg_match('/(?:台词内容|台词|对白|对话)[::]\s*([^\n]+)/u', $segmentContent, $dialogueMatch)) {
  3809. $segmentData['dialogue'] = trim($dialogueMatch[1]);
  3810. $data['dialogue'] = trim($dialogueMatch[1]);
  3811. }
  3812. if (preg_match('/(?:画面类型|镜头类型|类型)[::]\s*([^\n]+)/u', $segmentContent, $frameMatch)) {
  3813. $segmentData['frame_type'] = trim($frameMatch[1]);
  3814. $data['frame_type'] = trim($frameMatch[1]);
  3815. }
  3816. // 场景字段
  3817. if (preg_match('/(?:场景|拍摄场景|背景场景|环境)[::]\s*([^\n]+)/u', $segmentContent, $sceneMatch)) {
  3818. $segmentData['scene'] = trim($sceneMatch[1]);
  3819. $data['scene'] = trim($sceneMatch[1]);
  3820. }
  3821. // 出镜角色字段
  3822. if (preg_match('/(?:出镜角色|角色出镜|登场角色|人物)[::]\s*([^\n]+)/u', $segmentContent, $charactersMatch)) {
  3823. $segmentData['characters'] = trim($charactersMatch[1]);
  3824. $data['characters'] = trim($charactersMatch[1]);
  3825. }
  3826. // 尾帧描述字段
  3827. if (preg_match('/(?:尾帧描述|尾帧|结束帧|最后一帧|结尾画面|结束画面)[::]\s*([^\n]+)/u', $segmentContent, $tailFrameMatch)) {
  3828. $segmentData['tail_frame'] = trim($tailFrameMatch[1]);
  3829. $data['tail_frame'] = trim($tailFrameMatch[1]);
  3830. }
  3831. // 情感字段
  3832. if (preg_match('/(?:情感|情绪|感情)[::]\s*([^\n]+)/u', $segmentContent, $emotionMatch)) {
  3833. $replaceEmptyArr[] = trim($emotionMatch[0]);
  3834. $segmentData['emotion'] = trim($emotionMatch[1]);
  3835. $data['emotion'] = trim($emotionMatch[1]);
  3836. }
  3837. // 性别字段
  3838. if (preg_match('/(?:性别)[::]\s*([^\n]+)/u', $segmentContent, $genderMatch)) {
  3839. $replaceEmptyArr[] = trim($genderMatch[0]);
  3840. $genderStr = trim($genderMatch[1]);
  3841. if (strpos($genderStr, '男') !== false || $genderStr === '1') {
  3842. $segmentData['gender'] = '1';
  3843. $data['gender'] = '1';
  3844. } elseif (strpos($genderStr, '女') !== false || $genderStr === '2') {
  3845. $segmentData['gender'] = '2';
  3846. $data['gender'] = '2';
  3847. } else {
  3848. $segmentData['gender'] = '0';
  3849. $data['gender'] = '0';
  3850. }
  3851. }
  3852. // 语速字段
  3853. if (preg_match('/(?:语速|说话速度)[::]\s*([-+]?[0-9]*\.?[0-9]+)/u', $segmentContent, $speedMatch)) {
  3854. $replaceEmptyArr[] = trim($speedMatch[0]);
  3855. $segmentData['speed_ratio'] = (float)trim($speedMatch[1]);
  3856. $data['speed_ratio'] = (float)trim($speedMatch[1]);
  3857. }
  3858. // 音量字段
  3859. if (preg_match('/(?:音量|声音大小)[::]\s*([-+]?[0-9]*\.?[0-9]+)/u', $segmentContent, $loudnessMatch)) {
  3860. $replaceEmptyArr[] = trim($loudnessMatch[0]);
  3861. $segmentData['loudness_ratio'] = (float)trim($loudnessMatch[1]);
  3862. $data['loudness_ratio'] = (float)trim($loudnessMatch[1]);
  3863. }
  3864. // 情感强度字段
  3865. if (preg_match('/(?:情感强度|情绪强度)[::]\s*([0-9]+)/u', $segmentContent, $scaleMatch)) {
  3866. $replaceEmptyArr[] = trim($scaleMatch[0]);
  3867. $segmentData['emotion_scale'] = (int)trim($scaleMatch[1]);
  3868. $data['emotion_scale'] = (int)trim($scaleMatch[1]);
  3869. }
  3870. // 音调字段
  3871. if (preg_match('/(?:音调|音高)[::]\s*([-+]?[0-9]+)/u', $segmentContent, $pitchMatch)) {
  3872. $replaceEmptyArr[] = trim($pitchMatch[0]);
  3873. $segmentData['pitch'] = (int)trim($pitchMatch[1]);
  3874. $data['pitch'] = (int)trim($pitchMatch[1]);
  3875. }
  3876. // 从 segment_content 中移除已提取的配音参数字段
  3877. if (!empty($replaceEmptyArr)) {
  3878. $data['segment_content'] = str_replace($replaceEmptyArr, '', $segmentContent);
  3879. }
  3880. // 如果有配音角色,查询音色信息并验证情感
  3881. $voice_actor = $segmentData['voice_actor'];
  3882. if (!empty($voice_actor) && $voice_actor !== '旁白') {
  3883. // 从当前分镜所属的剧集或动漫中查找角色音色信息
  3884. $anime_id = getProp($data, 'anime_id');
  3885. $episode_id = getProp($data, 'episode_id');
  3886. // 优先从剧集的角色列表中查找
  3887. $roles = [];
  3888. if ($episode_id) {
  3889. $episode = DB::table('mp_anime_episodes')->where('id', $episode_id)->first();
  3890. if ($episode && getProp($episode, 'roles')) {
  3891. $roles = json_decode(getProp($episode, 'roles'), true) ?: [];
  3892. }
  3893. }
  3894. // 如果剧集中没有,从动漫的角色列表中查找
  3895. if (empty($roles) && $anime_id) {
  3896. $anime = DB::table('mp_animes')->where('id', $anime_id)->first();
  3897. if ($anime && getProp($anime, 'roles')) {
  3898. $roles = json_decode(getProp($anime, 'roles'), true) ?: [];
  3899. }
  3900. }
  3901. // 查找匹配的角色音色信息
  3902. $timbre_info = null;
  3903. foreach ($roles as $role) {
  3904. if (getProp($role, 'role') === $voice_actor) {
  3905. $timbre_info = $role;
  3906. break;
  3907. }
  3908. }
  3909. // 如果找到音色信息,添加到数据中
  3910. if ($timbre_info) {
  3911. $voice_type = getProp($timbre_info, 'voice_type');
  3912. $voice_name = getProp($timbre_info, 'voice_name');
  3913. $voice_audio_url = getProp($timbre_info, 'voice_audio_url');
  3914. if ($voice_type) {
  3915. $data['voice_type'] = $voice_type;
  3916. $segmentData['voice_type'] = $voice_type;
  3917. }
  3918. if ($voice_name) {
  3919. $data['voice_name'] = $voice_name;
  3920. $segmentData['voice_name'] = $voice_name;
  3921. }
  3922. if ($voice_audio_url) {
  3923. $data['voice_audio_url'] = $voice_audio_url;
  3924. $segmentData['voice_audio_url'] = $voice_audio_url;
  3925. }
  3926. // 验证情感是否在音色支持的情感列表中
  3927. if ($voice_type) {
  3928. $timbre_emotion = DB::table('mp_timbres')->where('timbre_type', $voice_type)->value('emotion');
  3929. if ($timbre_emotion) {
  3930. $timbre_emotion = explode(',', $timbre_emotion);
  3931. } else {
  3932. $timbre_emotion = [];
  3933. }
  3934. $emotion = getProp($segmentData, 'emotion', '中性');
  3935. if (!in_array($emotion, $timbre_emotion)) {
  3936. $emotion = '中性';
  3937. }
  3938. $emotion_list = DB::table('mp_emotion_list')->where('is_enabled', 1)->pluck('emotion_name', 'emotion_code')->toArray();
  3939. $emotion_list = array_flip($emotion_list);
  3940. $emotion_type = isset($emotion_list[$emotion]) ? $emotion_list[$emotion] : 'neutral';
  3941. $data['emotion_type'] = $emotion_type;
  3942. $segmentData['emotion_type'] = $emotion_type;
  3943. }
  3944. }
  3945. }
  3946. return $segmentData;
  3947. }
  3948. public function createSegmentVideoTask($data) {
  3949. $segment_id = getProp($data, 'segment_id');
  3950. $tail_frame = getProp($data, 'tail_frame');
  3951. $first_frame_url = getProp($data, 'first_frame_url');
  3952. $tail_frame_url = getProp($data, 'tail_frame_url');
  3953. $generate_audio = getProp($data, 'generate_audio', 0);
  3954. if (!$segment_id) {
  3955. Utils::throwError('1002:分镜ID不能为空');
  3956. }
  3957. // 获取分镜信息
  3958. $segment = DB::table('mp_episode_segments')->where('segment_id', $segment_id)->first();
  3959. if (!$segment) {
  3960. Utils::throwError('20003:分镜不存在');
  3961. }
  3962. $segment = (array)$segment;
  3963. $episode_id = getProp($segment, 'episode_id');
  3964. $ratio = DB::table('mp_anime_episodes')->where('id', $episode_id)->value('ratio');
  3965. if (!$ratio) $ratio = '9:16';
  3966. // 获取分镜内容
  3967. $segmentContent = getProp($segment, 'segment_content', '');
  3968. // 检查 $segmentContent 中是否已有尾帧描述
  3969. $contentHasTailFrame = preg_match('/(?:尾帧描述|尾帧)[::]\s*([^\n]+)/u', $segmentContent, $contentTailFrameMatch);
  3970. // 确定最终使用的尾帧描述(优先级:用户输入 > segmentContent自带 > 分镜表字段)
  3971. $finalTailFrame = '';
  3972. if ($tail_frame) {
  3973. // 用户输入了尾帧描述,优先使用
  3974. $finalTailFrame = $tail_frame;
  3975. // 如果 segmentContent 中已有尾帧描述,需要替换
  3976. if ($contentHasTailFrame) {
  3977. $segmentContent = preg_replace('/(?:尾帧描述|尾帧)[::]\s*[^\n]+/u', "尾帧描述:$tail_frame", $segmentContent);
  3978. }
  3979. } elseif ($contentHasTailFrame) {
  3980. // segmentContent 中有尾帧描述,使用它
  3981. $finalTailFrame = trim($contentTailFrameMatch[1]);
  3982. } else {
  3983. // 两者都没有,使用分镜表中的尾帧描述
  3984. $finalTailFrame = getProp($segment, 'tail_frame', '');
  3985. }
  3986. // 判断 $segmentContent 是否有台词内容,如果有则确保使用中文左右双引号
  3987. $hasDialogue = false;
  3988. if (preg_match('/(?:台词内容|台词|对白|对话)[::]\s*([^\n]+)/u', $segmentContent, $dialogueMatch)) {
  3989. $dialogue = trim($dialogueMatch[1]);
  3990. // 如果台词不为空且不是"无"
  3991. if (!empty($dialogue) && $dialogue !== '无') {
  3992. // 过滤掉所有符号(引号、标点、空格等),只保留文字内容来判断是否有实际台词
  3993. $dialogueFiltered = preg_replace('/[""\'\',。!?、;:…—\-\s\p{P}\p{S}]/u', '', $dialogue);
  3994. if (!empty($dialogueFiltered) && $dialogueFiltered !== '无') {
  3995. $hasDialogue = true;
  3996. }
  3997. $dialogue = preg_replace('/^["”]/u', '“', $dialogue); // 替换句首英文双引号或中文右双引号
  3998. $dialogue = preg_replace('/["“]$/u', '”', $dialogue); // 替换句尾英文双引号或中文左双引号
  3999. // 句首或句尾没有中文双引号,则分别添加中文左右双引号
  4000. if (!preg_match('/^[“]/', $dialogue)) {
  4001. $dialogue = '“' . $dialogue;
  4002. }
  4003. if (!preg_match('/[”]$/', $dialogue)) {
  4004. $dialogue .= '”';
  4005. }
  4006. // 将修改后的台词替换回 $segmentContent
  4007. $originalDialogue = $dialogueMatch[1];
  4008. $segmentContent = str_replace($originalDialogue, $dialogue, $segmentContent);
  4009. }
  4010. }
  4011. // 构建完整的提示词
  4012. $fullPrompt = $segmentContent;
  4013. if ($finalTailFrame && !$contentHasTailFrame) {
  4014. // 只有当 segmentContent 中没有尾帧描述时才追加
  4015. $fullPrompt .= "\n尾帧描述:$finalTailFrame";
  4016. }
  4017. // 去除多余的换行符(将连续多个换行符替换为单个换行符)
  4018. $fullPrompt = preg_replace('/\n{2,}/', "\n", $fullPrompt);
  4019. $fullPrompt = trim($fullPrompt);
  4020. // 当前是否启用音效同出(没台词强制关闭音效同出,节省资源收费)
  4021. $current_generate_audio = $hasDialogue ? $generate_audio : 0;
  4022. // 智能选择视频时长
  4023. // $videoDuration = $this->calculateOptimalVideoDuration($segmentContent, $tail_frame);
  4024. $videoDuration = -1;
  4025. // 处理视频模型
  4026. $model = getProp($data, 'model');
  4027. if (!$model) {
  4028. // 用户没有输入,从episode表获取
  4029. $episode = DB::table('mp_anime_episodes')->where('id', getProp($segment, 'episode_id'))->first();
  4030. $model = getProp($episode, 'video_model');
  4031. if (!$model) {
  4032. // episode表也没有,使用默认值
  4033. $model = 'doubao-seedance-1-5-pro-251215';
  4034. }
  4035. }
  4036. // 验证模型是否在可用模型表中
  4037. if (!DB::table('mp_video_models')->where('model', $model)->where('is_enabled', 1)->exists()) {
  4038. $model = 'doubao-seedance-1-5-pro-251215';
  4039. }
  4040. // 保存到episode表
  4041. $episode_id = getProp($segment, 'episode_id');
  4042. DB::table('mp_anime_episodes')->where('id', $episode_id)->update([
  4043. 'video_model' => $model,
  4044. 'updated_at' => date('Y-m-d H:i:s')
  4045. ]);
  4046. // 构建视频生成参数
  4047. $videoParams = [
  4048. 'model' => $model,
  4049. 'alias_segment_id' => $segment_id,
  4050. 'prompt' => trim($fullPrompt),
  4051. 'video_duration' => $videoDuration,
  4052. 'video_resolution' => '720P',
  4053. 'seed' => -1,
  4054. 'ratio' => $ratio,
  4055. 'generate_audio' => (int)$current_generate_audio === 0 ? false : true,
  4056. 'draft' => false,
  4057. 'watermark' => false,
  4058. 'camera_fixed' => false,
  4059. // 'callback_url' => 'http://mpaudio.yqsd.cn/api/video/seedanceCallback'
  4060. ];
  4061. // 如果分镜有图片,作为首帧
  4062. $hasImage = !empty(getProp($segment, 'img_url')) || $first_frame_url;
  4063. $hasVideo = !empty(getProp($segment, 'video_url'));
  4064. if ($hasImage) {
  4065. if ($first_frame_url) {
  4066. $videoParams['first_frame_url'] = $first_frame_url;
  4067. }else {
  4068. $videoParams['first_frame_url'] = getProp($segment, 'img_url');
  4069. }
  4070. if ($tail_frame_url) $videoParams['tail_frame_url'] = $tail_frame_url;
  4071. }
  4072. // 构建content数组
  4073. $videoParams['content'] = [
  4074. [
  4075. 'type' => 'text',
  4076. 'text' => $videoParams['prompt'],
  4077. ]
  4078. ];
  4079. // 如果有首帧图片,添加到content中
  4080. if ($hasImage) {
  4081. 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'])) {
  4082. $videoParams['content'][] = [
  4083. 'type' => 'image_url',
  4084. 'image_url' => [
  4085. 'url' => $videoParams['first_frame_url'],
  4086. ],
  4087. 'role' => 'reference_image',
  4088. ];
  4089. if (isset($videoParams['tail_frame_url'])) {
  4090. $videoParams['content'][] = [
  4091. 'type' => 'image_url',
  4092. 'image_url' => [
  4093. 'url' => $videoParams['tail_frame_url'],
  4094. ],
  4095. 'role' => 'reference_image',
  4096. ];
  4097. }
  4098. }else {
  4099. $videoParams['content'][] = [
  4100. 'type' => 'image_url',
  4101. 'image_url' => [
  4102. 'url' => $videoParams['first_frame_url'],
  4103. ],
  4104. 'role' => 'first_frame',
  4105. ];
  4106. if (isset($videoParams['tail_frame_url'])) {
  4107. $videoParams['content'][] = [
  4108. 'type' => 'image_url',
  4109. 'image_url' => [
  4110. 'url' => $videoParams['tail_frame_url'],
  4111. ],
  4112. 'role' => 'last_frame',
  4113. ];
  4114. }
  4115. }
  4116. }
  4117. // 获取配音音频URL
  4118. $audioUrl = getProp($segment, 'audio_url');
  4119. $audioDuration = getProp($segment, 'audio_duration');
  4120. // 音频传入的前提:必须有至少一张图片或一个视频
  4121. $canUseAudio = ($hasImage || $hasVideo) && !empty($audioUrl);
  4122. // 余额预检:按预估时长计算所需积分,不足直接报错
  4123. $chargeDuration = (int)ceil((float)$audioDuration);
  4124. if ($chargeDuration <= 0) {
  4125. $chargeDuration = 5; // 无音频时长时按默认5秒预估
  4126. }
  4127. $this->pointsService->checkUserPointsEnough(
  4128. $this->pointsService->getVideoChargePoints([
  4129. 'model' => $model,
  4130. 'video_resolution' => strtolower($videoParams['video_resolution'] ?? '720P'),
  4131. 'video_duration' => $chargeDuration,
  4132. 'ratio' => $ratio,
  4133. 'generate_audio' => $current_generate_audio,
  4134. ])
  4135. );
  4136. // dd($videoParams);
  4137. // 根据模型选择不同的视频生成方法
  4138. if (strpos($model, 'jimeng') !== false) {
  4139. // 即梦模型参数调整
  4140. $videoParams['video_duration'] = $audioDuration > 5 ? 10 : 5; // 即梦只支持5s或10s
  4141. unset($videoParams['content']); // 即梦不使用content格式
  4142. $task = $this->aiVideoGenerationService->createJimengTask($videoParams);
  4143. } elseif (strpos($model, 'kling') !== false) {
  4144. // Keling模型参数调整
  4145. $videoParams['video_duration'] = max(3, min(15, ceil($audioDuration))); // Keling支持3-15秒
  4146. $videoParams['aspect_ratio'] = $videoParams['ratio']; // Keling使用aspect_ratio
  4147. unset($videoParams['ratio']);
  4148. unset($videoParams['content']); // Keling不使用content格式
  4149. $task = $this->aiVideoGenerationService->createKelingOmniTask($videoParams);
  4150. } elseif (strpos($model, 'zhizhen') !== false) {
  4151. // 智帧20等新模型使用统一API
  4152. // 构建统一API参数
  4153. $unifiedParams = [
  4154. 'model_code' => $model,
  4155. 'alias_segment_id' => $segment_id,
  4156. 'prompt' => trim($fullPrompt),
  4157. 'video_duration' => $audioDuration > 0 ? max(5, min(15, ceil($audioDuration))) : 5,
  4158. 'video_resolution' => strtolower($videoParams['video_resolution']),
  4159. 'video_ratio' => $ratio,
  4160. 'seed' => -1,
  4161. ];
  4162. // 构建parameters参数
  4163. $parameters = [
  4164. 'seconds' => $unifiedParams['video_duration'],
  4165. 'resolution' => $unifiedParams['video_resolution'],
  4166. 'ratio' => $ratio,
  4167. // 'video_mode' => 'multi_image',
  4168. // 'mode' => 'multi_image',
  4169. 'generate_audio' => (int)$current_generate_audio === 1 ? true : false,
  4170. ];
  4171. $hasImage = false;
  4172. // 处理首帧和尾帧(智帧20模型必须要有首帧图片)
  4173. if ($hasImage) {
  4174. $parameters['first_frame_url'] = $videoParams['first_frame_url'];
  4175. if (isset($videoParams['tail_frame_url'])) {
  4176. $parameters['last_frame_url'] = $videoParams['tail_frame_url'];
  4177. }
  4178. // 只有在有图片的情况下才能添加参考音频
  4179. if ($audioUrl) {
  4180. // $parameters['reference_audios'] = [$audioUrl];
  4181. }
  4182. } else {
  4183. // 没有图片时,记录错误日志
  4184. logDB('anime', 'error', '智帧20模型缺少首帧图片', [
  4185. 'segment_id' => $segment_id,
  4186. 'model' => $model
  4187. ]);
  4188. }
  4189. $unifiedParams['parameters'] = $parameters;
  4190. // 调用统一API创建任务
  4191. $task = $this->aiVideoGenerationService->createUnifiedApiTask($unifiedParams);
  4192. } else {
  4193. // Seedance模型(默认)
  4194. // 快快AI Seedance 2.0/2.5:配音音频需先上传为素材,走聚合网关 /v1/video/generations
  4195. if ($this->isKuaikuaiSeedanceModel($model)) {
  4196. $videoParams['gateway_base_url'] = env('KUAIKUAI_AI_BASE_URL', 'https://ai-api.kkidc.com');
  4197. if ($canUseAudio && $audioUrl) {
  4198. // 上传配音音频为素材(上传失败时同步清理提示词中的<音频N>标记,不阻断任务)
  4199. $reference_audio_assets = $this->aiVideoGenerationService->processReferenceAudiosToKuaikuaiAssets([$audioUrl], $fullPrompt);
  4200. $videoParams['reference_audio_assets'] = $reference_audio_assets;
  4201. // 优化提示词,增加音频相关描述
  4202. $audioPrompt = "全程使用音频1作为视频配音。" . $fullPrompt;
  4203. $videoParams['prompt'] = $audioPrompt;
  4204. } elseif ($audioDuration) { // 有音频时长则需将视频时长设置为比音频时长更长的整数
  4205. $videoParams['video_duration'] = max(4, min(12, ceil($audioDuration)));
  4206. }
  4207. $task = $this->aiVideoGenerationService->createKuaikuaiVideoTask($videoParams);
  4208. } 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'])) {
  4209. // 检查是否为 Seedance 2.0 模型,如果是则需要处理配音音频
  4210. // 添加配音音频到content中
  4211. $videoParams['content'][] = [
  4212. 'type' => 'audio_url',
  4213. 'audio_url' => [
  4214. 'url' => $audioUrl,
  4215. ],
  4216. 'role' => 'reference_audio',
  4217. ];
  4218. // 优化提示词,增加音频相关描述
  4219. $audioPrompt = "全程使用音频1作为视频配音。" . $fullPrompt;
  4220. $videoParams['prompt'] = $audioPrompt;
  4221. $videoParams['content'][0]['text'] = $audioPrompt;
  4222. } else {
  4223. if ($audioDuration) { // 有音频时长则需将视频时长设置为比音频时长更长的整数
  4224. $videoParams['video_duration'] = max(4, min(12, ceil($audioDuration))); // seedance支持2-12s
  4225. }
  4226. $task = $this->aiVideoGenerationService->createSeedanceTask($videoParams);
  4227. }
  4228. }
  4229. // 更新分镜表的视频任务信息
  4230. DB::table('mp_episode_segments')->where('segment_id', $segment_id)->update([
  4231. 'video_task_id' => $task->id,
  4232. 'video_task_status' => '生成中',
  4233. 'generate_audio' => $generate_audio,
  4234. 'updated_at' => date('Y-m-d H:i:s')
  4235. ]);
  4236. return [
  4237. 'task_id' => $task->id,
  4238. 'status' => $task->status,
  4239. 'segment_id' => $segment_id,
  4240. 'video_duration' => $videoDuration
  4241. ];
  4242. }
  4243. /**
  4244. * 是否为快快AI Seedance 2.0/2.5 系列模型
  4245. * 快快AI平台模型ID:seed-2-fast / seed-2-mini / seed-2.5 / seed-2
  4246. *
  4247. * @param string $model
  4248. * @return bool
  4249. */
  4250. public function isKuaikuaiSeedanceModel(string $model): bool
  4251. {
  4252. return in_array($model, ['seed-2-fast', 'seed-2-mini', 'seed-2.5', 'seed-2'], true);
  4253. }
  4254. /**
  4255. * 是否为百度AI网关Seedance 2.0系列模型(系统内使用 baidu- 前缀名,请求网关时映射为 doubao- 原名)
  4256. *
  4257. * @param string $model
  4258. * @return bool
  4259. */
  4260. public function isBaiduSeedanceModel(string $model): bool
  4261. {
  4262. return in_array($model, [
  4263. 'baidu-doubao-seedance-2-0-260128',
  4264. 'baidu-doubao-seedance-2-0-fast-260128',
  4265. 'baidu-doubao-seedance-2-0-mini-260615',
  4266. 'baidu-doubao-seedance-2-5-260628',
  4267. ], true);
  4268. }
  4269. /**
  4270. * 是否为海外百度Seedance(dreamina真人素材空间)模型
  4271. * 系统内使用 baidu-dreamina- 前缀名,请求网关时映射为 dreamina-* 原名
  4272. *
  4273. * @param string $model
  4274. * @return bool
  4275. */
  4276. public function isOverseasBaiduSeedanceModel(string $model): bool
  4277. {
  4278. return in_array($model, [
  4279. 'baidu-dreamina-seedance-2-0-260128',
  4280. 'baidu-dreamina-seedance-2-0-fast-260128',
  4281. 'baidu-dreamina-seedance-2-0-mini-260615',
  4282. 'baidu-dreamina-seedance-2-5-260628',
  4283. ], true);
  4284. }
  4285. /**
  4286. * 是否为 Seedance 2.0 系列模型(百度 doubao-seedance-2.0 / baidu-doubao-* / baidu-dreamina-* / 快快AI seed-2 系列)
  4287. * 供单条与批量生成入口统一判断,避免各入口各自维护模型白名单
  4288. *
  4289. * @param string $model
  4290. * @return bool
  4291. */
  4292. public function isSeedance20SeriesModel(string $model): bool
  4293. {
  4294. return strpos($model, 'doubao-seedance-2.0') !== false
  4295. || $this->isKuaikuaiSeedanceModel($model)
  4296. || $this->isBaiduSeedanceModel($model)
  4297. || $this->isOverseasBaiduSeedanceModel($model);
  4298. }
  4299. public function createActVideoTask($data) {
  4300. $act_id = getProp($data, 'act_id');
  4301. $first_frame_url = getProp($data, 'first_frame_url');
  4302. $tail_frame_url = getProp($data, 'tail_frame_url');
  4303. $generate_audio = getProp($data, 'generate_audio', 1);
  4304. $video_duration = getProp($data, 'video_duration');
  4305. $video_resolution = getProp($data, 'video_resolution');
  4306. $ratio = getProp($data, 'ratio');
  4307. $products = getProp($data, 'products', []);
  4308. $reference_images = array_unique(getProp($data, 'reference_images', []));
  4309. if (!is_array($reference_images) || !is_array($products)) {
  4310. Utils::throwError('20003:传入的参考图或资产格式不正确');
  4311. }
  4312. if (!$act_id) {
  4313. Utils::throwError('1002:片段ID不能为空');
  4314. }
  4315. // 获取片段信息
  4316. $act = DB::table('mp_episode_segments')->where('id', $act_id)->first();
  4317. if (!$act) {
  4318. Utils::throwError('20003:片段不存在');
  4319. }
  4320. $act = (array)$act;
  4321. $anime_id = getProp($act, 'anime_id');
  4322. $episode_id = getProp($act, 'episode_id');
  4323. $anime = DB::table('mp_animes')->where('id', $anime_id)->first();
  4324. $ace_mode = getProp($anime, 'ace_mode');
  4325. $art_style_type = getProp($anime, 'art_style_type');
  4326. $art_style = getProp($anime, 'art_style');
  4327. $episode = DB::table('mp_anime_episodes')->where('id', $episode_id)->first();
  4328. if (!$ratio) $ratio = getProp($episode, 'ratio', '9:16');
  4329. if (!$video_resolution) $video_resolution = getProp($episode, 'video_resolution', '720p');
  4330. // 将资产中新出现的资产放到extra_products中
  4331. // 满足以下要求: 遍历传入的$products,将product_name与$episode中的roles、scenes和props做比对,如果不在其中,则与$episode中的extra_products做比对,如果有同名的则覆盖,没有则新增后存入$episode中的extra_products字段中
  4332. if (!empty($products) && $episode) {
  4333. // 获取剧集中的角色、场景和道具列表
  4334. $roles = json_decode(getProp($episode, 'roles', '[]'), true) ?: [];
  4335. $scenes = json_decode(getProp($episode, 'scenes', '[]'), true) ?: [];
  4336. $props = json_decode(getProp($episode, 'props', '[]'), true) ?: [];
  4337. $extra_products = json_decode(getProp($episode, 'extra_products', '[]'), true) ?: [];
  4338. // 构建角色名称列表
  4339. $role_names = array_column($roles, 'role');
  4340. // 构建场景名称列表
  4341. $scene_names = array_column($scenes, 'scene');
  4342. // 构建道具名称列表
  4343. $prop_names = array_column($props, 'prop');
  4344. // 遍历传入的products
  4345. foreach ($products as $product) {
  4346. $product_name = getProp($product, 'product_name');
  4347. // 如果product_name不在roles、scenes和props中
  4348. if (!in_array($product_name, $role_names) && !in_array($product_name, $scene_names) && !in_array($product_name, $prop_names)) {
  4349. // 查找是否在extra_products中存在同名的
  4350. $found = false;
  4351. foreach ($extra_products as $key => $extra_product) {
  4352. if (getProp($extra_product, 'product_name') === $product_name) {
  4353. // 有同名的则覆盖
  4354. $extra_products[$key] = $product;
  4355. $found = true;
  4356. break;
  4357. }
  4358. }
  4359. // 没有则新增
  4360. if (!$found) {
  4361. $extra_products[] = $product;
  4362. }
  4363. }
  4364. }
  4365. if ($extra_products) {
  4366. // 保存到数据库
  4367. DB::table('mp_anime_episodes')
  4368. ->where('id', $episode_id)
  4369. ->update([
  4370. 'extra_products' => json_encode($extra_products, 256),
  4371. 'updated_at' => date('Y-m-d H:i:s')
  4372. ]);
  4373. }
  4374. }
  4375. // 获取分镜内容
  4376. $actContent = getProp($act, 'act_show_content', '');
  4377. // 音效同出(默认使用)
  4378. $current_generate_audio = $generate_audio ? 1 : 0;
  4379. // 构建完整的提示词
  4380. $processResult = $this->processActContentWithProducts($actContent, $products);
  4381. $fullPrompt = $processResult['content'];
  4382. // if ($art_style_type == '3D真人风格') $fullPrompt = "美术风格: $art_style\n\n".$fullPrompt;
  4383. $reference_images = array_merge($processResult['reference_images'], $reference_images);
  4384. $videoDuration = $video_duration ? $video_duration : getProp($act, 'act_duration');
  4385. // 处理视频模型
  4386. $model = getProp($data, 'model');
  4387. if (!$model) {
  4388. $model = getProp($episode, 'video_model');
  4389. if (!$model) {
  4390. // episode表也没有,使用默认值
  4391. $model = 'seed-2';
  4392. }
  4393. }
  4394. // 验证模型是否在可用模型表中(全能模式片段转视频仅允许 ace_mode=1 的模型)
  4395. $valid_models = DB::table('mp_video_models')->where('ace_mode', 1)->select('model')->pluck('model')->toArray();
  4396. if (!in_array($model, $valid_models)) {
  4397. $model = 'seed-2';
  4398. }
  4399. // 保存到episode表(仅在专用方法中更新模型)
  4400. // DB::table('mp_anime_episodes')->where('id', $episode_id)->update([
  4401. // 'video_model' => $model,
  4402. // 'updated_at' => date('Y-m-d H:i:s')
  4403. // ]);
  4404. // 余额预检:按预估时长计算所需积分,不足直接报错
  4405. $chargeDuration = (int)$videoDuration;
  4406. if ($chargeDuration <= 0) {
  4407. $chargeDuration = 5; // 无时长时按默认5秒预估
  4408. }
  4409. $this->pointsService->checkUserPointsEnough(
  4410. $this->pointsService->getVideoChargePoints([
  4411. 'model' => $model,
  4412. 'video_resolution' => strtolower($video_resolution ?? '720p'),
  4413. 'video_duration' => $chargeDuration,
  4414. 'ratio' => $ratio,
  4415. 'generate_audio' => $current_generate_audio,
  4416. ])
  4417. );
  4418. // 构建视频生成参数
  4419. $videoParams = [
  4420. 'model' => $model,
  4421. 'alias_act_id' => $act_id,
  4422. 'prompt' => trim($fullPrompt),
  4423. 'video_duration' => $videoDuration,
  4424. 'video_resolution' => $video_resolution,
  4425. 'seed' => -1,
  4426. 'ratio' => $ratio,
  4427. 'generate_audio' => (int)$current_generate_audio === 0 ? false : true,
  4428. 'draft' => false,
  4429. 'watermark' => false,
  4430. 'camera_fixed' => false,
  4431. // 'callback_url' => 'http://mpaudio.yqsd.cn/api/video/seedanceCallback'
  4432. ];
  4433. // 如果分镜有图片,作为首帧
  4434. $hasImage = !empty(getProp($act, 'img_url')) || $first_frame_url;
  4435. $hasVideo = !empty(getProp($act, 'video_url'));
  4436. if ($hasImage) {
  4437. if ($first_frame_url) {
  4438. $videoParams['first_frame_url'] = $first_frame_url;
  4439. }else {
  4440. $videoParams['first_frame_url'] = getProp($act, 'img_url');
  4441. }
  4442. if ($tail_frame_url) $videoParams['tail_frame_url'] = $tail_frame_url;
  4443. }
  4444. // 构建content数组
  4445. $videoParams['content'] = [
  4446. [
  4447. 'type' => 'text',
  4448. 'text' => $videoParams['prompt'],
  4449. ]
  4450. ];
  4451. // 如果有首帧图片,添加到content中
  4452. if ($hasImage) {
  4453. 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'])) {
  4454. $videoParams['content'][] = [
  4455. 'type' => 'image_url',
  4456. 'image_url' => [
  4457. 'url' => $videoParams['first_frame_url'],
  4458. ],
  4459. 'role' => 'reference_image',
  4460. ];
  4461. if (isset($videoParams['tail_frame_url'])) {
  4462. $videoParams['content'][] = [
  4463. 'type' => 'image_url',
  4464. 'image_url' => [
  4465. 'url' => $videoParams['tail_frame_url'],
  4466. ],
  4467. 'role' => 'reference_image',
  4468. ];
  4469. }
  4470. }else {
  4471. $videoParams['content'][] = [
  4472. 'type' => 'image_url',
  4473. 'image_url' => [
  4474. 'url' => $videoParams['first_frame_url'],
  4475. ],
  4476. 'role' => 'first_frame',
  4477. ];
  4478. if (isset($videoParams['tail_frame_url'])) {
  4479. $videoParams['content'][] = [
  4480. 'type' => 'image_url',
  4481. 'image_url' => [
  4482. 'url' => $videoParams['tail_frame_url'],
  4483. ],
  4484. 'role' => 'last_frame',
  4485. ];
  4486. }
  4487. }
  4488. }
  4489. // dd($videoParams);
  4490. // 根据模型选择不同的视频生成方法
  4491. try {
  4492. if (strpos($model, 'jimeng') !== false) {
  4493. // 即梦模型参数调整
  4494. unset($videoParams['content']); // 即梦不使用content格式
  4495. $task = $this->aiVideoGenerationService->createJimengTask($videoParams);
  4496. } elseif (strpos($model, 'kling') !== false) {
  4497. // Keling模型参数调整
  4498. $videoParams['aspect_ratio'] = $videoParams['ratio']; // Keling使用aspect_ratio
  4499. unset($videoParams['ratio']);
  4500. unset($videoParams['content']); // Keling不使用content格式
  4501. $task = $this->aiVideoGenerationService->createKelingOmniTask($videoParams);
  4502. } elseif (strpos($model, 'zhizhen') !== false) {
  4503. // 智帧20等新模型使用统一API
  4504. // 构建统一API参数
  4505. $unifiedParams = [
  4506. 'model_code' => $model,
  4507. 'alias_act_id' => $act_id,
  4508. 'prompt' => trim($fullPrompt),
  4509. 'video_duration' => $videoDuration,
  4510. 'video_resolution' => strtolower($videoParams['video_resolution']),
  4511. 'video_ratio' => $ratio,
  4512. 'seed' => -1,
  4513. ];
  4514. // 构建parameters参数
  4515. $parameters = [
  4516. 'seconds' => $unifiedParams['video_duration'],
  4517. 'resolution' => $unifiedParams['video_resolution'],
  4518. 'ratio' => $ratio,
  4519. // 'video_mode' => 'multi_image',
  4520. // 'mode' => 'multi_image',
  4521. 'generate_audio' => (int)$current_generate_audio === 1 ? true : false,
  4522. ];
  4523. $hasImage = false;
  4524. // 处理首帧和尾帧(智帧20模型必须要有首帧图片)
  4525. if ($hasImage) {
  4526. $parameters['first_frame_url'] = $videoParams['first_frame_url'];
  4527. if (isset($videoParams['tail_frame_url'])) {
  4528. $parameters['last_frame_url'] = $videoParams['tail_frame_url'];
  4529. }
  4530. } else {
  4531. // 没有图片时,记录错误日志
  4532. logDB('anime', 'error', '智帧20模型缺少首帧图片', [
  4533. 'act_id' => $act_id,
  4534. 'model' => $model
  4535. ]);
  4536. }
  4537. if ($reference_images) {
  4538. // 限制只传入9张参考图
  4539. $reference_images = array_slice($reference_images, 0, 9);
  4540. // 在处理之前先保存原始reference_images到任务参数中
  4541. $unifiedParams['ref_image_url'] = json_encode($reference_images, 256);
  4542. $reference_images = $this->aiImageGenerationService->processReferenceImagesToAssets($reference_images, $unifiedParams['prompt']);
  4543. $parameters['reference_images'] = $reference_images;
  4544. $parameters['video_mode'] = 'multi_image';
  4545. $parameters['mode'] = 'multi_image';
  4546. }
  4547. $unifiedParams['parameters'] = $parameters;
  4548. // 调用统一API创建任务
  4549. $task = $this->aiVideoGenerationService->createUnifiedApiTask($unifiedParams);
  4550. } elseif ($this->isSeedance20SeriesModel($model)) {
  4551. // 豆包Seedance 2.0(百度AI网关)/ 快快AI Seedance 2.0/2.5:图片需要先上传为素材
  4552. $isKuaikuai = $this->isKuaikuaiSeedanceModel($model);
  4553. $isDreamina = $this->isOverseasBaiduSeedanceModel($model);
  4554. // 保存原始参考图用于任务记录
  4555. $videoParams['reference_images'] = $reference_images;
  4556. if ($reference_images) {
  4557. // 限制只传入9张参考图
  4558. $reference_images = array_slice($reference_images, 0, 9);
  4559. // 维护ref_image_url字段(参考图URL,JSON数组,与智帧分支保持一致)
  4560. $videoParams['ref_image_url'] = json_encode($reference_images, 256);
  4561. // 参考图上传为素材(国内百度/海外百度dreamina/快快AI),上传失败时同步清理提示词中的<图片N>标记
  4562. $reference_image_assets = $isKuaikuai
  4563. ? $this->aiVideoGenerationService->processReferenceImagesToKuaikuaiAssets($reference_images, $fullPrompt)
  4564. : ($isDreamina
  4565. ? $this->aiVideoGenerationService->processReferenceImagesToBaiduDreaminaAssets($reference_images, $fullPrompt)
  4566. : $this->aiVideoGenerationService->processReferenceImagesToSeedance20Assets($reference_images, $fullPrompt));
  4567. // 素材上传失败后提示词可能被清理,同步更新视频参数中的提示词
  4568. $videoParams['prompt'] = trim($fullPrompt);
  4569. $videoParams['content'][0]['text'] = trim($fullPrompt);
  4570. $videoParams['reference_image_assets'] = $reference_image_assets;
  4571. }
  4572. // 快快AI走聚合网关 /v1/video/generations(火山豆包格式)
  4573. if ($isKuaikuai) {
  4574. $videoParams['gateway_base_url'] = env('KUAIKUAI_AI_BASE_URL', 'https://ai-api.kkidc.com');
  4575. $task = $this->aiVideoGenerationService->createKuaikuaiVideoTask($videoParams);
  4576. } else {
  4577. $task = $this->aiVideoGenerationService->createSeedance20Task($videoParams);
  4578. }
  4579. } else {
  4580. $task = $this->aiVideoGenerationService->createSeedanceTask($videoParams);
  4581. }
  4582. } catch (ApiException $e) {
  4583. // 上游调用抛出的网关异常统一做友好化处理;本地业务错误(非1001)保持原提示不变
  4584. if ($e->getCode() === 1001) {
  4585. Utils::throwError('1001:' . mapErrorMessage($e->getMessage()));
  4586. }
  4587. throw $e;
  4588. } catch (\Exception $e) {
  4589. // 其他未包装的异常,同样只对报错信息做格式化,便于前端展示友好提示
  4590. Utils::throwError('20003:' . mapErrorMessage($e->getMessage()));
  4591. }
  4592. // 更新分镜表的视频任务信息
  4593. DB::table('mp_episode_segments')->where('id', $act_id)->update([
  4594. 'video_task_id' => $task->id,
  4595. 'video_task_status' => '生成中',
  4596. 'generate_audio' => $generate_audio,
  4597. 'updated_at' => date('Y-m-d H:i:s')
  4598. ]);
  4599. // 如果是全能模式,并且是第一集的第一个片段,将act_id存入Redis
  4600. $episode_number = getProp($act, 'episode_number');
  4601. $act_number = getProp($act, 'act_number');
  4602. if ((int)$ace_mode === 1 && (int)$episode_number === 1 && (int)$act_number === 1) {
  4603. Redis::sadd('anime_act_first_frame_urls', $act_id);
  4604. }
  4605. $result = [
  4606. 'task_id' => $task->id,
  4607. 'status' => $task->status,
  4608. 'act_id' => $act_id,
  4609. 'video_duration' => $videoDuration
  4610. ];
  4611. // 仅当任务提交阶段就已失败时,附带格式化后的错误信息;正常返回结构不受影响
  4612. if ($task->status === 'failed' && !empty($task->error_message)) {
  4613. $result['error_message'] = mapErrorMessage($task->error_message);
  4614. }
  4615. return $result;
  4616. }
  4617. /**
  4618. * 文生视频通用方法
  4619. * 支持传入视频参数、提示词、参考图等信息,不支持products入参
  4620. * 用户提示词不做任何处理,直接组装参数后根据模型调用
  4621. *
  4622. * @param array $data 请求参数
  4623. * @return array
  4624. */
  4625. public function generateVideo($data) {
  4626. $prompt = getProp($data, 'prompt');
  4627. if (empty($prompt)) {
  4628. Utils::throwError('20003:提示词不能为空');
  4629. }
  4630. $model = getProp($data, 'model');
  4631. if (!$model) {
  4632. $model = 'seed-2';
  4633. }
  4634. // 验证模型是否在可用模型表中
  4635. if (!DB::table('mp_video_models')->where('model', $model)->where('is_enabled', 1)->exists()) {
  4636. Utils::throwError('20003:该模型已不可用,请更换!');
  4637. }
  4638. $video_duration = getProp($data, 'video_duration', 5);
  4639. // 默认超分720p档(按480p生成后本地超分到720p);480p为原始档需前端显式指定
  4640. $video_resolution = getProp($data, 'video_resolution', 'sr_720p');
  4641. $ratio = getProp($data, 'ratio', '9:16');
  4642. $generate_audio = getProp($data, 'generate_audio', 1);
  4643. $seed = getProp($data, 'seed', -1);
  4644. $first_frame_url = getProp($data, 'first_frame_url');
  4645. $tail_frame_url = getProp($data, 'tail_frame_url');
  4646. // 参考图(支持数组或JSON字符串,最多9张)
  4647. $reference_images = getProp($data, 'reference_images', []);
  4648. if (is_string($reference_images)) {
  4649. $reference_images = json_decode($reference_images, true) ?: [];
  4650. }
  4651. if (!is_array($reference_images)) {
  4652. Utils::throwError('20003:参考图格式不正确');
  4653. }
  4654. $reference_images = array_values(array_unique(array_filter($reference_images)));
  4655. $reference_images = array_slice($reference_images, 0, 9);
  4656. // 参考视频(支持数组或JSON字符串,最多3个)
  4657. $reference_videos = getProp($data, 'reference_videos', []);
  4658. if (is_string($reference_videos)) {
  4659. $reference_videos = json_decode($reference_videos, true) ?: [];
  4660. }
  4661. if (!is_array($reference_videos)) {
  4662. Utils::throwError('20003:参考视频格式不正确');
  4663. }
  4664. $reference_videos = array_values(array_unique(array_filter($reference_videos)));
  4665. if (count($reference_videos) > 3) {
  4666. Utils::throwError('20003:参考视频最多选择3个');
  4667. }
  4668. $reference_videos = array_slice($reference_videos, 0, 3);
  4669. // 参考音频(支持数组或JSON字符串,最多3个)
  4670. $reference_audios = getProp($data, 'reference_audios', []);
  4671. if (is_string($reference_audios)) {
  4672. $reference_audios = json_decode($reference_audios, true) ?: [];
  4673. }
  4674. if (!is_array($reference_audios)) {
  4675. Utils::throwError('20003:参考音频格式不正确');
  4676. }
  4677. $reference_audios = array_values(array_unique(array_filter($reference_audios)));
  4678. if (count($reference_audios) > 3) {
  4679. Utils::throwError('20003:参考音频最多选择3个');
  4680. }
  4681. $reference_audios = array_slice($reference_audios, 0, 3);
  4682. // 余额预检:按预估时长计算所需积分,不足直接报错
  4683. $chargeDuration = (int)ceil((float)$video_duration);
  4684. if ($chargeDuration <= 0) {
  4685. $chargeDuration = 5; // 无时长时按默认5秒预估
  4686. }
  4687. $this->pointsService->checkUserPointsEnough(
  4688. $this->pointsService->getVideoChargePoints([
  4689. 'model' => $model,
  4690. 'video_resolution' => strtolower($video_resolution ?? '720p'),
  4691. 'video_duration' => $chargeDuration,
  4692. 'ratio' => $ratio,
  4693. 'generate_audio' => (int)$generate_audio,
  4694. ])
  4695. );
  4696. // 构建视频生成参数(用户参数直接透传,提示词不做处理)
  4697. $videoParams = [
  4698. 'model' => $model,
  4699. 'prompt' => $prompt,
  4700. 'video_duration' => $video_duration,
  4701. 'video_resolution' => $video_resolution,
  4702. 'seed' => $seed,
  4703. 'ratio' => $ratio,
  4704. 'generate_audio' => (int)$generate_audio === 1 ? true : false,
  4705. 'draft' => getProp($data, 'draft', false),
  4706. 'watermark' => getProp($data, 'watermark', false),
  4707. 'camera_fixed' => getProp($data, 'camera_fixed', false),
  4708. ];
  4709. if ($first_frame_url) $videoParams['first_frame_url'] = $first_frame_url;
  4710. if ($tail_frame_url) $videoParams['tail_frame_url'] = $tail_frame_url;
  4711. // 构建content数组
  4712. $videoParams['content'] = [
  4713. [
  4714. 'type' => 'text',
  4715. 'text' => $prompt,
  4716. ]
  4717. ];
  4718. // 根据模型选择不同的视频生成方法
  4719. if (strpos($model, 'jimeng') !== false) {
  4720. // 即梦模型参数调整
  4721. unset($videoParams['content']); // 即梦不使用content格式
  4722. $task = $this->aiVideoGenerationService->createJimengTask($videoParams);
  4723. } elseif (strpos($model, 'kling') !== false) {
  4724. // 可灵模型参数调整
  4725. $videoParams['aspect_ratio'] = $videoParams['ratio']; // 可灵使用aspect_ratio
  4726. unset($videoParams['ratio']);
  4727. unset($videoParams['content']); // 可灵不使用content格式
  4728. $task = $this->aiVideoGenerationService->createKelingOmniTask($videoParams);
  4729. } elseif (strpos($model, 'zhizhen') !== false) {
  4730. // 智帧等新模型使用统一API
  4731. $unifiedParams = [
  4732. 'model_code' => $model,
  4733. 'prompt' => $prompt,
  4734. 'video_duration' => $video_duration,
  4735. 'video_resolution' => strtolower($video_resolution),
  4736. 'video_ratio' => $ratio,
  4737. 'seed' => $seed,
  4738. ];
  4739. // 构建parameters参数
  4740. $parameters = [
  4741. 'seconds' => $unifiedParams['video_duration'],
  4742. 'resolution' => $unifiedParams['video_resolution'],
  4743. 'ratio' => $ratio,
  4744. 'generate_audio' => (int)$generate_audio === 1 ? true : false,
  4745. ];
  4746. // 首帧和尾帧
  4747. if ($first_frame_url) $parameters['first_frame_url'] = $first_frame_url;
  4748. if ($tail_frame_url) $parameters['last_frame_url'] = $tail_frame_url;
  4749. // 维护ref_image_url字段(参考图+参考视频+参考音频URL,JSON数组,与参考图处理方式一致)
  4750. $refImageUrls = array_merge($reference_images, $reference_videos, $reference_audios);
  4751. if ($refImageUrls) {
  4752. $unifiedParams['ref_image_url'] = json_encode(array_values(array_filter($refImageUrls)), 256);
  4753. }
  4754. // 参考图处理
  4755. if ($reference_images) {
  4756. $reference_images = $this->aiImageGenerationService->processReferenceImagesToAssets($reference_images, $unifiedParams['prompt']);
  4757. $parameters['reference_images'] = $reference_images;
  4758. $parameters['video_mode'] = 'multi_image';
  4759. $parameters['mode'] = 'multi_image';
  4760. }
  4761. // 参考视频和参考音频(与参考图一致,先上传为智帧素材)
  4762. if ($reference_videos) {
  4763. $reference_videos = $this->aiImageGenerationService->processReferenceVideosToAssets($reference_videos, $unifiedParams['prompt']);
  4764. $parameters['reference_videos'] = $reference_videos;
  4765. }
  4766. if ($reference_audios) {
  4767. $reference_audios = $this->aiImageGenerationService->processReferenceAudiosToAssets($reference_audios, $unifiedParams['prompt']);
  4768. $parameters['reference_audios'] = $reference_audios;
  4769. }
  4770. $unifiedParams['parameters'] = $parameters;
  4771. // 调用统一API创建任务
  4772. $task = $this->aiVideoGenerationService->createUnifiedApiTask($unifiedParams);
  4773. } elseif ($this->isSeedance20SeriesModel($model)) {
  4774. // 豆包Seedance 2.0(百度AI网关)/ 快快AI Seedance 2.0/2.5:图片/视频/音频需要先上传为素材
  4775. $isKuaikuai = $this->isKuaikuaiSeedanceModel($model);
  4776. $isDreamina = $this->isOverseasBaiduSeedanceModel($model);
  4777. $videoParams['reference_images'] = $reference_images;
  4778. // 维护ref_image_url字段(参考图+参考视频+参考音频URL,JSON数组)
  4779. $refImageUrls = array_merge($reference_images, $reference_videos, $reference_audios);
  4780. if ($refImageUrls) {
  4781. $videoParams['ref_image_url'] = json_encode(array_values(array_filter($refImageUrls)), 256);
  4782. }
  4783. if ($reference_images) {
  4784. // 参考图上传为素材(国内百度/海外百度dreamina/快快AI)
  4785. $reference_image_assets = $isKuaikuai
  4786. ? $this->aiVideoGenerationService->processReferenceImagesToKuaikuaiAssets($reference_images, $videoParams['prompt'])
  4787. : ($isDreamina
  4788. ? $this->aiVideoGenerationService->processReferenceImagesToBaiduDreaminaAssets($reference_images, $videoParams['prompt'])
  4789. : $this->aiVideoGenerationService->processReferenceImagesToSeedance20Assets($reference_images, $videoParams['prompt']));
  4790. $videoParams['reference_image_assets'] = $reference_image_assets;
  4791. }
  4792. // 参考视频上传为素材(国内百度/海外百度dreamina/快快AI)
  4793. if ($reference_videos) {
  4794. $reference_video_assets = $isKuaikuai
  4795. ? $this->aiVideoGenerationService->processReferenceVideosToKuaikuaiAssets($reference_videos, $videoParams['prompt'])
  4796. : ($isDreamina
  4797. ? $this->aiVideoGenerationService->processReferenceVideosToBaiduDreaminaAssets($reference_videos, $videoParams['prompt'])
  4798. : $this->aiVideoGenerationService->processReferenceVideosToSeedance20Assets($reference_videos, $videoParams['prompt']));
  4799. $videoParams['reference_video_assets'] = $reference_video_assets;
  4800. }
  4801. // 参考音频上传为素材(国内百度/海外百度dreamina/快快AI)
  4802. if ($reference_audios) {
  4803. $reference_audio_assets = $isKuaikuai
  4804. ? $this->aiVideoGenerationService->processReferenceAudiosToKuaikuaiAssets($reference_audios, $videoParams['prompt'])
  4805. : ($isDreamina
  4806. ? $this->aiVideoGenerationService->processReferenceAudiosToBaiduDreaminaAssets($reference_audios, $videoParams['prompt'])
  4807. : $this->aiVideoGenerationService->processReferenceAudiosToSeedance20Assets($reference_audios, $videoParams['prompt']));
  4808. $videoParams['reference_audio_assets'] = $reference_audio_assets;
  4809. }
  4810. // 参考素材上传失败时可能清理提示词中的素材标记,需要同步回content文本
  4811. if ($reference_images || $reference_videos || $reference_audios) {
  4812. $videoParams['content'][0]['text'] = $videoParams['prompt'];
  4813. }
  4814. // 快快AI走聚合网关 /v1/video/generations(火山豆包格式)
  4815. if ($isKuaikuai) {
  4816. $videoParams['gateway_base_url'] = env('KUAIKUAI_AI_BASE_URL', 'https://ai-api.kkidc.com');
  4817. $task = $this->aiVideoGenerationService->createKuaikuaiVideoTask($videoParams);
  4818. } else {
  4819. $task = $this->aiVideoGenerationService->createSeedance20Task($videoParams);
  4820. }
  4821. } else {
  4822. // 官方Seedance模型:兼容参考视频和参考音频(content直接透传公网URL)
  4823. // 维护ref_image_url字段(参考图+参考视频+参考音频URL,JSON数组)
  4824. $refImageUrls = array_merge($reference_images, $reference_videos, $reference_audios);
  4825. if ($refImageUrls) {
  4826. $videoParams['ref_image_url'] = json_encode(array_values(array_filter($refImageUrls)), 256);
  4827. }
  4828. if ($reference_videos) {
  4829. foreach ($reference_videos as $videoUrl) {
  4830. $videoParams['content'][] = [
  4831. 'type' => 'video_url',
  4832. 'video_url' => [
  4833. 'url' => $videoUrl,
  4834. ],
  4835. 'role' => 'reference_video',
  4836. ];
  4837. }
  4838. }
  4839. if ($reference_audios) {
  4840. foreach ($reference_audios as $audioUrl) {
  4841. $videoParams['content'][] = [
  4842. 'type' => 'audio_url',
  4843. 'audio_url' => [
  4844. 'url' => $audioUrl,
  4845. ],
  4846. 'role' => 'reference_audio',
  4847. ];
  4848. }
  4849. }
  4850. $task = $this->aiVideoGenerationService->createSeedanceTask($videoParams);
  4851. }
  4852. return [
  4853. 'task_id' => $task->id,
  4854. 'status' => $task->status,
  4855. 'model' => $model,
  4856. 'video_duration' => $video_duration,
  4857. 'video_resolution' => $video_resolution,
  4858. 'ratio' => $ratio
  4859. ];
  4860. }
  4861. /**
  4862. * 预估生成所需积分(mode=chat/image/video,支持多数量总额)
  4863. *
  4864. * chat : count(默认1,AI对话单次10积分);批量分集可传 anime_id + generate_episode_number 按实际待创建集数估算
  4865. * image : model 必传;resolution(1k/2k/4k)或 width/height 自动归一化;image_num(默认1)
  4866. * video : model 必传;video_resolution(默认720p);video_duration(默认5秒);count(默认1);scene(默认video_generation)
  4867. *
  4868. * @param array $data
  4869. * @return array
  4870. */
  4871. public function previewCharge(array $data): array
  4872. {
  4873. $mode = (string)getProp($data, 'mode', '');
  4874. if (!in_array($mode, ['chat', 'image', 'video'])) {
  4875. Utils::throwError('1003:请传入mode参数(chat/image/video)');
  4876. }
  4877. // 视频计费场景(video_generation/video_to_video),默认视频生成
  4878. $scene = (string)getProp($data, 'scene', 'video_generation');
  4879. // 未显式传scene且带参考视频时,自动按video_to_video定价
  4880. if ($mode === 'video' && !array_key_exists('scene', $data) && !empty(getProp($data, 'reference_videos', []))) {
  4881. $scene = 'video_to_video';
  4882. }
  4883. $items = [];
  4884. $model = '';
  4885. $resolution = '';
  4886. if ($mode === 'video') {
  4887. // 通用视频预估:单价/秒 × 时长 × 数量(多个视频计算总额)
  4888. $model = (string)getProp($data, 'model', '');
  4889. if (!$model) {
  4890. Utils::throwError('1002:model参数不能为空');
  4891. }
  4892. $resolution = strtolower((string)getProp($data, 'video_resolution', '720p'));
  4893. $duration = (int)getProp($data, 'video_duration', 5);
  4894. if ($duration <= 0) {
  4895. $duration = 5;
  4896. }
  4897. $count = max(1, (int)getProp($data, 'count', 1));
  4898. $pointsPerVideo = $this->pointsService->getVideoChargePoints([
  4899. 'model' => $model,
  4900. 'video_resolution' => $resolution,
  4901. 'video_duration' => $duration,
  4902. 'mode' => $scene,
  4903. ]);
  4904. $points = $pointsPerVideo * $count;
  4905. $items[] = [
  4906. 'type' => 'video',
  4907. 'model' => $model,
  4908. 'video_resolution' => $resolution,
  4909. 'video_duration' => $duration,
  4910. 'count' => $count,
  4911. 'points' => $points,
  4912. ];
  4913. } elseif ($mode === 'image') {
  4914. // 通用图片预估:单张价格 × 张数(resolution 可直传,或传 width/height 自动归一化)
  4915. $model = (string)getProp($data, 'model', '');
  4916. if (!$model) {
  4917. Utils::throwError('1002:model参数不能为空');
  4918. }
  4919. $resolution = strtolower((string)getProp($data, 'resolution', ''));
  4920. if (!$resolution) {
  4921. $width = (int)getProp($data, 'width', 0);
  4922. $height = (int)getProp($data, 'height', 0);
  4923. if ($width <= 0 || $height <= 0) {
  4924. $width = 1600;
  4925. $height = 2848;
  4926. }
  4927. $resolution = $this->pointsService->normalizeImageResolutionKey($width, $height);
  4928. }
  4929. $imageNum = max(1, (int)getProp($data, 'image_num', 1));
  4930. $points = $this->pointsService->getImageChargePoints([
  4931. 'model' => $model,
  4932. 'resolution' => $resolution,
  4933. ]) * $imageNum;
  4934. $items[] = [
  4935. 'type' => 'image',
  4936. 'model' => $model,
  4937. 'resolution' => $resolution,
  4938. 'image_num' => $imageNum,
  4939. 'points' => $points,
  4940. ];
  4941. } else {
  4942. // AI对话预估:按 price_type 档位取价(special 默认10 / normal 3);
  4943. // 批量生成分集传 anime_id + generate_episode_number 时按实际待创建集数估算(该场景实际扣费固定 special 档)
  4944. $priceType = (string)getProp($data, 'price_type', 'special');
  4945. if (!in_array($priceType, ['special', 'normal'], true)) {
  4946. Utils::throwError('1003:price_type参数仅支持special或normal');
  4947. }
  4948. $count = max(1, (int)getProp($data, 'count', 1));
  4949. $animeId = getProp($data, 'anime_id');
  4950. $generateEpisodes = (int)getProp($data, 'generate_episode_number', 0);
  4951. if ($animeId && $generateEpisodes > 0) {
  4952. // 批量生成分集按 special 档预估,与实际扣费口径一致
  4953. $priceType = 'special';
  4954. $currentMaxEpisode = DB::table('mp_anime_episodes')
  4955. ->where('anime_id', $animeId)
  4956. ->where('is_default', 1)
  4957. ->max('episode_number');
  4958. $currentMaxEpisode = $currentMaxEpisode ?: 0;
  4959. $startEpisodeNumber = $currentMaxEpisode + 1;
  4960. $endEpisodeNumber = $startEpisodeNumber + $generateEpisodes - 1;
  4961. $existingSkipped = DB::table('mp_batch_episode_generation_details')
  4962. ->where('anime_id', $animeId)
  4963. ->whereBetween('episode_number', [$startEpisodeNumber, $endEpisodeNumber])
  4964. ->whereIn('status', ['pending', 'processing', 'completed'])
  4965. ->count();
  4966. $count = ($endEpisodeNumber - $startEpisodeNumber + 1) - $existingSkipped;
  4967. if ($count < 0) {
  4968. $count = 0;
  4969. }
  4970. }
  4971. $points = $this->pointsService->getChatChargePoints((string)$model, $priceType) * $count;
  4972. $items[] = [
  4973. 'type' => 'chat',
  4974. 'count' => $count,
  4975. 'price_type' => $priceType,
  4976. 'points' => $points,
  4977. ];
  4978. }
  4979. $totalPoints = 0;
  4980. foreach ($items as $item) {
  4981. $totalPoints += $item['points'];
  4982. }
  4983. return [
  4984. 'mode' => $mode,
  4985. 'total_points' => $totalPoints,
  4986. 'items' => $items,
  4987. 'points_balance' => $this->pointsService->getUserPointsBalance(),
  4988. 'remark' => '积分为预估值,实际扣费以生成完成后的实际消耗为准',
  4989. ];
  4990. }
  4991. /**
  4992. * 根据提示词内容智能计算最优视频时长
  4993. *
  4994. * @param string $segmentContent 分镜内容
  4995. * @param string $tailFrame 尾帧描述
  4996. * @return int 视频时长(2-12秒)
  4997. */
  4998. public function calculateOptimalVideoDuration($segmentContent, $tailFrame = '') {
  4999. // 合并所有文本内容
  5000. $fullText = trim($segmentContent . ' ' . $tailFrame);
  5001. // 如果没有内容,返回默认时长
  5002. if (empty($fullText)) {
  5003. return 5;
  5004. }
  5005. // 计算文本长度(中文字符按2个字符计算)
  5006. $textLength = mb_strlen($fullText, 'UTF-8');
  5007. $chineseCharCount = preg_match_all('/[\x{4e00}-\x{9fff}]/u', $fullText);
  5008. $adjustedLength = $textLength + $chineseCharCount; // 中文字符权重更高
  5009. // 分析内容复杂度
  5010. $complexityScore = $this->analyzeContentComplexity($fullText);
  5011. // 基础时长计算(根据文本长度)
  5012. $baseDuration = 3; // 默认2秒
  5013. // if ($adjustedLength <= 20) {
  5014. // $baseDuration = 3;
  5015. // } elseif ($adjustedLength <= 40) {
  5016. // $baseDuration = 4;
  5017. // } elseif ($adjustedLength <= 60) {
  5018. // $baseDuration = 5;
  5019. // } elseif ($adjustedLength <= 80) {
  5020. // $baseDuration = 6;
  5021. // } elseif ($adjustedLength <= 100) {
  5022. // $baseDuration = 7;
  5023. // } elseif ($adjustedLength <= 120) {
  5024. // $baseDuration = 8;
  5025. // } else {
  5026. // $baseDuration = 9;
  5027. // }
  5028. // 根据内容复杂度调整时长
  5029. $finalDuration = $baseDuration + $complexityScore;
  5030. // 确保时长在2-12秒范围内
  5031. return max(4, min(12, $finalDuration));
  5032. }
  5033. /**
  5034. * 分析内容复杂度,返回时长调整值
  5035. *
  5036. * @param string $text 文本内容
  5037. * @return int 调整值(-2到+3)
  5038. */
  5039. private function analyzeContentComplexity($text) {
  5040. $score = 0;
  5041. // 动作关键词(需要更长时间展现)
  5042. $actionKeywords = [
  5043. '跑步', '奔跑', '飞行', '跳跃', '战斗', '打斗', '追逐', '逃跑', '舞蹈', '表演',
  5044. '变化', '变身', '爆炸', '崩塌', '建造', '制作', '烹饪', '绘画', '写字',
  5045. '移动', '旋转', '翻滚', '攀爬', '游泳', '潜水', '滑行', '飞翔'
  5046. ];
  5047. // 静态关键词(可以用较短时间)
  5048. $staticKeywords = [
  5049. '站立', '坐着', '躺着', '静止', '凝视', '思考', '沉思', '观察', '等待',
  5050. '睡觉', '休息', '静坐', '冥想', '阅读', '听音乐'
  5051. ];
  5052. // 复杂场景关键词(需要更长时间)
  5053. $complexSceneKeywords = [
  5054. '人群', '聚会', '会议', '战争', '庆典', '仪式', '表演', '比赛', '竞技',
  5055. '多人', '群体', '团队', '合作', '互动', '对话', '争论', '讨论'
  5056. ];
  5057. // 情感关键词(需要适中时间表现)
  5058. $emotionKeywords = [
  5059. '哭泣', '笑容', '愤怒', '惊讶', '恐惧', '悲伤', '喜悦', '兴奋', '紧张',
  5060. '感动', '震惊', '困惑', '失望', '希望', '绝望', '温柔', '严肃'
  5061. ];
  5062. // 检查动作关键词
  5063. foreach ($actionKeywords as $keyword) {
  5064. if (strpos($text, $keyword) !== false) {
  5065. $score += 1;
  5066. break; // 避免重复加分
  5067. }
  5068. }
  5069. // 检查静态关键词
  5070. foreach ($staticKeywords as $keyword) {
  5071. if (strpos($text, $keyword) !== false) {
  5072. $score -= 1;
  5073. break;
  5074. }
  5075. }
  5076. // 检查复杂场景关键词
  5077. foreach ($complexSceneKeywords as $keyword) {
  5078. if (strpos($text, $keyword) !== false) {
  5079. $score += 1;
  5080. break;
  5081. }
  5082. }
  5083. // 检查情感关键词
  5084. foreach ($emotionKeywords as $keyword) {
  5085. if (strpos($text, $keyword) !== false) {
  5086. $score += 1;
  5087. break;
  5088. }
  5089. }
  5090. // 检查时间相关词汇
  5091. if (preg_match('/缓慢|慢慢|渐渐|逐渐|慢动作/', $text)) {
  5092. $score += 1;
  5093. }
  5094. if (preg_match('/快速|迅速|急速|瞬间|立刻|马上/', $text)) {
  5095. $score -= 1;
  5096. }
  5097. // 检查转场词汇
  5098. if (preg_match('/然后|接着|随后|紧接着|同时|与此同时/', $text)) {
  5099. $score += 1;
  5100. }
  5101. // 检查环境描述(复杂环境需要更多时间)
  5102. if (preg_match('/风景|景色|环境|背景|氛围|光线|阴影|色彩|细节/', $text)) {
  5103. $score += 1;
  5104. }
  5105. // 检查对话内容(对话需要更多时间)
  5106. if (preg_match('/说|讲|告诉|回答|询问|问|对话|交谈/', $text)) {
  5107. $score += 1;
  5108. }
  5109. // 限制调整范围
  5110. return max(-1, min(4, $score));
  5111. }
  5112. /**
  5113. * 创建完整视频合成任务
  5114. *
  5115. * @param array $data
  5116. * @return array
  5117. */
  5118. public function createCompleteVideoTask($data)
  5119. {
  5120. $animeId = getProp($data, 'anime_id');
  5121. $episodeId = getProp($data, 'episode_id');
  5122. // 验证参数
  5123. if (!$animeId || !$episodeId) {
  5124. Utils::throwError('20003:anime_id 和 episode_id 不能为空');
  5125. }
  5126. // 检查是否已存在处理中的任务
  5127. $existingTask = DB::table('mp_complete_video_tasks')
  5128. ->where('anime_id', $animeId)
  5129. ->where('episode_id', $episodeId)
  5130. ->whereIn('generate_status', ['执行中'])
  5131. ->first();
  5132. if ($existingTask) {
  5133. Utils::throwError('20003:该剧集已有正在处理的视频合成任务');
  5134. }
  5135. // 获取全能模式状态
  5136. $ace_mode = DB::table('mp_animes')->where('id', $animeId)->value('ace_mode');
  5137. if ((int)$ace_mode === 1) {
  5138. // 获取所有片段的配音视频,按 act_number 排序
  5139. $segments = DB::table('mp_episode_segments')
  5140. ->where('anime_id', $animeId)
  5141. ->where('episode_id', $episodeId)
  5142. ->orderBy('segment_number')
  5143. ->select('id as act_id', 'act_number', 'video_url', 'audio_url', 'video_time_point_start', 'video_time_point_end')
  5144. ->get();
  5145. // 检查是否所有片段都有视频
  5146. $missingVideos = $segments->filter(function($segment) {
  5147. return empty($segment->video_url);
  5148. });
  5149. if ($missingVideos->isNotEmpty()) {
  5150. Utils::throwError('20003:存在未完成视频的片段,请确保所有片段都已完成配音');
  5151. }
  5152. }else {
  5153. // 获取所有分镜的配音视频,按 segment_number 排序
  5154. $segments = DB::table('mp_episode_segments')
  5155. ->where('anime_id', $animeId)
  5156. ->where('episode_id', $episodeId)
  5157. ->orderBy('segment_number')
  5158. ->select('segment_id', 'segment_number', 'video_url', 'audio_url', 'video_time_point_start', 'video_time_point_end')
  5159. ->get();
  5160. // 检查是否所有分镜都有配音和视频
  5161. $missingVideos = $segments->filter(function($segment) {
  5162. return empty($segment->audio_url) || empty($segment->video_url);
  5163. });
  5164. if ($missingVideos->isNotEmpty()) {
  5165. Utils::throwError('20003:存在未完成配音或视频的分镜,请确保所有分镜都已完成配音或视频');
  5166. }
  5167. }
  5168. if ($segments->isEmpty()) {
  5169. Utils::throwError('20003:未找到该剧集的分镜数据');
  5170. }
  5171. // 获取当前完整视频url
  5172. $completeVideoUrl = DB::table('mp_anime_episodes')
  5173. ->where('anime_id', $animeId)
  5174. ->where('id', $episodeId)
  5175. ->value('complete_video_url');
  5176. // 构建 generate_json
  5177. $generateJson = [];
  5178. $sequence = 1;
  5179. foreach ($segments as $segment) {
  5180. if ((int)$ace_mode === 1) {
  5181. $generateJson[] = [
  5182. 'sequence' => $sequence++,
  5183. 'video_url' => $segment->video_url,
  5184. 'video_time_point_start' => $segment->video_time_point_start,
  5185. 'video_time_point_end' => $segment->video_time_point_end
  5186. ];
  5187. }else {
  5188. $generateJson[] = [
  5189. 'sequence' => $sequence++,
  5190. 'video_url' => $segment->video_url,
  5191. 'audio_url' => $segment->audio_url,
  5192. 'video_time_point_start' => $segment->video_time_point_start,
  5193. 'video_time_point_end' => $segment->video_time_point_end
  5194. ];
  5195. }
  5196. }
  5197. // 创建任务
  5198. $now = date('Y-m-d H:i:s');
  5199. $taskId = DB::table('mp_complete_video_tasks')->insertGetId([
  5200. 'anime_id' => $animeId,
  5201. 'episode_id' => $episodeId,
  5202. 'generate_json' => json_encode($generateJson, 256),
  5203. 'generate_status' => '执行中',
  5204. 'complete_video_url' => '',
  5205. 'created_at' => $now,
  5206. 'updated_at' => $now
  5207. ]);
  5208. if (!$taskId) {
  5209. Utils::throwError('20003:创建任务失败');
  5210. }
  5211. // 更新剧集表的任务ID和状态
  5212. $boolen = DB::table('mp_anime_episodes')
  5213. ->where('anime_id', $animeId)
  5214. ->where('id', $episodeId)
  5215. ->update([
  5216. 'complete_video_task_id' => $taskId,
  5217. 'complete_video_task_status' => '执行中',
  5218. 'updated_at' => $now
  5219. ]);
  5220. if (!$boolen) {
  5221. Utils::throwError('20003:更新剧集表失败');
  5222. }
  5223. dLog('anime')->info('创建完整视频合成任务', [
  5224. 'task_id' => $taskId,
  5225. 'anime_id' => $animeId,
  5226. 'episode_id' => $episodeId,
  5227. 'segment_count' => count($generateJson)
  5228. ]);
  5229. // 请求远程服务器执行生成
  5230. $client = new Client(['timeout' => 600, 'verify' => false]);
  5231. try {
  5232. $result = $client->get("http://122.9.129.83:5000/api/anime/genVideo?taskId={$taskId}");
  5233. $response = $result->getBody()->getContents();
  5234. $response_arr = json_decode($response, true);
  5235. if (!isset($response_arr['code']) || (int)$response_arr['code'] !== 0) {
  5236. $error_msg = isset($response_arr['msg']) ? $response_arr['msg'] : '未知错误';
  5237. dLog('anime')->error('火山合成完整视频失败', ['error' => $error_msg, 'task_id' => $taskId]);
  5238. // // 更新任务状态为失败
  5239. // DB::table('mp_complete_video_tasks')
  5240. // ->where('id', $taskId)
  5241. // ->update([
  5242. // 'generate_status' => '执行失败',
  5243. // 'error_message' => $error_msg,
  5244. // 'updated_at' => date('Y-m-d H:i:s')
  5245. // ]);
  5246. // // 同步更新剧集表状态
  5247. // DB::table('mp_anime_episodes')
  5248. // ->where('complete_video_task_id', $taskId)
  5249. // ->update([
  5250. // 'complete_video_task_status' => '执行失败',
  5251. // 'updated_at' => date('Y-m-d H:i:s')
  5252. // ]);
  5253. Utils::throwError('20003:火山合成完整视频失败: ' . $error_msg);
  5254. }
  5255. } catch (\Exception $e) {
  5256. dLog('anime')->error('调用远程服务器失败', ['error' => $e->getMessage(), 'task_id' => $taskId]);
  5257. // 更新任务状态为失败
  5258. DB::table('mp_complete_video_tasks')
  5259. ->where('id', $taskId)
  5260. ->update([
  5261. 'generate_status' => '执行失败',
  5262. 'error_message' => $e->getMessage(),
  5263. 'updated_at' => date('Y-m-d H:i:s')
  5264. ]);
  5265. // 同步更新剧集表状态
  5266. DB::table('mp_anime_episodes')
  5267. ->where('complete_video_task_id', $taskId)
  5268. ->update([
  5269. 'complete_video_task_status' => '执行失败',
  5270. 'updated_at' => date('Y-m-d H:i:s')
  5271. ]);
  5272. Utils::throwError('20003:调用远程服务器失败: ' . $e->getMessage());
  5273. }
  5274. // 开始轮询任务状态
  5275. $maxAttempts = 60; // 5分钟 = 60次 * 5秒
  5276. $pollInterval = 5; // 每5秒轮询一次
  5277. $attempt = 0;
  5278. dLog('anime')->info('开始轮询任务状态', ['task_id' => $taskId]);
  5279. while ($attempt < $maxAttempts) {
  5280. sleep($pollInterval);
  5281. $attempt++;
  5282. // 查询任务状态
  5283. $task = DB::table('mp_complete_video_tasks')
  5284. ->where('id', $taskId)
  5285. ->first();
  5286. if (!$task) {
  5287. dLog('anime')->error('任务不存在', ['task_id' => $taskId]);
  5288. Utils::throwError('20003:任务不存在');
  5289. }
  5290. dLog('anime')->info('轮询任务状态', [
  5291. 'task_id' => $taskId,
  5292. 'attempt' => $attempt,
  5293. 'status' => $task->generate_status
  5294. ]);
  5295. // 检查任务是否完成
  5296. if ($task->generate_status === '执行成功') {
  5297. // 同步更新剧集表状态
  5298. $boolen3 = DB::table('mp_anime_episodes')
  5299. ->where('anime_id', $animeId)
  5300. ->where('id', $episodeId)
  5301. ->update([
  5302. 'complete_video_url' => $task->complete_video_url,
  5303. 'complete_video_task_status' => '执行成功',
  5304. 'updated_at' => date('Y-m-d H:i:s')
  5305. ]);
  5306. dLog('anime')->info('视频合成任务完成', [
  5307. 'task_id' => $taskId,
  5308. 'video_url' => $task->complete_video_url,
  5309. 'attempts' => $attempt
  5310. ]);
  5311. // 如果更新成功则远程删除之前的文件
  5312. if ($boolen3 && $completeVideoUrl) {
  5313. $encode_url = urlencode($completeVideoUrl);
  5314. $client = new Client(['timeout' => 300, 'verify' => false]);
  5315. // 根据ID通过API通知合成音频
  5316. // $result = $client->get("http://47.240.171.155:5000/api/fileDelete?url={$encode_url}");
  5317. $result = $client->get("http://122.9.129.83:5000/api/fileDelete?url={$encode_url}");
  5318. $response = $result->getBody()->getContents();
  5319. $response_arr = json_decode($response, true);
  5320. Log::info('火山删除音频返回: '.$response);
  5321. if (!isset($response_arr['status']) || (int)$response_arr['status'] !== 0) {
  5322. $error_msg = isset($response_arr['msg']) ? $response_arr['msg'] : '未知错误';
  5323. Log::info('火山删除音频失败: '.$error_msg);
  5324. // Utils::throwError('20003:火山删除音频失败');
  5325. }
  5326. }
  5327. return [
  5328. 'task_id' => $taskId,
  5329. 'anime_id' => $animeId,
  5330. 'episode_id' => $episodeId,
  5331. 'segment_count' => count($generateJson),
  5332. 'generate_status' => '执行成功',
  5333. 'complete_video_url' => $task->complete_video_url,
  5334. ];
  5335. }
  5336. // 检查任务是否失败
  5337. if ($task->generate_status === '执行失败') {
  5338. // 同步更新剧集表状态
  5339. DB::table('mp_anime_episodes')
  5340. ->where('anime_id', $animeId)
  5341. ->where('id', $episodeId)
  5342. ->update([
  5343. 'complete_video_task_status' => '执行失败',
  5344. 'updated_at' => date('Y-m-d H:i:s')
  5345. ]);
  5346. $errorMessage = $task->error_message ?? '未知错误';
  5347. dLog('anime')->error('视频合成任务失败', [
  5348. 'task_id' => $taskId,
  5349. 'error' => $errorMessage,
  5350. 'attempts' => $attempt
  5351. ]);
  5352. return [
  5353. 'task_id' => $taskId,
  5354. 'anime_id' => $animeId,
  5355. 'episode_id' => $episodeId,
  5356. 'segment_count' => count($generateJson),
  5357. 'generate_status' => '执行失败',
  5358. 'error_message' => $errorMessage
  5359. ];
  5360. }
  5361. }
  5362. // 超时处理
  5363. dLog('anime')->warning('视频合成任务超时', [
  5364. 'task_id' => $taskId,
  5365. 'max_attempts' => $maxAttempts,
  5366. 'timeout_seconds' => $maxAttempts * $pollInterval
  5367. ]);
  5368. // 更新任务状态为超时
  5369. DB::table('mp_complete_video_tasks')
  5370. ->where('id', $taskId)
  5371. ->update([
  5372. 'generate_status' => '超时',
  5373. 'error_message' => '任务执行超时(5分钟)',
  5374. 'updated_at' => date('Y-m-d H:i:s')
  5375. ]);
  5376. return [
  5377. 'task_id' => $taskId,
  5378. 'anime_id' => $animeId,
  5379. 'episode_id' => $episodeId,
  5380. 'segment_count' => count($generateJson),
  5381. 'generate_status' => '超时',
  5382. 'error_message' => '任务执行超时,请稍后查询任务状态'
  5383. ];
  5384. }
  5385. /**
  5386. * 根据 inner_prompt_type 附加内置提示词
  5387. *
  5388. * @param string $prompt 用户提示词
  5389. * @param int $innerPromptType 内置提示词类型(1=三视图, 2=九宫格)
  5390. * @return string 合并后的提示词
  5391. */
  5392. public static function appendInnerPrompt($prompt, $innerPromptType = 0)
  5393. {
  5394. $innerPromptMap = [
  5395. 1 => '基于参考图生成主体的标准正面、侧面、后面三视图,主体完整。在最左侧添加主体正视图的特写,特写大小为标准一寸照,人物不要带表情。右侧是全身的三视图,其中正面、侧面的三视图给人脸打白色码、不显示五官。主体清晰完整。背景修改成纯白色,整体保持与参考图一致的美术风格和色彩搭配。画面无说明文字。',
  5396. 2 => '基于参考图及提示词内容,生成9张连贯的系列图片:9张图片围绕同一主体展开,保持角色形象、美术风格和色彩搭配完全一致,画面内容依次衔接、情节连贯,整体构成一组完整的系列图。每张图片主体完整清晰,构图合理,画面干净,无文字、无水印、无字幕。',
  5397. ];
  5398. if (!isset($innerPromptMap[$innerPromptType])) {
  5399. return $prompt;
  5400. }
  5401. return trim((string)$prompt) . "\n" . $innerPromptMap[$innerPromptType];
  5402. }
  5403. /**
  5404. * 根据 inner_prompt_type 获取生成图片数量
  5405. *
  5406. * @param int $innerPromptType 内置提示词类型
  5407. * @param int $imageNum 传入的图片张数
  5408. * @return int 图片数量
  5409. */
  5410. public static function getInnerImageNum($innerPromptType = 0, $imageNum)
  5411. {
  5412. return (int)$innerPromptType === 2 ? 9 : $imageNum;
  5413. }
  5414. /**
  5415. * 提取图片生成结果URL
  5416. *
  5417. * @param mixed $resultUrl 任务结果URL(数组、JSON字符串或普通字符串)
  5418. * @param int $innerPromptType 内置提示词类型
  5419. * @return mixed 类型2返回全部URL数组,其它类型返回首个URL
  5420. */
  5421. public static function extractResultUrls($resultUrl, $innerPromptType = 0)
  5422. {
  5423. $resultUrls = is_array($resultUrl) ? $resultUrl : json_decode((string)$resultUrl, true);
  5424. if (is_array($resultUrls) && !empty($resultUrls)) {
  5425. $resultUrls = array_values($resultUrls);
  5426. return (int)$innerPromptType === 2 ? $resultUrls : $resultUrls[0];
  5427. }
  5428. if (!empty($resultUrl)) {
  5429. return (int)$innerPromptType === 2 ? [$resultUrl] : $resultUrl;
  5430. }
  5431. return (int)$innerPromptType === 2 ? [] : '';
  5432. }
  5433. public function generateImg($data, $onTaskCreated = null, $onPoll = null) {
  5434. $prompt = getProp($data, 'prompt');
  5435. $episode_id = getProp($data, 'episode_id');
  5436. $ref_img_urls = getProp($data, 'ref_img_urls');
  5437. $ratio = getProp($data, 'ratio', '9:16');
  5438. $resolution = getProp($data, 'resolution', '2k');
  5439. $inner_prompt_type = getProp($data, 'inner_prompt_type', 0);
  5440. $imageNum = (int)getProp($data, 'image_num', 1);
  5441. // 分辨率档位与尺寸映射统一从 BaseConst 获取
  5442. $sizeMap = BaseConst::IMAGE_RESOLUTION_SIZE_MAP;
  5443. // 参数验证
  5444. $resolution = strtolower($resolution);
  5445. if (!isset($sizeMap[$resolution])) {
  5446. Utils::throwError('20003:分辨率参数错误,仅支持 2k、3k、4k');
  5447. }
  5448. if (!isset($sizeMap[$resolution][$ratio])) {
  5449. Utils::throwError('20003:宽高比参数错误,该分辨率下不支持 ' . $ratio . ' 比例');
  5450. }
  5451. // 根据 ratio 和 resolution 确定宽高
  5452. $width = $sizeMap[$resolution][$ratio]['width'];
  5453. $height = $sizeMap[$resolution][$ratio]['height'];
  5454. if (!is_array($ref_img_urls) && !empty($ref_img_urls)) {
  5455. if (is_json($ref_img_urls)) {
  5456. $ref_img_urls = json_decode($ref_img_urls, true);
  5457. }else {
  5458. $ref_img_urls = explode(',', $ref_img_urls);
  5459. }
  5460. }
  5461. // 处理图片模型
  5462. $model = getProp($data, 'model');
  5463. if (!$model) {
  5464. // 用户没有输入,从episode表获取
  5465. if ($episode_id) {
  5466. $episode = DB::table('mp_anime_episodes')->where('id', $episode_id)->first();
  5467. $model = getProp($episode, 'image_model');
  5468. }
  5469. if (!$model) {
  5470. // episode表也没有,使用默认值
  5471. $model = 'gpt-image-2';
  5472. }
  5473. }
  5474. // 验证模型是否在可用模型表中
  5475. if (!DB::table('mp_image_models')->where('model', $model)->where('is_enabled', 1)->exists()) {
  5476. // $model = 'gpt-image-2';
  5477. Utils::throwError('20003:该模型已不可用,请更换!');
  5478. }
  5479. // 保存到episode表
  5480. if ($episode_id) {
  5481. DB::table('mp_anime_episodes')->where('id', $episode_id)->update([
  5482. 'image_model' => $model,
  5483. 'updated_at' => date('Y-m-d H:i:s')
  5484. ]);
  5485. }
  5486. // 参数验证
  5487. if (!$prompt) Utils::throwError('20003:请提供提示词');
  5488. // 根据 inner_prompt_type 附加内置提示词并确定生成图片数量
  5489. $prompt = self::appendInnerPrompt($prompt, $inner_prompt_type);
  5490. $imageNum = self::getInnerImageNum($inner_prompt_type, $imageNum);
  5491. try {
  5492. // 创建图片生成任务
  5493. $params = [
  5494. 'prompt' => $prompt,
  5495. 'model' => $model,
  5496. 'ref_img_urls' => '',
  5497. 'width' => $width,
  5498. 'height' => $height,
  5499. 'image_num' => $imageNum,
  5500. // 计费锚点(动漫/剧集/剧本),上下文没有时不记录
  5501. 'anime_id' => getProp($data, 'anime_id'),
  5502. 'episode_id' => $episode_id,
  5503. ];
  5504. if ($ref_img_urls) $params['ref_img_urls'] = is_array($ref_img_urls) ? $ref_img_urls : [$ref_img_urls];
  5505. $task = $this->aiImageGenerationService->createImageGenerationTask($params);
  5506. $task_id = $task->id;
  5507. if (!$task_id) {
  5508. Utils::throwError('20003:创建图片生成任务失败');
  5509. }
  5510. // 创建任务中心记录并关联图片任务ID
  5511. $taskCenter = $this->taskCenterService->createTask('image', [
  5512. 'title' => '文生图',
  5513. 'ref_task_id' => $task_id,
  5514. // 'prompt' => $prompt,
  5515. // 'params' => json_encode($data, JSON_UNESCAPED_UNICODE),
  5516. ]);
  5517. $taskCenterId = $taskCenter->id;
  5518. // 组装本次任务信息(用于init消息,类似generateVideo)
  5519. $taskInfo = [
  5520. 'task_id' => $task_id,
  5521. 'status' => getProp($task, 'status', 'processing'),
  5522. 'model' => $model,
  5523. 'ratio' => $ratio,
  5524. 'resolution' => $resolution,
  5525. 'image_num' => $imageNum,
  5526. ];
  5527. // 创建图片任务后立即回调(类似generateVideo的init消息,返回任务中心ID和任务信息)
  5528. if (is_callable($onTaskCreated)) {
  5529. $onTaskCreated($taskCenterId, $taskInfo);
  5530. }
  5531. // 检查任务模型类型(火山模型和GPT模型都支持直接检查任务状态)
  5532. $model = getProp($task, 'model');
  5533. $isVolcModel = in_array($model, \App\Consts\BaseConst::VOLC_PIC_MODELS);
  5534. $isGptModel = in_array($model, \App\Consts\BaseConst::GPT_IMAGE2_MODELS);
  5535. $isSyncModel = $isVolcModel || $isGptModel;
  5536. // 任务需要轮询获取结果(15分钟超时,每3秒查询一次)
  5537. $start_time = time();
  5538. $timeout = 900; // 15分钟
  5539. $img_url = '';
  5540. $img_urls = [];
  5541. $lastQueueMessageTime = $start_time; // 记录上次发送队列消息的时间
  5542. $queueMessageInterval = 60; // 队列消息发送间隔(秒)
  5543. while (time() - $start_time < $timeout) {
  5544. sleep(3);
  5545. // 每分钟发送一次队列状态消息(仅流式模式)
  5546. if (is_callable($onPoll)) {
  5547. $currentTime = time();
  5548. if ($currentTime - $lastQueueMessageTime >= $queueMessageInterval) {
  5549. $onPoll($taskCenterId, $task_id, $currentTime - $start_time);
  5550. $lastQueueMessageTime = $currentTime;
  5551. }
  5552. }
  5553. // 火山API和GPT-Image2 API是同步返回结果的,直接检查任务状态
  5554. if ($isSyncModel) {
  5555. // 刷新任务状态
  5556. $task = MpGeneratePicTask::where('id', $task_id)->first();
  5557. if ($task->status === 'success' && $task->result_url) {
  5558. $resultUrls = is_array($task->result_url) ? $task->result_url : json_decode((string)$task->result_url, true);
  5559. $resultUrls = is_array($resultUrls) ? array_values(array_filter($resultUrls)) : [];
  5560. if (!empty($resultUrls)) {
  5561. $img_urls = $resultUrls;
  5562. $img_url = $resultUrls[0];
  5563. } else {
  5564. $img_url = (string)$task->result_url;
  5565. }
  5566. break;
  5567. } elseif ($task->status === 'failed') {
  5568. $errorMsg = mapErrorMessage($task->error_message ?? '');
  5569. Utils::throwError('20003:图片生成失败,' . $errorMsg);
  5570. }
  5571. // // 如果还在处理中,提示用户稍后查看
  5572. // Utils::throwError('20003:图片生成中,请稍后刷新查看结果');
  5573. }else {
  5574. $task = MpGeneratePicTask::where('id', $task_id)->first();
  5575. $statusInfo = $this->aiImageGenerationService->queryTaskStatus($task);
  5576. if ($statusInfo['status'] === 'success') {
  5577. $task->updateStatus('success', [
  5578. 'result_url' => $statusInfo['result_url'],
  5579. 'result_json' => $statusInfo['result_json'] ?? []
  5580. ]);
  5581. $resultUrls = is_array($statusInfo['result_url']) ? $statusInfo['result_url'] : json_decode((string)$statusInfo['result_url'], true);
  5582. $resultUrls = is_array($resultUrls) ? array_values(array_filter($resultUrls)) : [];
  5583. if (!empty($resultUrls)) {
  5584. $img_urls = $resultUrls;
  5585. $img_url = $resultUrls[0];
  5586. } else {
  5587. $img_url = (string)$statusInfo['result_url'];
  5588. }
  5589. break;
  5590. } elseif ($statusInfo['status'] === 'failed') {
  5591. $task->updateStatus('failed', [
  5592. 'error_message' => $statusInfo['error_message'],
  5593. 'result_json' => $statusInfo['result_json'] ?? []
  5594. ]);
  5595. dLog('anime')->error('图片生成失败,', [
  5596. 'error' => $statusInfo['error_message'] ?? '未知错误'
  5597. ]);
  5598. $errorMsg = mapErrorMessage($statusInfo['error_message'] ?? '');
  5599. Utils::throwError('20003:图片生成失败,' . $errorMsg);
  5600. }
  5601. }
  5602. }
  5603. if (empty($img_url)) {
  5604. Utils::throwError('20003:图片生成超时,请稍后重试');
  5605. }
  5606. // 多张图片返回全部URL数组(配合控制器输出image_urls字段)
  5607. if (count($img_urls) > 1) {
  5608. return [
  5609. 'img_url' => $img_url,
  5610. 'image_urls' => $img_urls,
  5611. 'task_id' => $taskCenterId,
  5612. ];
  5613. }
  5614. return [
  5615. 'img_url' => $img_url,
  5616. 'task_id' => $taskCenterId,
  5617. ];
  5618. } catch (\Exception $e) {
  5619. dLog('anime')->error('更新角色或场景失败', [
  5620. 'error' => $e->getMessage()
  5621. ]);
  5622. logDB('anime', 'error', '更新角色或场景失败', ['error' => $e->getMessage()]);
  5623. Utils::throwError('20003:' . $e->getMessage());
  5624. }
  5625. }
  5626. /**
  5627. * 使用文生文模型解析分镜内容
  5628. */
  5629. private function parseSegmentContentWithAI($segment_content) {
  5630. try {
  5631. // 使用DeepSeek服务的公开方法解析分镜内容
  5632. return $this->DeepSeekService->parseSegmentContent($segment_content);
  5633. } catch (\Exception $e) {
  5634. // 如果AI解析失败,记录日志并返回原内容
  5635. dLog('anime')->error('AI解析分镜内容失败: ' . $e->getMessage());
  5636. return $segment_content;
  5637. }
  5638. }
  5639. /**
  5640. * 处理分集的角色和场景数据(继承全局数据或创建新任务)
  5641. *
  5642. * @param int $episode_id 分集ID
  5643. * @param int $anime_id 动漫ID
  5644. * @param array $roles 分集角色数组(引用传递)
  5645. * @param array $scenes 分集场景数组(引用传递)
  5646. * @param array $episode 分集数据
  5647. */
  5648. private function processEpisodeRolesAndScenes($episode_id, $anime_id, &$roles, &$scenes, $episode) {
  5649. // 获取全局动漫的角色和场景数据
  5650. $anime = DB::table('mp_animes')->where('id', $anime_id)->first();
  5651. if (!$anime) return;
  5652. $art_style_type = getProp($anime, 'art_style_type');
  5653. $character_prefix = '';
  5654. $scene_prefix = '';
  5655. if ($art_style_type) {
  5656. $art_style_arr = $this->DeepSeekService->getArtStyleShortPromptByInput($art_style_type);
  5657. $character_prefix = isset($art_style_arr['character_prefix']) ? $art_style_arr['character_prefix'] : '';
  5658. $scene_prefix = isset($art_style_arr['scene_prefix']) ? $art_style_arr['scene_prefix'] : '';
  5659. }
  5660. $global_roles = json_decode(getProp($anime, 'roles'), true) ?: [];
  5661. $global_scenes = json_decode(getProp($anime, 'scenes'), true) ?: [];
  5662. $roles_updated = false;
  5663. $scenes_updated = false;
  5664. // 处理角色
  5665. foreach ($roles as &$role) {
  5666. $role_name = getProp($role, 'role');
  5667. $role_description = getProp($role, 'description');
  5668. $role_pic_prompt = getProp($role, 'pic_prompt');
  5669. $role_url = getProp($role, 'url');
  5670. $role_task_id = getProp($role, 'task_id');
  5671. // 如果已有URL或已有任务ID,跳过
  5672. if (!empty($role_url) || !empty($role_task_id) || $role_name === '旁白') {
  5673. continue;
  5674. }
  5675. $url_inherited = false;
  5676. // 尝试从全局数据中继承
  5677. foreach ($global_roles as $global_role) {
  5678. $global_role_name = getProp($global_role, 'role');
  5679. $global_role_description = getProp($global_role, 'description');
  5680. $global_role_pic_prompt = getProp($global_role, 'pic_prompt');
  5681. $global_role_url = getProp($global_role, 'url');
  5682. $global_role_task_id = getProp($global_role, 'task_id');
  5683. $global_role_task_status = getProp($global_role, 'task_status');
  5684. // 满足条件:角色名相同、描述相同、pic_prompt相同、全局有URL
  5685. if ($role_name === $global_role_name
  5686. && $role_description === $global_role_description
  5687. && $role_pic_prompt === $global_role_pic_prompt
  5688. && !empty($global_role_url)) {
  5689. // 继承 task_id、task_status 和 url
  5690. $role['task_id'] = $global_role_task_id;
  5691. $role['task_status'] = $global_role_task_status;
  5692. $role['url'] = $global_role_url;
  5693. $roles_updated = true;
  5694. $url_inherited = true;
  5695. dLog('anime')->info("分集ID:{$episode_id} 角色:{$role_name} 继承全局数据");
  5696. break;
  5697. }
  5698. }
  5699. // 如果无法继承且没有任务ID,创建新任务
  5700. if (!$url_inherited && empty($role_task_id)) {
  5701. try {
  5702. $art_style = getProp($episode, 'art_style');
  5703. // 优先使用 pic_prompt,如果没有则使用 description
  5704. $description = !empty($role_pic_prompt) ? trim((string)$role_pic_prompt) : $role_description;
  5705. // if ($art_style) {
  5706. // // $description = "美术风格:\n{$art_style}\n主体描述:{$description}\n图片要求:图片侧重点是人物,不要出现场景或背景,并且只能生成一个人物";
  5707. // $description = "主体描述:{$description}\n图片要求:图片侧重点是人物,不要出现场景或背景,并且只能生成一个人物";
  5708. // }
  5709. $description = "{$character_prefix}。\n主体描述:{$description}\n超高清,高细节,主体突出,构图合理,画面干净,无场景或背景,单人物,无文字,无水印,无字幕,电影级光影,视觉焦点明确";
  5710. $params = [
  5711. 'prompt' => $description,
  5712. 'ref_img_urls' => [],
  5713. // 计费锚点(动漫/剧集/剧本),用于积分明细归属统计
  5714. 'anime_id' => $anime_id,
  5715. 'episode_id' => $episode_id,
  5716. 'episode_number' => getProp($episode, 'episode_number'),
  5717. ];
  5718. $task = $this->aiImageGenerationService->createImageGenerationTask($params);
  5719. $task_id = $task->id;
  5720. if ($task_id) {
  5721. $role['task_id'] = $task_id;
  5722. $role['task_status'] = 'processing';
  5723. $roles_updated = true;
  5724. dLog('anime')->info("分集ID:{$episode_id} 角色:{$role_name} 创建图片生成任务,任务ID:{$task_id}");
  5725. }
  5726. } catch (\Exception $e) {
  5727. dLog('anime')->error("分集ID:{$episode_id} 角色:{$role_name} 创建图片生成任务失败: " . $e->getMessage());
  5728. }
  5729. }
  5730. }
  5731. // 处理场景
  5732. foreach ($scenes as &$scene) {
  5733. $scene_name = getProp($scene, 'scene');
  5734. $scene_description = getProp($scene, 'description');
  5735. $scene_pic_prompt = getProp($scene, 'pic_prompt');
  5736. $scene_url = getProp($scene, 'url');
  5737. $scene_task_id = getProp($scene, 'task_id');
  5738. // 如果已有URL或已有任务ID,跳过
  5739. if (!empty($scene_url) || !empty($scene_task_id)) {
  5740. continue;
  5741. }
  5742. $url_inherited = false;
  5743. // 尝试从全局数据中继承
  5744. foreach ($global_scenes as $global_scene) {
  5745. $global_scene_name = getProp($global_scene, 'scene');
  5746. $global_scene_description = getProp($global_scene, 'description');
  5747. $global_scene_pic_prompt = getProp($global_scene, 'pic_prompt');
  5748. $global_scene_url = getProp($global_scene, 'url');
  5749. $global_scene_task_id = getProp($global_scene, 'task_id');
  5750. $global_scene_task_status = getProp($global_scene, 'task_status');
  5751. // 满足条件:场景名相同、描述相同、pic_prompt相同、全局有URL
  5752. if ($scene_name === $global_scene_name
  5753. && $scene_description === $global_scene_description
  5754. && $scene_pic_prompt === $global_scene_pic_prompt
  5755. && !empty($global_scene_url)) {
  5756. // 继承 task_id、task_status 和 url
  5757. $scene['task_id'] = $global_scene_task_id;
  5758. $scene['task_status'] = $global_scene_task_status;
  5759. $scene['url'] = $global_scene_url;
  5760. $scenes_updated = true;
  5761. $url_inherited = true;
  5762. dLog('anime')->info("分集ID:{$episode_id} 场景:{$scene_name} 继承全局数据");
  5763. break;
  5764. }
  5765. }
  5766. // 如果无法继承且没有任务ID,创建新任务
  5767. if (!$url_inherited && empty($scene_task_id)) {
  5768. try {
  5769. $art_style = getProp($episode, 'art_style');
  5770. // 优先使用 pic_prompt,如果没有则使用 description
  5771. $description = !empty($scene_pic_prompt) ? trim((string)$scene_pic_prompt) : $scene_description;
  5772. // if ($art_style) {
  5773. // // $description = "美术风格:\n{$art_style}\n场景描述:{$description}\n图片要求: 图片侧重点是场景,生成的是场景环境图片,不要出现人物(此为第一优先要求)";
  5774. // $description = "场景描述:{$description}\n图片要求: 图片侧重点是场景,生成的是场景环境图片,不要出现人物(此为第一优先要求)";
  5775. // }
  5776. $description = "{$scene_prefix}。\n场景描述:{$description}\n无人物,超高清,高细节,主体突出,构图合理,画面干净,无文字,无水印,无字幕,电影级光影,视觉焦点明确";
  5777. $params = [
  5778. 'prompt' => $description,
  5779. 'ref_img_urls' => [],
  5780. // 计费锚点(动漫/剧集/剧本),用于积分明细归属统计
  5781. 'anime_id' => $anime_id,
  5782. 'episode_id' => $episode_id,
  5783. 'episode_number' => getProp($episode, 'episode_number'),
  5784. ];
  5785. $task = $this->aiImageGenerationService->createImageGenerationTask($params);
  5786. $task_id = $task->id;
  5787. if ($task_id) {
  5788. $scene['task_id'] = $task_id;
  5789. $scene['task_status'] = 'processing';
  5790. $scenes_updated = true;
  5791. dLog('anime')->info("分集ID:{$episode_id} 场景:{$scene_name} 创建图片生成任务,任务ID:{$task_id}");
  5792. }
  5793. } catch (\Exception $e) {
  5794. dLog('anime')->error("分集ID:{$episode_id} 场景:{$scene_name} 创建图片生成任务失败: " . $e->getMessage());
  5795. }
  5796. }
  5797. }
  5798. // 如果有更新,保存到数据库
  5799. if ($roles_updated || $scenes_updated) {
  5800. $update_data = ['updated_at' => date('Y-m-d H:i:s')];
  5801. if ($roles_updated) {
  5802. $update_data['roles'] = json_encode($roles, JSON_UNESCAPED_UNICODE);
  5803. }
  5804. if ($scenes_updated) {
  5805. $update_data['scenes'] = json_encode($scenes, JSON_UNESCAPED_UNICODE);
  5806. }
  5807. DB::table('mp_anime_episodes')->where('id', $episode_id)->update($update_data);
  5808. dLog('anime')->info("分集ID:{$episode_id} 角色和场景数据已更新");
  5809. }
  5810. }
  5811. /**
  5812. * 根据图片URL使用AI反推图片提示词
  5813. *
  5814. * @param string $img_url 图片URL
  5815. * @return string 反推的提示词
  5816. */
  5817. private function generateImagePromptFromUrl($img_url) {
  5818. try {
  5819. // 获取默认模型
  5820. $model = 'doubao-seed-2-0-mini-260215';
  5821. // 构建messages参数
  5822. $messages = [
  5823. [
  5824. 'role' => 'user',
  5825. 'content' => [
  5826. [
  5827. 'type' => 'text',
  5828. 'text' => '请解析这张参考图,并直接输出一段专业中文反推提示词。提示词用于短剧分镜图片生成,必须聚焦角色和场景本身,可包含姿态、镜头视角、构图、画风、色彩氛围、光线、景深或光圈质感等要素。不要输出解释、标题、列表或无关背景,只输出可直接用于文生图的分镜图片提示词'
  5829. ],
  5830. [
  5831. 'type' => 'image_url',
  5832. 'image_url' => [
  5833. 'url' => $img_url
  5834. ]
  5835. ]
  5836. ]
  5837. ]
  5838. ];
  5839. // 构建请求参数
  5840. $params = [
  5841. 'model' => $model,
  5842. 'messages' => $messages,
  5843. 'stream' => false,
  5844. 'thinking' => ['type' => 'disabled'] // 不使用思考模式
  5845. ];
  5846. // 调用DeepSeek服务的volcEngineChatCompletion方法(非流式)
  5847. $result = $this->DeepSeekService->volcEngineChatCompletion($params);
  5848. // 仅记录 token 使用明细(不扣积分)
  5849. $uid = 0;
  5850. try {
  5851. $uid = (int)Site::getUid();
  5852. } catch (\Throwable $e) {
  5853. // 非请求上下文(如命令行)下可能无法获取用户ID,置为0跳过记录
  5854. }
  5855. $this->pointsService->recordTokenOnlyDetail(
  5856. $uid,
  5857. $this->pointsService->getTokensFromUsage($result['usage'] ?? []),
  5858. [
  5859. 'model' => $model,
  5860. 'img_url' => $img_url,
  5861. 'source' => 'generateImagePromptFromUrl',
  5862. ],
  5863. 'chat',
  5864. $model,
  5865. ''
  5866. );
  5867. // 返回生成的内容
  5868. return getProp($result, 'fullContent', '图片描述生成失败');
  5869. } catch (\Exception $e) {
  5870. dLog('anime')->error('AI反推图片提示词失败: ' . $e->getMessage(), [
  5871. 'img_url' => $img_url
  5872. ]);
  5873. logDB('anime', 'error', 'AI反推图片提示词失败', [
  5874. 'error' => $e->getMessage(),
  5875. 'img_url' => $img_url
  5876. ]);
  5877. return '图片描述生成失败: ' . $e->getMessage();
  5878. }
  5879. }
  5880. /**
  5881. * 音频试听接口
  5882. * 创建音频任务并轮询获取结果
  5883. *
  5884. * @param array $data 参数数组
  5885. * @return array 返回音频URL或错误信息
  5886. */
  5887. public function previewAudio($data) {
  5888. $dialogue = getProp($data, 'dialogue');
  5889. // 必填参数验证
  5890. if (!$dialogue) Utils::throwError('20003:dialogue不能为空');
  5891. // 获取参数,优先使用传入的参数,否则使用分镜中的参数
  5892. $voice_type = getProp($data, 'voice_type');
  5893. $voice_name = getProp($data, 'voice_name');
  5894. $voice_actor = getProp($data, 'voice_actor');
  5895. $emotion_type = getProp($data, 'emotion_type');
  5896. $gender = getProp($data, 'gender', 0);
  5897. $emotion = getProp($data, 'emotion');
  5898. $speed_ratio = getProp($data, 'speed_ratio', 0);
  5899. $loudness_ratio = getProp($data, 'loudness_ratio', 0);
  5900. $emotion_scale = getProp($data, 'emotion_scale', 0);
  5901. $pitch = getProp($data, 'pitch', 0);
  5902. try {
  5903. $now = date('Y-m-d H:i:s');
  5904. // 构建生成参数
  5905. $generate_json = json_encode([
  5906. 'text' => $dialogue,
  5907. 'role' => $voice_actor,
  5908. 'voice_type' => $voice_type,
  5909. 'voice_name' => $voice_name,
  5910. 'emotion' => $emotion,
  5911. 'emotion_type' => $emotion_type,
  5912. 'gender' => $gender,
  5913. 'speed_ratio' => $speed_ratio,
  5914. 'loudness_ratio' => $loudness_ratio,
  5915. 'emotion_scale' => $emotion_scale,
  5916. 'pitch' => $pitch,
  5917. ], 256);
  5918. // 请求远程服务器执行生成
  5919. $client = new Client(['timeout' => 600, 'verify' => false]);
  5920. $result = $client->get("http://122.9.129.83:5000/api/anime/audioPreview?generateJson={$generate_json}");
  5921. $response = $result->getBody()->getContents();
  5922. $response_arr = json_decode($response, true);
  5923. if (!isset($response_arr['code']) || (int)$response_arr['code'] !== 0) {
  5924. $error_msg = isset($response_arr['msg']) ? $response_arr['msg'] : '未知错误';
  5925. dLog('anime')->error('音频试听任务创建失败', ['error' => $error_msg, 'response_arr' => $response_arr]);
  5926. Utils::throwError('20003:音频试听任务创建失败: ' . $error_msg);
  5927. }
  5928. $arr = $response_arr['data'];
  5929. $subtitle_info = $arr['subtitle_info'];
  5930. $audio_duration = json_decode($subtitle_info, true)['duration'];
  5931. if (!isset($arr['url']) || !$audio_duration || !$subtitle_info) Utils::throwError('20003:音频参数生成异常');
  5932. return [
  5933. 'audio_url' => $arr['url'],
  5934. 'subtitle_info' => $subtitle_info,
  5935. 'audio_duration' => round($audio_duration, 2)
  5936. ];
  5937. } catch (\Exception $e) {
  5938. dLog('anime')->error('音频试听失败', ['error' => $e->getMessage()]);
  5939. Utils::throwError('20003:' . $e->getMessage());
  5940. }
  5941. }
  5942. /**
  5943. * 获取角色库列表(支持文件夹递归查询)
  5944. * @param array $data 包含 parent_id(父文件夹ID,默认0表示最外层)、role(搜索关键词)、is_public(筛选类型)
  5945. * @return array 返回当前目录下的所有子目录和角色列表(递归)
  5946. */
  5947. public function globalProducts($data) {
  5948. $uid = Site::getUid();
  5949. $cpid = Site::getCpid();
  5950. $role = Site::getRole();
  5951. $id = getProp($data, 'id', 0);
  5952. $parent_id = getProp($data, 'parent_id', 0);
  5953. $product_name = getProp($data, 'product_name');
  5954. $product = getProp($data, 'product'); // 1.角色 2.场景 3.道具
  5955. $is_public = getProp($data, 'public_type', 2); // 0=仅个人库 1=仅公共库 2=个人库+公共库
  5956. if (!$product) {
  5957. Utils::throwError('20003:请选择产品类型');
  5958. }
  5959. // 根据角色和is_public参数确定查询范围
  5960. // admin角色:获取所有个人库+公共库(忽略is_public参数)
  5961. // user角色:根据is_public参数筛选
  5962. $query_user_ids = [];
  5963. if ($role === 'admin') {
  5964. // admin获取所有个人库和公共库
  5965. $query_user_ids = [$uid, 0];
  5966. } else {
  5967. // user角色根据is_public参数筛选
  5968. if ($is_public == 2) {
  5969. // 个人库+公共库
  5970. $query_user_ids = [$uid, 0];
  5971. } elseif ($is_public == 0) {
  5972. // 仅个人库
  5973. $query_user_ids = [$uid];
  5974. } elseif ($is_public == 1) {
  5975. // 仅公共库
  5976. $query_user_ids = [0];
  5977. }
  5978. }
  5979. // 如果有搜索条件(product_name 或 id),按条件搜索文件夹和产品
  5980. if ($id || $product_name) {
  5981. $query = DB::table('mp_products')
  5982. ->where('cpid', $cpid)
  5983. ->whereIn('user_id', $query_user_ids)
  5984. ->where('is_deleted', 0);
  5985. // 如果指定了 id,按 id 精确查询
  5986. if ($id) {
  5987. $query->where('id', $id);
  5988. }
  5989. // 如果指定了 product_name,按名称模糊查询
  5990. if ($product_name) {
  5991. $query->where('product_name', 'like', "%{$product_name}%");
  5992. }
  5993. // 如果指定了 product,添加筛选条件
  5994. if ($product) {
  5995. $query->where('product', $product);
  5996. }
  5997. $result = $query->select('id', 'type', 'parent_id', 'level', 'product_name', 'url', 'pic_prompt', 'three_view_image_url', 'timbre_url', 'versions', 'product', 'user_id', 'created_at')
  5998. ->orderByRaw('type DESC, CASE WHEN user_id = '.$uid.' THEN 0 ELSE 1 END ASC, sort_order DESC, created_at DESC')
  5999. ->get()
  6000. ->map(function($value) {
  6001. $value = (array)$value;
  6002. $value['created_at'] = transDate($value['created_at'], 'Y-m-d');
  6003. $value['type'] = (int)$value['type'];
  6004. $value['parent_id'] = (int)$value['parent_id'];
  6005. $value['level'] = (int)$value['level'];
  6006. $value['product'] = (int)($value['product'] ?? 1);
  6007. $value['is_public'] = (int)$value['user_id'] === 0 ? 1 : 0;
  6008. $value['timbre_url'] = $value['timbre_url'] ?? '';
  6009. $value['versions'] = json_decode($value['versions'], true) ?: [];
  6010. unset($value['user_id']);
  6011. return $value;
  6012. })
  6013. ->toArray();
  6014. return $result;
  6015. }
  6016. // 递归获取所有子目录和角色
  6017. return $this->getChildrenRecursive($cpid, $parent_id, $product, $query_user_ids, $uid);
  6018. }
  6019. /**
  6020. * 递归获取指定目录下的所有子目录和角色
  6021. * @param int $cpid 公司ID
  6022. * @param int $parent_id 父目录ID
  6023. * @param int|null $product 产品类型筛选 1.角色 2.场景 3.道具
  6024. * @param array $query_user_ids 用户ID数组(支持多个)
  6025. * @param int $current_uid 当前用户ID(用于排序)
  6026. * @return array
  6027. */
  6028. private function getChildrenRecursive($cpid, $parent_id, $product = null, $query_user_ids = [], $current_uid = 0) {
  6029. // 查询当前层级的所有项(文件夹和角色)
  6030. $query = DB::table('mp_products')
  6031. ->where('cpid', $cpid)
  6032. ->where('is_deleted', 0)
  6033. ->where('parent_id', $parent_id);
  6034. // 添加用户ID验证(支持多个user_id)
  6035. if (!empty($query_user_ids)) {
  6036. $query->whereIn('user_id', $query_user_ids);
  6037. }
  6038. // 如果指定了 product,添加筛选条件(文件夹和角色都需要筛选)
  6039. if ($product) {
  6040. $query->where('product', $product);
  6041. }
  6042. // 排序规则:
  6043. // 1. 文件夹在前(type DESC)
  6044. // 2. 个人库在前,公共库在后(CASE WHEN user_id = current_uid)
  6045. // 3. 其他排序规则
  6046. $items = $query->select('id', 'type', 'parent_id', 'level', 'product_name', 'url', 'pic_prompt', 'three_view_image_url', 'timbre_url', 'versions', 'product', 'user_id', 'created_at')
  6047. ->orderByRaw('type DESC, CASE WHEN user_id = '.$current_uid.' THEN 0 ELSE 1 END ASC, sort_order DESC, created_at DESC')
  6048. ->get();
  6049. $result = [];
  6050. foreach ($items as $item) {
  6051. $itemArray = [
  6052. 'id' => $item->id,
  6053. 'type' => (int)$item->type,
  6054. 'parent_id' => (int)$item->parent_id,
  6055. 'level' => (int)$item->level,
  6056. 'product_name' => $item->product_name,
  6057. 'url' => $item->url,
  6058. 'pic_prompt' => $item->pic_prompt ?? '',
  6059. 'three_view_image_url' => $item->three_view_image_url,
  6060. 'timbre_url' => $item->timbre_url ?? '',
  6061. 'product' => (int)($item->product ?? 1),
  6062. 'is_public' => (int)$item->user_id === 0 ? 1 : 0,
  6063. 'created_at' => transDate($item->created_at, 'Y-m-d')
  6064. ];
  6065. $itemArray['versions'] = json_decode($item->versions, true) ?: [];
  6066. // 如果是文件夹,递归获取其子项
  6067. if ($item->type == 2) {
  6068. $children = $this->getChildrenRecursive($cpid, $item->id, $product, $query_user_ids, $current_uid);
  6069. if (!empty($children)) {
  6070. $itemArray['children'] = $children;
  6071. }
  6072. }
  6073. $result[] = $itemArray;
  6074. }
  6075. return $result;
  6076. }
  6077. /**
  6078. * 创建文件夹
  6079. * @param array $data 包含 parent_id(父文件夹ID)、product_name(文件夹名称)、product(产品类型)
  6080. * @return int 返回新建文件夹ID
  6081. */
  6082. public function createFolder($data) {
  6083. $uid = Site::getUid();
  6084. $cpid = Site::getCpid();
  6085. $role = Site::getRole();
  6086. $parent_id = getProp($data, 'parent_id', 0);
  6087. $folder_name = getProp($data, 'product_name', '新建文件夹');
  6088. $is_public = getProp($data, 'is_public', 0); // 0=个人资产库 1=公共资产库
  6089. // 如果是公共库操作,需要admin权限
  6090. if ($is_public && $role !== 'admin') {
  6091. Utils::throwError('20003:只有管理员才能操作公共资产库');
  6092. }
  6093. // 根据is_public参数确定存储的user_id(公共库user_id=0,cpid保持不变)
  6094. $store_uid = $is_public ? 0 : $uid;
  6095. // 获取 product 字段:1.角色 2.场景 3.道具,默认为1
  6096. $product = getProp($data, 'product');
  6097. if (!in_array($product, [1, 2, 3])) {
  6098. // Utils::throwError('20003:product 参数错误,只能是 1(角色)、2(场景) 或 3(道具)');
  6099. }
  6100. // 验证父文件夹
  6101. $parent_level = 0;
  6102. if ($parent_id > 0) {
  6103. $parent = DB::table('mp_products')
  6104. ->where('id', $parent_id)
  6105. ->where('cpid', $cpid)
  6106. ->where('user_id', $store_uid)
  6107. ->where('type', 2)
  6108. ->where('is_deleted', 0)
  6109. ->first();
  6110. if (!$parent) {
  6111. Utils::throwError('20003:父文件夹不存在');
  6112. }
  6113. // 检查父文件夹的 product 类型是否一致
  6114. if ($parent->product != $product) {
  6115. Utils::throwError('20003:文件夹类型必须与父文件夹一致');
  6116. }
  6117. $parent_level = $parent->level;
  6118. // 检查层级限制(最多3层)
  6119. if ($parent_level >= 3) {
  6120. Utils::throwError('20003:文件夹层级不能超过3层');
  6121. }
  6122. }
  6123. // 检查当前目录下是否已存在空白文件夹
  6124. $empty_folder_exists = DB::table('mp_products')
  6125. ->where('parent_id', $parent_id)
  6126. ->where('cpid', $cpid)
  6127. ->where('user_id', $store_uid)
  6128. ->where('type', 2)
  6129. ->where('product', $product)
  6130. ->where('product_name', '新建文件夹')
  6131. ->where('is_deleted', 0)
  6132. ->exists();
  6133. if ($empty_folder_exists && $folder_name == '新建文件夹') {
  6134. Utils::throwError('20003:不允许创建多个空白文件夹,请先重命名现有文件夹');
  6135. }
  6136. // 创建文件夹
  6137. $folder_id = DB::table('mp_products')->insertGetId([
  6138. 'user_id' => $store_uid,
  6139. 'cpid' => $cpid,
  6140. 'type' => 2,
  6141. 'parent_id' => $parent_id,
  6142. 'level' => $parent_level + 1,
  6143. 'product_name' => $folder_name,
  6144. 'product' => $product,
  6145. 'sort_order' => time(), // 使用时间戳作为排序权重
  6146. 'is_deleted' => 0,
  6147. 'created_at' => date('Y-m-d H:i:s'),
  6148. 'updated_at' => date('Y-m-d H:i:s')
  6149. ]);
  6150. return [
  6151. 'id' => $folder_id,
  6152. 'type' => 2,
  6153. 'parent_id' => $parent_id,
  6154. 'level' => $parent_level + 1,
  6155. 'product_name' => $folder_name,
  6156. 'product' => $product,
  6157. ];
  6158. }
  6159. /**
  6160. * 重命名文件夹或角色
  6161. * @param array $data 包含 id、product_name(新名称)
  6162. * @return bool
  6163. */
  6164. public function renameFolder($data) {
  6165. $uid = Site::getUid();
  6166. $cpid = Site::getCpid();
  6167. $role = Site::getRole();
  6168. $id = getProp($data, 'id');
  6169. $new_name = getProp($data, 'product_name');
  6170. $is_public = getProp($data, 'is_public', 0); // 0=个人资产库 1=公共资产库
  6171. if (!$id || !$new_name) {
  6172. Utils::throwError('20003:参数不完整');
  6173. }
  6174. // 根据is_public参数确定查询的user_id(公共库user_id=0,cpid保持不变)
  6175. $query_uid = $is_public ? 0 : $uid;
  6176. // 如果是公共库操作,需要admin权限
  6177. if ($is_public && $role !== 'admin') {
  6178. Utils::throwError('20003:只有管理员才能操作公共资产库');
  6179. }
  6180. // 检查是否存在
  6181. $item = DB::table('mp_products')
  6182. ->where('id', $id)
  6183. ->where('cpid', $cpid)
  6184. ->where('user_id', $query_uid)
  6185. ->where('is_deleted', 0)
  6186. ->first();
  6187. if (!$item) {
  6188. Utils::throwError('20003:项目不存在');
  6189. }
  6190. return DB::table('mp_products')
  6191. ->where('id', $id)
  6192. ->where('cpid', $cpid)
  6193. ->where('user_id', $query_uid)
  6194. ->update([
  6195. 'product_name' => $new_name,
  6196. 'updated_at' => date('Y-m-d H:i:s')
  6197. ]);
  6198. }
  6199. /**
  6200. * 移动角色或文件夹到指定文件夹
  6201. * @param array $data 包含 id(要移动的项目ID)、target_parent_id(目标父文件夹ID)
  6202. * @return bool
  6203. */
  6204. public function moveProductOrFolder($data) {
  6205. $uid = Site::getUid();
  6206. $cpid = Site::getCpid();
  6207. $role = Site::getRole();
  6208. $id = getProp($data, 'id');
  6209. $target_parent_id = getProp($data, 'target_parent_id', 0);
  6210. $is_public = getProp($data, 'is_public', 0); // 0=个人资产库 1=公共资产库
  6211. if (!$id) {
  6212. Utils::throwError('20003:请选择要移动的项目');
  6213. }
  6214. // 根据is_public参数确定查询的user_id(公共库user_id=0,cpid保持不变)
  6215. $query_uid = $is_public ? 0 : $uid;
  6216. // 如果是公共库操作,需要admin权限
  6217. if ($is_public && $role !== 'admin') {
  6218. Utils::throwError('20003:只有管理员才能操作公共资产库');
  6219. }
  6220. // 检查要移动的项目
  6221. $item = DB::table('mp_products')
  6222. ->where('id', $id)
  6223. ->where('cpid', $cpid)
  6224. ->where('user_id', $query_uid)
  6225. ->where('is_deleted', 0)
  6226. ->first();
  6227. if (!$item) {
  6228. Utils::throwError('20003:项目不存在');
  6229. }
  6230. // 验证目标文件夹
  6231. $target_level = 0;
  6232. $target_product = $item->product; // 默认使用当前项目的 product
  6233. if ($target_parent_id > 0) {
  6234. $target_parent = DB::table('mp_products')
  6235. ->where('id', $target_parent_id)
  6236. ->where('cpid', $cpid)
  6237. ->where('user_id', $query_uid)
  6238. ->where('type', 2)
  6239. ->where('is_deleted', 0)
  6240. ->first();
  6241. if (!$target_parent) {
  6242. Utils::throwError('20003:目标文件夹不存在');
  6243. }
  6244. // 检查 product 类型是否一致
  6245. if ($target_parent->product != $item->product) {
  6246. Utils::throwError('20003:不能移动到不同类型的文件夹下');
  6247. }
  6248. $target_level = $target_parent->level;
  6249. $target_product = $target_parent->product;
  6250. // 如果移动的是文件夹,需要检查层级
  6251. if ($item->type == 2) {
  6252. // 计算移动后的最大层级
  6253. $max_child_level = $this->getMaxChildLevel($id);
  6254. $depth = $max_child_level - $item->level;
  6255. if ($target_level + 1 + $depth > 3) {
  6256. Utils::throwError('20003:移动后文件夹层级将超过3层限制');
  6257. }
  6258. // 不能移动到自己或自己的子文件夹下
  6259. if ($this->isDescendant($target_parent_id, $id)) {
  6260. Utils::throwError('20003:不能移动到自己或子文件夹下');
  6261. }
  6262. }
  6263. }
  6264. // 更新父文件夹和层级
  6265. $new_level = $target_level + 1;
  6266. DB::table('mp_products')
  6267. ->where('id', $id)
  6268. ->update([
  6269. 'parent_id' => $target_parent_id,
  6270. 'level' => $new_level,
  6271. 'updated_at' => date('Y-m-d H:i:s')
  6272. ]);
  6273. // 如果是文件夹,需要递归更新所有子项的层级
  6274. if ($item->type == 2) {
  6275. $this->updateChildrenLevel($id, $new_level);
  6276. }
  6277. return true;
  6278. }
  6279. /**
  6280. * 获取文件夹下最大子层级
  6281. * @param int $folder_id
  6282. * @return int
  6283. */
  6284. private function getMaxChildLevel($folder_id) {
  6285. $max_level = DB::table('mp_products')
  6286. ->where('parent_id', $folder_id)
  6287. ->where('is_deleted', 0)
  6288. ->max('level');
  6289. if (!$max_level) {
  6290. return DB::table('mp_products')->where('id', $folder_id)->value('level');
  6291. }
  6292. // 递归查找子文件夹
  6293. $children = DB::table('mp_products')
  6294. ->where('parent_id', $folder_id)
  6295. ->where('type', 2)
  6296. ->where('is_deleted', 0)
  6297. ->pluck('id');
  6298. foreach ($children as $child_id) {
  6299. $child_max = $this->getMaxChildLevel($child_id);
  6300. if ($child_max > $max_level) {
  6301. $max_level = $child_max;
  6302. }
  6303. }
  6304. return $max_level;
  6305. }
  6306. /**
  6307. * 检查 target_id 是否是 folder_id 的后代
  6308. * @param int $target_id
  6309. * @param int $folder_id
  6310. * @return bool
  6311. */
  6312. private function isDescendant($target_id, $folder_id) {
  6313. if ($target_id == $folder_id) {
  6314. return true;
  6315. }
  6316. $parent = DB::table('mp_products')
  6317. ->where('id', $target_id)
  6318. ->where('is_deleted', 0)
  6319. ->first();
  6320. if (!$parent || $parent->parent_id == 0) {
  6321. return false;
  6322. }
  6323. return $this->isDescendant($parent->parent_id, $folder_id);
  6324. }
  6325. /**
  6326. * 递归更新子项层级
  6327. * @param int $parent_id
  6328. * @param int $parent_level
  6329. */
  6330. private function updateChildrenLevel($parent_id, $parent_level) {
  6331. $children = DB::table('mp_products')
  6332. ->where('parent_id', $parent_id)
  6333. ->where('is_deleted', 0)
  6334. ->get();
  6335. foreach ($children as $child) {
  6336. $new_level = $parent_level + 1;
  6337. DB::table('mp_products')
  6338. ->where('id', $child->id)
  6339. ->update([
  6340. 'level' => $new_level,
  6341. 'updated_at' => date('Y-m-d H:i:s')
  6342. ]);
  6343. // 如果是文件夹,继续递归
  6344. if ($child->type == 2) {
  6345. $this->updateChildrenLevel($child->id, $new_level);
  6346. }
  6347. }
  6348. }
  6349. /**
  6350. * 获取文件夹路径(面包屑导航)
  6351. * @param array $data 包含 folder_id
  6352. * @return array 返回路径数组
  6353. */
  6354. public function getFolderPath($data) {
  6355. $uid = Site::getUid();
  6356. $cpid = Site::getCpid();
  6357. $folder_id = getProp($data, 'id', 0);
  6358. $is_public = getProp($data, 'is_public', 0); // 0=个人资产库 1=公共资产库
  6359. if ($folder_id == 0) {
  6360. return [
  6361. ['id' => 0, 'name' => '根目录']
  6362. ];
  6363. }
  6364. // 根据is_public参数确定查询的user_id(公共库user_id=0,cpid保持不变)
  6365. $query_uid = $is_public ? 0 : $uid;
  6366. $path = [];
  6367. $current_id = $folder_id;
  6368. while ($current_id > 0) {
  6369. $folder = DB::table('mp_products')
  6370. ->where('id', $current_id)
  6371. ->where('cpid', $cpid)
  6372. ->where('user_id', $query_uid)
  6373. ->where('type', 2)
  6374. ->where('is_deleted', 0)
  6375. ->first();
  6376. if (!$folder) {
  6377. break;
  6378. }
  6379. array_unshift($path, [
  6380. 'id' => $folder->id,
  6381. 'name' => $folder->product_name
  6382. ]);
  6383. $current_id = $folder->parent_id;
  6384. }
  6385. // 添加根目录
  6386. array_unshift($path, ['id' => 0, 'name' => '根目录']);
  6387. return $path;
  6388. }
  6389. public function createProduct($data) {
  6390. $uid = Site::getUid();
  6391. $cpid = Site::getCpid();
  6392. $role = Site::getRole();
  6393. $is_public = getProp($data, 'is_public', 0); // 0=个人资产库 1=公共资产库
  6394. // 如果是公共库操作,需要admin权限
  6395. if ($is_public && $role !== 'admin') {
  6396. Utils::throwError('20003:只有管理员才能操作公共资产库');
  6397. }
  6398. // 根据is_public参数确定存储的user_id(公共库user_id=0,cpid保持不变)
  6399. $store_uid = $is_public ? 0 : $uid;
  6400. // 新增参数:剧本ID和剧集序号(支持数组传参,多个序号也可用英文逗号隔开)
  6401. $script_id = (int)getProp($data, 'script_id', 0);
  6402. $episode_numbers = $this->normalizeEpisodeNumbers(getProp($data, 'episode_number', []));
  6403. if ($script_id && empty($episode_numbers)) {
  6404. Utils::throwError('20003:剧集序号不能为空');
  6405. }
  6406. if (!$script_id && !empty($episode_numbers)) {
  6407. Utils::throwError('20003:请提供剧本ID');
  6408. }
  6409. $product_name = trim(getProp($data, 'product_name'));
  6410. if (!$product_name) Utils::throwError('20003:名称不能为空');
  6411. $product_name = preg_replace('/^[\s*\[\]【】[]{}{}\x{3000}]+|[\s*\[\]【】[]{}{}\x{3000}]+$/u', '', $product_name);
  6412. // $exists_id = DB::table('mp_products')->where('cpid', $cpid)->where('type', 1)->where('product_name', $product_name)->where('is_deleted', 0)->value('id');
  6413. // if ($exists_id) Utils::throwError('20003:名称不能重复,请修改');
  6414. $url = trim(getProp($data, 'url'));
  6415. if (!$url) Utils::throwError('20003:图片地址不能为空');
  6416. $versions = getProp($data, 'versions');
  6417. // 检查是否是正确的图片格式
  6418. $allowedExtensions = ['jpg', 'jpeg', 'png', 'gif', 'webp', 'bmp'];
  6419. $urlPath = parse_url($url, PHP_URL_PATH);
  6420. $extension = strtolower(pathinfo($urlPath, PATHINFO_EXTENSION));
  6421. if (!in_array($extension, $allowedExtensions)) {
  6422. Utils::throwError('20003:图片格式不正确,仅支持 jpg、jpeg、png、gif、webp、bmp 格式');
  6423. }
  6424. // 选填三视图图片地址,格式校验与 url 一致
  6425. $three_view_image_url = trim(getProp($data, 'three_view_image_url', ''));
  6426. if ($three_view_image_url) {
  6427. $threeViewPath = parse_url($three_view_image_url, PHP_URL_PATH);
  6428. $threeViewExtension = strtolower(pathinfo($threeViewPath, PATHINFO_EXTENSION));
  6429. if (!in_array($threeViewExtension, $allowedExtensions)) {
  6430. Utils::throwError('20003:三视图图片格式不正确,仅支持 jpg、jpeg、png、gif、webp、bmp 格式');
  6431. }
  6432. }
  6433. // 选填音色音频地址(兼容 timbre_url/audio_url/timbre 传参)
  6434. $timbre_url = $this->getProductTimbreUrl($data);
  6435. if ($timbre_url) {
  6436. $this->validateProductAudioUrl($timbre_url);
  6437. }
  6438. $pic_prompt = trim(getProp($data, 'pic_prompt'));
  6439. if (!$pic_prompt) Utils::throwError('20003:提示词不能为空');
  6440. // 获取 product 字段:1.角色 2.场景 3.道具,默认为1
  6441. $product = getProp($data, 'product');
  6442. if (!in_array($product, [1, 2, 3])) {
  6443. // Utils::throwError('20003:产品类型只能是 1(角色)、2(场景) 或 3(道具)');
  6444. }
  6445. // 获取父文件夹ID和层级
  6446. $parent_id = getProp($data, 'parent_id', 0);
  6447. $parent_level = 0;
  6448. if ($parent_id > 0) {
  6449. $parent = DB::table('mp_products')
  6450. ->where('id', $parent_id)
  6451. ->where('cpid', $cpid)
  6452. ->where('user_id', $store_uid)
  6453. ->where('type', 2)
  6454. ->where('is_deleted', 0)
  6455. ->first();
  6456. if (!$parent) {
  6457. Utils::throwError('20003:父文件夹不存在');
  6458. }
  6459. $parent_level = $parent->level;
  6460. }
  6461. // 创建资产并保存剧本资产关联关系(同一事务)
  6462. DB::beginTransaction();
  6463. try {
  6464. $id = DB::table('mp_products')->insertGetId([
  6465. 'user_id' => $store_uid,
  6466. 'cpid' => $cpid,
  6467. 'type' => 1, // 1=角色图片
  6468. 'parent_id' => $parent_id,
  6469. 'level' => $parent_level + 1,
  6470. 'product_name' => $product_name,
  6471. 'url' => $url,
  6472. 'three_view_image_url' => $three_view_image_url,
  6473. 'timbre_url' => $timbre_url,
  6474. 'pic_prompt' => $pic_prompt,
  6475. 'product' => $product,
  6476. 'versions' => json_encode($versions, 256),
  6477. 'sort_order' => time(), // 使用时间戳作为排序权重
  6478. 'created_at' => date('Y-m-d H:i:s'),
  6479. 'updated_at' => date('Y-m-d H:i:s')
  6480. ]);
  6481. if (!$id) Utils::throwError('20003:创建失败');
  6482. // 保存剧本资产关联关系
  6483. if ($script_id) {
  6484. $this->saveProductScriptMapping($id, $script_id, $episode_numbers);
  6485. }
  6486. DB::commit();
  6487. } catch (\Exception $e) {
  6488. DB::rollback();
  6489. throw $e;
  6490. }
  6491. return [
  6492. 'id' => $id,
  6493. 'type' => 1,
  6494. 'parent_id' => $parent_id,
  6495. 'level' => $parent_level + 1,
  6496. 'product_name' => $product_name,
  6497. 'url' => $url,
  6498. 'three_view_image_url' => $three_view_image_url,
  6499. 'timbre_url' => $timbre_url,
  6500. 'pic_prompt' => $pic_prompt,
  6501. 'product' => $product,
  6502. 'versions' => $versions
  6503. ];
  6504. }
  6505. public function editProduct($data) {
  6506. $uid = Site::getUid();
  6507. $cpid = Site::getCpid();
  6508. $role = Site::getRole();
  6509. $id = getProp($data, 'id');
  6510. if (!$id) Utils::throwError('20003:ID不能为空');
  6511. $versions = getProp($data, 'versions');
  6512. $is_public = getProp($data, 'is_public', 0); // 0=个人资产库 1=公共资产库
  6513. // 新增参数:剧本ID和剧集序号(支持数组传参,多个序号也可用英文逗号隔开)
  6514. $script_id = (int)getProp($data, 'script_id', 0);
  6515. $episode_numbers = $this->normalizeEpisodeNumbers(getProp($data, 'episode_number', []));
  6516. if ($script_id && empty($episode_numbers)) {
  6517. Utils::throwError('20003:剧集序号不能为空');
  6518. }
  6519. if (!$script_id && !empty($episode_numbers)) {
  6520. Utils::throwError('20003:请提供剧本ID');
  6521. }
  6522. // 根据is_public参数确定查询的user_id(公共库user_id=0,cpid保持不变)
  6523. $query_uid = $is_public ? 0 : $uid;
  6524. // 如果是公共库操作,需要admin权限
  6525. if ($is_public && $role !== 'admin') {
  6526. Utils::throwError('20003:只有管理员才能操作公共资产库');
  6527. }
  6528. // 检查是否存在且属于当前用户或公共库
  6529. $role = DB::table('mp_products')
  6530. ->where('id', $id)
  6531. ->where('cpid', $cpid)
  6532. ->where('user_id', $query_uid)
  6533. ->where('type', 1)->first();
  6534. if (!$role) Utils::throwError('20003:记录不存在');
  6535. $updateData = [];
  6536. // $needVersionRecord = false; // 是否需要记录版本
  6537. // 名称
  6538. $product_name = trim(getProp($data, 'product_name'));
  6539. if ($product_name) {
  6540. $product_name = preg_replace('/^[\s*\[\]【】[]{}{}\x{3000}]+|[\s*\[\]【】[]{}{}\x{3000}]+$/u', '', $product_name);
  6541. $updateData['product_name'] = $product_name;
  6542. }
  6543. // $exists_id = DB::table('mp_products')->where('cpid', $cpid)->where('type', 1)->where('product_name', $product_name)->where('is_deleted', 0)->value('id');
  6544. // if ($exists_id && $exists_id != $id) Utils::throwError('20003:名称不能重复,请修改');
  6545. // 图片地址
  6546. $allowedExtensions = ['jpg', 'jpeg', 'png', 'gif', 'webp', 'bmp'];
  6547. $url = trim(getProp($data, 'url'));
  6548. if ($url) {
  6549. // 检查是否是正确的图片格式
  6550. $urlPath = parse_url($url, PHP_URL_PATH);
  6551. $extension = strtolower(pathinfo($urlPath, PATHINFO_EXTENSION));
  6552. if (!in_array($extension, $allowedExtensions)) {
  6553. Utils::throwError('20003:图片格式不正确,仅支持 jpg、jpeg、png、gif、webp、bmp 格式');
  6554. }
  6555. // // 如果 url 有变更,记录版本
  6556. // if ($url !== $role->url) {
  6557. // $needVersionRecord = true;
  6558. // }
  6559. $updateData['url'] = $url;
  6560. }
  6561. // 三视图图片地址(选填),格式校验与 url 一致;显式传空表示当前版本没有三视图
  6562. $three_view_image_url = trim(getProp($data, 'three_view_image_url', ''));
  6563. if ($three_view_image_url) {
  6564. $threeViewPath = parse_url($three_view_image_url, PHP_URL_PATH);
  6565. $threeViewExtension = strtolower(pathinfo($threeViewPath, PATHINFO_EXTENSION));
  6566. if (!in_array($threeViewExtension, $allowedExtensions)) {
  6567. Utils::throwError('20003:三视图图片格式不正确,仅支持 jpg、jpeg、png、gif、webp、bmp 格式');
  6568. }
  6569. }
  6570. // 显式传入三视图(含空值)时同步写入,空值表示当前版本没有三视图
  6571. if (array_key_exists('three_view_image_url', $data)) {
  6572. $updateData['three_view_image_url'] = $three_view_image_url;
  6573. }
  6574. // 音色音频地址(选填,显式传空字符串可清除已有音色)
  6575. if (array_key_exists('timbre_url', $data) || array_key_exists('audio_url', $data) || array_key_exists('timbre', $data)) {
  6576. $timbre_url = $this->getProductTimbreUrl($data);
  6577. if ($timbre_url) {
  6578. $this->validateProductAudioUrl($timbre_url);
  6579. }
  6580. $updateData['timbre_url'] = $timbre_url;
  6581. }
  6582. // 提示词
  6583. $pic_prompt = trim(getProp($data, 'pic_prompt'));
  6584. if ($pic_prompt) {
  6585. // // 如果 pic_prompt 有变更,记录版本
  6586. // if ($pic_prompt !== $role->pic_prompt) {
  6587. // $needVersionRecord = true;
  6588. // }
  6589. $updateData['pic_prompt'] = $pic_prompt;
  6590. }else {
  6591. Utils::throwError('20003:请输入提示词');
  6592. }
  6593. if (empty($updateData) && !$script_id) {
  6594. Utils::throwError('20003:没有需要更新的数据');
  6595. }
  6596. // // 如果需要记录版本,将数据添加到 versions 数组
  6597. // if ($needVersionRecord) {
  6598. // // 获取现有的 versions 数据
  6599. // $versions = json_decode($role->versions, true) ?: [];
  6600. // $isFirstVersion = empty($versions); // 判断是否是第一次记录版本
  6601. // // 如果是第一次记录版本,先添加旧版本(变更前)
  6602. // if ($isFirstVersion) {
  6603. // $oldVersion = [
  6604. // 'url' => $role->url,
  6605. // 'description' => $role->pic_prompt,
  6606. // ];
  6607. // // 旧版本添加到数组末尾
  6608. // $versions[] = $oldVersion;
  6609. // }
  6610. // // 构建新版本(变更后)
  6611. // $newVersion = [
  6612. // 'url' => isset($updateData['url']) ? $updateData['url'] : $role->url,
  6613. // 'description' => isset($updateData['pic_prompt']) ? $updateData['pic_prompt'] : $role->pic_prompt,
  6614. // ];
  6615. // // 检查新版本是否已存在于历史版本中
  6616. // $existingIndex = -1;
  6617. // foreach ($versions as $index => $version) {
  6618. // if ($version['url'] === $newVersion['url'] && $version['description'] === $newVersion['description']) {
  6619. // $existingIndex = $index;
  6620. // break;
  6621. // }
  6622. // }
  6623. // if ($existingIndex !== -1) {
  6624. // // 如果已存在,移除旧的位置
  6625. // array_splice($versions, $existingIndex, 1);
  6626. // }
  6627. // // 新版本添加到数组开头(最新的在前)
  6628. // array_unshift($versions, $newVersion);
  6629. // // // 限制版本数量(可选,例如只保留最近10个版本)
  6630. // // if (count($versions) > 10) {
  6631. // // $versions = array_slice($versions, 0, 10);
  6632. // // }
  6633. // $updateData['versions'] = json_encode($versions, 256);
  6634. // }
  6635. if ($versions) {
  6636. $updateData['versions'] = json_encode($versions, 256);
  6637. }
  6638. if (!empty($updateData)) {
  6639. $updateData['updated_at'] = date('Y-m-d H:i:s');
  6640. }
  6641. // 更新资产并保存剧本资产关联关系(同一事务)
  6642. DB::beginTransaction();
  6643. try {
  6644. $updated = true;
  6645. if (!empty($updateData)) {
  6646. $updated = DB::table('mp_products')
  6647. ->where('cpid', $cpid)
  6648. ->where('id', $id)
  6649. ->update($updateData);
  6650. }
  6651. // 保存剧本资产关联关系
  6652. if ($script_id) {
  6653. $this->saveProductScriptMapping($id, $script_id, $episode_numbers);
  6654. }
  6655. DB::commit();
  6656. } catch (\Exception $e) {
  6657. DB::rollback();
  6658. throw $e;
  6659. }
  6660. return $updated;
  6661. }
  6662. /**
  6663. * 获取资产音色音频地址
  6664. * 兼容 timbre_url/audio_url/timbre 三种传参,timbre 支持字符串或 {"url":"..."} 结构
  6665. *
  6666. * @param array $data
  6667. * @return string
  6668. */
  6669. private function getProductTimbreUrl($data) {
  6670. foreach (['timbre_url', 'audio_url', 'timbre'] as $key) {
  6671. if (!array_key_exists($key, $data)) {
  6672. continue;
  6673. }
  6674. $value = $data[$key];
  6675. if (is_array($value)) {
  6676. $value = getProp($value, 'url', $value[0] ?? '');
  6677. }
  6678. if (!is_string($value)) {
  6679. continue;
  6680. }
  6681. return trim($value);
  6682. }
  6683. return '';
  6684. }
  6685. /**
  6686. * 校验资产音色音频地址格式
  6687. *
  6688. * @param string $url 音频地址
  6689. * @return void
  6690. */
  6691. private function validateProductAudioUrl($url) {
  6692. $allowedExtensions = ['mp3', 'wav', 'm4a', 'aac', 'ogg', 'oga', 'flac', 'amr', 'wma', 'weba'];
  6693. $urlPath = parse_url($url, PHP_URL_PATH);
  6694. $extension = strtolower(pathinfo($urlPath, PATHINFO_EXTENSION));
  6695. if (!in_array($extension, $allowedExtensions)) {
  6696. Utils::throwError('20003:音色音频格式不正确,仅支持 mp3、wav、m4a、aac、ogg、flac、amr、wma 格式');
  6697. }
  6698. }
  6699. /**
  6700. * 保存单一资产与剧本剧集的关联关系
  6701. *
  6702. * @param int $product_id 资产ID
  6703. * @param int $script_id 剧本ID
  6704. * @param array $episode_numbers 剧集序号数组(序号从1开始)
  6705. * @return int 新增关联数量
  6706. */
  6707. private function saveProductScriptMapping($product_id, $script_id, $episode_numbers) {
  6708. $uid = Site::getUid();
  6709. // 验证剧本是否存在
  6710. $script = DB::table('mp_scripts')
  6711. ->where('id', $script_id)
  6712. ->where('is_deleted', 0)
  6713. ->first();
  6714. if (!$script) {
  6715. Utils::throwError('20003:剧本不存在');
  6716. }
  6717. // 验证剧本归属:只能关联自己的剧本
  6718. if ((int)$script->user_id !== (int)$uid) {
  6719. Utils::throwError('20003:只能添加到自己的剧本');
  6720. }
  6721. // 使用 splitContent 拆分剧本内容获取总集数
  6722. $totalEpisodes = $this->getScriptTotalEpisodeCount($script);
  6723. // 解析剧集序号(数组)
  6724. $episodes = [];
  6725. foreach ($episode_numbers as $item) {
  6726. if (is_array($item)) {
  6727. continue;
  6728. }
  6729. $item = trim((string)$item);
  6730. if ($item === '' || !is_numeric($item)) {
  6731. Utils::throwError('20003:剧集序号格式不正确,仅支持数字数组或英文逗号分隔的数字');
  6732. }
  6733. $episodes[] = (int)$item;
  6734. }
  6735. // 去重并校验序号范围(序号从1开始)
  6736. $episodes = array_values(array_unique($episodes));
  6737. if (empty($episodes)) {
  6738. Utils::throwError('20003:剧集序号不能为空');
  6739. }
  6740. foreach ($episodes as $episode) {
  6741. if ($episode < 1 || $episode > $totalEpisodes) {
  6742. Utils::throwError('20003:剧集序号 ' . $episode . ' 超出范围,剧本共 ' . $totalEpisodes . ' 集(序号从1开始)');
  6743. }
  6744. }
  6745. $now = now();
  6746. // 过滤已存在的关联,避免重复
  6747. $existingEpisodes = DB::table('mp_script_product_mappings')
  6748. ->where('script_id', $script_id)
  6749. ->where('product_id', $product_id)
  6750. ->whereIn('episode_number', $episodes)
  6751. ->pluck('episode_number')
  6752. ->all();
  6753. $mappingRecords = [];
  6754. foreach ($episodes as $episode) {
  6755. if (in_array($episode, $existingEpisodes)) {
  6756. continue;
  6757. }
  6758. $mappingRecords[] = [
  6759. 'script_id' => $script_id,
  6760. 'product_id' => $product_id,
  6761. 'episode_number' => $episode,
  6762. 'created_at' => $now,
  6763. 'updated_at' => $now,
  6764. ];
  6765. }
  6766. $insertedCount = 0;
  6767. if (!empty($mappingRecords)) {
  6768. $insertedCount = DB::table('mp_script_product_mappings')->insert($mappingRecords) ? count($mappingRecords) : 0;
  6769. }
  6770. return $insertedCount;
  6771. }
  6772. /**
  6773. * 规范化剧集序号参数,统一为数组
  6774. * 兼容传入数组(如 [1, 3, 5])、逗号分隔字符串(如 "1,3,5")以及字符串数组(如 ["1,3", 5])
  6775. *
  6776. * @param mixed $episode_number 剧集序号参数
  6777. * @return array
  6778. */
  6779. private function normalizeEpisodeNumbers($episode_number) {
  6780. if (!is_array($episode_number)) {
  6781. $episode_number = explode(',', (string)$episode_number);
  6782. }
  6783. $items = [];
  6784. foreach ($episode_number as $item) {
  6785. if (is_array($item)) {
  6786. continue;
  6787. }
  6788. foreach (explode(',', (string)$item) as $part) {
  6789. $part = trim($part);
  6790. if ($part !== '') {
  6791. $items[] = $part;
  6792. }
  6793. }
  6794. }
  6795. return $items;
  6796. }
  6797. /**
  6798. * 获取剧本总集数(通过 splitContent 拆分剧本内容)
  6799. *
  6800. * @param object $script 剧本记录
  6801. * @return int 总集数
  6802. */
  6803. private function getScriptTotalEpisodeCount($script) {
  6804. if (empty($script->content)) {
  6805. Utils::throwError('20003:剧本内容为空,无法确定剧集数量');
  6806. }
  6807. $totalEpisodes = count(splitContent($script->content));
  6808. if ($totalEpisodes < 1) {
  6809. Utils::throwError('20003:剧本内容无法拆分出剧集');
  6810. }
  6811. return $totalEpisodes;
  6812. }
  6813. /**
  6814. * 获取剧本总集数
  6815. *
  6816. * @param array $data 包含 script_id(剧本ID)
  6817. * @return array
  6818. */
  6819. public function getScriptTotalEpisodes($data) {
  6820. $script_id = (int)getProp($data, 'script_id', 0);
  6821. if (!$script_id) {
  6822. Utils::throwError('20003:请提供剧本ID');
  6823. }
  6824. // 验证剧本是否存在
  6825. $script = DB::table('mp_scripts')
  6826. ->where('id', $script_id)
  6827. ->where('is_deleted', 0)
  6828. ->first();
  6829. if (!$script) {
  6830. Utils::throwError('20003:剧本不存在');
  6831. }
  6832. return [
  6833. 'script_id' => $script_id,
  6834. 'script_name' => $script->script_name ?? 'script_' . $script_id,
  6835. 'episode_num' => $this->getScriptTotalEpisodeCount($script),
  6836. ];
  6837. }
  6838. /**
  6839. * 获取角色版本历史
  6840. * @param array $data 包含 id(角色ID)
  6841. * @return array 返回版本历史列表
  6842. */
  6843. public function getProductVersions($data) {
  6844. $cpid = Site::getCpid();
  6845. $id = getProp($data, 'id');
  6846. if (!$id) Utils::throwError('20003:角色ID不能为空');
  6847. $role = DB::table('mp_products')
  6848. ->where('id', $id)
  6849. ->where('cpid', $cpid)
  6850. ->where('type', 1)
  6851. ->first();
  6852. if (!$role) Utils::throwError('20003:角色不存在');
  6853. // 获取版本历史
  6854. $versions = json_decode($role->versions, true) ?: [];
  6855. // 添加当前版本作为最新版本
  6856. $currentVersion = [
  6857. 'version' => 0, // 0 表示当前版本
  6858. 'url' => $role->url,
  6859. 'pic_prompt' => $role->pic_prompt,
  6860. 'updated_at' => $role->updated_at,
  6861. 'is_current' => true
  6862. ];
  6863. array_unshift($versions, $currentVersion);
  6864. return $versions;
  6865. }
  6866. /**
  6867. * 恢复到指定版本
  6868. * @param array $data 包含 id(角色ID)、version(版本号)
  6869. * @return bool
  6870. */
  6871. public function restoreProductVersion($data) {
  6872. $uid = Site::getUid();
  6873. $cpid = Site::getCpid();
  6874. $id = getProp($data, 'id');
  6875. $version = getProp($data, 'version');
  6876. if (!$id) Utils::throwError('20003:角色ID不能为空');
  6877. if (!$version) Utils::throwError('20003:版本号不能为空');
  6878. $role = DB::table('mp_products')
  6879. ->where('id', $id)
  6880. ->where('cpid', $cpid)
  6881. ->where('type', 1)
  6882. ->first();
  6883. if (!$role) Utils::throwError('20003:角色不存在');
  6884. // 获取版本历史
  6885. $versions = json_decode($role->versions, true) ?: [];
  6886. // 查找指定版本
  6887. $targetVersion = null;
  6888. foreach ($versions as $v) {
  6889. if ($v['version'] == $version) {
  6890. $targetVersion = $v;
  6891. break;
  6892. }
  6893. }
  6894. if (!$targetVersion) Utils::throwError('20003:版本不存在');
  6895. // 先将当前版本保存到历史
  6896. $newVersion = [
  6897. 'version' => count($versions) + 1,
  6898. 'url' => $role->url,
  6899. 'pic_prompt' => $role->pic_prompt,
  6900. 'updated_at' => date('Y-m-d H:i:s'),
  6901. 'updated_by' => $uid
  6902. ];
  6903. array_unshift($versions, $newVersion);
  6904. // 限制版本数量
  6905. if (count($versions) > 10) {
  6906. $versions = array_slice($versions, 0, 10);
  6907. }
  6908. // 恢复到指定版本
  6909. return DB::table('mp_products')
  6910. ->where('id', $id)
  6911. ->where('cpid', $cpid)
  6912. ->update([
  6913. 'url' => $targetVersion['url'],
  6914. 'pic_prompt' => $targetVersion['pic_prompt'],
  6915. 'versions' => json_encode($versions, JSON_UNESCAPED_UNICODE),
  6916. 'updated_at' => date('Y-m-d H:i:s')
  6917. ]);
  6918. }
  6919. public function deleteProduct($data) {
  6920. $uid = Site::getUid();
  6921. $cpid = Site::getCpid();
  6922. $role = Site::getRole();
  6923. $id = getProp($data, 'id');
  6924. if (!$id) Utils::throwError('20003:ID不能为空');
  6925. $ids = explode(',', $id);
  6926. $is_public = getProp($data, 'is_public', 0); // 0=个人资产库 1=公共资产库
  6927. // 根据is_public参数确定查询的user_id(公共库user_id=0,cpid保持不变)
  6928. $query_uid = $is_public ? 0 : $uid;
  6929. // 如果是公共库操作,需要admin权限
  6930. if ($is_public && $role !== 'admin') {
  6931. Utils::throwError('20003:只有管理员才能操作公共资产库');
  6932. }
  6933. // 检查是否存在且属于当前用户或公共库
  6934. $role = DB::table('mp_products')
  6935. ->whereIn('id', $ids)
  6936. ->where('cpid', $cpid)
  6937. ->where('user_id', $query_uid)
  6938. ->get();
  6939. if (!$role) Utils::throwError('20003:记录不存在');
  6940. return DB::table('mp_products')
  6941. ->where('cpid', $cpid)
  6942. ->where('user_id', $query_uid)
  6943. ->whereIn('id', $ids)
  6944. ->update([
  6945. 'is_deleted' => 1,
  6946. 'updated_at' => date('Y-m-d H:i:s')
  6947. ]);
  6948. }
  6949. public function generateThreeView($data) {
  6950. $uid = Site::getUid();
  6951. $cpid = Site::getCpid();
  6952. $role = Site::getRole();
  6953. $id = getProp($data, 'id');
  6954. if (!$id) Utils::throwError('20003:ID不能为空');
  6955. $is_public = getProp($data, 'is_public', 0); // 0=个人资产库 1=公共资产库
  6956. // 根据is_public参数确定查询的user_id(公共库user_id=0,cpid保持不变)
  6957. $query_uid = $is_public ? 0 : $uid;
  6958. // 如果是公共库操作,需要admin权限
  6959. if ($is_public && $role !== 'admin') {
  6960. Utils::throwError('20003:只有管理员才能操作公共资产库');
  6961. }
  6962. // 检查是否存在且属于当前用户或公共库
  6963. $product = DB::table('mp_products')
  6964. ->where('id', $id)
  6965. ->where('cpid', $cpid)
  6966. ->where('user_id', $query_uid)
  6967. ->where('type', 1)->first();
  6968. if (!$product) Utils::throwError('20003:资产不存在');
  6969. $prompt = trim(getProp($data, 'prompt', '基于参考图生成主体的标准正面、侧面、后面三视图,主体完整。在最左侧添加主体正视图的特写,特写大小为标准一寸照,人物不要带表情。右侧是全身的三视图,其中正面、侧面的三视图给人脸打白色码、不显示五官。主体清晰完整。背景修改成纯白色,整体保持与参考图一致的美术风格和色彩搭配。画面无说明文字。'));
  6970. $ref_img_url = trim(getProp($data, 'ref_img_url'));
  6971. if (!$ref_img_url) {
  6972. // 如果没有传入参考图,使用角色表中的图片
  6973. $ref_img_url = $product->url ?? '';
  6974. if (!$ref_img_url) {
  6975. Utils::throwError('20003:参考图不能为空');
  6976. }
  6977. }
  6978. $pic_prompt = getProp($product, 'pic_prompt');
  6979. if ($pic_prompt) {
  6980. $prompt .= '\n参考图原始提示词: '.$pic_prompt;
  6981. }
  6982. // 检查参考图是否是正确的图片格式
  6983. $allowedExtensions = ['jpg', 'jpeg', 'png', 'gif', 'webp', 'bmp'];
  6984. $urlPath = parse_url($ref_img_url, PHP_URL_PATH);
  6985. $extension = strtolower(pathinfo($urlPath, PATHINFO_EXTENSION));
  6986. if (!in_array($extension, $allowedExtensions)) {
  6987. Utils::throwError('20003:参考图格式不正确,仅支持 jpg、jpeg、png、gif、webp、bmp 格式');
  6988. }
  6989. // 处理图片模型
  6990. $model = getProp($data, 'model');
  6991. if (!$model) {
  6992. // 使用默认模型
  6993. $model = 'gpt-image-2';
  6994. }
  6995. // 验证模型是否在可用模型表中
  6996. if (!DB::table('mp_image_models')->where('model', $model)->where('is_enabled', 1)->exists()) {
  6997. Utils::throwError('20003:该模型已不可用,请更换!');
  6998. }
  6999. $ratio = getProp($data, 'ratio', '16:9');
  7000. $resolution = getProp($data, 'resolution', '2k');
  7001. // 分辨率档位与尺寸映射统一从 BaseConst 获取
  7002. $sizeMap = BaseConst::IMAGE_RESOLUTION_SIZE_MAP;
  7003. // 参数验证
  7004. $resolution = strtolower($resolution);
  7005. if (!isset($sizeMap[$resolution])) {
  7006. Utils::throwError('20003:分辨率参数错误,仅支持 2k、3k、4k');
  7007. }
  7008. if (!isset($sizeMap[$resolution][$ratio])) {
  7009. Utils::throwError('20003:宽高比参数错误,该分辨率下不支持 ' . $ratio . ' 比例');
  7010. }
  7011. // 根据 ratio 和 resolution 确定宽高
  7012. $width = $sizeMap[$resolution][$ratio]['width'];
  7013. $height = $sizeMap[$resolution][$ratio]['height'];
  7014. try {
  7015. // 创建图片生成任务
  7016. $params = [
  7017. 'prompt' => $prompt,
  7018. 'model' => $model,
  7019. 'ref_img_urls' => [$ref_img_url],
  7020. 'width' => $width,
  7021. 'height' => $height
  7022. ];
  7023. $task = $this->aiImageGenerationService->createImageGenerationTask($params);
  7024. $task_id = $task->id;
  7025. if (!$task_id) {
  7026. Utils::throwError('20003:创建图片生成任务失败');
  7027. }
  7028. // 轮询获取结果
  7029. // 只查询数据库,不调用API,不更新任务表
  7030. $start_time = time();
  7031. $timeout = 1800;
  7032. $img_url = '';
  7033. while (time() - $start_time < $timeout) {
  7034. sleep(5);
  7035. // 只查询数据库中的任务状态,不调用API,不更新任务表
  7036. $task = DB::table('mp_generate_pic_tasks')
  7037. ->where('id', $task_id)
  7038. ->first();
  7039. if (!$task) {
  7040. Utils::throwError('20003:任务不存在');
  7041. }
  7042. if ($task->status === 'success' && $task->result_url) {
  7043. $result_urls = is_string($task->result_url)
  7044. ? json_decode($task->result_url, true)
  7045. : $task->result_url;
  7046. $img_url = is_array($result_urls) ? $result_urls[0] : $task->result_url;
  7047. break;
  7048. } elseif ($task->status === 'failed') {
  7049. Utils::throwError('20003:三视图生成失败,' . ($task->error_message ?? '未知错误'));
  7050. }
  7051. // 其他状态继续轮询
  7052. }
  7053. if (empty($img_url)) {
  7054. Utils::throwError('20003:三视图生成超时,请稍后重试');
  7055. }
  7056. // 更新 mp_products 表(不是任务表)
  7057. DB::table('mp_products')
  7058. ->where('id', $id)
  7059. ->where('cpid', $cpid)
  7060. ->update([
  7061. 'three_view_image_url' => $img_url,
  7062. 'updated_at' => date('Y-m-d H:i:s')
  7063. ]);
  7064. return ['three_view_image_url' => $img_url];
  7065. } catch (\Exception $e) {
  7066. dLog('anime')->error('生成三视图失败', [
  7067. 'error' => $e->getMessage()
  7068. ]);
  7069. logDB('anime', 'error', '生成三视图失败', ['error' => $e->getMessage()]);
  7070. Utils::throwError('20003:' . $e->getMessage());
  7071. }
  7072. }
  7073. /**
  7074. * 推送(复制)资产或文件夹到目标位置
  7075. * @param array $data 包含 product_id(要推送的资产或文件夹ID)、target_parent_id(目标父文件夹ID,0表示根目录)
  7076. * @return array 返回推送结果
  7077. */
  7078. public function pushProductOrFolder($data) {
  7079. $uid = Site::getUid();
  7080. $cpid = Site::getCpid();
  7081. $role = Site::getRole();
  7082. $product_id = getProp($data, 'product_id');
  7083. $target_parent_id = getProp($data, 'target_parent_id', 0);
  7084. $target_product = getProp($data, 'product'); // 目标 product 类型,用于跨类型推送
  7085. if (!$product_id) {
  7086. Utils::throwError('20003:请选择要推送的项目');
  7087. }
  7088. // 查询源项目(只通过cpid查询,不限制user_id)
  7089. $sourceItem = DB::table('mp_products')
  7090. ->where('id', $product_id)
  7091. ->where('cpid', $cpid)
  7092. ->where('is_deleted', 0)
  7093. ->first();
  7094. if (!$sourceItem) {
  7095. Utils::throwError('20003:要推送的项目不存在');
  7096. }
  7097. // 通过user_id判断源是公共库还是个人库
  7098. $source_uid = $sourceItem->user_id;
  7099. $source_is_public = ($source_uid == 0) ? 1 : 0;
  7100. // 验证目标文件夹并确定目标是公共库还是个人库
  7101. $target_level = 0;
  7102. $target_uid = $uid; // 默认推送到个人库
  7103. $target_is_public = 0;
  7104. $final_product_type = $sourceItem->product; // 默认使用源的 product 类型
  7105. if ($target_parent_id > 0) {
  7106. // 查询目标文件夹(只通过cpid查询,不限制user_id)
  7107. $targetParent = DB::table('mp_products')
  7108. ->where('id', $target_parent_id)
  7109. ->where('cpid', $cpid)
  7110. ->where('type', 2)
  7111. ->where('is_deleted', 0)
  7112. ->first();
  7113. if (!$targetParent) {
  7114. Utils::throwError('20003:目标文件夹不存在');
  7115. }
  7116. // 通过user_id判断目标是公共库还是个人库
  7117. $target_level = $targetParent->level;
  7118. $target_uid = $targetParent->user_id;
  7119. $target_is_public = ($target_uid == 0) ? 1 : 0;
  7120. // 使用目标文件夹的 product 类型
  7121. $final_product_type = $targetParent->product;
  7122. }
  7123. // 如果 target_parent_id = 0(推送到根目录),需要通过参数判断推送到个人库还是公共库
  7124. else {
  7125. $push_to_public = getProp($data, 'push_to_public');
  7126. if ($push_to_public === '') {
  7127. Utils::throwError('20003:请选择是否推送到公共库');
  7128. }
  7129. if ($push_to_public) {
  7130. $target_uid = 0;
  7131. $target_is_public = 1;
  7132. }
  7133. // 推送到根目录时,必须指定 product 类型
  7134. if ($target_product === null || $target_product === '') {
  7135. Utils::throwError('20003:推送到根目录时必须指定目标类型(product)');
  7136. }
  7137. $final_product_type = $target_product;
  7138. }
  7139. // 如果目标是公共库,需要admin权限
  7140. if ($target_is_public && $role !== 'admin') {
  7141. Utils::throwError('20003:只有管理员才能推送到公共资产库');
  7142. }
  7143. // 权限验证:验证是否符合允许的推送规则
  7144. $this->validatePushPermission($source_uid, $target_uid, $uid);
  7145. try {
  7146. DB::beginTransaction();
  7147. // 如果是资产,直接复制(支持跨类型推送,更新 product 字段)
  7148. if ($sourceItem->type == 1) {
  7149. $newId = $this->copyProduct($sourceItem, $target_parent_id, $target_level + 1, $cpid, $target_uid, $final_product_type);
  7150. DB::commit();
  7151. return [
  7152. 'product_id' => $newId,
  7153. ];
  7154. }
  7155. // 如果是文件夹,递归复制(支持跨类型推送)
  7156. $newFolderId = $this->copyFolderRecursive($sourceItem, $target_parent_id, $target_level + 1, $cpid, $target_uid, $source_uid, $final_product_type);
  7157. DB::commit();
  7158. return [
  7159. 'product_id' => $newFolderId,
  7160. ];
  7161. } catch (\Exception $e) {
  7162. DB::rollBack();
  7163. dLog('anime')->error('推送失败', [
  7164. 'error' => $e->getMessage(),
  7165. 'product_id' => $product_id
  7166. ]);
  7167. Utils::throwError('20003:' . $e->getMessage());
  7168. }
  7169. }
  7170. /**
  7171. * 验证推送权限
  7172. * 允许的推送规则:
  7173. * 1. 自己推送给自己的个人库(个人库 → 个人库,同一用户)
  7174. * 2. 公共库推送给自己的个人库(公共库 → 个人库)
  7175. * 3. 公共库推送给公共库(公共库 → 公共库)
  7176. *
  7177. * @param int $source_uid 源的user_id
  7178. * @param int $target_uid 目标的user_id
  7179. * @param int $current_uid 当前用户ID
  7180. * @throws \Exception
  7181. */
  7182. private function validatePushPermission($source_uid, $target_uid, $current_uid) {
  7183. // 规则1:自己推送给自己的个人库(个人库 → 个人库,同一用户)
  7184. if ($source_uid == $current_uid && $target_uid == $current_uid) {
  7185. return; // 允许
  7186. }
  7187. // 规则2:公共库推送给自己的个人库(公共库 → 个人库)
  7188. if ($source_uid == 0 && $target_uid == $current_uid) {
  7189. return; // 允许
  7190. }
  7191. // 规则3:公共库推送给公共库(公共库 → 公共库)
  7192. if ($source_uid == 0 && $target_uid == 0) {
  7193. return; // 允许
  7194. }
  7195. // 其他情况都不允许
  7196. if ($source_uid != 0 && $source_uid != $current_uid) {
  7197. // 源是别人的个人库
  7198. Utils::throwError('20003:无权限访问该资产');
  7199. } elseif ($source_uid == $current_uid && $target_uid == 0) {
  7200. // 个人库推送给公共库(不允许)
  7201. Utils::throwError('20003:不允许将个人资产推送到公共库');
  7202. } elseif ($source_uid != 0 && $target_uid != 0 && $source_uid != $target_uid) {
  7203. // 不同用户的个人库之间推送(不允许)
  7204. Utils::throwError('20003:不允许推送到其他用户的个人库');
  7205. } else {
  7206. // 其他未知情况
  7207. Utils::throwError('20003:不允许的推送操作');
  7208. }
  7209. }
  7210. /**
  7211. * 复制单个资产
  7212. * @param object $sourceProduct 源资产对象
  7213. * @param int $targetParentId 目标父文件夹ID
  7214. * @param int $targetLevel 目标层级
  7215. * @param int $cpid 公司ID
  7216. * @param int $targetUid 目标用户ID
  7217. * @return int 返回新资产ID
  7218. */
  7219. private function copyProduct($sourceProduct, $targetParentId, $targetLevel, $cpid, $targetUid, $productType = null) {
  7220. // 如果指定了 productType,使用指定的;否则使用源的 product 类型
  7221. $finalProductType = ($productType !== null) ? $productType : $sourceProduct->product;
  7222. $newProductData = [
  7223. 'user_id' => $targetUid,
  7224. 'cpid' => $cpid,
  7225. 'type' => 1,
  7226. 'parent_id' => $targetParentId,
  7227. 'level' => $targetLevel,
  7228. 'product_name' => $sourceProduct->product_name,
  7229. 'url' => $sourceProduct->url,
  7230. 'pic_prompt' => $sourceProduct->pic_prompt ?? '',
  7231. 'three_view_image_url' => $sourceProduct->three_view_image_url ?? '',
  7232. 'product' => $finalProductType,
  7233. 'versions' => $sourceProduct->versions ?? '',
  7234. 'sort_order' => time(),
  7235. 'is_deleted' => 0,
  7236. 'created_at' => date('Y-m-d H:i:s'),
  7237. 'updated_at' => date('Y-m-d H:i:s')
  7238. ];
  7239. return DB::table('mp_products')->insertGetId($newProductData);
  7240. }
  7241. /**
  7242. * 递归复制文件夹及其子项
  7243. * @param object $sourceFolder 源文件夹对象
  7244. * @param int $targetParentId 目标父文件夹ID
  7245. * @param int $targetLevel 目标层级
  7246. * @param int $cpid 公司ID
  7247. * @param int $targetUid 目标用户ID
  7248. * @param int $sourceUid 源用户ID
  7249. * @return int 返回新文件夹ID
  7250. */
  7251. private function copyFolderRecursive($sourceFolder, $targetParentId, $targetLevel, $cpid, $targetUid, $sourceUid, $productType = null) {
  7252. // 如果指定了 productType,使用指定的;否则使用源的 product 类型
  7253. $finalProductType = ($productType !== null) ? $productType : $sourceFolder->product;
  7254. // 创建新文件夹
  7255. $newFolderData = [
  7256. 'user_id' => $targetUid,
  7257. 'cpid' => $cpid,
  7258. 'type' => 2,
  7259. 'parent_id' => $targetParentId,
  7260. 'level' => $targetLevel,
  7261. 'product_name' => $sourceFolder->product_name,
  7262. 'product' => $finalProductType,
  7263. 'sort_order' => time(),
  7264. 'is_deleted' => 0,
  7265. 'created_at' => date('Y-m-d H:i:s'),
  7266. 'updated_at' => date('Y-m-d H:i:s')
  7267. ];
  7268. $newFolderId = DB::table('mp_products')->insertGetId($newFolderData);
  7269. // 获取源文件夹下的所有子项
  7270. $children = DB::table('mp_products')
  7271. ->where('parent_id', $sourceFolder->id)
  7272. ->where('cpid', $cpid)
  7273. ->where('user_id', $sourceUid)
  7274. ->where('is_deleted', 0)
  7275. ->orderByRaw('type DESC, sort_order DESC, created_at DESC')
  7276. ->get();
  7277. // 递归复制子项(子项继承目标文件夹的 product 类型)
  7278. foreach ($children as $child) {
  7279. if ($child->type == 1) {
  7280. // 资产
  7281. $this->copyProduct($child, $newFolderId, $targetLevel + 1, $cpid, $targetUid, $finalProductType);
  7282. } else {
  7283. // 文件夹
  7284. $this->copyFolderRecursive($child, $newFolderId, $targetLevel + 1, $cpid, $targetUid, $sourceUid, $finalProductType);
  7285. }
  7286. }
  7287. return $newFolderId;
  7288. }
  7289. /**
  7290. * 转让剧本归属(剧本及其关联资产)
  7291. *
  7292. * 仅调整 mp_scripts.user_id 与 mp_products.user_id,其他表保持不变。
  7293. * 权限:仅 admin / superadmin 可操作;目标用户必须是同组(cpid 相同)且角色为 user(组员)的用户,禁止跨组转让。
  7294. * 多个剧本逐个独立事务处理,单个剧本失败不影响其他剧本;
  7295. * 单个剧本内的剧本记录与关联资产必须全部更新成功,否则整体回滚。
  7296. *
  7297. * @param array $data 请求参数:script_ids(数组或英文逗号分隔,兼容单个 script_id)、target_user_id
  7298. * @return array
  7299. */
  7300. public function transferScriptOwner($data) {
  7301. $operatorRole = Site::getRole();
  7302. $operatorCpid = Site::getCpid();
  7303. // 1.权限校验:仅管理员和超管可操作
  7304. if (!in_array($operatorRole, ['admin', 'superadmin'], true)) {
  7305. Utils::throwError(ErrorConst::NOT_ACCESS);
  7306. }
  7307. // 2.目标用户校验:必须存在且角色为 user(组员)
  7308. $targetUserId = (int)getProp($data, 'target_user_id', 0);
  7309. if ($targetUserId < 1) {
  7310. Utils::throwError('1002:请选择转让的目标用户');
  7311. }
  7312. $targetUser = DB::table('mp_manage_users')
  7313. ->where('id', $targetUserId)
  7314. ->where('is_deleted', 0)
  7315. ->first();
  7316. if (!$targetUser) {
  7317. Utils::throwError('20003:目标用户不存在');
  7318. }
  7319. if ((string)getProp($targetUser, 'role') !== 'user') {
  7320. Utils::throwError('20003:只能转让给角色为组员(user)的用户');
  7321. }
  7322. $targetCpid = (int)getProp($targetUser, 'cpid');
  7323. // 3.规范化剧本ID列表(兼容数组、逗号分隔字符串、script_id 单值)
  7324. $rawScriptIds = getProp($data, 'script_ids');
  7325. if (empty($rawScriptIds)) {
  7326. $rawScriptIds = getProp($data, 'script_id');
  7327. }
  7328. $scriptIds = $this->normalizeIdList($rawScriptIds);
  7329. if (empty($scriptIds)) {
  7330. Utils::throwError('20003:请提供剧本ID');
  7331. }
  7332. // 预取剧本名称,便于失败结果中回显
  7333. $scriptNameMap = DB::table('mp_scripts')
  7334. ->whereIn('id', $scriptIds)
  7335. ->pluck('script_name', 'id')
  7336. ->all();
  7337. $successList = [];
  7338. $failedList = [];
  7339. // 4.逐个剧本独立事务处理,单个失败不影响其他剧本
  7340. foreach ($scriptIds as $scriptId) {
  7341. DB::beginTransaction();
  7342. try {
  7343. $successList[] = $this->transferSingleScriptOwner(
  7344. $scriptId,
  7345. $targetUserId,
  7346. $targetCpid,
  7347. $operatorRole,
  7348. $operatorCpid,
  7349. Site::getUid()
  7350. );
  7351. DB::commit();
  7352. } catch (\Throwable $e) {
  7353. DB::rollBack();
  7354. $failedList[] = [
  7355. 'script_id' => (int)$scriptId,
  7356. 'script_name' => (string)($scriptNameMap[$scriptId] ?? ''),
  7357. 'reason' => $e->getMessage() !== '' ? $e->getMessage() : '转让失败',
  7358. ];
  7359. dLog('anime')->error('剧本归属转让失败', [
  7360. 'script_id' => $scriptId,
  7361. 'target_user_id' => $targetUserId,
  7362. 'operator_uid' => Site::getUid(),
  7363. 'error' => $e->getMessage(),
  7364. ]);
  7365. }
  7366. }
  7367. return [
  7368. 'target_user_id' => $targetUserId,
  7369. 'success_count' => count($successList),
  7370. 'failed_count' => count($failedList),
  7371. 'success_list' => $successList,
  7372. 'failed_list' => $failedList,
  7373. ];
  7374. }
  7375. /**
  7376. * 单个剧本的归属转让(需在事务中调用)
  7377. *
  7378. * @param int $scriptId 剧本ID
  7379. * @param int $targetUserId 目标用户ID
  7380. * @param int $targetCpid 目标用户所属公司ID
  7381. * @param string $operatorRole 操作人角色
  7382. * @param int $operatorCpid 操作人所属公司ID
  7383. * @param int $operatorUid 操作人用户ID
  7384. * @return array
  7385. */
  7386. private function transferSingleScriptOwner($scriptId, $targetUserId, $targetCpid, $operatorRole, $operatorCpid, $operatorUid) {
  7387. $script = DB::table('mp_scripts')
  7388. ->where('id', $scriptId)
  7389. ->where('is_deleted', 0)
  7390. ->first();
  7391. if (!$script) {
  7392. Utils::throwError('20003:剧本不存在');
  7393. }
  7394. $scriptCpid = (int)getProp($script, 'cpid');
  7395. $fromUserId = (int)getProp($script, 'user_id');
  7396. // 管理员仅可操作本组剧本
  7397. if ($operatorRole !== 'superadmin' && $scriptCpid !== $operatorCpid) {
  7398. Utils::throwError(ErrorConst::NOT_ACCESS);
  7399. }
  7400. // 管理员仅可转让自己创建的剧本(超管不做此验证)
  7401. if ($operatorRole !== 'superadmin' && $fromUserId !== (int)$operatorUid) {
  7402. Utils::throwError('20003:管理员仅能转让自己创建的剧本和资产');
  7403. }
  7404. // 禁止跨组转让:目标用户必须与剧本同组
  7405. if ($targetCpid !== $scriptCpid) {
  7406. Utils::throwError('20003:不能跨组转让,目标用户与剧本不在同一组');
  7407. }
  7408. // 关联资产ID(同一资产可能关联多个剧集序号,需去重)
  7409. $productIds = $this->normalizeIdList(
  7410. DB::table('mp_script_product_mappings')
  7411. ->where('script_id', $scriptId)
  7412. ->pluck('product_id')
  7413. ->all()
  7414. );
  7415. $folderIds = [];
  7416. if (!empty($productIds)) {
  7417. $products = DB::table('mp_products')
  7418. ->whereIn('id', $productIds)
  7419. ->select('id', 'cpid', 'parent_id', 'user_id')
  7420. ->get();
  7421. // 关联资产必须全部存在,否则视为数据异常,不提交
  7422. if ($products->count() !== count($productIds)) {
  7423. Utils::throwError('20003:剧本存在已丢失的关联资产,无法完成转让');
  7424. }
  7425. foreach ($products as $product) {
  7426. // 关联资产必须与剧本同组,避免误转让跨组资产
  7427. if ((int)getProp($product, 'cpid') !== $scriptCpid) {
  7428. Utils::throwError('20003:剧本存在跨组关联资产,无法完成转让');
  7429. }
  7430. $parentId = (int)getProp($product, 'parent_id', 0);
  7431. if ($parentId > 0 && !in_array($parentId, $folderIds, true)) {
  7432. $folderIds[] = $parentId;
  7433. }
  7434. }
  7435. // 仅转让归属于原剧本所有者的资产
  7436. $folderIds = DB::table('mp_products')
  7437. ->whereIn('id', $folderIds)
  7438. ->where('type', 2)
  7439. ->where('cpid', $scriptCpid)
  7440. ->where('user_id', $fromUserId)
  7441. ->pluck('id')
  7442. ->map('intval')
  7443. ->all();
  7444. // 管理员仅可转让自己创建的资产及其所属文件夹(超管不做此验证)
  7445. if ($operatorRole !== 'superadmin') {
  7446. foreach ($products as $product) {
  7447. if ((int)getProp($product, 'user_id') !== (int)$operatorUid) {
  7448. Utils::throwError('20003:管理员仅能转让自己创建的剧本和资产');
  7449. }
  7450. }
  7451. foreach ($products as $product) {
  7452. $parentId = (int)getProp($product, 'parent_id', 0);
  7453. if ($parentId > 0 && !in_array($parentId, $folderIds, true)) {
  7454. Utils::throwError('20003:管理员仅能转让自己创建的剧本和资产');
  7455. }
  7456. }
  7457. }
  7458. }
  7459. $now = now();
  7460. // 5.更新剧本归属
  7461. DB::table('mp_scripts')
  7462. ->where('id', $scriptId)
  7463. ->update([
  7464. 'user_id' => $targetUserId,
  7465. 'updated_at' => $now,
  7466. ]);
  7467. // 6.更新关联资产归属
  7468. if (!empty($productIds)) {
  7469. DB::table('mp_products')
  7470. ->whereIn('id', $productIds)
  7471. ->update([
  7472. 'user_id' => $targetUserId,
  7473. 'updated_at' => $now,
  7474. ]);
  7475. }
  7476. // 7.更新资产所属的类型根文件夹归属(文件夹属于 mp_products,随资产一并转让)
  7477. if (!empty($folderIds)) {
  7478. DB::table('mp_products')
  7479. ->whereIn('id', $folderIds)
  7480. ->update([
  7481. 'user_id' => $targetUserId,
  7482. 'updated_at' => $now,
  7483. ]);
  7484. }
  7485. // 8.校验剧本与资产是否全部更新成功,任一未成功则回滚
  7486. $scriptOwner = (int)DB::table('mp_scripts')->where('id', $scriptId)->value('user_id');
  7487. if ($scriptOwner !== $targetUserId) {
  7488. Utils::throwError('20003:剧本归属更新失败');
  7489. }
  7490. if (!empty($productIds)) {
  7491. $updatedProductCount = DB::table('mp_products')
  7492. ->whereIn('id', $productIds)
  7493. ->where('user_id', $targetUserId)
  7494. ->count();
  7495. if ($updatedProductCount !== count($productIds)) {
  7496. Utils::throwError('20003:部分剧本资产转让失败,已回滚');
  7497. }
  7498. }
  7499. if (!empty($folderIds)) {
  7500. $updatedFolderCount = DB::table('mp_products')
  7501. ->whereIn('id', $folderIds)
  7502. ->where('user_id', $targetUserId)
  7503. ->count();
  7504. if ($updatedFolderCount !== count($folderIds)) {
  7505. Utils::throwError('20003:部分资产文件夹转让失败,已回滚');
  7506. }
  7507. }
  7508. return [
  7509. 'script_id' => (int)$scriptId,
  7510. 'script_name' => (string)getProp($script, 'script_name', ''),
  7511. 'from_user_id' => $fromUserId,
  7512. 'to_user_id' => $targetUserId,
  7513. 'product_count' => count($productIds),
  7514. 'folder_count' => count($folderIds),
  7515. ];
  7516. }
  7517. /**
  7518. * 规范化ID列表,兼容数组、逗号分隔字符串以及字符串数组
  7519. *
  7520. * @param mixed $ids 待处理的ID集合
  7521. * @return array 去重后的正整数ID数组
  7522. */
  7523. private function normalizeIdList($ids) {
  7524. if (!is_array($ids)) {
  7525. $ids = explode(',', (string)$ids);
  7526. }
  7527. $result = [];
  7528. foreach ($ids as $item) {
  7529. if (is_array($item)) {
  7530. continue;
  7531. }
  7532. foreach (explode(',', (string)$item) as $part) {
  7533. $part = trim($part);
  7534. if ($part !== '' && is_numeric($part) && (int)$part > 0) {
  7535. $result[] = (int)$part;
  7536. }
  7537. }
  7538. }
  7539. return array_values(array_unique($result));
  7540. }
  7541. /**
  7542. * 通过 Excel 批量导入剧本资产(独立实现,不依赖 saveScriptProducts)
  7543. *
  7544. * 流程:
  7545. * 1. 校验剧本存在且属于当前用户
  7546. * 2. 解析 Excel 并校验强制列与数据完整性(资产类型/资产名称/使用范围/参考提示词)
  7547. * 3. 名称去重(与 Excel 内及该剧本已有关联资产比对)
  7548. * 4. 事务内创建类型文件夹、资产与剧本映射
  7549. * 5. 为没有图片的资产创建图片生成任务,生成中返回 SSE 轮询
  7550. *
  7551. * @param array $data 请求参数
  7552. * @param \Illuminate\Http\UploadedFile $file 上传的 Excel 文件
  7553. * @return array|\Generator
  7554. */
  7555. public function importScriptProductsByExcel($data, $file) {
  7556. $uid = Site::getUid();
  7557. $cpid = Site::getCpid();
  7558. $script_id = (int)getProp($data, 'script_id', 0);
  7559. if (!$script_id) {
  7560. Utils::throwError('20003:请提供剧本ID');
  7561. }
  7562. // 验证剧本是否存在,且只能导入自己创建的剧本
  7563. $script = DB::table('mp_scripts')
  7564. ->where('id', $script_id)
  7565. ->where('is_deleted', 0)
  7566. ->where('user_id', $uid)
  7567. ->first();
  7568. if (!$script) {
  7569. Utils::throwError('20003:剧本不存在或无权限操作');
  7570. }
  7571. $script_name = $script->script_name ?? 'script_' . $script_id;
  7572. // 校验上传文件
  7573. if (!$file) {
  7574. Utils::throwError('20003:请上传Excel文件');
  7575. }
  7576. $extension = strtolower($file->getClientOriginalExtension());
  7577. if (!in_array($extension, ['xlsx', 'xls'])) {
  7578. Utils::throwError('20003:文件格式错误,仅支持 xlsx、xls 格式');
  7579. }
  7580. if ($file->getSize() > 10 * 1024 * 1024) {
  7581. Utils::throwError('20003:文件大小不能超过10M');
  7582. }
  7583. // 解析 Excel(第一行为表头)
  7584. $rows = $this->readImportExcelRows($file);
  7585. if (empty($rows)) {
  7586. Utils::throwError('20003:Excel内容为空');
  7587. }
  7588. $headers = array_shift($rows);
  7589. // 定位强制列
  7590. $typeColumnIndex = $this->findImportExcelColumnIndex($headers, ['资产类型'], ['资产类型', '类型']);
  7591. $nameColumnIndex = $this->findImportExcelColumnIndex($headers, ['资产名称'], ['资产名称', '名称']);
  7592. $rangeColumnIndex = $this->findImportExcelColumnIndex($headers, ['使用范围'], ['使用范围', '范围']);
  7593. $promptColumnIndex = $this->findImportExcelColumnIndex($headers, ['参考提示词', '提示词'], ['提示词']);
  7594. $missingColumns = [];
  7595. if ($typeColumnIndex < 0) {
  7596. $missingColumns[] = '资产类型';
  7597. }
  7598. if ($nameColumnIndex < 0) {
  7599. $missingColumns[] = '资产名称';
  7600. }
  7601. if ($rangeColumnIndex < 0) {
  7602. $missingColumns[] = '使用范围';
  7603. }
  7604. if ($promptColumnIndex < 0) {
  7605. $missingColumns[] = '参考提示词';
  7606. }
  7607. if (!empty($missingColumns)) {
  7608. Utils::throwError('20003:Excel缺少必填列:' . implode('、', $missingColumns));
  7609. }
  7610. // 先整体校验 Excel 数据,所有异常行一次性返回
  7611. $validation = $this->validateImportExcelRows(
  7612. $rows,
  7613. $typeColumnIndex,
  7614. $nameColumnIndex,
  7615. $rangeColumnIndex,
  7616. $promptColumnIndex
  7617. );
  7618. $errors = $validation['errors'];
  7619. $checkedRows = $validation['checked_rows'];
  7620. if (empty($checkedRows)) {
  7621. $errors[] = 'Excel中没有有效的数据行';
  7622. }
  7623. if (!empty($errors)) {
  7624. Utils::throwError('20003:Excel数据校验失败:' . implode(';', $errors));
  7625. }
  7626. // 名称去重:Excel 内部 + 该剧本已关联资产(按 createProduct 的名称判断逻辑)
  7627. $existingNames = $this->getScriptProductNames($script_id, $cpid);
  7628. $dedupResult = $this->deduplicateImportRows($checkedRows, $existingNames);
  7629. $validRows = $dedupResult['valid_rows'];
  7630. $skipped = $dedupResult['skipped'];
  7631. // 图片生成参数(与 saveScriptProducts 保持一致的校验规则)
  7632. $model = getProp($data, 'model');
  7633. if (!$model) {
  7634. $model = 'gpt-image-2';
  7635. }
  7636. if (!DB::table('mp_image_models')->where('model', $model)->where('is_enabled', 1)->exists()) {
  7637. Utils::throwError('20003:该模型已不可用,请更换!');
  7638. }
  7639. $ratio = getProp($data, 'ratio', '9:16');
  7640. $resolution = strtolower(getProp($data, 'resolution', '2k'));
  7641. $sizeMap = BaseConst::IMAGE_RESOLUTION_SIZE_MAP;
  7642. if (!isset($sizeMap[$resolution])) {
  7643. Utils::throwError('20003:分辨率参数错误,仅支持 2k、3k、4k');
  7644. }
  7645. if (!isset($sizeMap[$resolution][$ratio])) {
  7646. Utils::throwError('20003:宽高比参数错误,该分辨率下不支持 ' . $ratio . ' 比例');
  7647. }
  7648. $width = $sizeMap[$resolution][$ratio]['width'];
  7649. $height = $sizeMap[$resolution][$ratio]['height'];
  7650. $autoRaw = getProp($data, 'auto_generate_images', true);
  7651. $auto_generate_images = !in_array($autoRaw, [false, 0, '0', 'false', 'False'], true);
  7652. // 创建/复用任务中心记录(md5 验重,避免重复任务)
  7653. $taskCenterId = $this->createScriptProductTaskCenter(
  7654. $uid,
  7655. $cpid,
  7656. $script_id,
  7657. $validRows,
  7658. $model,
  7659. $ratio,
  7660. $resolution,
  7661. $auto_generate_images
  7662. );
  7663. // 全部为重复项:参照 saveScriptProducts,检查已存在资产的图片状态,缺图的补建任务
  7664. if (empty($validRows)) {
  7665. $existingTaskInfo = $this->prepareExistingScriptProductTasks(
  7666. $script_id,
  7667. $model,
  7668. $width,
  7669. $height,
  7670. $auto_generate_images
  7671. );
  7672. $productTaskMap = $existingTaskInfo['product_task_map'];
  7673. $typeFolderIds = $existingTaskInfo['type_folder_ids'];
  7674. if (!empty($productTaskMap)) {
  7675. $message = 'Excel中的资产均已存在,正在为缺少图片的资产生成图片';
  7676. } elseif (!$existingTaskInfo['has_all_tasks']) {
  7677. $message = 'Excel中的资产均已存在,部分资产没有参考提示词,无法生成图片';
  7678. } else {
  7679. $message = 'Excel中的资产均已存在,且图片已全部生成完成';
  7680. }
  7681. $resultData = [
  7682. 'success' => true,
  7683. 'message' => $message,
  7684. 'script_id' => $script_id,
  7685. 'script_name' => $script_name,
  7686. 'imported_count' => 0,
  7687. 'existing_products' => $existingTaskInfo['product_count'],
  7688. 'skipped_count' => count($skipped),
  7689. 'skipped' => $skipped,
  7690. 'created_products' => [],
  7691. 'type_folder_ids' => $typeFolderIds,
  7692. 'pending_tasks_count' => count($productTaskMap),
  7693. 'image_tasks_created' => $existingTaskInfo['created_count'],
  7694. 'task_center_id' => $taskCenterId,
  7695. ];
  7696. // 有需要轮询的任务(已有任务或本次补建):走 SSE 轮询
  7697. if (!empty($productTaskMap)) {
  7698. return $this->pollProductImageTasks(
  7699. $script_id,
  7700. $script_name,
  7701. $productTaskMap,
  7702. $typeFolderIds,
  7703. $taskCenterId,
  7704. ['import_result' => $resultData],
  7705. ['import_result' => $resultData]
  7706. );
  7707. }
  7708. // 没有需要轮询的任务:直接通过 complete 事件返回导入结果
  7709. return $this->streamImportComplete($script_id, $script_name, $resultData, $typeFolderIds, $taskCenterId);
  7710. }
  7711. // 事务内创建资产、类型文件夹与剧本映射
  7712. $typeFolderIds = [];
  7713. $createdProducts = [];
  7714. $mappingRecords = [];
  7715. $now = now();
  7716. DB::beginTransaction();
  7717. try {
  7718. foreach ($validRows as $row) {
  7719. $type = $row['type'];
  7720. if (!isset($typeFolderIds[$type])) {
  7721. // 与 createProduct 一致:先查找该剧本已存在的类型文件夹,没有则创建
  7722. $folder = DB::table('mp_products')
  7723. ->where('cpid', $cpid)
  7724. ->where('type', 2)
  7725. ->where('product', $type)
  7726. ->where('product_name', $script_name)
  7727. ->where('parent_id', 0)
  7728. ->where('is_deleted', 0)
  7729. ->first();
  7730. if ($folder) {
  7731. $typeFolderIds[$type] = $folder->id;
  7732. } else {
  7733. $typeFolderIds[$type] = DB::table('mp_products')->insertGetId([
  7734. 'user_id' => $uid,
  7735. 'cpid' => $cpid,
  7736. 'type' => 2, // 文件夹
  7737. 'product' => $type, // 1=角色 2=场景 3=道具
  7738. 'parent_id' => 0,
  7739. 'level' => 1,
  7740. 'product_name' => $script_name,
  7741. 'sort_order' => time() + $type,
  7742. 'is_deleted' => 0,
  7743. 'created_at' => $now,
  7744. 'updated_at' => $now,
  7745. ]);
  7746. }
  7747. }
  7748. $folder_id = $typeFolderIds[$type];
  7749. $product_id = DB::table('mp_products')->insertGetId([
  7750. 'user_id' => $uid,
  7751. 'cpid' => $cpid,
  7752. 'type' => 1, // 资产
  7753. 'product' => $type,
  7754. 'parent_id' => $folder_id,
  7755. 'level' => 2,
  7756. 'product_name' => $row['product_name'],
  7757. 'pic_prompt' => $row['pic_prompt'],
  7758. 'sort_order' => time(),
  7759. 'is_deleted' => 0,
  7760. 'created_at' => $now,
  7761. 'updated_at' => $now,
  7762. ]);
  7763. $createdProducts[] = [
  7764. 'id' => $product_id,
  7765. 'type' => $type,
  7766. 'product_name' => $row['product_name'],
  7767. 'pic_prompt' => $row['pic_prompt'],
  7768. ];
  7769. // 为每个使用范围(集数)创建映射记录
  7770. foreach ($row['episode_numbers'] as $episodeNumber) {
  7771. $mappingRecords[] = [
  7772. 'script_id' => $script_id,
  7773. 'product_id' => $product_id,
  7774. 'episode_number' => $episodeNumber,
  7775. 'created_at' => $now,
  7776. 'updated_at' => $now,
  7777. ];
  7778. }
  7779. }
  7780. // 批量插入映射数据(使用 insertOrIgnore 避免重复插入)
  7781. DB::table('mp_script_product_mappings')->insertOrIgnore($mappingRecords);
  7782. // 剧本已有资产,同步更新is_products标记
  7783. DB::table('mp_scripts')->where('id', $script_id)->update([
  7784. 'is_products' => 1,
  7785. 'updated_at' => $now,
  7786. ]);
  7787. DB::commit();
  7788. } catch (\Exception $e) {
  7789. DB::rollback();
  7790. if ($taskCenterId) {
  7791. $this->taskCenterService->updateTask($taskCenterId, [
  7792. 'status' => MpTaskCenter::STATUS_FAILED,
  7793. 'error_message' => $e->getMessage(),
  7794. ]);
  7795. }
  7796. dLog('anime')->error('Excel导入剧本资产失败: ' . $e->getMessage(), [
  7797. 'script_id' => $script_id,
  7798. 'error' => $e->getMessage(),
  7799. 'trace' => $e->getTraceAsString(),
  7800. ]);
  7801. Utils::throwError('20003:Excel导入剧本资产失败:' . $e->getMessage());
  7802. }
  7803. // 参照 saveScriptProducts:为新建资产以及已存在但缺图的资产统一补建图片生成任务
  7804. $existingTaskInfo = $this->prepareExistingScriptProductTasks(
  7805. $script_id,
  7806. $model,
  7807. $width,
  7808. $height,
  7809. $auto_generate_images
  7810. );
  7811. $productTaskMap = $existingTaskInfo['product_task_map'];
  7812. $resultData = [
  7813. 'success' => true,
  7814. 'message' => '导入完成',
  7815. 'script_id' => $script_id,
  7816. 'script_name' => $script_name,
  7817. 'imported_count' => count($createdProducts),
  7818. 'skipped_count' => count($skipped),
  7819. 'skipped' => $skipped,
  7820. 'created_products' => array_map(function ($item) {
  7821. return [
  7822. 'id' => $item['id'],
  7823. 'type' => $item['type'],
  7824. 'product_name' => $item['product_name'],
  7825. ];
  7826. }, $createdProducts),
  7827. 'type_folder_ids' => $typeFolderIds,
  7828. 'pending_tasks_count' => count($productTaskMap),
  7829. 'image_tasks_created' => $existingTaskInfo['created_count'],
  7830. 'task_center_id' => $taskCenterId,
  7831. ];
  7832. // 有待生成的图片任务:返回 SSE 轮询结果(导入统计在 init 与 complete 事件中)
  7833. if (!empty($productTaskMap)) {
  7834. return $this->pollProductImageTasks(
  7835. $script_id,
  7836. $script_name,
  7837. $productTaskMap,
  7838. $typeFolderIds,
  7839. $taskCenterId,
  7840. ['import_result' => $resultData],
  7841. ['import_result' => $resultData]
  7842. );
  7843. }
  7844. // 没有需要轮询的任务:直接通过 complete 事件返回导入结果
  7845. return $this->streamImportComplete($script_id, $script_name, $resultData, $typeFolderIds, $taskCenterId);
  7846. }
  7847. /**
  7848. * 校验 Excel 数据行(先校验完毕,再进行后续逻辑)
  7849. *
  7850. * @param array $rows
  7851. * @param int $typeColumnIndex
  7852. * @param int $nameColumnIndex
  7853. * @param int $rangeColumnIndex
  7854. * @param int $promptColumnIndex
  7855. * @return array ['errors' => [], 'checked_rows' => []]
  7856. */
  7857. private function validateImportExcelRows(array $rows, $typeColumnIndex, $nameColumnIndex, $rangeColumnIndex, $promptColumnIndex) {
  7858. $errors = [];
  7859. $checkedRows = [];
  7860. foreach ($rows as $rowIndex => $row) {
  7861. // 数据从第2行开始(表头占第1行)
  7862. $excelRowNo = $rowIndex + 2;
  7863. if (!is_array($row) || $this->isImportExcelRowEmpty($row)) {
  7864. continue;
  7865. }
  7866. $typeRaw = trim((string)($row[$typeColumnIndex] ?? ''));
  7867. $nameRaw = trim((string)($row[$nameColumnIndex] ?? ''));
  7868. $rangeRaw = trim((string)($row[$rangeColumnIndex] ?? ''));
  7869. $promptRaw = trim((string)($row[$promptColumnIndex] ?? ''));
  7870. $missingFields = [];
  7871. if ($typeRaw === '') {
  7872. $missingFields[] = '资产类型';
  7873. }
  7874. if ($nameRaw === '') {
  7875. $missingFields[] = '资产名称';
  7876. }
  7877. if ($rangeRaw === '') {
  7878. $missingFields[] = '使用范围';
  7879. }
  7880. if ($promptRaw === '') {
  7881. $missingFields[] = '参考提示词';
  7882. }
  7883. if (!empty($missingFields)) {
  7884. $errors[] = "第{$excelRowNo}行:" . implode('、', $missingFields) . '不能为空';
  7885. continue;
  7886. }
  7887. // 资产类型校验
  7888. $productType = $this->resolveImportProductType($typeRaw);
  7889. if (!$productType) {
  7890. $errors[] = "第{$excelRowNo}行:资产类型「{$typeRaw}」不正确,仅支持 角色/场景/道具";
  7891. continue;
  7892. }
  7893. // 资产名称去除两边特殊符号
  7894. $productName = $this->normalizeImportProductName($nameRaw);
  7895. if ($productName === '') {
  7896. $errors[] = "第{$excelRowNo}行:资产名称「{$nameRaw}」去除特殊符号后为空";
  7897. continue;
  7898. }
  7899. if (mb_strlen($productName, 'UTF-8') > 64) {
  7900. $errors[] = "第{$excelRowNo}行:资产名称「{$productName}」超过64个字符";
  7901. continue;
  7902. }
  7903. // 解析使用范围(逗号分隔的集数)
  7904. $episodeNumbers = $this->parseImportEpisodeNumbers($rangeRaw);
  7905. if (empty($episodeNumbers)) {
  7906. $errors[] = "第{$excelRowNo}行:使用范围「{$rangeRaw}」格式错误,仅支持数字或逗号分隔的数字";
  7907. continue;
  7908. }
  7909. $checkedRows[] = [
  7910. 'row' => $excelRowNo,
  7911. 'type' => $productType,
  7912. 'product_name' => $productName,
  7913. 'episode_numbers' => $episodeNumbers,
  7914. 'pic_prompt' => $promptRaw,
  7915. ];
  7916. }
  7917. return [
  7918. 'errors' => $errors,
  7919. 'checked_rows' => $checkedRows,
  7920. ];
  7921. }
  7922. /**
  7923. * Excel 资产名称去重:Excel 内部 + 剧本已有关联资产
  7924. *
  7925. * @param array $checkedRows
  7926. * @param array $existingNames 剧本已有关联资产名称集合(name => true)
  7927. * @return array ['valid_rows' => [], 'skipped' => []]
  7928. */
  7929. private function deduplicateImportRows(array $checkedRows, array $existingNames) {
  7930. $seenNames = [];
  7931. $validRows = [];
  7932. $skipped = [];
  7933. foreach ($checkedRows as $row) {
  7934. $nameKey = $row['product_name'];
  7935. $typeText = $this->getImportProductTypeText($row['type']);
  7936. if (isset($seenNames[$nameKey])) {
  7937. $skipped[] = [
  7938. 'row' => $row['row'],
  7939. 'type' => $typeText,
  7940. 'product_name' => $row['product_name'],
  7941. 'reason' => 'Excel中资产名称重复',
  7942. ];
  7943. continue;
  7944. }
  7945. if (isset($existingNames[$nameKey])) {
  7946. $skipped[] = [
  7947. 'row' => $row['row'],
  7948. 'type' => $typeText,
  7949. 'product_name' => $row['product_name'],
  7950. 'reason' => '剧本中已存在同名资产',
  7951. ];
  7952. continue;
  7953. }
  7954. $seenNames[$nameKey] = true;
  7955. $validRows[] = $row;
  7956. }
  7957. return [
  7958. 'valid_rows' => $validRows,
  7959. 'skipped' => $skipped,
  7960. ];
  7961. }
  7962. /**
  7963. * 读取 Excel 文件为二维数组(第一行为表头)
  7964. *
  7965. * @param \Illuminate\Http\UploadedFile $file
  7966. * @return array
  7967. */
  7968. private function readImportExcelRows($file) {
  7969. try {
  7970. $reader = IOFactory::createReaderForFile($file->getRealPath());
  7971. $reader->setReadDataOnly(true);
  7972. $spreadsheet = $reader->load($file->getRealPath());
  7973. $sheet = $spreadsheet->getSheet(0);
  7974. $rows = $sheet->toArray(null, true, true, false);
  7975. $spreadsheet->disconnectWorksheets();
  7976. unset($spreadsheet);
  7977. return $rows;
  7978. } catch (\Exception $e) {
  7979. dLog('anime')->error('Excel文件解析失败', [
  7980. 'error' => $e->getMessage(),
  7981. ]);
  7982. Utils::throwError('20003:Excel文件解析失败,请确认文件格式正确');
  7983. }
  7984. }
  7985. /**
  7986. * 查找 Excel 表头列索引(先精确匹配,再模糊匹配)
  7987. *
  7988. * @param array $headers
  7989. * @param array $exactKeywords
  7990. * @param array $fuzzyKeywords
  7991. * @return int
  7992. */
  7993. private function findImportExcelColumnIndex(array $headers, array $exactKeywords, array $fuzzyKeywords) {
  7994. foreach ($headers as $index => $header) {
  7995. $header = trim((string)$header);
  7996. if ($header === '') {
  7997. continue;
  7998. }
  7999. foreach ($exactKeywords as $keyword) {
  8000. if ($header === $keyword) {
  8001. return $index;
  8002. }
  8003. }
  8004. }
  8005. foreach ($headers as $index => $header) {
  8006. $header = trim((string)$header);
  8007. if ($header === '') {
  8008. continue;
  8009. }
  8010. foreach ($fuzzyKeywords as $keyword) {
  8011. if (mb_strpos($header, $keyword) !== false) {
  8012. return $index;
  8013. }
  8014. }
  8015. }
  8016. return -1;
  8017. }
  8018. /**
  8019. * 判断 Excel 行是否为空行
  8020. *
  8021. * @param array $row
  8022. * @return bool
  8023. */
  8024. private function isImportExcelRowEmpty(array $row) {
  8025. foreach ($row as $cell) {
  8026. if (trim((string)$cell) !== '') {
  8027. return false;
  8028. }
  8029. }
  8030. return true;
  8031. }
  8032. /**
  8033. * 资产名称去除两边特殊符号(与 createProduct 保持一致)
  8034. *
  8035. * @param string $name
  8036. * @return string
  8037. */
  8038. private function normalizeImportProductName($name) {
  8039. $name = trim((string)$name);
  8040. $name = preg_replace('/^[\s*\[\]【】[]{}{}\x{3000}]+|[\s*\[\]【】[]{}{}\x{3000}]+$/u', '', $name);
  8041. if (!$name || preg_match('/^[-—_]+$/u', $name)) {
  8042. return '';
  8043. }
  8044. return $name;
  8045. }
  8046. /**
  8047. * 解析 Excel 中的资产类型
  8048. *
  8049. * @param string $value
  8050. * @return int|null 1=角色 2=场景 3=道具
  8051. */
  8052. private function resolveImportProductType($value) {
  8053. $value = trim((string)$value);
  8054. $map = [
  8055. '角色' => 1,
  8056. '主体' => 1,
  8057. '人物' => 1,
  8058. '1' => 1,
  8059. '场景' => 2,
  8060. '2' => 2,
  8061. '道具' => 3,
  8062. '3' => 3,
  8063. ];
  8064. return isset($map[$value]) ? $map[$value] : null;
  8065. }
  8066. /**
  8067. * 资产类型文案
  8068. *
  8069. * @param int $type
  8070. * @return string
  8071. */
  8072. private function getImportProductTypeText($type) {
  8073. $map = [1 => '角色', 2 => '场景', 3 => '道具'];
  8074. return isset($map[$type]) ? $map[$type] : (string)$type;
  8075. }
  8076. /**
  8077. * 解析使用范围(逗号分隔的集数)
  8078. *
  8079. * @param string $value
  8080. * @return array
  8081. */
  8082. private function parseImportEpisodeNumbers($value) {
  8083. $parts = preg_split('/[,,、\s]+/u', trim((string)$value));
  8084. $episodeNumbers = [];
  8085. foreach ($parts as $part) {
  8086. if ($part === '') {
  8087. continue;
  8088. }
  8089. if (!is_numeric($part)) {
  8090. return [];
  8091. }
  8092. $episodeNumbers[] = (int)$part;
  8093. }
  8094. $episodeNumbers = array_values(array_unique($episodeNumbers));
  8095. sort($episodeNumbers);
  8096. return $episodeNumbers;
  8097. }
  8098. /**
  8099. * 获取剧本已关联资产名称集合(按 createProduct 的名称判断逻辑)
  8100. *
  8101. * @param int $script_id
  8102. * @param int $cpid
  8103. * @return array
  8104. */
  8105. private function getScriptProductNames($script_id, $cpid) {
  8106. $products = DB::table('mp_script_product_mappings as m')
  8107. ->join('mp_products as p', 'm.product_id', '=', 'p.id')
  8108. ->where('m.script_id', $script_id)
  8109. ->where('p.cpid', $cpid)
  8110. ->where('p.type', 1)
  8111. ->where('p.is_deleted', 0)
  8112. ->get(['p.product_name']);
  8113. $names = [];
  8114. foreach ($products as $product) {
  8115. $name = $this->normalizeImportProductName($product->product_name);
  8116. if ($name !== '') {
  8117. $names[$name] = true;
  8118. }
  8119. }
  8120. return $names;
  8121. }
  8122. /**
  8123. * 获取剧本已关联的资产名称(仅按剧本判重,不区分资产类型)
  8124. *
  8125. * @param int $script_id
  8126. * @return array ['资产名称' => true]
  8127. */
  8128. private function getScriptAssetNames($script_id) {
  8129. $products = DB::table('mp_script_product_mappings as m')
  8130. ->join('mp_products as p', 'm.product_id', '=', 'p.id')
  8131. ->where('m.script_id', $script_id)
  8132. ->where('p.type', 1)
  8133. ->where('p.is_deleted', 0)
  8134. ->get(['p.product_name']);
  8135. $names = [];
  8136. foreach ($products as $product) {
  8137. $name = $this->normalizeImportProductName($product->product_name);
  8138. if ($name !== '') {
  8139. $names[$name] = true;
  8140. }
  8141. }
  8142. return $names;
  8143. }
  8144. /**
  8145. * 校验并提取本次入参中的新增资产行
  8146. *
  8147. * 规则:
  8148. * - 资产名称为空(或仅剩占位符):跳过
  8149. * - 同一份入参内重名(跨类型):保留最后一条
  8150. * - 与剧本已关联资产同名(跨类型判重,仅限当前剧本):不算新增
  8151. * - 新增行的参考提示词为空:直接报错,不进行任何后续处理
  8152. *
  8153. * @param int $script_id
  8154. * @param mixed $products 入参(数组或 JSON 字符串)
  8155. * @return array [['type' => int, 'product_name' => string, 'pic_prompt' => string, 'episode_numbers' => []]]
  8156. */
  8157. private function extractNewScriptProductRows($script_id, $products) {
  8158. // 兼容 JSON 字符串;无法解析时按"没有新增行"处理,由后续创建逻辑给出原有报错
  8159. if (is_string($products)) {
  8160. $decoded = json_decode($products, true);
  8161. $products = (json_last_error() === JSON_ERROR_NONE) ? $decoded : [];
  8162. }
  8163. if (!is_array($products) || empty($products)) {
  8164. return [];
  8165. }
  8166. $rowMap = [];
  8167. foreach ($products as $productGroup) {
  8168. $type = getProp($productGroup, 'type');
  8169. $content = getProp($productGroup, 'content', []);
  8170. if (!in_array($type, [1, 2, 3]) || empty($content) || count($content) < 2) {
  8171. continue;
  8172. }
  8173. // 获取表头(第一行)并查找关键列的位置
  8174. $headers = $content[0];
  8175. $nameColumnIndex = -1;
  8176. $sequenceColumnIndex = -1;
  8177. $promptColumnIndex = -1;
  8178. $fallbackPromptColumnIndex = -1;
  8179. foreach ($headers as $index => $header) {
  8180. if (strpos($header, '资产名称') !== false || strpos($header, '名称') !== false) {
  8181. $nameColumnIndex = $index;
  8182. }
  8183. if (strpos($header, '使用范围') !== false || strpos($header, '范围') !== false) {
  8184. $sequenceColumnIndex = $index;
  8185. }
  8186. if (strpos($header, '参考') !== false && strpos($header, '提示词') !== false) {
  8187. $promptColumnIndex = $index;
  8188. } elseif (strpos($header, '提示词') !== false && $fallbackPromptColumnIndex === -1) {
  8189. // 与 Excel 导入保持一致:优先"参考提示词",否则兼容"提示词"列
  8190. $fallbackPromptColumnIndex = $index;
  8191. }
  8192. }
  8193. if ($promptColumnIndex === -1) {
  8194. $promptColumnIndex = $fallbackPromptColumnIndex;
  8195. }
  8196. if ($nameColumnIndex === -1) {
  8197. continue;
  8198. }
  8199. for ($i = 1; $i < count($content); $i++) {
  8200. $row = $content[$i];
  8201. if (empty($row) || !isset($row[$nameColumnIndex])) {
  8202. continue;
  8203. }
  8204. // 处理product_name两边的符号;名称为空或仅剩占位符号则跳过
  8205. $product_name = $this->normalizeImportProductName($row[$nameColumnIndex]);
  8206. if ($product_name === '') {
  8207. continue;
  8208. }
  8209. $pic_prompt = '';
  8210. if ($promptColumnIndex >= 0 && isset($row[$promptColumnIndex])) {
  8211. $pic_prompt = trim((string)$row[$promptColumnIndex]);
  8212. }
  8213. // 解析使用范围(逗号分隔的序号),为空时由创建逻辑写入默认映射(序号0)
  8214. $sequences = [];
  8215. $sequence_str = ($sequenceColumnIndex >= 0 && isset($row[$sequenceColumnIndex]))
  8216. ? trim((string)$row[$sequenceColumnIndex])
  8217. : '';
  8218. if ($sequence_str !== '') {
  8219. foreach (array_map('trim', explode(',', $sequence_str)) as $part) {
  8220. if (is_numeric($part)) {
  8221. $sequences[] = (int)$part;
  8222. }
  8223. }
  8224. }
  8225. // 跨类型判重,同一份入参内重名保留最后一条
  8226. $rowMap[$product_name] = [
  8227. 'type' => (int)$type,
  8228. 'product_name' => $product_name,
  8229. 'pic_prompt' => $pic_prompt,
  8230. 'episode_numbers' => $sequences,
  8231. ];
  8232. }
  8233. }
  8234. // 与剧本已关联资产判重(仅限当前剧本,跨类型)
  8235. $existingNames = $this->getScriptAssetNames($script_id);
  8236. $newRows = [];
  8237. $emptyPromptNames = [];
  8238. foreach ($rowMap as $name => $row) {
  8239. if (isset($existingNames[$name])) {
  8240. continue;
  8241. }
  8242. if ($row['pic_prompt'] === '') {
  8243. $emptyPromptNames[] = $name;
  8244. continue;
  8245. }
  8246. $newRows[] = $row;
  8247. }
  8248. // 新增行的参考提示词为空:直接报错,不进行任何后续处理
  8249. if (!empty($emptyPromptNames)) {
  8250. Utils::throwError('20003:以下新增资产的参考提示词不能为空:' . implode('、', $emptyPromptNames));
  8251. }
  8252. return $newRows;
  8253. }
  8254. /**
  8255. * 已有关联资产的图片任务处理(参照 saveScriptProducts 的处理方式)
  8256. *
  8257. * - 已有图片任务的资产:收集任务ID,交给轮询
  8258. * - 已有图片且生成成功的资产:跳过
  8259. * - 没有图片的资产:允许自动生成时补建图片任务(需要提示词)
  8260. *
  8261. * @param int $script_id
  8262. * @param string $model
  8263. * @param int $width
  8264. * @param int $height
  8265. * @param bool $auto_generate_images
  8266. * @return array ['product_task_map' => [], 'type_folder_ids' => [], 'has_all_tasks' => bool, 'product_count' => int, 'created_count' => int]
  8267. */
  8268. private function prepareExistingScriptProductTasks($script_id, $model, $width, $height, $auto_generate_images) {
  8269. $productTaskMap = [];
  8270. $typeFolderIds = [];
  8271. $hasAllTasks = true;
  8272. $createdCount = 0;
  8273. $existingMappings = DB::table('mp_script_product_mappings')
  8274. ->where('script_id', $script_id)
  8275. ->get();
  8276. $productIds = $existingMappings->pluck('product_id')->unique()->toArray();
  8277. $productsWithTasks = DB::table('mp_products')
  8278. ->whereIn('id', $productIds)
  8279. ->where('is_deleted', 0)
  8280. ->get();
  8281. foreach ($productsWithTasks as $product) {
  8282. // 收集类型文件夹ID
  8283. if ($product->parent_id > 0 && !in_array($product->parent_id, $typeFolderIds)) {
  8284. $parentFolder = DB::table('mp_products')
  8285. ->where('id', $product->parent_id)
  8286. ->where('type', 2)
  8287. ->first();
  8288. if ($parentFolder) {
  8289. $typeFolderIds[$parentFolder->product] = $parentFolder->id;
  8290. }
  8291. }
  8292. // 检查是否有图片生成任务
  8293. if (!empty($product->pic_task_id)) {
  8294. $productTaskMap[$product->id] = $product->pic_task_id;
  8295. } elseif ($product->url && $product->pic_task_status == '生成成功') {
  8296. continue;
  8297. } else {
  8298. // 有资产没有图片
  8299. $hasAllTasks = false;
  8300. }
  8301. }
  8302. // 为没有图片的资产补建图片生成任务
  8303. if (!$hasAllTasks && $auto_generate_images && $productsWithTasks->isNotEmpty()) {
  8304. DB::beginTransaction();
  8305. try {
  8306. foreach ($productsWithTasks as $product) {
  8307. // 跳过已有任务的资产
  8308. if (!empty($product->pic_task_id)) {
  8309. continue;
  8310. }
  8311. // 跳过没有提示词的资产
  8312. if (empty($product->pic_prompt)) {
  8313. dLog('anime')->warning('资产没有提示词,跳过图片生成', [
  8314. 'product_id' => $product->id,
  8315. 'product_name' => $product->product_name,
  8316. ]);
  8317. continue;
  8318. }
  8319. try {
  8320. $task = $this->aiImageGenerationService->createImageGenerationTask([
  8321. 'prompt' => $product->pic_prompt,
  8322. 'model' => $model,
  8323. 'ref_img_urls' => [],
  8324. 'width' => $width,
  8325. 'height' => $height,
  8326. // 计费锚点(剧本),用于积分明细归属统计
  8327. 'script_id' => $script_id,
  8328. ]);
  8329. $task_id = $task->id;
  8330. if ($task_id) {
  8331. $productTaskMap[$product->id] = $task_id;
  8332. $createdCount++;
  8333. DB::table('mp_products')
  8334. ->where('id', $product->id)
  8335. ->update([
  8336. 'pic_task_id' => $task_id,
  8337. 'pic_task_status' => '生成中',
  8338. 'updated_at' => now(),
  8339. ]);
  8340. dLog('anime')->info('为已存在资产创建图片生成任务', [
  8341. 'product_id' => $product->id,
  8342. 'task_id' => $task_id,
  8343. ]);
  8344. }
  8345. } catch (\Exception $e) {
  8346. dLog('anime')->error('创建资产图片生成任务失败', [
  8347. 'product_id' => $product->id,
  8348. 'error' => $e->getMessage(),
  8349. ]);
  8350. DB::table('mp_products')
  8351. ->where('id', $product->id)
  8352. ->update([
  8353. 'pic_task_status' => '生成失败',
  8354. 'updated_at' => now(),
  8355. ]);
  8356. }
  8357. }
  8358. DB::commit();
  8359. } catch (\Exception $e) {
  8360. DB::rollback();
  8361. dLog('anime')->error('为已存在资产创建图片任务失败', [
  8362. 'script_id' => $script_id,
  8363. 'error' => $e->getMessage(),
  8364. ]);
  8365. Utils::throwError('20003:创建图片任务失败:' . $e->getMessage());
  8366. }
  8367. }
  8368. return [
  8369. 'product_task_map' => $productTaskMap,
  8370. 'type_folder_ids' => $typeFolderIds,
  8371. 'has_all_tasks' => $hasAllTasks,
  8372. 'product_count' => count($productIds),
  8373. 'created_count' => $createdCount,
  8374. ];
  8375. }
  8376. /**
  8377. * 保存剧本资产关联关系
  8378. * @param array $data 请求参数
  8379. * @return bool
  8380. */
  8381. public function saveScriptProducts($data) {
  8382. $uid = Site::getUid();
  8383. $cpid = Site::getCpid();
  8384. $script_id = getProp($data, 'script_id');
  8385. $products = getProp($data, 'products', []);
  8386. $auto_generate_images = getProp($data, 'auto_generate_images', true); // 是否自动生成图片,默认true
  8387. if (!$script_id) {
  8388. Utils::throwError('20003:请提供剧本ID');
  8389. }
  8390. // 验证剧本是否存在
  8391. $script = DB::table('mp_scripts')
  8392. ->where('id', $script_id)
  8393. ->where('is_deleted', 0)
  8394. ->first();
  8395. if (!$script) {
  8396. Utils::throwError('20003:剧本不存在');
  8397. }
  8398. // 处理图片模型
  8399. $model = getProp($data, 'model');
  8400. if (!$model) {
  8401. // 使用默认模型
  8402. $model = 'gpt-image-2';
  8403. }
  8404. // 验证模型是否在可用模型表中
  8405. if (!DB::table('mp_image_models')->where('model', $model)->where('is_enabled', 1)->exists()) {
  8406. Utils::throwError('20003:该模型已不可用,请更换!');
  8407. }
  8408. $ratio = getProp($data, 'ratio', '9:16');
  8409. $resolution = getProp($data, 'resolution', '2k');
  8410. // 分辨率档位与尺寸映射统一从 BaseConst 获取
  8411. $sizeMap = BaseConst::IMAGE_RESOLUTION_SIZE_MAP;
  8412. // 参数验证
  8413. $resolution = strtolower($resolution);
  8414. if (!isset($sizeMap[$resolution])) {
  8415. Utils::throwError('20003:分辨率参数错误,仅支持 2k、3k、4k');
  8416. }
  8417. if (!isset($sizeMap[$resolution][$ratio])) {
  8418. Utils::throwError('20003:宽高比参数错误,该分辨率下不支持 ' . $ratio . ' 比例');
  8419. }
  8420. // 根据 ratio 和 resolution 确定宽高
  8421. $width = $sizeMap[$resolution][$ratio]['width'];
  8422. $height = $sizeMap[$resolution][$ratio]['height'];
  8423. $script_name = $script->script_name ?? 'script_' . $script_id;
  8424. // 先校验并提取本次入参中的新增资产行:
  8425. // 新增行的参考提示词为空时直接报错,不写任何数据、不创建任务中心记录
  8426. $newRows = $this->extractNewScriptProductRows($script_id, $products);
  8427. // 根据入参创建/复用任务中心记录(params md5 验重,避免重复任务)
  8428. $taskCenterId = $this->createScriptProductTaskCenter(
  8429. $uid,
  8430. $cpid,
  8431. $script_id,
  8432. $products,
  8433. $model,
  8434. $ratio,
  8435. $resolution,
  8436. $auto_generate_images
  8437. );
  8438. // 检查是否已经有该剧本的资产数据
  8439. $existingMappings = DB::table('mp_script_product_mappings')
  8440. ->where('script_id', $script_id)
  8441. ->get();
  8442. // 已有资产且本次没有新增行时,走原有的"已存在"处理;否则走下方创建逻辑
  8443. if ($existingMappings->isNotEmpty() && empty($newRows)) {
  8444. // 已存在资产映射,检查是否所有资产都有图片生成任务
  8445. $productIds = $existingMappings->pluck('product_id')->unique()->toArray();
  8446. // 查询这些资产的图片生成任务状态
  8447. $productsWithTasks = DB::table('mp_products')
  8448. ->whereIn('id', $productIds)
  8449. ->where('is_deleted', 0)
  8450. ->get();
  8451. $productTaskMap = [];
  8452. $typeFolderIds = [];
  8453. $hasAllTasks = true;
  8454. foreach ($productsWithTasks as $product) {
  8455. // 收集类型文件夹ID
  8456. if ($product->parent_id > 0 && !in_array($product->parent_id, $typeFolderIds)) {
  8457. $parentFolder = DB::table('mp_products')
  8458. ->where('id', $product->parent_id)
  8459. ->where('type', 2)
  8460. ->first();
  8461. if ($parentFolder) {
  8462. $typeFolderIds[$parentFolder->product] = $parentFolder->id;
  8463. }
  8464. }
  8465. // 检查是否有图片生成任务
  8466. if (!empty($product->pic_task_id)) {
  8467. $productTaskMap[$product->id] = $product->pic_task_id;
  8468. } else if($product->url && $product->pic_task_status == '生成成功') {
  8469. continue;
  8470. } else {
  8471. // 有资产没有图片任务
  8472. $hasAllTasks = false;
  8473. }
  8474. }
  8475. // 如果所有资产都有任务ID,直接轮询返回结果
  8476. if ($hasAllTasks && !empty($productTaskMap)) {
  8477. dLog('anime')->info('剧本资产已存在且都有图片任务,直接轮询结果', [
  8478. 'script_id' => $script_id,
  8479. 'script_name' => $script_name,
  8480. 'product_count' => count($productTaskMap)
  8481. ]);
  8482. // 直接返回 SSE 流轮询结果
  8483. return $this->pollProductImageTasks($script_id, $script_name, $productTaskMap, $typeFolderIds, $taskCenterId);
  8484. }
  8485. // 如果部分资产没有任务ID,只为这些资产创建任务
  8486. if (!$hasAllTasks && $auto_generate_images) {
  8487. dLog('anime')->info('剧本资产已存在,但部分资产没有图片任务,为缺失的资产创建任务', [
  8488. 'script_id' => $script_id,
  8489. 'script_name' => $script_name
  8490. ]);
  8491. // 开启事务
  8492. DB::beginTransaction();
  8493. try {
  8494. foreach ($productsWithTasks as $product) {
  8495. // 跳过已有任务的资产
  8496. if (!empty($product->pic_task_id)) {
  8497. continue;
  8498. }
  8499. // 跳过没有提示词的资产
  8500. if (empty($product->pic_prompt)) {
  8501. dLog('anime')->warning('资产没有提示词,跳过图片生成', [
  8502. 'product_id' => $product->id,
  8503. 'product_name' => $product->product_name
  8504. ]);
  8505. continue;
  8506. }
  8507. try {
  8508. // 创建图片生成任务
  8509. $params = [
  8510. 'prompt' => $product->pic_prompt,
  8511. 'model' => $model,
  8512. 'ref_img_urls' => [],
  8513. 'width' => $width,
  8514. 'height' => $height,
  8515. // 计费锚点(剧本),用于积分明细归属统计
  8516. 'script_id' => $script_id,
  8517. ];
  8518. $task = $this->aiImageGenerationService->createImageGenerationTask($params);
  8519. $task_id = $task->id;
  8520. if ($task_id) {
  8521. $productTaskMap[$product->id] = $task_id;
  8522. // 在事务中更新资产表的任务ID和状态
  8523. DB::table('mp_products')
  8524. ->where('id', $product->id)
  8525. ->update([
  8526. 'pic_task_id' => $task_id,
  8527. 'pic_task_status' => '生成中',
  8528. 'updated_at' => now()
  8529. ]);
  8530. dLog('anime')->info('为已存在资产创建图片生成任务', [
  8531. 'product_id' => $product->id,
  8532. 'task_id' => $task_id
  8533. ]);
  8534. }
  8535. } catch (\Exception $e) {
  8536. dLog('anime')->error('创建资产图片生成任务失败', [
  8537. 'product_id' => $product->id,
  8538. 'error' => $e->getMessage()
  8539. ]);
  8540. // 标记为失败(仍在事务中)
  8541. DB::table('mp_products')
  8542. ->where('id', $product->id)
  8543. ->update([
  8544. 'pic_task_status' => '生成失败',
  8545. 'updated_at' => now()
  8546. ]);
  8547. }
  8548. }
  8549. // 提交事务
  8550. DB::commit();
  8551. // 如果有新创建的任务,返回 SSE 流
  8552. if (!empty($productTaskMap)) {
  8553. return $this->pollProductImageTasks($script_id, $script_name, $productTaskMap, $typeFolderIds, $taskCenterId);
  8554. }
  8555. } catch (\Exception $e) {
  8556. // 回滚事务
  8557. DB::rollback();
  8558. dLog('anime')->error('为已存在资产创建图片任务失败', [
  8559. 'script_id' => $script_id,
  8560. 'error' => $e->getMessage()
  8561. ]);
  8562. Utils::throwError('20003:创建图片任务失败:' . $e->getMessage());
  8563. }
  8564. }
  8565. // 如果不需要生成图片,返回已存在的信息
  8566. $resultData = [
  8567. 'success' => true,
  8568. 'message' => '剧本资产已存在',
  8569. 'script_id' => $script_id,
  8570. 'script_name' => $script_name,
  8571. 'type_folder_ids' => $typeFolderIds,
  8572. 'existing_products' => count($productIds),
  8573. 'tasks_count' => count($productTaskMap),
  8574. 'task_center_id' => $taskCenterId
  8575. ];
  8576. // 接口已正常完成,更新任务中心状态和结果
  8577. if ($taskCenterId) {
  8578. $this->taskCenterService->updateTask($taskCenterId, [
  8579. 'status' => MpTaskCenter::STATUS_SUCCESS,
  8580. 'result' => json_encode($resultData, JSON_UNESCAPED_UNICODE),
  8581. 'error_message' => null
  8582. ]);
  8583. }
  8584. return $resultData;
  8585. }
  8586. // 走到这里说明有新行需要创建(或剧本还没有任何资产),保留原有的入参校验报错
  8587. if (empty($newRows)) {
  8588. $decodedProducts = $products;
  8589. if (is_string($decodedProducts)) {
  8590. $decodedProducts = json_decode($decodedProducts, true);
  8591. if (json_last_error() !== JSON_ERROR_NONE) {
  8592. Utils::throwError('20003:产品数据格式错误');
  8593. }
  8594. }
  8595. if (!is_array($decodedProducts) || empty($decodedProducts)) {
  8596. Utils::throwError('20003:产品数据不能为空');
  8597. }
  8598. Utils::throwError('20003:没有有效的产品数据');
  8599. }
  8600. // 仅保留本次新增的资产行,复用下方原有的创建逻辑
  8601. $products = [];
  8602. foreach ($newRows as $newRow) {
  8603. if (!isset($products[$newRow['type']])) {
  8604. $products[$newRow['type']] = [
  8605. 'type' => $newRow['type'],
  8606. 'content' => [['资产名称', '使用范围', '参考提示词']],
  8607. ];
  8608. }
  8609. $products[$newRow['type']]['content'][] = [
  8610. $newRow['product_name'],
  8611. implode(',', $newRow['episode_numbers']),
  8612. $newRow['pic_prompt'],
  8613. ];
  8614. }
  8615. $products = array_values($products);
  8616. // 以下是原有的创建逻辑...
  8617. // 开启事务
  8618. DB::beginTransaction();
  8619. try {
  8620. $now = now();
  8621. $mappingRecords = [];
  8622. $createdProductIds = []; // 记录所有创建的资产ID
  8623. // 获取剧本名称
  8624. $script_name = $script->script_name ?? 'script_' . $script_id;
  8625. // 存储每个类型的根文件夹ID
  8626. $typeFolderIds = [];
  8627. // 遍历每个产品类型(type: 1=角色, 2=场景, 3=道具)
  8628. foreach ($products as $productGroup) {
  8629. $type = getProp($productGroup, 'type');
  8630. $title = getProp($productGroup, 'title', '');
  8631. $content = getProp($productGroup, 'content', []);
  8632. if (!in_array($type, [1, 2, 3]) || empty($content) || count($content) < 2) {
  8633. continue;
  8634. }
  8635. // 为当前类型获取根文件夹:该剧本已存在则复用,避免重复创建根文件夹
  8636. if (!isset($typeFolderIds[$type])) {
  8637. $folder = DB::table('mp_products')
  8638. ->where('cpid', $cpid)
  8639. ->where('type', 2)
  8640. ->where('product', $type)
  8641. ->where('product_name', $script_name)
  8642. ->where('parent_id', 0)
  8643. ->where('is_deleted', 0)
  8644. ->first();
  8645. if ($folder) {
  8646. $typeFolderIds[$type] = $folder->id;
  8647. } else {
  8648. $typeFolderIds[$type] = DB::table('mp_products')->insertGetId([
  8649. 'user_id' => $uid,
  8650. 'cpid' => $cpid,
  8651. 'type' => 2, // 1.资产 2文件夹
  8652. 'product' => $type, // 1.主体 2.场景 3.道具
  8653. 'parent_id' => 0, // 根文件夹,parent_id=0
  8654. 'level' => 1, // 第一层级
  8655. 'product_name' => $script_name,
  8656. 'sort_order' => time() + $type,
  8657. 'is_deleted' => 0,
  8658. 'created_at' => $now,
  8659. 'updated_at' => $now
  8660. ]);
  8661. }
  8662. }
  8663. $folder_id = $typeFolderIds[$type];
  8664. // 获取表头(第一行)并查找关键列的位置
  8665. $headers = $content[0];
  8666. $nameColumnIndex = -1; // 资产名称列索引
  8667. $sequenceColumnIndex = -1; // 使用范围列索引
  8668. $promptColumnIndex = -1; // 参考提示词列索引
  8669. foreach ($headers as $index => $header) {
  8670. // 查找"资产名称"列
  8671. if (strpos($header, '资产名称') !== false || strpos($header, '名称') !== false) {
  8672. $nameColumnIndex = $index;
  8673. }
  8674. // 查找"使用范围"列
  8675. if (strpos($header, '使用范围') !== false || strpos($header, '范围') !== false) {
  8676. $sequenceColumnIndex = $index;
  8677. }
  8678. // 查找"参考提示词"列(可能是"干净参考图提示词"、"参考提示词"等)
  8679. if (strpos($header, '参考') !== false && strpos($header, '提示词') !== false) {
  8680. $promptColumnIndex = $index;
  8681. }
  8682. }
  8683. // 验证必要的列是否都找到了
  8684. if ($nameColumnIndex === -1) {
  8685. dLog('anime')->warning('未找到资产名称列', ['type' => $type, 'headers' => $headers]);
  8686. continue;
  8687. }
  8688. if ($sequenceColumnIndex === -1) {
  8689. dLog('anime')->warning('未找到使用范围列', ['type' => $type, 'headers' => $headers]);
  8690. continue;
  8691. }
  8692. // 跳过表头,解析每一行数据
  8693. for ($i = 1; $i < count($content); $i++) {
  8694. $row = $content[$i];
  8695. // 确保行数据有效
  8696. if (empty($row) || count($row) <= max($nameColumnIndex, $sequenceColumnIndex)) {
  8697. continue;
  8698. }
  8699. // 根据动态查找的列索引提取数据
  8700. $product_name = isset($row[$nameColumnIndex]) ? trim((string)$row[$nameColumnIndex]) : '';
  8701. $sequence_str = isset($row[$sequenceColumnIndex]) ? trim($row[$sequenceColumnIndex]) : '';
  8702. $pic_prompt = '';
  8703. // 提取参考提示词(如果找到了该列)
  8704. if ($promptColumnIndex >= 0 && isset($row[$promptColumnIndex])) {
  8705. $pic_prompt = trim($row[$promptColumnIndex]);
  8706. }
  8707. // 解析使用范围(逗号分隔的序号)
  8708. $sequences = [];
  8709. if (!empty($sequence_str)) {
  8710. $sequenceParts = array_map('trim', explode(',', $sequence_str));
  8711. foreach ($sequenceParts as $part) {
  8712. if (is_numeric($part)) {
  8713. $sequences[] = (int)$part;
  8714. }
  8715. }
  8716. }
  8717. if (empty($product_name)) {
  8718. continue;
  8719. }
  8720. // 处理product_name两边的符号
  8721. $product_name = preg_replace('/^[\s*\[\]【】[]{}{}\x{3000}]+|[\s*\[\]【】[]{}{}\x{3000}]+$/u', '', $product_name);
  8722. // 如果名称不存在或仅剩占位符号,则跳过
  8723. if (!$product_name || preg_match('/^[-—_]+$/u', $product_name)) {
  8724. dLog('anime')->warning('资产名称无效,跳过保存', [
  8725. 'script_id' => $script_id,
  8726. 'type' => $type,
  8727. 'product_name' => $product_name
  8728. ]);
  8729. continue;
  8730. }
  8731. // 直接插入新资产到 mp_products 表(parent_id 指向对应类型的根文件夹)
  8732. $product_id = DB::table('mp_products')->insertGetId([
  8733. 'product_name' => $product_name,
  8734. 'type' => 1, // 1=资产 2.文件夹
  8735. 'product' => $type, // 1=角色, 2=场景, 3=道具
  8736. 'parent_id' => $folder_id, // 父文件夹是该类型的根文件夹
  8737. 'level' => 2, // 第二层级
  8738. 'pic_prompt' => $pic_prompt,
  8739. 'user_id' => $uid,
  8740. 'cpid' => $cpid,
  8741. 'sort_order' => time(),
  8742. 'is_deleted' => 0,
  8743. 'created_at' => $now,
  8744. 'updated_at' => $now,
  8745. ]);
  8746. // 记录创建的资产ID
  8747. $createdProductIds[] = $product_id;
  8748. // 为每个序号创建映射记录
  8749. if (!empty($sequences)) {
  8750. foreach ($sequences as $sequence) {
  8751. $mappingRecords[] = [
  8752. 'script_id' => $script_id,
  8753. 'product_id' => $product_id,
  8754. 'episode_number' => $sequence,
  8755. 'created_at' => $now,
  8756. 'updated_at' => $now,
  8757. ];
  8758. }
  8759. } else {
  8760. // 如果没有指定序号,创建一个默认映射(序号为0)
  8761. $mappingRecords[] = [
  8762. 'script_id' => $script_id,
  8763. 'product_id' => $product_id,
  8764. 'episode_number' => 0,
  8765. 'created_at' => $now,
  8766. 'updated_at' => $now,
  8767. ];
  8768. }
  8769. }
  8770. }
  8771. if (empty($mappingRecords)) {
  8772. Utils::throwError('20003:没有有效的产品数据');
  8773. }
  8774. // 批量插入映射数据(使用 insertOrIgnore 避免重复插入)
  8775. $insertedCount = DB::table('mp_script_product_mappings')->insertOrIgnore($mappingRecords);
  8776. // 剧本已有资产,同步更新is_products标记
  8777. DB::table('mp_scripts')->where('id', $script_id)->update([
  8778. 'is_products' => 1,
  8779. 'updated_at' => $now
  8780. ]);
  8781. // 如果需要自动生成图片,在事务中创建图片生成任务
  8782. $productTaskMap = [];
  8783. if ($auto_generate_images && !empty($createdProductIds)) {
  8784. // 查询所有创建的资产
  8785. $productsToGenerate = DB::table('mp_products')
  8786. ->whereIn('id', $createdProductIds)
  8787. ->where('is_deleted', 0)
  8788. ->get();
  8789. foreach ($productsToGenerate as $product) {
  8790. if (empty($product->pic_prompt)) {
  8791. dLog('anime')->warning('资产没有提示词,跳过图片生成', [
  8792. 'product_id' => $product->id,
  8793. 'product_name' => $product->product_name
  8794. ]);
  8795. continue;
  8796. }
  8797. try {
  8798. // 创建图片生成任务
  8799. $params = [
  8800. 'prompt' => $product->pic_prompt,
  8801. 'model' => $model,
  8802. 'ref_img_urls' => [],
  8803. 'width' => $width,
  8804. 'height' => $height,
  8805. // 计费锚点(剧本),用于积分明细归属统计
  8806. 'script_id' => $script_id,
  8807. ];
  8808. $task = $this->aiImageGenerationService->createImageGenerationTask($params);
  8809. $task_id = $task->id;
  8810. if ($task_id) {
  8811. $productTaskMap[$product->id] = $task_id;
  8812. // 在事务中更新资产表的任务ID和状态
  8813. DB::table('mp_products')
  8814. ->where('id', $product->id)
  8815. ->update([
  8816. 'pic_task_id' => $task_id,
  8817. 'pic_task_status' => '生成中',
  8818. 'updated_at' => now()
  8819. ]);
  8820. dLog('anime')->info('创建资产图片生成任务', [
  8821. 'product_id' => $product->id,
  8822. 'task_id' => $task_id
  8823. ]);
  8824. }
  8825. } catch (\Exception $e) {
  8826. dLog('anime')->error('创建资产图片生成任务失败', [
  8827. 'product_id' => $product->id,
  8828. 'error' => $e->getMessage()
  8829. ]);
  8830. // 标记为失败(仍在事务中)
  8831. DB::table('mp_products')
  8832. ->where('id', $product->id)
  8833. ->update([
  8834. 'pic_task_status' => '生成失败',
  8835. 'updated_at' => now()
  8836. ]);
  8837. }
  8838. }
  8839. }
  8840. // 提交事务
  8841. DB::commit();
  8842. // 本次新增资产创建的图片任务
  8843. $createdTaskMap = $productTaskMap;
  8844. } catch (\Exception $e) {
  8845. // 回滚事务
  8846. DB::rollback();
  8847. // 更新任务中心状态为失败
  8848. if (!empty($taskCenterId)) {
  8849. $this->taskCenterService->updateTask($taskCenterId, [
  8850. 'status' => MpTaskCenter::STATUS_FAILED,
  8851. 'error_message' => $e->getMessage()
  8852. ]);
  8853. }
  8854. // 记录错误日志
  8855. dLog('anime')->error('保存剧本资产失败: ' . $e->getMessage(), [
  8856. 'script_id' => $script_id,
  8857. 'error' => $e->getMessage(),
  8858. 'trace' => $e->getTraceAsString()
  8859. ]);
  8860. // 统一使用 Utils::throwError 抛出错误
  8861. Utils::throwError('20003:保存剧本资产失败:' . $e->getMessage());
  8862. }
  8863. // 落库成功后统一处理图片任务:
  8864. // 1) 本次新增资产的图片任务已在上方事务中创建
  8865. // 2) 剧本内已存在但缺图的资产在此补建,并与新增资产的任务一并收集为待轮询任务
  8866. $existingTaskInfo = $this->prepareExistingScriptProductTasks(
  8867. $script_id,
  8868. $model,
  8869. $width,
  8870. $height,
  8871. $auto_generate_images
  8872. );
  8873. $productTaskMap = $existingTaskInfo['product_task_map'];
  8874. // 创建阶段解析到的类型根文件夹优先
  8875. $typeFolderIds = $typeFolderIds + $existingTaskInfo['type_folder_ids'];
  8876. // 保存结果(SSE 的 init / complete 事件会携带该结构)
  8877. $resultData = [
  8878. 'success' => true,
  8879. 'message' => '保存完成',
  8880. 'script_id' => $script_id,
  8881. 'script_name' => $script_name,
  8882. 'type_folder_ids' => $typeFolderIds,
  8883. 'inserted_count' => $insertedCount,
  8884. 'total_records' => count($mappingRecords),
  8885. 'created_products' => count($createdProductIds),
  8886. 'pending_tasks_count' => count($productTaskMap),
  8887. 'image_tasks_created' => count($createdTaskMap) + $existingTaskInfo['created_count'],
  8888. 'task_center_id' => $taskCenterId,
  8889. ];
  8890. // 有待完成的图片任务:返回 SSE 轮询流(事务外轮询)
  8891. if ($auto_generate_images && !empty($productTaskMap)) {
  8892. return $this->pollProductImageTasks(
  8893. $script_id,
  8894. $script_name,
  8895. $productTaskMap,
  8896. $typeFolderIds,
  8897. $taskCenterId,
  8898. ['import_result' => $resultData],
  8899. ['import_result' => $resultData]
  8900. );
  8901. }
  8902. // 没有需要轮询的任务:通过 SSE complete 事件返回保存结果
  8903. return $this->streamImportComplete($script_id, $script_name, $resultData, $typeFolderIds, $taskCenterId);
  8904. }
  8905. /**
  8906. * 根据入参创建或复用任务中心记录
  8907. *
  8908. * 以规范化入参计算 md5 并保存到任务中心 params 字段中用于验重:
  8909. * 同一用户/企业下,相同入参且任务未结束(pending/processing)时复用已有任务,
  8910. * 避免生成重复任务。
  8911. *
  8912. * @param int|string $uid
  8913. * @param int|string $cpid
  8914. * @param int|string $script_id
  8915. * @param mixed $products
  8916. * @param string $model
  8917. * @param string $ratio
  8918. * @param string $resolution
  8919. * @param mixed $auto_generate_images
  8920. * @return int 任务中心ID
  8921. */
  8922. private function createScriptProductTaskCenter($uid, $cpid, $script_id, $products, $model, $ratio, $resolution, $auto_generate_images) {
  8923. // 规范化 products(兼容 JSON 字符串和数组),保证 md5 稳定
  8924. if (is_string($products)) {
  8925. $decoded = json_decode($products, true);
  8926. if (json_last_error() === JSON_ERROR_NONE) {
  8927. $products = $decoded;
  8928. }
  8929. }
  8930. $params = [
  8931. 'script_id' => (int)$script_id,
  8932. 'products' => $products,
  8933. 'model' => $model,
  8934. 'ratio' => $ratio,
  8935. 'resolution' => $resolution,
  8936. 'auto_generate_images' => (bool)$auto_generate_images,
  8937. ];
  8938. $paramsMd5 = md5(json_encode($params, JSON_UNESCAPED_UNICODE | JSON_UNESCAPED_SLASHES));
  8939. // 验重:相同 md5 且任务未结束(pending/processing)时复用已有任务中心记录
  8940. $existing = DB::table('mp_task_center')
  8941. ->where('uid', (int)$uid)
  8942. ->where('cpid', (int)$cpid)
  8943. ->where('task_type', MpTaskCenter::TYPE_SAVE_SCRIPT_PRODUCTS)
  8944. ->whereIn('status', [MpTaskCenter::STATUS_PENDING, MpTaskCenter::STATUS_PROCESSING])
  8945. ->where('params_md5', $paramsMd5)
  8946. ->orderBy('id', 'desc')
  8947. ->first();
  8948. if ($existing) {
  8949. dLog('anime')->info('复用已有任务中心记录,避免重复任务', [
  8950. 'script_id' => $script_id,
  8951. 'task_center_id' => $existing->id,
  8952. 'params_md5' => $paramsMd5,
  8953. ]);
  8954. return (int)$existing->id;
  8955. }
  8956. // 唯一索引 (uid, cpid, task_type, params_md5) 兜底并发重复,冲突时静默忽略
  8957. $now = date('Y-m-d H:i:s');
  8958. DB::table('mp_task_center')->insertOrIgnore([
  8959. 'uid' => (int)$uid,
  8960. 'cpid' => (int)$cpid,
  8961. 'task_type' => MpTaskCenter::TYPE_SAVE_SCRIPT_PRODUCTS,
  8962. 'title' => '剧本资产图片生成',
  8963. 'ref_task_id' => 0,
  8964. 'status' => MpTaskCenter::STATUS_PROCESSING,
  8965. 'result' => null,
  8966. 'error_message' => null,
  8967. 'prompt' => null,
  8968. 'params' => json_encode($params + ['params_md5' => $paramsMd5], JSON_UNESCAPED_UNICODE | JSON_UNESCAPED_SLASHES),
  8969. 'params_md5' => $paramsMd5,
  8970. 'created_at' => $now,
  8971. 'updated_at' => $now,
  8972. ]);
  8973. // 获取任务中心ID(insertOrIgnore 冲突时复用并发插入的已有记录)
  8974. $taskId = (int)DB::table('mp_task_center')
  8975. ->where('uid', (int)$uid)
  8976. ->where('cpid', (int)$cpid)
  8977. ->where('task_type', MpTaskCenter::TYPE_SAVE_SCRIPT_PRODUCTS)
  8978. ->where('params_md5', $paramsMd5)
  8979. ->orderBy('id', 'desc')
  8980. ->value('id');
  8981. dLog('anime')->info('创建任务中心记录', [
  8982. 'script_id' => $script_id,
  8983. 'task_center_id' => $taskId,
  8984. 'params_md5' => $paramsMd5,
  8985. ]);
  8986. return $taskId;
  8987. }
  8988. /**
  8989. * 任务结束时更新任务中心记录的状态和结果
  8990. *
  8991. * result 字段保存与 saveScriptProducts 接口返回给客户端一致的结果数据
  8992. * (普通数组返回为完整返回数组,SSE 轮询为 complete/timeout 事件载荷)。
  8993. *
  8994. * @param int|null $taskCenterId
  8995. * @param array $resultData 接口返回结果数组
  8996. * @param bool $timeout 是否超时未完成
  8997. */
  8998. private function finishScriptProductTask($taskCenterId, array $resultData, $timeout = false) {
  8999. if (!$taskCenterId) {
  9000. return;
  9001. }
  9002. $stats = $resultData['stats'] ?? [];
  9003. $successCount = (int)array_sum(array_column((array)$stats, 'success'));
  9004. $completedCount = (int)array_sum(array_column((array)$stats, 'completed'));
  9005. $failedCount = $completedCount - $successCount;
  9006. // 与接口返回给客户端的结果保持一致
  9007. $result = json_encode($resultData, JSON_UNESCAPED_UNICODE);
  9008. if ($timeout) {
  9009. $this->taskCenterService->updateTask((int)$taskCenterId, [
  9010. 'status' => MpTaskCenter::STATUS_FAILED,
  9011. 'result' => $result,
  9012. 'error_message' => '部分任务超时,请稍后查看结果',
  9013. ]);
  9014. return;
  9015. }
  9016. $this->taskCenterService->updateTask((int)$taskCenterId, [
  9017. 'status' => $failedCount > 0 ? MpTaskCenter::STATUS_FAILED : MpTaskCenter::STATUS_SUCCESS,
  9018. 'result' => $result,
  9019. 'error_message' => $failedCount > 0 ? ('有 ' . $failedCount . ' 个资产生成失败') : null,
  9020. ]);
  9021. }
  9022. /**
  9023. * 批量为剧本资产生成图片
  9024. *
  9025. * @param array $data 请求参数
  9026. * @return \Generator 返回 SSE 流
  9027. */
  9028. public function batchGenerateProductImages($data) {
  9029. $script_id = getProp($data, 'script_id');
  9030. $type_folder_ids = getProp($data, 'type_folder_ids', []); // {1: 角色文件夹ID, 2: 场景文件夹ID, 3: 道具文件夹ID}
  9031. if (!$script_id) {
  9032. Utils::throwError('20003:请提供剧本ID');
  9033. }
  9034. // 验证剧本是否存在
  9035. $script = DB::table('mp_scripts')
  9036. ->where('id', $script_id)
  9037. ->where('is_deleted', 0)
  9038. ->first();
  9039. if (!$script) {
  9040. Utils::throwError('20003:剧本不存在');
  9041. }
  9042. $script_name = $script->script_name ?? 'script_' . $script_id;
  9043. // 获取需要生成图片的所有资产
  9044. $products = DB::table('mp_products')
  9045. ->whereIn('parent_id', array_values($type_folder_ids))
  9046. ->where('is_deleted', 0)
  9047. ->whereIn('type', [1, 2, 3]) // 只处理资产,不处理文件夹
  9048. ->get();
  9049. if ($products->isEmpty()) {
  9050. Utils::throwError('20003:没有找到需要生成图片的资产');
  9051. }
  9052. // 默认参数
  9053. $model = 'gpt-image-2';
  9054. $width = 1600;
  9055. $height = 2848;
  9056. // 开始为每个资产创建图片生成任务
  9057. $taskIds = [];
  9058. $productTaskMap = []; // 资产ID到任务ID的映射
  9059. foreach ($products as $product) {
  9060. if (empty($product->pic_prompt)) {
  9061. dLog('anime')->warning('资产没有提示词,跳过', ['product_id' => $product->id, 'product_name' => $product->product_name]);
  9062. continue;
  9063. }
  9064. try {
  9065. // 创建图片生成任务
  9066. $params = [
  9067. 'prompt' => $product->pic_prompt,
  9068. 'model' => $model,
  9069. 'ref_img_urls' => [],
  9070. 'width' => $width,
  9071. 'height' => $height,
  9072. // 计费锚点(剧本),用于积分明细归属统计
  9073. 'script_id' => $script_id,
  9074. ];
  9075. $task = $this->aiImageGenerationService->createImageGenerationTask($params);
  9076. $task_id = $task->id;
  9077. if ($task_id) {
  9078. $taskIds[] = $task_id;
  9079. $productTaskMap[$product->id] = $task_id;
  9080. // 更新资产表的任务ID和状态
  9081. DB::table('mp_products')
  9082. ->where('id', $product->id)
  9083. ->update([
  9084. 'pic_task_id' => $task_id,
  9085. 'pic_task_status' => '生成中',
  9086. 'updated_at' => now()
  9087. ]);
  9088. dLog('anime')->info('创建资产图片生成任务', ['product_id' => $product->id, 'task_id' => $task_id]);
  9089. }
  9090. } catch (\Exception $e) {
  9091. dLog('anime')->error('创建资产图片生成任务失败', [
  9092. 'product_id' => $product->id,
  9093. 'error' => $e->getMessage()
  9094. ]);
  9095. // 标记为失败
  9096. DB::table('mp_products')
  9097. ->where('id', $product->id)
  9098. ->update([
  9099. 'pic_task_status' => '生成失败',
  9100. 'updated_at' => now()
  9101. ]);
  9102. }
  9103. }
  9104. if (empty($taskIds)) {
  9105. Utils::throwError('20003:没有成功创建任何图片生成任务');
  9106. }
  9107. // 返回 SSE 流
  9108. return $this->pollProductImageTasks($script_id, $script_name, $productTaskMap, $type_folder_ids);
  9109. }
  9110. /**
  9111. * 无需轮询时的 SSE 返回:直接通过 complete 事件返回导入结果
  9112. *
  9113. * @param int $script_id
  9114. * @param string $script_name
  9115. * @param array $resultData 导入结果(原普通 JSON 的 data 内容)
  9116. * @param array $type_folder_ids
  9117. * @param int|null $taskCenterId
  9118. * @return \Generator
  9119. */
  9120. private function streamImportComplete($script_id, $script_name, array $resultData, $type_folder_ids, $taskCenterId = null) {
  9121. if ($taskCenterId) {
  9122. $initResponse = [
  9123. 'type' => 'init',
  9124. 'script_id' => $script_id,
  9125. 'script_name' => $script_name,
  9126. 'timestamp' => date('Y-m-d H:i:s'),
  9127. 'task_center_id' => (int)$taskCenterId,
  9128. 'import_result' => $resultData,
  9129. ];
  9130. yield "data: " . json_encode($initResponse, JSON_UNESCAPED_UNICODE) . "\n\n";
  9131. }
  9132. $stats = $this->collectScriptProductStats($script_id);
  9133. $response = [
  9134. 'type' => 'complete',
  9135. 'script_id' => $script_id,
  9136. 'script_name' => $script_name,
  9137. 'stats' => $stats,
  9138. 'timestamp' => date('Y-m-d H:i:s'),
  9139. 'import_result' => $resultData,
  9140. ];
  9141. if ($taskCenterId) {
  9142. $response['task_center_id'] = (int)$taskCenterId;
  9143. }
  9144. yield "data: " . json_encode($response, JSON_UNESCAPED_UNICODE) . "\n\n";
  9145. // 更新任务中心状态和结果
  9146. $this->finishScriptProductTask($taskCenterId, $response);
  9147. }
  9148. /**
  9149. * 统计剧本资产的图片生成状态(仅按 mp_products 当前状态统计,不驱动任务)
  9150. *
  9151. * @param int $script_id
  9152. * @return array
  9153. */
  9154. private function collectScriptProductStats($script_id) {
  9155. $stats = [
  9156. 'character' => ['total' => 0, 'success' => 0, 'completed' => 0],
  9157. 'scene' => ['total' => 0, 'success' => 0, 'completed' => 0],
  9158. 'prop' => ['total' => 0, 'success' => 0, 'completed' => 0],
  9159. ];
  9160. $typeNames = [1 => 'roles', 2 => 'scenes', 3 => 'props'];
  9161. $productIds = DB::table('mp_script_product_mappings')
  9162. ->where('script_id', $script_id)
  9163. ->pluck('product_id')
  9164. ->unique()
  9165. ->toArray();
  9166. if (empty($productIds)) {
  9167. return [];
  9168. }
  9169. $products = DB::table('mp_products')
  9170. ->whereIn('id', $productIds)
  9171. ->where('is_deleted', 0)
  9172. ->get();
  9173. foreach ($products as $product) {
  9174. $typeName = $typeNames[$product->product] ?? 'unknown';
  9175. if (!isset($stats[$typeName])) {
  9176. $stats[$typeName] = ['total' => 0, 'success' => 0, 'completed' => 0];
  9177. }
  9178. $stats[$typeName]['total']++;
  9179. if ($product->pic_task_status === '生成成功') {
  9180. $stats[$typeName]['success']++;
  9181. $stats[$typeName]['completed']++;
  9182. } elseif ($product->pic_task_status === '生成失败') {
  9183. $stats[$typeName]['completed']++;
  9184. }
  9185. }
  9186. foreach ($stats as $typeName => $stat) {
  9187. if ($stat['total'] === 0) {
  9188. unset($stats[$typeName]);
  9189. }
  9190. }
  9191. return $stats;
  9192. }
  9193. /**
  9194. * 轮询资产图片生成任务状态(SSE流式返回)
  9195. * 只通过查询数据库获取任务状态,不主动调用API
  9196. *
  9197. * @param int $script_id 剧本ID
  9198. * @param string $script_name 剧本名称
  9199. * @param array $productTaskMap 资产ID到任务ID的映射
  9200. * @param array $type_folder_ids 类型文件夹ID映射
  9201. * @param int|null $taskCenterId 任务中心ID
  9202. * @param array $initExtra 追加到 init 事件中的额外数据
  9203. * @param array $completeExtra 追加到 complete、timeout 事件中的额外数据
  9204. * @return \Generator
  9205. */
  9206. private function pollProductImageTasks($script_id, $script_name, $productTaskMap, $type_folder_ids, $taskCenterId = null, array $initExtra = [], array $completeExtra = []) {
  9207. $startTime = time();
  9208. $timeout = 1800; // 30分钟超时
  9209. $pollInterval = 10; // 10秒轮询一次
  9210. $lastStatus = []; // 记录上次的状态,用于判断是否有变化
  9211. // 流一开始即返回 init 事件(saveScriptProducts 场景下携带任务中心ID)
  9212. if ($taskCenterId) {
  9213. $initResponse = array_merge([
  9214. 'type' => 'init',
  9215. 'script_id' => $script_id,
  9216. 'script_name' => $script_name,
  9217. 'timestamp' => date('Y-m-d H:i:s'),
  9218. 'task_center_id' => (int)$taskCenterId,
  9219. ], $initExtra);
  9220. yield "data: " . json_encode($initResponse, JSON_UNESCAPED_UNICODE) . "\n\n";
  9221. }
  9222. // 定义类型名称映射
  9223. $typeNames = [
  9224. 1 => 'roles', // 角色
  9225. 2 => 'scenes', // 场景
  9226. 3 => 'props' // 道具
  9227. ];
  9228. while (time() - $startTime < $timeout) {
  9229. sleep($pollInterval);
  9230. // 从 mp_script_product_mappings 表获取该剧本的所有资产ID
  9231. $mappings = DB::table('mp_script_product_mappings')
  9232. ->where('script_id', $script_id)
  9233. ->pluck('product_id')
  9234. ->unique()
  9235. ->toArray();
  9236. if (empty($mappings)) {
  9237. dLog('anime')->warning('该剧本没有关联的资产', [
  9238. 'script_id' => $script_id,
  9239. 'script_name' => $script_name
  9240. ]);
  9241. break;
  9242. }
  9243. // 查询所有资产的当前状态
  9244. $products = DB::table('mp_products')
  9245. ->whereIn('id', $mappings)
  9246. ->where('is_deleted', 0)
  9247. ->get();
  9248. // 统计各类型的状态(使用类型名称作为键名)
  9249. $stats = [
  9250. 'character' => ['total' => 0, 'success' => 0, 'completed' => 0], // 角色
  9251. 'scene' => ['total' => 0, 'success' => 0, 'completed' => 0], // 场景
  9252. 'prop' => ['total' => 0, 'success' => 0, 'completed' => 0], // 道具
  9253. ];
  9254. $allCompleted = true;
  9255. $hasStatusChange = false;
  9256. foreach ($products as $product) {
  9257. $type = $product->product;
  9258. $typeName = $typeNames[$type] ?? 'unknown'; // 使用 unknown 作为未知类型
  9259. // 如果类型名称不在 stats 中,初始化
  9260. if (!isset($stats[$typeName])) {
  9261. $stats[$typeName] = ['total' => 0, 'success' => 0, 'completed' => 0];
  9262. }
  9263. $stats[$typeName]['total']++;
  9264. $task_id = $product->pic_task_id;
  9265. $currentStatus = $product->pic_task_status;
  9266. // 检查状态是否有变化
  9267. if (!isset($lastStatus[$product->id]) || $lastStatus[$product->id] !== $currentStatus) {
  9268. $hasStatusChange = true;
  9269. $lastStatus[$product->id] = $currentStatus;
  9270. }
  9271. // 如果是生成中,查询任务表状态
  9272. if ($currentStatus === '生成中' && $task_id) {
  9273. // 只查询数据库,不调用API
  9274. $task = DB::table('mp_generate_pic_tasks')
  9275. ->where('id', $task_id)
  9276. ->first();
  9277. if ($task) {
  9278. // 检查任务状态
  9279. if ($task->status === 'success' && $task->result_url) {
  9280. // 解析图片URL
  9281. $result_urls = $task->result_url;
  9282. if (is_string($result_urls)) {
  9283. $result_urls = json_decode($result_urls, true);
  9284. }
  9285. $img_url = is_array($result_urls) ? $result_urls[0] : $task->result_url;
  9286. // 更新资产表状态
  9287. DB::table('mp_products')
  9288. ->where('id', $product->id)
  9289. ->update([
  9290. 'pic_task_status' => '生成成功',
  9291. 'url' => $img_url,
  9292. 'updated_at' => now()
  9293. ]);
  9294. $stats[$typeName]['success']++;
  9295. $stats[$typeName]['completed']++;
  9296. $hasStatusChange = true;
  9297. dLog('anime')->info('资产图片生成成功', [
  9298. 'product_id' => $product->id,
  9299. 'task_id' => $task_id,
  9300. 'img_url' => $img_url
  9301. ]);
  9302. } elseif ($task->status === 'failed') {
  9303. // 更新资产表状态
  9304. DB::table('mp_products')
  9305. ->where('id', $product->id)
  9306. ->update([
  9307. 'pic_task_status' => '生成失败',
  9308. 'updated_at' => now()
  9309. ]);
  9310. $stats[$typeName]['completed']++;
  9311. $hasStatusChange = true;
  9312. dLog('anime')->warning('资产图片生成失败', [
  9313. 'product_id' => $product->id,
  9314. 'task_id' => $task_id,
  9315. 'error' => $task->error_message ?? '未知错误'
  9316. ]);
  9317. } else {
  9318. // 任务还在处理中
  9319. $allCompleted = false;
  9320. }
  9321. } else {
  9322. // 任务不存在,标记为失败
  9323. DB::table('mp_products')
  9324. ->where('id', $product->id)
  9325. ->update([
  9326. 'pic_task_status' => '生成失败',
  9327. 'updated_at' => now()
  9328. ]);
  9329. $stats[$typeName]['completed']++;
  9330. $hasStatusChange = true;
  9331. dLog('anime')->error('图片生成任务不存在', [
  9332. 'product_id' => $product->id,
  9333. 'task_id' => $task_id
  9334. ]);
  9335. }
  9336. } elseif ($currentStatus === '生成成功') {
  9337. $stats[$typeName]['success']++;
  9338. $stats[$typeName]['completed']++;
  9339. } elseif ($currentStatus === '生成失败') {
  9340. $stats[$typeName]['completed']++;
  9341. } else {
  9342. // 其他状态也认为未完成
  9343. $allCompleted = false;
  9344. }
  9345. }
  9346. // 移除没有数据的类型(total=0)
  9347. foreach ($stats as $typeName => $stat) {
  9348. if ($stat['total'] === 0) {
  9349. unset($stats[$typeName]);
  9350. }
  9351. }
  9352. // 如果有状态变化,发送 SSE 更新
  9353. if ($hasStatusChange) {
  9354. $eventType = $allCompleted ? 'complete' : 'update';
  9355. $response = [
  9356. 'type' => $eventType,
  9357. 'script_id' => $script_id,
  9358. 'script_name' => $script_name,
  9359. 'stats' => $stats,
  9360. 'timestamp' => date('Y-m-d H:i:s')
  9361. ];
  9362. if ($taskCenterId) {
  9363. $response['task_center_id'] = $taskCenterId;
  9364. }
  9365. if ($eventType === 'complete') {
  9366. $response = array_merge($response, $completeExtra);
  9367. }
  9368. yield "data: " . json_encode($response, JSON_UNESCAPED_UNICODE) . "\n\n";
  9369. dLog('anime')->info('SSE更新', [
  9370. 'event_type' => $eventType,
  9371. 'script_id' => $script_id,
  9372. 'script_name' => $script_name,
  9373. 'stats' => $stats
  9374. ]);
  9375. if ($allCompleted) {
  9376. dLog('anime')->info('所有资产图片生成任务已完成', [
  9377. 'script_id' => $script_id,
  9378. 'script_name' => $script_name,
  9379. 'stats' => $stats
  9380. ]);
  9381. // 全部任务完成,更新任务中心状态和结果
  9382. $this->finishScriptProductTask($taskCenterId, $response);
  9383. break;
  9384. }
  9385. }
  9386. }
  9387. // 超时处理
  9388. if (time() - $startTime >= $timeout && !$allCompleted) {
  9389. $response = [
  9390. 'type' => 'timeout',
  9391. 'message' => '部分任务超时,请稍后查看结果',
  9392. 'script_id' => $script_id,
  9393. 'script_name' => $script_name,
  9394. 'timestamp' => date('Y-m-d H:i:s')
  9395. ];
  9396. if ($taskCenterId) {
  9397. $response['task_center_id'] = $taskCenterId;
  9398. }
  9399. $response = array_merge($response, $completeExtra);
  9400. yield "data: " . json_encode($response, JSON_UNESCAPED_UNICODE) . "\n\n";
  9401. dLog('anime')->warning('资产图片生成任务超时', [
  9402. 'script_id' => $script_id,
  9403. 'script_name' => $script_name,
  9404. 'timeout' => $timeout
  9405. ]);
  9406. // 超时未完成,更新任务中心状态和结果
  9407. $this->finishScriptProductTask($taskCenterId, $response, true);
  9408. }
  9409. }
  9410. /**
  9411. * 定时任务:检查产品图片生成任务状态并更新产品记录
  9412. * 扫描 mp_products 中 pic_task_id 非空且 pic_task_status 为生成中的记录,
  9413. * 通过 pic_task_id 查询 mp_generate_pic_tasks 获取生成结果,按结果更新状态
  9414. *
  9415. * @return array ['total' => 总数, 'success' => 成功数, 'failed' => 失败数, 'pending' => 待处理数]
  9416. */
  9417. public function checkProductPicTasks() {
  9418. // 查询所有生成中的产品图片任务
  9419. $products = DB::table('mp_products')
  9420. ->whereNotNull('pic_task_id')
  9421. ->where('pic_task_status', '生成中')
  9422. ->where('is_deleted', 0)
  9423. ->get();
  9424. $stats = [
  9425. 'total' => $products->count(),
  9426. 'success' => 0,
  9427. 'failed' => 0,
  9428. 'pending' => 0,
  9429. ];
  9430. foreach ($products as $product) {
  9431. try {
  9432. $task_id = $product->pic_task_id;
  9433. // 通过 pic_task_id 查询图片生成任务结果
  9434. $task = DB::table('mp_generate_pic_tasks')
  9435. ->where('id', $task_id)
  9436. ->first();
  9437. if ($task) {
  9438. if ($task->status === 'success' && $task->result_url) {
  9439. // 解析图片URL
  9440. $result_urls = $task->result_url;
  9441. if (is_string($result_urls)) {
  9442. $result_urls = json_decode($result_urls, true);
  9443. }
  9444. $img_url = is_array($result_urls) ? ($result_urls[0] ?? $task->result_url) : $task->result_url;
  9445. // 更新资产表状态
  9446. DB::table('mp_products')
  9447. ->where('id', $product->id)
  9448. ->update([
  9449. 'pic_task_status' => '生成成功',
  9450. 'url' => $img_url,
  9451. 'updated_at' => now()
  9452. ]);
  9453. $stats['success']++;
  9454. dLog('anime')->info('资产图片生成成功', [
  9455. 'product_id' => $product->id,
  9456. 'task_id' => $task_id,
  9457. 'img_url' => $img_url
  9458. ]);
  9459. } elseif ($task->status === 'failed') {
  9460. // 更新资产表状态
  9461. DB::table('mp_products')
  9462. ->where('id', $product->id)
  9463. ->update([
  9464. 'pic_task_status' => '生成失败',
  9465. 'updated_at' => now()
  9466. ]);
  9467. $stats['failed']++;
  9468. dLog('anime')->warning('资产图片生成失败', [
  9469. 'product_id' => $product->id,
  9470. 'task_id' => $task_id,
  9471. 'error' => $task->error_message ?? '未知错误'
  9472. ]);
  9473. } else {
  9474. // 任务还在处理中
  9475. $stats['pending']++;
  9476. }
  9477. } else {
  9478. // 任务不存在,标记为失败
  9479. DB::table('mp_products')
  9480. ->where('id', $product->id)
  9481. ->update([
  9482. 'pic_task_status' => '生成失败',
  9483. 'updated_at' => now()
  9484. ]);
  9485. $stats['failed']++;
  9486. dLog('anime')->error('图片生成任务不存在', [
  9487. 'product_id' => $product->id,
  9488. 'task_id' => $task_id
  9489. ]);
  9490. }
  9491. } catch (\Exception $e) {
  9492. dLog('anime')->error('检查产品图片生成任务异常', [
  9493. 'product_id' => $product->id,
  9494. 'task_id' => $product->pic_task_id ?? null,
  9495. 'error' => $e->getMessage()
  9496. ]);
  9497. }
  9498. }
  9499. return $stats;
  9500. }
  9501. /**
  9502. * 定时任务:检查任务中心中 saveScriptProducts 类型的任务是否已完成
  9503. *
  9504. * 当保存剧本资产的 SSE 连接中断等原因导致任务中心记录未及时更新时,
  9505. * 通过关联资产的图片生成状态兜底判断任务是否全部完成;
  9506. * 全部完成后更新任务中心的状态和结果(result 与 saveScriptProducts 接口返回保持一致)。
  9507. *
  9508. * @return int 更新的任务中心记录数
  9509. */
  9510. public function checkSaveScriptProductTaskCenters() {
  9511. $updated = 0;
  9512. // 只扫描尚未结束的 saveScriptProducts 任务
  9513. $tasks = DB::table('mp_task_center')
  9514. ->where('task_type', MpTaskCenter::TYPE_SAVE_SCRIPT_PRODUCTS)
  9515. ->whereIn('status', [MpTaskCenter::STATUS_PENDING, MpTaskCenter::STATUS_PROCESSING])
  9516. ->orderBy('id', 'desc')
  9517. ->limit(500)
  9518. ->get();
  9519. // 与 pollProductImageTasks 保持一致的类型名称映射
  9520. $typeNames = [
  9521. 1 => 'roles', // 角色
  9522. 2 => 'scenes', // 场景
  9523. 3 => 'props', // 道具
  9524. ];
  9525. foreach ($tasks as $task) {
  9526. try {
  9527. $taskParams = json_decode((string)$task->params, true);
  9528. $script_id = is_array($taskParams) ? (int)($taskParams['script_id'] ?? 0) : 0;
  9529. if (!$script_id) {
  9530. dLog('command')->warning('saveScriptProducts任务缺少script_id,跳过', [
  9531. 'task_center_id' => $task->id,
  9532. ]);
  9533. continue;
  9534. }
  9535. // 获取该剧本关联的全部资产ID
  9536. $productIds = DB::table('mp_script_product_mappings')
  9537. ->where('script_id', $script_id)
  9538. ->pluck('product_id')
  9539. ->unique()
  9540. ->toArray();
  9541. if (empty($productIds)) {
  9542. // 剧本没有关联资产,不视为完成,等待下一次检查
  9543. continue;
  9544. }
  9545. $products = DB::table('mp_products')
  9546. ->whereIn('id', $productIds)
  9547. ->where('is_deleted', 0)
  9548. ->get();
  9549. $stats = [];
  9550. $allCompleted = true;
  9551. foreach ($products as $product) {
  9552. $typeName = $typeNames[$product->product] ?? 'unknown';
  9553. if (!isset($stats[$typeName])) {
  9554. $stats[$typeName] = ['total' => 0, 'success' => 0, 'completed' => 0];
  9555. }
  9556. $stats[$typeName]['total']++;
  9557. if ($product->pic_task_status === '生成成功') {
  9558. $stats[$typeName]['success']++;
  9559. $stats[$typeName]['completed']++;
  9560. } elseif ($product->pic_task_status === '生成失败') {
  9561. $stats[$typeName]['completed']++;
  9562. } else {
  9563. // 仍有资产在生成中或未生成,任务未完成
  9564. $allCompleted = false;
  9565. }
  9566. }
  9567. if (!$allCompleted) {
  9568. continue;
  9569. }
  9570. // 全部完成,更新任务中心状态和结果(与接口返回结果保持一致)
  9571. $script = DB::table('mp_scripts')
  9572. ->where('id', $script_id)
  9573. ->where('is_deleted', 0)
  9574. ->first();
  9575. $script_name = $script->script_name ?? 'script_' . $script_id;
  9576. $this->finishScriptProductTask($task->id, [
  9577. 'type' => 'complete',
  9578. 'script_id' => $script_id,
  9579. 'script_name' => $script_name,
  9580. 'stats' => $stats,
  9581. 'timestamp' => date('Y-m-d H:i:s'),
  9582. 'task_center_id' => (int)$task->id,
  9583. ]);
  9584. $updated++;
  9585. dLog('command')->info('saveScriptProducts任务已完成,更新任务中心', [
  9586. 'task_center_id' => $task->id,
  9587. 'script_id' => $script_id,
  9588. 'stats' => $stats,
  9589. ]);
  9590. } catch (\Exception $e) {
  9591. dLog('command')->error('检查saveScriptProducts任务中心状态异常', [
  9592. 'task_center_id' => $task->id,
  9593. 'error' => $e->getMessage(),
  9594. ]);
  9595. }
  9596. }
  9597. return $updated;
  9598. }
  9599. /**
  9600. * 获取剧本关联的资产列表
  9601. * @param array $data 请求参数
  9602. * @return array
  9603. */
  9604. public function getScriptProducts($data) {
  9605. $uid = Site::getUid();
  9606. $cpid = Site::getCpid();
  9607. $script_id = getProp($data, 'script_id');
  9608. $episode_number = getProp($data, 'episode_number');
  9609. if (!$script_id) {
  9610. Utils::throwError('20003:请提供剧本ID');
  9611. }
  9612. // 验证剧本是否存在
  9613. $script = DB::table('mp_scripts')
  9614. ->where('id', $script_id)
  9615. ->where('is_deleted', 0)
  9616. ->first();
  9617. if (!$script) {
  9618. Utils::throwError('20003:剧本不存在');
  9619. }
  9620. // 联表查询资产信息
  9621. $query = DB::table('mp_script_product_mappings as mapping')
  9622. ->join('mp_products as product', 'mapping.product_id', '=', 'product.id')
  9623. ->where('mapping.script_id', $script_id)
  9624. ->where('product.cpid', $cpid)
  9625. ->where('product.is_deleted', 0);
  9626. // 如果提供了 episode_number,则过滤指定集数
  9627. if ($episode_number !== null && $episode_number !== '') {
  9628. $query->where('mapping.episode_number', $episode_number);
  9629. }
  9630. $mappings = $query->select(
  9631. 'mapping.script_id',
  9632. 'mapping.product_id',
  9633. 'mapping.episode_number',
  9634. 'product.product_name',
  9635. 'product.type',
  9636. 'product.product',
  9637. 'product.pic_prompt',
  9638. 'product.url',
  9639. 'product.pic_task_id',
  9640. 'product.pic_task_status',
  9641. 'product.three_view_image_url',
  9642. 'product.timbre_url',
  9643. 'mapping.created_at'
  9644. )
  9645. ->orderBy('mapping.product_id', 'asc')
  9646. ->orderBy('mapping.episode_number', 'asc')
  9647. ->get();
  9648. // 按 product_id 分组,合并 episode_number
  9649. $productMap = [];
  9650. foreach ($mappings as $item) {
  9651. $product_id = $item->product_id;
  9652. if (!isset($productMap[$product_id])) {
  9653. $productMap[$product_id] = [
  9654. 'product_id' => $product_id,
  9655. 'product_name' => $item->product_name,
  9656. 'type' => (int)$item->type,
  9657. 'product' => (int)$item->product,
  9658. 'pic_prompt' => $item->pic_prompt,
  9659. 'url' => $item->url,
  9660. 'timbre_url' => $item->timbre_url,
  9661. 'pic_task_id' => $item->pic_task_id,
  9662. 'pic_task_status' => $item->pic_task_status,
  9663. 'episode_numbers' => [],
  9664. 'created_at' => $item->created_at,
  9665. ];
  9666. }
  9667. // 添加 episode_number(去重)
  9668. if (!in_array($item->episode_number, $productMap[$product_id]['episode_numbers'])) {
  9669. $productMap[$product_id]['episode_numbers'][] = $item->episode_number;
  9670. }
  9671. }
  9672. // 按类型分组
  9673. $roles = []; // type=1 角色/主体
  9674. $scenes = []; // type=2 场景
  9675. $props = []; // type=3 道具
  9676. foreach ($productMap as $product) {
  9677. // 将 episode_numbers 数组转换为逗号分隔的字符串
  9678. $episodeNumbersStr = implode(',', $product['episode_numbers']);
  9679. // 构造返回数据
  9680. $productData = [
  9681. 'product_id' => $product['product_id'],
  9682. 'product_name' => $product['product_name'],
  9683. 'product' => $product['product'],
  9684. 'pic_prompt' => $product['pic_prompt'],
  9685. 'url' => $product['url'],
  9686. 'timbre_url' => $product['timbre_url'] ?? '',
  9687. 'pic_task_id' => $product['pic_task_id'],
  9688. 'pic_task_status' => $product['pic_task_status'],
  9689. 'episode_numbers' => $episodeNumbersStr,
  9690. 'created_at' => $product['created_at'],
  9691. ];
  9692. // 根据 type 分类(注意:type 字段表示资产类型,不是文件夹)
  9693. // 根据 product 字段分类(1=角色, 2=场景, 3=道具)
  9694. switch ($product['product']) {
  9695. case 1:
  9696. $roles[] = $productData;
  9697. break;
  9698. case 2:
  9699. $scenes[] = $productData;
  9700. break;
  9701. case 3:
  9702. $props[] = $productData;
  9703. break;
  9704. }
  9705. }
  9706. return [
  9707. 'script_id' => $script_id,
  9708. 'script_name' => $script->script_name ?? '',
  9709. 'roles' => $roles, // 主体
  9710. 'scenes' => $scenes, // 场景
  9711. 'props' => $props, // 道具
  9712. ];
  9713. }
  9714. /**
  9715. * 处理act_content中的{}标记,替换为product_name(图+序号)格式,并收集参考图片
  9716. * @param string $actContent 原始内容
  9717. * @param array $products 产品数组(包含product_name和url)
  9718. * @return array ['content' => 处理后的内容, 'reference_images' => 参考图片数组]
  9719. */
  9720. public function processActContentWithProducts($actContent, $products) {
  9721. if (empty($actContent) || empty($products)) {
  9722. return [
  9723. 'content' => $actContent,
  9724. 'reference_images' => []
  9725. ];
  9726. }
  9727. // 构建产品名称到产品信息的映射
  9728. $product_dict = [];
  9729. foreach ($products as $product) {
  9730. $product_name = getProp($product, 'product_name');
  9731. if ($product_name) {
  9732. $product_dict[$product_name] = [
  9733. // 优先使用三视图图片作为素材/参考图,否则使用原图 url
  9734. 'url' => getProp($product, 'three_view_image_url') ?: getProp($product, 'url'),
  9735. 'voice_prompt' => getProp($product, 'voice_prompt')
  9736. ];
  9737. }
  9738. }
  9739. // 第一步:查找内容中所有 {产品名称} 格式的标记(按出现顺序,去重)
  9740. preg_match_all('/\{([^}]+)\}/u', $actContent, $matches);
  9741. $reference_images = [];
  9742. $product_index_map = []; // 产品名称 => 图片序号的映射
  9743. $voice_prompts = []; // 存储需要添加到开头的voice_prompt信息
  9744. $narrator_voice_prompt = ''; // 单独存储旁白的voice_prompt
  9745. $current_index = 1;
  9746. if (!empty($matches[1])) {
  9747. // 按照在内容中第一次出现的顺序,为每个产品分配序号
  9748. $seen_products = []; // 用于去重
  9749. foreach ($matches[1] as $product_name) {
  9750. // 跳过已处理的产品
  9751. if (isset($seen_products[$product_name])) {
  9752. continue;
  9753. }
  9754. $seen_products[$product_name] = true;
  9755. // 检查产品是否在字典中
  9756. if (isset($product_dict[$product_name])) {
  9757. $url = $product_dict[$product_name]['url'];
  9758. $voice_prompt = $product_dict[$product_name]['voice_prompt'];
  9759. // 处理voice_prompt(旁白不在这里处理,旁白是公共的在后面单独处理)
  9760. if (!empty($voice_prompt) && $product_name !== '旁白') {
  9761. $voice_prompts[] = $product_name . ':' . $voice_prompt . "\n";
  9762. }
  9763. // 只有URL非空才分配序号和添加到参考图片
  9764. if (!empty($url)) {
  9765. // 检查URL是否已经在reference_images中(去重)
  9766. if (!in_array($url, $reference_images)) {
  9767. $reference_images[] = $url;
  9768. $product_index_map[$product_name] = $current_index;
  9769. $current_index++;
  9770. } else {
  9771. // URL重复,找到已有的序号
  9772. $existing_index = array_search($url, $reference_images) + 1;
  9773. $product_index_map[$product_name] = $existing_index;
  9774. }
  9775. } else {
  9776. // URL为空,不分配序号(后续直接去掉{})
  9777. $product_index_map[$product_name] = 0;
  9778. }
  9779. } else {
  9780. // 产品不在字典中,不分配序号
  9781. $product_index_map[$product_name] = 0;
  9782. }
  9783. }
  9784. }
  9785. // 第二步:替换内容中的 {产品名称}
  9786. $processedContent = $actContent;
  9787. foreach ($product_index_map as $product_name => $index) {
  9788. $escaped_name = preg_quote($product_name, '/');
  9789. if ($index > 0) {
  9790. // 有图片,替换为:产品名称(图X)
  9791. $replacement = $product_name . '<图片' . $index . '>';
  9792. } else {
  9793. // 无图片,只保留产品名称
  9794. $replacement = $product_name;
  9795. }
  9796. // 替换所有 {产品名称} 为处理后的格式
  9797. $processedContent = preg_replace('/\{' . $escaped_name . '\}/u', $replacement, $processedContent);
  9798. }
  9799. // 第三步:单独处理旁白的voice_prompt(旁白是公共的,不依赖product_dict)
  9800. foreach ($products as $product) {
  9801. $product_name = getProp($product, 'product_name');
  9802. $voice_prompt = getProp($product, 'voice_prompt');
  9803. if ($product_name === '旁白' && !empty($voice_prompt)) {
  9804. $narrator_voice_prompt = $product_name . ':' . $voice_prompt . "\n";
  9805. break; // 找到旁白后退出循环
  9806. }
  9807. }
  9808. // 第四步:将voice_prompt信息添加到内容最前面
  9809. $voice_prompt_prefix = '';
  9810. if (!empty($voice_prompts)) {
  9811. $voice_prompt_prefix .= implode('', $voice_prompts);
  9812. }
  9813. // 旁白的voice_prompt放在最后
  9814. if (!empty($narrator_voice_prompt)) {
  9815. $voice_prompt_prefix .= $narrator_voice_prompt;
  9816. }
  9817. // 如果有voice_prompt信息,添加到内容开头
  9818. if (!empty($voice_prompt_prefix)) {
  9819. $processedContent = "人物音色:\n" . $voice_prompt_prefix . "\n" . $processedContent;
  9820. }
  9821. return [
  9822. 'content' => $processedContent,
  9823. 'reference_images' => $reference_images
  9824. ];
  9825. }
  9826. public function saveActVideoGenerateParams($data) {
  9827. $episode_id = getProp($data, 'episode_id');
  9828. $model = getProp($data, 'video_model');
  9829. $valid_models = DB::table('mp_video_models')->where('ace_mode', 1)->select('model')->pluck('model')->toArray();
  9830. if (!in_array($model, $valid_models)) {
  9831. Utils::throwError('20003:该模型不可用');
  9832. }
  9833. // 验证模型是否在可用模型表中
  9834. if (!DB::table('mp_video_models')->where('model', $model)->where('is_enabled', 1)->exists()) {
  9835. Utils::throwError('20003:该模型已不可用,请更换!');
  9836. }
  9837. $video_resolution = getProp($data, 'video_resolution', '720p');
  9838. $ratio = getProp($data, 'ratio');
  9839. if (!$ratio) $ratio = '9:16';
  9840. $episode = DB::table('mp_anime_episodes')->where('id', $episode_id)->first(['anime_id']);
  9841. if (!$episode) {
  9842. Utils::throwError('20003:分集不存在');
  9843. }
  9844. dLog('anime')->info('保存分集视频参数', $data);
  9845. try {
  9846. DB::beginTransaction();
  9847. $result = DB::table('mp_anime_episodes')->where('id', $episode_id)->update([
  9848. 'video_model' => $model,
  9849. 'video_resolution' => $video_resolution,
  9850. 'ratio' => $ratio,
  9851. 'updated_at' => date('Y-m-d H:i:s')
  9852. ]);
  9853. if ($result === false) {
  9854. Utils::throwError('20003:分集视频参数保存失败');
  9855. }
  9856. // 同步更新mp_animes表
  9857. $anime_result = DB::table('mp_animes')->where('id', $episode->anime_id)->update([
  9858. 'video_model' => $model,
  9859. 'video_resolution' => $video_resolution,
  9860. 'video_ratio' => $ratio,
  9861. 'updated_at' => date('Y-m-d H:i:s')
  9862. ]);
  9863. if ($anime_result === false) {
  9864. Utils::throwError('20003:动漫视频参数保存失败');
  9865. }
  9866. } catch (\Exception $e) {
  9867. DB::rollBack();
  9868. Utils::throwError('20003:'.$e->getMessage());
  9869. }
  9870. DB::commit();
  9871. return $result;
  9872. }
  9873. public function confirmActs($data) {
  9874. $episode_id = getProp($data, 'episode_id');
  9875. $episode = DB::table('mp_anime_episodes')->where('id', $episode_id)->first();
  9876. if (!$episode) {
  9877. Utils::throwError('20003:分集不存在');
  9878. }
  9879. $roles = json_decode(getProp($episode, 'roles'), true) ?: [];
  9880. $scenes = json_decode(getProp($episode, 'scenes'), true) ?: [];
  9881. $props = json_decode(getProp($episode, 'props'), true) ?: [];
  9882. // 确认前校验并等待角色、场景、道具图片全部生成(参照 episodePicsInfo 更新与监控逻辑),未全部生成不得继续后续逻辑
  9883. $this->waitForEpisodeAssetsImagesReady($episode_id, $roles, $scenes, $props);
  9884. // 获取所有片段数据
  9885. $acts = DB::table('mp_episode_segments')->where('episode_id', $episode_id)->orderBy('act_number')->get();
  9886. // 先构建完整的 products(角色、场景、道具、extra_products,并用资产库映射覆盖),
  9887. // 再处理每个片段的 act_content,避免 extra_products 等资产名未被格式化为 {资产名}
  9888. // 合并角色、场景、道具和extra_products作为products,统一字段名为product_name
  9889. // extra_products优先级更高,会覆盖同名的roles、scenes和props
  9890. $products = [];
  9891. // 先处理角色数组
  9892. foreach ($roles as $role) {
  9893. $product = $role;
  9894. // 将role字段重命名为product_name
  9895. if (isset($product['role'])) {
  9896. $product['product_name'] = $product['role'];
  9897. unset($product['role']);
  9898. $product['product'] = 1; // 标记类型为角色
  9899. $products[$product['product_name']] = $product; // 使用product_name作为key便于后续覆盖
  9900. }
  9901. }
  9902. // 处理场景数组
  9903. foreach ($scenes as $scene) {
  9904. $product = $scene;
  9905. // 将scene字段重命名为product_name
  9906. if (isset($product['scene'])) {
  9907. $product['product_name'] = $product['scene'];
  9908. unset($product['scene']);
  9909. $product['product'] = 2; // 标记类型为场景
  9910. $products[$product['product_name']] = $product; // 使用product_name作为key便于后续覆盖
  9911. }
  9912. }
  9913. // 处理道具数组(逻辑与场景一致)
  9914. foreach ($props as $prop) {
  9915. $product = $prop;
  9916. // 将prop字段重命名为product_name
  9917. if (isset($product['prop'])) {
  9918. $product['product_name'] = $product['prop'];
  9919. unset($product['prop']);
  9920. $product['product'] = 3; // 标记类型为道具
  9921. $products[$product['product_name']] = $product; // 使用product_name作为key便于后续覆盖
  9922. }
  9923. }
  9924. // extra_products优先级更高,直接覆盖同名的roles和scenes
  9925. $extra_products = json_decode(getProp($episode, 'extra_products', '[]'), true) ?: [];
  9926. foreach ($extra_products as $extra_product) {
  9927. $product_name = getProp($extra_product, 'product_name');
  9928. if ($product_name) {
  9929. $products[$product_name] = $extra_product; // 覆盖同名数据
  9930. }
  9931. }
  9932. // mp_script_product_mappings 信息优先级更高:
  9933. // 获取当前剧集所属动漫剧本下、与本集资产同名的资产库最新数据(url/三视图/提示词等),
  9934. // 覆盖分集 JSON 中保存的同名旧快照;分集内独有的 description、voice_prompt 等字段保留
  9935. $anime = DB::table('mp_animes')->where('id', getProp($episode, 'anime_id'))->first();
  9936. $script_id = $anime ? (int)getProp($anime, 'script_id', 0) : 0;
  9937. if ($script_id && !empty($products)) {
  9938. $currentProductNames = array_keys($products);
  9939. $normalizeName = function($name) {
  9940. return trim(preg_replace(
  9941. '/^[\s*\[\]【】[]{}{}\x{3000}]+|[\s*\[\]【】[]{}{}\x{3000}]+$/u',
  9942. '',
  9943. trim((string)$name)
  9944. ));
  9945. };
  9946. $mappingItems = DB::table('mp_script_product_mappings as mapping')
  9947. ->join('mp_products as product', 'mapping.product_id', '=', 'product.id')
  9948. ->where('mapping.script_id', $script_id)
  9949. ->where('product.is_deleted', 0)
  9950. ->whereIn('product.product_name', $currentProductNames)
  9951. ->select(
  9952. 'mapping.product_id',
  9953. 'product.product_name',
  9954. 'product.product',
  9955. 'product.pic_prompt',
  9956. 'product.url',
  9957. 'product.three_view_image_url',
  9958. )
  9959. ->get();
  9960. $mappingByName = [];
  9961. foreach ($mappingItems as $mappingItem) {
  9962. $normalizedName = $normalizeName($mappingItem->product_name);
  9963. if (!$normalizedName) continue;
  9964. $mappingByName[$normalizedName] = [
  9965. 'product_id' => (int)$mappingItem->product_id,
  9966. 'product_name' => $mappingItem->product_name,
  9967. 'product' => (int)$mappingItem->product,
  9968. 'pic_prompt' => $mappingItem->pic_prompt ?? '',
  9969. 'url' => $mappingItem->url ?? '',
  9970. 'three_view_image_url' => $mappingItem->three_view_image_url ?? '',
  9971. ];
  9972. }
  9973. foreach ($products as $key => &$product) {
  9974. $normalizedKey = $normalizeName($key);
  9975. if ($normalizedKey && isset($mappingByName[$normalizedKey])) {
  9976. $product = array_merge($product, $mappingByName[$normalizedKey]);
  9977. }
  9978. }
  9979. unset($product);
  9980. }
  9981. // 兼容返回 three_view_image_url 字段(旧数据可能没有该键,统一补空值)
  9982. foreach ($products as &$product) {
  9983. if (!isset($product['three_view_image_url'])) {
  9984. $product['three_view_image_url'] = '';
  9985. }
  9986. }
  9987. unset($product);
  9988. // 重新索引数组(去除key)
  9989. $products = array_values($products);
  9990. // 基于构建完成的 products 收集所有资产名称(含 extra_products 中的资产)
  9991. $product_names = [];
  9992. foreach ($products as $product) {
  9993. $product_name = getProp($product, 'product_name');
  9994. if ($product_name && $product_name !== '旁白') {
  9995. $product_names[] = $product_name;
  9996. }
  9997. }
  9998. // 去重并按长度降序排序(避免短名称先匹配到长名称的一部分)
  9999. $product_names = array_unique($product_names);
  10000. usort($product_names, function($a, $b) {
  10001. return mb_strlen($b) - mb_strlen($a);
  10002. });
  10003. try {
  10004. DB::beginTransaction();
  10005. // 处理每个片段
  10006. foreach ($acts as $act) {
  10007. $act_content = getProp($act, 'act_content');
  10008. if (!$act_content) continue;
  10009. $processed_content = $act_content;
  10010. // 统一替换所有资产名称为 {资产名} 格式
  10011. // 使用占位符避免嵌套替换问题
  10012. $placeholder_map = [];
  10013. $placeholder_index = 0;
  10014. foreach ($product_names as $product_name) {
  10015. // 转义特殊字符
  10016. $escaped_product = preg_quote($product_name, '/');
  10017. // 检查是否匹配且未被 {} 包裹
  10018. $processed_content = preg_replace_callback(
  10019. '/(?<![{])(' . $escaped_product . ')(?![}])/u',
  10020. function($matches) use (&$placeholder_map, &$placeholder_index) {
  10021. // 使用唯一占位符
  10022. $placeholder = '<<<PLACEHOLDER_' . $placeholder_index . '>>>';
  10023. $placeholder_map[$placeholder] = '{' . $matches[1] . '}';
  10024. $placeholder_index++;
  10025. return $placeholder;
  10026. },
  10027. $processed_content
  10028. );
  10029. }
  10030. // 将所有占位符替换回实际内容
  10031. foreach ($placeholder_map as $placeholder => $replacement) {
  10032. $processed_content = str_replace($placeholder, $replacement, $processed_content);
  10033. }
  10034. // 处理【镜头X】或【分镜X】重新编号为从1开始的连续整数【镜头X】
  10035. $shot_counter = 0;
  10036. $processed_content = preg_replace_callback(
  10037. '/【(?:镜头|分镜)(\d+)】/u',
  10038. function($matches) use (&$shot_counter) {
  10039. $shot_counter++;
  10040. return '【镜头' . $shot_counter . '】';
  10041. },
  10042. $processed_content
  10043. );
  10044. // 更新数据库
  10045. $boolen = DB::table('mp_episode_segments')
  10046. ->where('id', $act->id)
  10047. ->update([
  10048. 'act_show_content' => $processed_content,
  10049. 'updated_at' => date('Y-m-d H:i:s')
  10050. ]);
  10051. if (!$boolen) {
  10052. Utils::throwError('20003:片段处理失败');
  10053. }
  10054. }
  10055. }catch (\Exception $e) {
  10056. DB::rollBack();
  10057. Utils::throwError('20003:'.$e->getMessage());
  10058. }
  10059. $boolen1 = DB::table('mp_anime_episodes')->where('id', $episode_id)->update([
  10060. 'is_generated' => 1,
  10061. 'updated_at' => date('Y-m-d H:i:s')
  10062. ]);
  10063. if (!$boolen1) {
  10064. DB::rollBack();
  10065. Utils::throwError('20003:分集处理失败!');
  10066. }
  10067. DB::commit();
  10068. // 重新查询更新后的片段数据
  10069. $acts = DB::table('mp_episode_segments')->where('episode_id', $episode_id)->orderBy('act_number')->get();
  10070. // 构建返回的acts数组
  10071. $return_acts = [];
  10072. foreach ($acts as $act) {
  10073. $return_acts[] = [
  10074. 'act_id' => getProp($act, 'id'),
  10075. 'act_number' => getProp($act, 'act_number'),
  10076. 'act_duration' => getProp($act, 'video_duration') ? getProp($act, 'video_duration') : getProp($act, 'act_duration'),
  10077. 'act_show_content' => getProp($act, 'act_show_content'),
  10078. 'video_url' => getProp($act, 'video_url'),
  10079. 'video_duration' => getProp($act, 'video_duration'),
  10080. 'video_time_point_start' => getProp($act, 'video_time_point_start'),
  10081. 'video_time_point_end' => getProp($act, 'video_time_point_end'),
  10082. ];
  10083. }
  10084. return [
  10085. 'anime_id' => getProp($episode, 'anime_id'),
  10086. 'episode_id' => $episode_id,
  10087. 'title' => getProp($episode, 'title'),
  10088. 'episode_number' => getProp($episode, 'episode_number'),
  10089. 'is_generated' => getProp($episode, 'is_generated'),
  10090. 'video_params' => [
  10091. 'video_model' => getProp($episode, 'video_model'),
  10092. 'video_resolution' => getProp($episode, 'video_resolution'),
  10093. 'ratio' => getProp($episode, 'ratio'),
  10094. ],
  10095. 'products' => $products,
  10096. 'acts' => $return_acts
  10097. ];
  10098. }
  10099. /**
  10100. * 参照 episodePicsInfo 的更新与监控逻辑:
  10101. * 每5秒查询一次角色/场景/道具的图片任务状态,任务成功后将图片URL回填到对应资产并写回分集表。
  10102. * 所有需要图片的资产均已生成(url 非空)才返回;最多等待1分钟,仍有图片未生成则直接报错。
  10103. */
  10104. private function waitForEpisodeAssetsImagesReady($episode_id, &$roles, &$scenes, &$props) {
  10105. $pollInterval = 5; // 每5秒查询一次
  10106. $maxWaitSeconds = 60; // 最多持续1分钟
  10107. $startTime = time();
  10108. while (true) {
  10109. // 从数据库读取最新数据,兼容后台 Anime:checkImgUrl 等任务对角色/场景/道具图片URL的更新
  10110. $episode = DB::table('mp_anime_episodes')->where('id', $episode_id)->first();
  10111. if (!$episode) {
  10112. Utils::throwError('20003:分集不存在');
  10113. }
  10114. $roles = json_decode(getProp($episode, 'roles'), true) ?: [];
  10115. $scenes = json_decode(getProp($episode, 'scenes'), true) ?: [];
  10116. $props = json_decode(getProp($episode, 'props'), true) ?: [];
  10117. $updated = false;
  10118. $waitingAssets = []; // 任务仍在处理中,可等待后续轮询
  10119. $missingAssets = []; // 无任务或任务已失败/不存在,无法通过等待自动恢复
  10120. $this->refreshEpisodeAssetsImageTasks($roles, 'role', '旁白', $waitingAssets, $missingAssets, $updated);
  10121. $this->refreshEpisodeAssetsImageTasks($scenes, 'scene', '', $waitingAssets, $missingAssets, $updated);
  10122. $this->refreshEpisodeAssetsImageTasks($props, 'prop', '', $waitingAssets, $missingAssets, $updated);
  10123. // 有图片任务结果更新时写回分集表
  10124. if ($updated) {
  10125. DB::table('mp_anime_episodes')->where('id', $episode_id)->update([
  10126. 'roles' => json_encode($roles, JSON_UNESCAPED_UNICODE),
  10127. 'scenes' => json_encode($scenes, JSON_UNESCAPED_UNICODE),
  10128. 'props' => json_encode($props, JSON_UNESCAPED_UNICODE),
  10129. 'updated_at' => date('Y-m-d H:i:s')
  10130. ]);
  10131. }
  10132. // 所有需要图片的资产都已生成,允许继续 confirmActs 后续逻辑
  10133. if (empty($waitingAssets) && empty($missingAssets)) {
  10134. return;
  10135. }
  10136. // 其他任务都已处理完毕,仍有角色、场景或道具图片未生成,统一报错阻止后续逻辑
  10137. if (empty($waitingAssets)) {
  10138. Utils::throwError('20003:还有主体、场景或道具图片未生成,请等待图片生成后重试');
  10139. }
  10140. // 超过1分钟仍未生成完毕,阻止 confirmActs 后续逻辑
  10141. if (time() - $startTime >= $maxWaitSeconds) {
  10142. Utils::throwError('20003:还有主体、场景或道具图片未生成,请等待图片生成后重试');
  10143. }
  10144. sleep($pollInterval);
  10145. }
  10146. }
  10147. /**
  10148. * 参照 episodePicsInfo:遍历单个资产列表,对有图片任务但还没有图片URL的资产查询图片任务结果并回填。
  10149. * 无任务、任务不存在或生成失败的资产记录为缺失项,不在此处直接报错;
  10150. * 仍在处理中的任务记录为等待项,由外层统一等待所有任务完成后,再对缺失资产统一报错。
  10151. */
  10152. private function refreshEpisodeAssetsImageTasks(&$assets, $nameKey, $skipName, &$waitingAssets, &$missingAssets, &$updated) {
  10153. foreach ($assets as &$asset) {
  10154. $assetName = getProp($asset, $nameKey);
  10155. if ($assetName === '' || ($skipName !== '' && $assetName === $skipName)) {
  10156. continue;
  10157. }
  10158. // 已有图片URL的资产视为已生成
  10159. if (getProp($asset, 'url')) {
  10160. continue;
  10161. }
  10162. $task_id = getProp($asset, 'task_id');
  10163. // 没有图片任务且没有图片URL:记录为缺失项,继续遍历其他资产,待其他任务都完成后再统一报错
  10164. if (!$task_id) {
  10165. $missingAssets[] = $assetName;
  10166. continue;
  10167. }
  10168. $task = DB::table('mp_generate_pic_tasks')
  10169. ->where('id', $task_id)
  10170. ->select('status', 'result_url')
  10171. ->first();
  10172. // 任务不存在:同样记录为缺失项,不在此处直接报错
  10173. if (!$task) {
  10174. $missingAssets[] = $assetName;
  10175. continue;
  10176. }
  10177. if ($task->status === 'success') {
  10178. $result_url = getProp($task, 'result_url');
  10179. if ($result_url) {
  10180. $result_urls = is_json($result_url) ? json_decode($result_url, true) : [$result_url];
  10181. if (is_array($result_urls) && !empty($result_urls[0])) {
  10182. $asset['url'] = $result_urls[0];
  10183. $asset['task_status'] = 'success';
  10184. $updated = true;
  10185. continue;
  10186. }
  10187. }
  10188. // 任务成功但没有可用的结果URL,仍视为未生成,继续等待后续轮询结果
  10189. $waitingAssets[] = $assetName;
  10190. } elseif ($task->status === 'failed') {
  10191. // 生成失败:记录为缺失项,待其他任务处理完后统一报错
  10192. $missingAssets[] = $assetName;
  10193. } else {
  10194. // 任务仍在生成中,等待下一次轮询
  10195. $waitingAssets[] = $assetName;
  10196. }
  10197. }
  10198. unset($asset);
  10199. }
  10200. /**
  10201. * 导出动漫剧本为PDF(参照示例PDF版式)
  10202. * @param int $animeId 动漫ID
  10203. * @param int $episodeCount 导出集数,默认8,传-1表示全部
  10204. * @param string|null $savePath 指定保存路径(为空则直接下载输出)
  10205. * @return string|null
  10206. */
  10207. public function exportAnimeScriptAsPdf($animeId, $episodeCount = 8, $savePath = null) {
  10208. // 图片下载与转换可能占用较多内存
  10209. ini_set('memory_limit', '512M');
  10210. $anime = DB::table('mp_animes')->where('id', $animeId)->where('is_deleted', 0)->first();
  10211. if (!$anime) Utils::throwError('20003:该动漫不存在!');
  10212. $anime = (array)$anime;
  10213. // 剧本名去掉末尾"_数字"标识后缀,只保留剧名本身
  10214. $anime['anime_name'] = trim((string)preg_replace('/_\d+$/u', '', getProp($anime, 'anime_name', '')));
  10215. // 获取分集(默认展示版本,按集数升序)
  10216. $episodeQuery = DB::table('mp_anime_episodes')
  10217. ->where('anime_id', $animeId)
  10218. ->where('is_default', 1)
  10219. ->orderBy('episode_number')
  10220. ->orderBy('id');
  10221. if ($episodeCount > 0) {
  10222. $episodeQuery->limit($episodeCount);
  10223. }
  10224. $episodes = $episodeQuery->get()->map(function ($value) {
  10225. return (array)$value;
  10226. })->toArray();
  10227. if (!$episodes) Utils::throwError('20003:该动漫暂无分集数据');
  10228. // 聚合主体/场景/道具列表(前N集内容,按名称去重)
  10229. $roles = $this->mergeEpisodeItems($episodes, 'role');
  10230. $scenes = $this->mergeEpisodeItems($episodes, 'scene');
  10231. $props = $this->mergeEpisodeItems($episodes, 'prop');
  10232. // 组装分集剧本数据
  10233. $episodeScripts = [];
  10234. foreach ($episodes as $episode) {
  10235. $segments = DB::table('mp_episode_segments')
  10236. ->where('anime_id', $animeId)
  10237. ->where('episode_id', $episode['id'])
  10238. ->get();
  10239. // 按act_number分组,同一片段多版本时取最新一条(id最大)
  10240. $acts = [];
  10241. foreach ($segments as $segment) {
  10242. $segment = (array)$segment;
  10243. $actNumber = (int)getProp($segment, 'act_number', 0);
  10244. if ($actNumber <= 0) continue;
  10245. if (!isset($acts[$actNumber]) || (int)$segment['id'] > (int)$acts[$actNumber]['id']) {
  10246. $acts[$actNumber] = [
  10247. 'id' => (int)$segment['id'],
  10248. 'act_number' => $actNumber,
  10249. 'duration' => getProp($segment, 'act_duration', ''),
  10250. 'content' => getProp($segment, 'act_content', ''),
  10251. ];
  10252. }
  10253. }
  10254. ksort($acts);
  10255. // 分镜序号按出现先后重新编号(整集范围内保持连续,兼容【镜头N】/【分镜N】两种格式)
  10256. $segmentCounter = 0;
  10257. foreach ($acts as &$act) {
  10258. $act['content'] = $this->renumberSegmentBlocks($act['content'], $segmentCounter);
  10259. }
  10260. unset($act);
  10261. // 旁白音色:优先取分集roles中"旁白"的voice_prompt,否则从片段内容解析
  10262. $narratorVoice = '';
  10263. $episodeRoles = json_decode(getProp($episode, 'roles', ''), true) ?: [];
  10264. foreach ($episodeRoles as $role) {
  10265. if (getProp($role, 'role') === '旁白') {
  10266. $narratorVoice = trim((string)getProp($role, 'voice_prompt', ''));
  10267. break;
  10268. }
  10269. }
  10270. if ($narratorVoice === '') {
  10271. foreach ($acts as $act) {
  10272. if (preg_match('/旁白音色[::]\s*([^\n]+)/u', $act['content'], $match)) {
  10273. $narratorVoice = trim($match[1]);
  10274. break;
  10275. }
  10276. }
  10277. }
  10278. $episodeScripts[] = [
  10279. 'episode_number' => getProp($episode, 'episode_number'),
  10280. 'title' => getProp($episode, 'title', ''),
  10281. 'act_count' => count($acts),
  10282. 'narrator_voice' => $narratorVoice,
  10283. 'acts' => array_values($acts),
  10284. ];
  10285. }
  10286. // 并发下载列表图片(主体/场景/道具),url => 临时文件
  10287. $imageCache = $this->downloadImagesConcurrently(array_merge($roles, $scenes, $props));
  10288. // 构建PDF
  10289. $pdf = $this->buildAnimeScriptPdf($anime, $roles, $scenes, $props, $episodeScripts, $imageCache);
  10290. // 图片已嵌入PDF,清理临时文件
  10291. foreach ($imageCache as $imgFile) {
  10292. @unlink($imgFile);
  10293. }
  10294. $filename = $anime['anime_name'] . '_' . date('YmdHis');
  10295. if ($savePath) {
  10296. $pdf->Output($savePath, 'F');
  10297. return $savePath;
  10298. }
  10299. // 直接下载输出
  10300. header('Content-Type: application/pdf');
  10301. header("Content-Disposition: attachment; filename*=UTF-8''" . rawurlencode($filename . '.pdf'));
  10302. $pdf->Output($filename . '.pdf', 'D');
  10303. exit();
  10304. }
  10305. /**
  10306. * 聚合分集的主体/场景/道具列表,按名称去重(保留首次出现)
  10307. * @param array $episodes 分集数据
  10308. * @param string $nameKey role|scene|prop
  10309. * @return array
  10310. */
  10311. private function mergeEpisodeItems(array $episodes, $nameKey) {
  10312. $fieldMap = [
  10313. 'role' => 'roles',
  10314. 'scene' => 'scenes',
  10315. 'prop' => 'props',
  10316. ];
  10317. $field = isset($fieldMap[$nameKey]) ? $fieldMap[$nameKey] : $nameKey;
  10318. $items = [];
  10319. foreach ($episodes as $episode) {
  10320. $list = json_decode(getProp($episode, $field, ''), true) ?: [];
  10321. foreach ($list as $item) {
  10322. if (!is_array($item)) continue;
  10323. $name = trim((string)getProp($item, $nameKey, ''));
  10324. if ($name === '') continue;
  10325. // 旁白不进入主体列表(仅作为旁白音色来源)
  10326. if ($nameKey === 'role' && $name === '旁白') continue;
  10327. if (!isset($items[$name])) {
  10328. $items[$name] = $item;
  10329. }
  10330. }
  10331. }
  10332. return array_values($items);
  10333. }
  10334. /**
  10335. * 构建动漫剧本PDF
  10336. * @param array $anime 动漫信息
  10337. * @param array $roles 主体列表
  10338. * @param array $scenes 场景列表
  10339. * @param array $props 道具列表
  10340. * @param array $episodeScripts 分集剧本数据
  10341. * @param array $imageCache 图片缓存(url => 临时文件路径)
  10342. * @return \TCPDF
  10343. */
  10344. private function buildAnimeScriptPdf($anime, $roles, $scenes, $props, $episodeScripts, $imageCache = []) {
  10345. $pdf = new \TCPDF('P', 'mm', 'A4', true, 'UTF-8', false);
  10346. $pdf->SetCreator('动漫剧本导出系统');
  10347. $pdf->SetAuthor('系统');
  10348. $pdf->SetTitle(getProp($anime, 'anime_name', '动漫剧本'));
  10349. $pdf->SetSubject('动漫剧本导出');
  10350. $pdf->SetMargins(15, 15, 15);
  10351. $pdf->SetAutoPageBreak(true, 15);
  10352. // 剧本名
  10353. $pdf->AddPage();
  10354. $pdf->SetFont('simsun', 'B', 20);
  10355. $pdf->Cell(0, 15, getProp($anime, 'anime_name', ''), 0, 1, 'C');
  10356. $pdf->Ln(5);
  10357. // 故事梗概
  10358. $intro = trim((string)getProp($anime, 'intro', ''));
  10359. if ($intro !== '') {
  10360. $this->pdfSectionTitle($pdf, '故事梗概');
  10361. $this->pdfBody($pdf, $intro);
  10362. }
  10363. // 美术风格
  10364. $artStyle = trim((string)getProp($anime, 'art_style', ''));
  10365. if ($artStyle !== '') {
  10366. $this->pdfSectionTitle($pdf, '美术风格');
  10367. $this->pdfBody($pdf, $artStyle);
  10368. }
  10369. // 主体列表(文字+图片)
  10370. $this->pdfSectionTitle($pdf, '主体列表');
  10371. foreach ($roles as $index => $role) {
  10372. $this->pdfBody($pdf, ($index + 1) . '. ' . getProp($role, 'role', '') . ':' . getProp($role, 'description', ''));
  10373. }
  10374. $this->pdfItemImages($pdf, $roles, 'role', $imageCache);
  10375. // 场景列表(文字+图片)
  10376. $this->pdfSectionTitle($pdf, '场景列表');
  10377. foreach ($scenes as $index => $scene) {
  10378. $this->pdfBody($pdf, ($index + 1) . '. ' . getProp($scene, 'scene', '') . ':' . getProp($scene, 'description', ''));
  10379. }
  10380. $this->pdfItemImages($pdf, $scenes, 'scene', $imageCache);
  10381. // 道具列表(文字+图片)
  10382. $this->pdfSectionTitle($pdf, '道具列表');
  10383. foreach ($props as $index => $prop) {
  10384. $this->pdfBody($pdf, ($index + 1) . '. ' . getProp($prop, 'prop', '') . ':' . getProp($prop, 'description', ''));
  10385. }
  10386. $this->pdfItemImages($pdf, $props, 'prop', $imageCache);
  10387. // 分镜剧本
  10388. $this->pdfSectionTitle($pdf, '分镜剧本');
  10389. foreach ($episodeScripts as $episodeScript) {
  10390. $episodeTitle = '第' . getProp($episodeScript, 'episode_number') . '集';
  10391. $episodeTitleRaw = trim((string)getProp($episodeScript, 'title', ''));
  10392. if ($episodeTitleRaw !== '') {
  10393. // title 字段可能已带"第N集"前缀,避免重复
  10394. if (preg_match('/^第\d+集[::\s]/u', $episodeTitleRaw)) {
  10395. $episodeTitle = $episodeTitleRaw;
  10396. } else {
  10397. $episodeTitle .= ':' . $episodeTitleRaw;
  10398. }
  10399. }
  10400. $this->pdfSubTitle($pdf, $episodeTitle, 13);
  10401. $this->pdfBody($pdf, '片段数量:' . getProp($episodeScript, 'act_count', 0));
  10402. if (getProp($episodeScript, 'narrator_voice') !== '') {
  10403. $this->pdfBody($pdf, '旁白音色:' . getProp($episodeScript, 'narrator_voice'));
  10404. }
  10405. foreach (getProp($episodeScript, 'acts', []) as $act) {
  10406. $actTitle = '片段' . getProp($act, 'act_number');
  10407. if (getProp($act, 'duration') !== '' && getProp($act, 'duration') !== null) {
  10408. $actTitle .= ' 时长 ' . getProp($act, 'duration') . 's';
  10409. }
  10410. $this->pdfSubTitle($pdf, $actTitle, 12);
  10411. if (getProp($act, 'content') !== '') {
  10412. $this->pdfBody($pdf, getProp($act, 'content'));
  10413. }
  10414. }
  10415. }
  10416. return $pdf;
  10417. }
  10418. /**
  10419. * PDF章节标题(带分隔线)
  10420. */
  10421. private function pdfSectionTitle($pdf, $title) {
  10422. if ($pdf->GetY() > 230) {
  10423. $pdf->AddPage();
  10424. }
  10425. $pdf->SetFont('simsun', 'B', 15);
  10426. $pdf->Cell(0, 10, $title, 0, 1, 'L');
  10427. $y = $pdf->GetY();
  10428. $pdf->SetLineWidth(0.4);
  10429. $pdf->Line(15, $y, 195, $y);
  10430. $pdf->Ln(4);
  10431. }
  10432. /**
  10433. * PDF子标题(集数/片段标题)
  10434. */
  10435. private function pdfSubTitle($pdf, $title, $size = 13) {
  10436. if ($pdf->GetY() > 240) {
  10437. $pdf->AddPage();
  10438. }
  10439. $pdf->SetFont('simsun', 'B', $size);
  10440. $pdf->Cell(0, 8, $title, 0, 1, 'L');
  10441. $pdf->Ln(1);
  10442. }
  10443. /**
  10444. * PDF正文段落
  10445. */
  10446. private function pdfBody($pdf, $text) {
  10447. $pdf->SetFont('simsun', '', 11);
  10448. $pdf->MultiCell(0, 6, $text, 0, 'L');
  10449. $pdf->Ln(2);
  10450. }
  10451. /**
  10452. * 输出列表项图片(每张图单独一页,图下标注名称)
  10453. * @param \TCPDF $pdf
  10454. * @param array $items 列表项
  10455. * @param string $nameKey role|scene|prop
  10456. * @param array $imageCache 图片缓存(url => 临时文件路径)
  10457. */
  10458. private function pdfItemImages($pdf, array $items, $nameKey, array $imageCache) {
  10459. foreach ($items as $item) {
  10460. $url = trim((string)getProp($item, 'url', ''));
  10461. $name = trim((string)getProp($item, $nameKey, ''));
  10462. if ($url === '' || !isset($imageCache[$url])) continue;
  10463. $imgPath = $imageCache[$url];
  10464. $size = @getimagesize($imgPath);
  10465. if (!$size || $size[0] <= 0 || $size[1] <= 0) {
  10466. continue;
  10467. }
  10468. $pdf->AddPage();
  10469. // 图片按比例缩放,居中偏上,为底部名称标注预留空间
  10470. $maxW = 160;
  10471. $maxH = 170;
  10472. $ratio = min($maxW / $size[0], $maxH / $size[1], 1);
  10473. $drawW = $size[0] * $ratio;
  10474. $drawH = $size[1] * $ratio;
  10475. $x = (210 - $drawW) / 2;
  10476. $y = max(15, (297 - $drawH) / 2 - 10);
  10477. $pdf->Image($imgPath, $x, $y, $drawW, $drawH, '', '', '', false, 300, '', false, false, 0, false, false, false);
  10478. // 图下标注名称
  10479. $pdf->SetFont('simsun', 'B', 13);
  10480. $pdf->SetY(297 - 28);
  10481. $pdf->Cell(0, 8, $name, 0, 1, 'C');
  10482. }
  10483. }
  10484. /**
  10485. * 并发下载远程图片到临时文件,并统一缩放转为JPEG
  10486. * @param array $items 包含url字段的列表项
  10487. * @return array url => 临时文件路径
  10488. */
  10489. private function downloadImagesConcurrently(array $items) {
  10490. // 收集唯一的图片URL
  10491. $urls = [];
  10492. foreach ($items as $item) {
  10493. $url = trim((string)getProp($item, 'url', ''));
  10494. if ($url !== '') $urls[$url] = true;
  10495. }
  10496. if (!$urls) return [];
  10497. $urls = array_keys($urls);
  10498. $tmpDir = sys_get_temp_dir();
  10499. $rawFiles = [];
  10500. foreach ($urls as $url) {
  10501. $rawFile = $tmpDir . '/anime_pdf_raw_' . md5($url) . '.img';
  10502. $rawFiles[$url] = $rawFile;
  10503. }
  10504. $client = new Client(['timeout' => 180, 'verify' => false]);
  10505. // 低并发下载,sink写入文件避免大图占用内存
  10506. $generator = (function () use ($urls, $client, $rawFiles) {
  10507. foreach ($urls as $url) {
  10508. yield $url => $client->getAsync($url, ['sink' => $rawFiles[$url]]);
  10509. }
  10510. })();
  10511. $errors = [];
  10512. $each = new \GuzzleHttp\Promise\EachPromise($generator, [
  10513. 'concurrency' => 4,
  10514. 'rejected' => function ($reason, $url) use (&$errors) {
  10515. $errors[$url] = $reason ? $reason->getMessage() : 'unknown';
  10516. },
  10517. ]);
  10518. $each->promise()->wait();
  10519. // 失败的图片串行重试一次(独占带宽,提高成功率)
  10520. foreach ($urls as $url) {
  10521. if (!isset($errors[$url])) continue;
  10522. try {
  10523. $client->get($url, ['sink' => $rawFiles[$url], 'timeout' => 300]);
  10524. unset($errors[$url]);
  10525. } catch (\Throwable $e) {
  10526. // 重试仍失败
  10527. }
  10528. }
  10529. $cache = [];
  10530. foreach ($urls as $url) {
  10531. $rawFile = $rawFiles[$url];
  10532. if (isset($errors[$url])) {
  10533. dLog('anime')->error('导出PDF图片下载失败', [
  10534. 'url' => $url,
  10535. 'error' => $errors[$url],
  10536. ]);
  10537. @unlink($rawFile);
  10538. continue;
  10539. }
  10540. $converted = $this->convertImageFile($rawFile, $url);
  10541. if ($converted !== null) {
  10542. $cache[$url] = $converted;
  10543. } else {
  10544. @unlink($rawFile);
  10545. }
  10546. }
  10547. return $cache;
  10548. }
  10549. /**
  10550. * 将已下载的图片文件缩放并转为JPEG
  10551. * @param string $rawFile 原始图片临时文件
  10552. * @param string $url 图片地址(用于命名)
  10553. * @return string|null 转换后的文件路径,转换失败返回null
  10554. */
  10555. private function convertImageFile($rawFile, $url) {
  10556. $content = @file_get_contents($rawFile);
  10557. if ($content === false || $content === '') return null;
  10558. if (!function_exists('imagecreatefromstring')) return null;
  10559. $image = @imagecreatefromstring($content);
  10560. if ($image === false) return null;
  10561. $jpeg = $this->compressImageForPdf($image, $rawFile, $url);
  10562. imagedestroy($image);
  10563. if ($jpeg !== null) {
  10564. @unlink($rawFile);
  10565. }
  10566. return $jpeg;
  10567. }
  10568. /**
  10569. * 图片压缩:白底合成后转JPEG,分级缩小尺寸与降低质量,保证每张不超过2MB
  10570. * @param resource $srcImage GD图片资源
  10571. * @param string $rawFile 原始图片临时文件
  10572. * @param string $url 图片地址(用于命名)
  10573. * @return string|null 压缩后的JPEG文件路径
  10574. */
  10575. private function compressImageForPdf($srcImage, $rawFile, $url) {
  10576. $maxBytes = 2 * 1024 * 1024; // 2MB
  10577. $sizes = [2048, 1600, 1280, 1024, 800];
  10578. $qualities = [85, 70, 55, 40];
  10579. $jpeg = dirname($rawFile) . '/anime_pdf_img_' . md5($url) . '.jpg';
  10580. foreach ($sizes as $size) {
  10581. $resized = $this->copyAndResize($srcImage, $size);
  10582. $flat = $this->flattenToWhite($resized);
  10583. imagedestroy($resized);
  10584. foreach ($qualities as $quality) {
  10585. ob_start();
  10586. $saved = imagejpeg($flat, null, $quality);
  10587. $data = ob_get_clean();
  10588. if ($saved && $data !== false && $data !== '' && strlen($data) <= $maxBytes) {
  10589. file_put_contents($jpeg, $data);
  10590. imagedestroy($flat);
  10591. dLog('anime')->info('导出PDF图片压缩完成', [
  10592. 'url' => $url,
  10593. 'size' => filesize($jpeg),
  10594. 'edge' => $size,
  10595. 'quality' => $quality,
  10596. ]);
  10597. return $jpeg;
  10598. }
  10599. }
  10600. imagedestroy($flat);
  10601. }
  10602. // 兜底:最小尺寸、最低质量强制输出
  10603. $resized = $this->copyAndResize($srcImage, 800);
  10604. $flat = $this->flattenToWhite($resized);
  10605. imagedestroy($resized);
  10606. $saved = imagejpeg($flat, $jpeg, 30);
  10607. imagedestroy($flat);
  10608. if (!$saved) return null;
  10609. dLog('anime')->info('导出PDF图片压缩完成(兜底)', [
  10610. 'url' => $url,
  10611. 'size' => filesize($jpeg),
  10612. ]);
  10613. return $jpeg;
  10614. }
  10615. /**
  10616. * 等比缩放图片副本(不销毁原图)
  10617. * @param resource $srcImage GD图片资源
  10618. * @param int $maxEdge 最大边长
  10619. * @return resource
  10620. */
  10621. private function copyAndResize($srcImage, $maxEdge) {
  10622. $width = imagesx($srcImage);
  10623. $height = imagesy($srcImage);
  10624. $max = max($width, $height);
  10625. if ($max <= $maxEdge) {
  10626. $copy = imagecreatetruecolor($width, $height);
  10627. imagecopy($copy, $srcImage, 0, 0, 0, 0, $width, $height);
  10628. return $copy;
  10629. }
  10630. $ratio = $maxEdge / $max;
  10631. $newWidth = max(1, (int)round($width * $ratio));
  10632. $newHeight = max(1, (int)round($height * $ratio));
  10633. $resized = imagecreatetruecolor($newWidth, $newHeight);
  10634. imagealphablending($resized, false);
  10635. imagesavealpha($resized, true);
  10636. imagecopyresampled($resized, $srcImage, 0, 0, 0, 0, $newWidth, $newHeight, $width, $height);
  10637. return $resized;
  10638. }
  10639. /**
  10640. * 将GD图片合成到白色背景上(处理透明通道,输出RGB)
  10641. * @param resource $image GD图片资源
  10642. * @return resource
  10643. */
  10644. private function flattenToWhite($image) {
  10645. $width = imagesx($image);
  10646. $height = imagesy($image);
  10647. $flat = imagecreatetruecolor($width, $height);
  10648. $white = imagecolorallocate($flat, 255, 255, 255);
  10649. imagefill($flat, 0, 0, $white);
  10650. imagecopy($flat, $image, 0, 0, 0, 0, $width, $height);
  10651. return $flat;
  10652. }
  10653. /**
  10654. * 将片段内容中的分镜序号按出现先后重新编号(保证整集连续)
  10655. * @param string $content 片段内容
  10656. * @param int $counter 当前已编号数量(引用传递,整集累计)
  10657. * @return string
  10658. */
  10659. private function renumberSegmentBlocks($content, &$counter) {
  10660. return preg_replace_callback('/^【(分镜|镜头)\d+】/mu', function ($match) use (&$counter) {
  10661. $counter++;
  10662. return '【' . $match[1] . $counter . '】';
  10663. }, $content);
  10664. }
  10665. }