AnimeService.php 567 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695705715725735745755765775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206216226236246256266276286296306316326336346356366376386396406416426436446456466476486496506516526536546556566576586596606616626636646656666676686696706716726736746756766776786796806816826836846856866876886896906916926936946956966976986997007017027037047057067077087097107117127137147157167177187197207217227237247257267277287297307317327337347357367377387397407417427437447457467477487497507517527537547557567577587597607617627637647657667677687697707717727737747757767777787797807817827837847857867877887897907917927937947957967977987998008018028038048058068078088098108118128138148158168178188198208218228238248258268278288298308318328338348358368378388398408418428438448458468478488498508518528538548558568578588598608618628638648658668678688698708718728738748758768778788798808818828838848858868878888898908918928938948958968978988999009019029039049059069079089099109119129139149159169179189199209219229239249259269279289299309319329339349359369379389399409419429439449459469479489499509519529539549559569579589599609619629639649659669679689699709719729739749759769779789799809819829839849859869879889899909919929939949959969979989991000100110021003100410051006100710081009101010111012101310141015101610171018101910201021102210231024102510261027102810291030103110321033103410351036103710381039104010411042104310441045104610471048104910501051105210531054105510561057105810591060106110621063106410651066106710681069107010711072107310741075107610771078107910801081108210831084108510861087108810891090109110921093109410951096109710981099110011011102110311041105110611071108110911101111111211131114111511161117111811191120112111221123112411251126112711281129113011311132113311341135113611371138113911401141114211431144114511461147114811491150115111521153115411551156115711581159116011611162116311641165116611671168116911701171117211731174117511761177117811791180118111821183118411851186118711881189119011911192119311941195119611971198119912001201120212031204120512061207120812091210121112121213121412151216121712181219122012211222122312241225122612271228122912301231123212331234123512361237123812391240124112421243124412451246124712481249125012511252125312541255125612571258125912601261126212631264126512661267126812691270127112721273127412751276127712781279128012811282128312841285128612871288128912901291129212931294129512961297129812991300130113021303130413051306130713081309131013111312131313141315131613171318131913201321132213231324132513261327132813291330133113321333133413351336133713381339134013411342134313441345134613471348134913501351135213531354135513561357135813591360136113621363136413651366136713681369137013711372137313741375137613771378137913801381138213831384138513861387138813891390139113921393139413951396139713981399140014011402140314041405140614071408140914101411141214131414141514161417141814191420142114221423142414251426142714281429143014311432143314341435143614371438143914401441144214431444144514461447144814491450145114521453145414551456145714581459146014611462146314641465146614671468146914701471147214731474147514761477147814791480148114821483148414851486148714881489149014911492149314941495149614971498149915001501150215031504150515061507150815091510151115121513151415151516151715181519152015211522152315241525152615271528152915301531153215331534153515361537153815391540154115421543154415451546154715481549155015511552155315541555155615571558155915601561156215631564156515661567156815691570157115721573157415751576157715781579158015811582158315841585158615871588158915901591159215931594159515961597159815991600160116021603160416051606160716081609161016111612161316141615161616171618161916201621162216231624162516261627162816291630163116321633163416351636163716381639164016411642164316441645164616471648164916501651165216531654165516561657165816591660166116621663166416651666166716681669167016711672167316741675167616771678167916801681168216831684168516861687168816891690169116921693169416951696169716981699170017011702170317041705170617071708170917101711171217131714171517161717171817191720172117221723172417251726172717281729173017311732173317341735173617371738173917401741174217431744174517461747174817491750175117521753175417551756175717581759176017611762176317641765176617671768176917701771177217731774177517761777177817791780178117821783178417851786178717881789179017911792179317941795179617971798179918001801180218031804180518061807180818091810181118121813181418151816181718181819182018211822182318241825182618271828182918301831183218331834183518361837183818391840184118421843184418451846184718481849185018511852185318541855185618571858185918601861186218631864186518661867186818691870187118721873187418751876187718781879188018811882188318841885188618871888188918901891189218931894189518961897189818991900190119021903190419051906190719081909191019111912191319141915191619171918191919201921192219231924192519261927192819291930193119321933193419351936193719381939194019411942194319441945194619471948194919501951195219531954195519561957195819591960196119621963196419651966196719681969197019711972197319741975197619771978197919801981198219831984198519861987198819891990199119921993199419951996199719981999200020012002200320042005200620072008200920102011201220132014201520162017201820192020202120222023202420252026202720282029203020312032203320342035203620372038203920402041204220432044204520462047204820492050205120522053205420552056205720582059206020612062206320642065206620672068206920702071207220732074207520762077207820792080208120822083208420852086208720882089209020912092209320942095209620972098209921002101210221032104210521062107210821092110211121122113211421152116211721182119212021212122212321242125212621272128212921302131213221332134213521362137213821392140214121422143214421452146214721482149215021512152215321542155215621572158215921602161216221632164216521662167216821692170217121722173217421752176217721782179218021812182218321842185218621872188218921902191219221932194219521962197219821992200220122022203220422052206220722082209221022112212221322142215221622172218221922202221222222232224222522262227222822292230223122322233223422352236223722382239224022412242224322442245224622472248224922502251225222532254225522562257225822592260226122622263226422652266226722682269227022712272227322742275227622772278227922802281228222832284228522862287228822892290229122922293229422952296229722982299230023012302230323042305230623072308230923102311231223132314231523162317231823192320232123222323232423252326232723282329233023312332233323342335233623372338233923402341234223432344234523462347234823492350235123522353235423552356235723582359236023612362236323642365236623672368236923702371237223732374237523762377237823792380238123822383238423852386238723882389239023912392239323942395239623972398239924002401240224032404240524062407240824092410241124122413241424152416241724182419242024212422242324242425242624272428242924302431243224332434243524362437243824392440244124422443244424452446244724482449245024512452245324542455245624572458245924602461246224632464246524662467246824692470247124722473247424752476247724782479248024812482248324842485248624872488248924902491249224932494249524962497249824992500250125022503250425052506250725082509251025112512251325142515251625172518251925202521252225232524252525262527252825292530253125322533253425352536253725382539254025412542254325442545254625472548254925502551255225532554255525562557255825592560256125622563256425652566256725682569257025712572257325742575257625772578257925802581258225832584258525862587258825892590259125922593259425952596259725982599260026012602260326042605260626072608260926102611261226132614261526162617261826192620262126222623262426252626262726282629263026312632263326342635263626372638263926402641264226432644264526462647264826492650265126522653265426552656265726582659266026612662266326642665266626672668266926702671267226732674267526762677267826792680268126822683268426852686268726882689269026912692269326942695269626972698269927002701270227032704270527062707270827092710271127122713271427152716271727182719272027212722272327242725272627272728272927302731273227332734273527362737273827392740274127422743274427452746274727482749275027512752275327542755275627572758275927602761276227632764276527662767276827692770277127722773277427752776277727782779278027812782278327842785278627872788278927902791279227932794279527962797279827992800280128022803280428052806280728082809281028112812281328142815281628172818281928202821282228232824282528262827282828292830283128322833283428352836283728382839284028412842284328442845284628472848284928502851285228532854285528562857285828592860286128622863286428652866286728682869287028712872287328742875287628772878287928802881288228832884288528862887288828892890289128922893289428952896289728982899290029012902290329042905290629072908290929102911291229132914291529162917291829192920292129222923292429252926292729282929293029312932293329342935293629372938293929402941294229432944294529462947294829492950295129522953295429552956295729582959296029612962296329642965296629672968296929702971297229732974297529762977297829792980298129822983298429852986298729882989299029912992299329942995299629972998299930003001300230033004300530063007300830093010301130123013301430153016301730183019302030213022302330243025302630273028302930303031303230333034303530363037303830393040304130423043304430453046304730483049305030513052305330543055305630573058305930603061306230633064306530663067306830693070307130723073307430753076307730783079308030813082308330843085308630873088308930903091309230933094309530963097309830993100310131023103310431053106310731083109311031113112311331143115311631173118311931203121312231233124312531263127312831293130313131323133313431353136313731383139314031413142314331443145314631473148314931503151315231533154315531563157315831593160316131623163316431653166316731683169317031713172317331743175317631773178317931803181318231833184318531863187318831893190319131923193319431953196319731983199320032013202320332043205320632073208320932103211321232133214321532163217321832193220322132223223322432253226322732283229323032313232323332343235323632373238323932403241324232433244324532463247324832493250325132523253325432553256325732583259326032613262326332643265326632673268326932703271327232733274327532763277327832793280328132823283328432853286328732883289329032913292329332943295329632973298329933003301330233033304330533063307330833093310331133123313331433153316331733183319332033213322332333243325332633273328332933303331333233333334333533363337333833393340334133423343334433453346334733483349335033513352335333543355335633573358335933603361336233633364336533663367336833693370337133723373337433753376337733783379338033813382338333843385338633873388338933903391339233933394339533963397339833993400340134023403340434053406340734083409341034113412341334143415341634173418341934203421342234233424342534263427342834293430343134323433343434353436343734383439344034413442344334443445344634473448344934503451345234533454345534563457345834593460346134623463346434653466346734683469347034713472347334743475347634773478347934803481348234833484348534863487348834893490349134923493349434953496349734983499350035013502350335043505350635073508350935103511351235133514351535163517351835193520352135223523352435253526352735283529353035313532353335343535353635373538353935403541354235433544354535463547354835493550355135523553355435553556355735583559356035613562356335643565356635673568356935703571357235733574357535763577357835793580358135823583358435853586358735883589359035913592359335943595359635973598359936003601360236033604360536063607360836093610361136123613361436153616361736183619362036213622362336243625362636273628362936303631363236333634363536363637363836393640364136423643364436453646364736483649365036513652365336543655365636573658365936603661366236633664366536663667366836693670367136723673367436753676367736783679368036813682368336843685368636873688368936903691369236933694369536963697369836993700370137023703370437053706370737083709371037113712371337143715371637173718371937203721372237233724372537263727372837293730373137323733373437353736373737383739374037413742374337443745374637473748374937503751375237533754375537563757375837593760376137623763376437653766376737683769377037713772377337743775377637773778377937803781378237833784378537863787378837893790379137923793379437953796379737983799380038013802380338043805380638073808380938103811381238133814381538163817381838193820382138223823382438253826382738283829383038313832383338343835383638373838383938403841384238433844384538463847384838493850385138523853385438553856385738583859386038613862386338643865386638673868386938703871387238733874387538763877387838793880388138823883388438853886388738883889389038913892389338943895389638973898389939003901390239033904390539063907390839093910391139123913391439153916391739183919392039213922392339243925392639273928392939303931393239333934393539363937393839393940394139423943394439453946394739483949395039513952395339543955395639573958395939603961396239633964396539663967396839693970397139723973397439753976397739783979398039813982398339843985398639873988398939903991399239933994399539963997399839994000400140024003400440054006400740084009401040114012401340144015401640174018401940204021402240234024402540264027402840294030403140324033403440354036403740384039404040414042404340444045404640474048404940504051405240534054405540564057405840594060406140624063406440654066406740684069407040714072407340744075407640774078407940804081408240834084408540864087408840894090409140924093409440954096409740984099410041014102410341044105410641074108410941104111411241134114411541164117411841194120412141224123412441254126412741284129413041314132413341344135413641374138413941404141414241434144414541464147414841494150415141524153415441554156415741584159416041614162416341644165416641674168416941704171417241734174417541764177417841794180418141824183418441854186418741884189419041914192419341944195419641974198419942004201420242034204420542064207420842094210421142124213421442154216421742184219422042214222422342244225422642274228422942304231423242334234423542364237423842394240424142424243424442454246424742484249425042514252425342544255425642574258425942604261426242634264426542664267426842694270427142724273427442754276427742784279428042814282428342844285428642874288428942904291429242934294429542964297429842994300430143024303430443054306430743084309431043114312431343144315431643174318431943204321432243234324432543264327432843294330433143324333433443354336433743384339434043414342434343444345434643474348434943504351435243534354435543564357435843594360436143624363436443654366436743684369437043714372437343744375437643774378437943804381438243834384438543864387438843894390439143924393439443954396439743984399440044014402440344044405440644074408440944104411441244134414441544164417441844194420442144224423442444254426442744284429443044314432443344344435443644374438443944404441444244434444444544464447444844494450445144524453445444554456445744584459446044614462446344644465446644674468446944704471447244734474447544764477447844794480448144824483448444854486448744884489449044914492449344944495449644974498449945004501450245034504450545064507450845094510451145124513451445154516451745184519452045214522452345244525452645274528452945304531453245334534453545364537453845394540454145424543454445454546454745484549455045514552455345544555455645574558455945604561456245634564456545664567456845694570457145724573457445754576457745784579458045814582458345844585458645874588458945904591459245934594459545964597459845994600460146024603460446054606460746084609461046114612461346144615461646174618461946204621462246234624462546264627462846294630463146324633463446354636463746384639464046414642464346444645464646474648464946504651465246534654465546564657465846594660466146624663466446654666466746684669467046714672467346744675467646774678467946804681468246834684468546864687468846894690469146924693469446954696469746984699470047014702470347044705470647074708470947104711471247134714471547164717471847194720472147224723472447254726472747284729473047314732473347344735473647374738473947404741474247434744474547464747474847494750475147524753475447554756475747584759476047614762476347644765476647674768476947704771477247734774477547764777477847794780478147824783478447854786478747884789479047914792479347944795479647974798479948004801480248034804480548064807480848094810481148124813481448154816481748184819482048214822482348244825482648274828482948304831483248334834483548364837483848394840484148424843484448454846484748484849485048514852485348544855485648574858485948604861486248634864486548664867486848694870487148724873487448754876487748784879488048814882488348844885488648874888488948904891489248934894489548964897489848994900490149024903490449054906490749084909491049114912491349144915491649174918491949204921492249234924492549264927492849294930493149324933493449354936493749384939494049414942494349444945494649474948494949504951495249534954495549564957495849594960496149624963496449654966496749684969497049714972497349744975497649774978497949804981498249834984498549864987498849894990499149924993499449954996499749984999500050015002500350045005500650075008500950105011501250135014501550165017501850195020502150225023502450255026502750285029503050315032503350345035503650375038503950405041504250435044504550465047504850495050505150525053505450555056505750585059506050615062506350645065506650675068506950705071507250735074507550765077507850795080508150825083508450855086508750885089509050915092509350945095509650975098509951005101510251035104510551065107510851095110511151125113511451155116511751185119512051215122512351245125512651275128512951305131513251335134513551365137513851395140514151425143514451455146514751485149515051515152515351545155515651575158515951605161516251635164516551665167516851695170517151725173517451755176517751785179518051815182518351845185518651875188518951905191519251935194519551965197519851995200520152025203520452055206520752085209521052115212521352145215521652175218521952205221522252235224522552265227522852295230523152325233523452355236523752385239524052415242524352445245524652475248524952505251525252535254525552565257525852595260526152625263526452655266526752685269527052715272527352745275527652775278527952805281528252835284528552865287528852895290529152925293529452955296529752985299530053015302530353045305530653075308530953105311531253135314531553165317531853195320532153225323532453255326532753285329533053315332533353345335533653375338533953405341534253435344534553465347534853495350535153525353535453555356535753585359536053615362536353645365536653675368536953705371537253735374537553765377537853795380538153825383538453855386538753885389539053915392539353945395539653975398539954005401540254035404540554065407540854095410541154125413541454155416541754185419542054215422542354245425542654275428542954305431543254335434543554365437543854395440544154425443544454455446544754485449545054515452545354545455545654575458545954605461546254635464546554665467546854695470547154725473547454755476547754785479548054815482548354845485548654875488548954905491549254935494549554965497549854995500550155025503550455055506550755085509551055115512551355145515551655175518551955205521552255235524552555265527552855295530553155325533553455355536553755385539554055415542554355445545554655475548554955505551555255535554555555565557555855595560556155625563556455655566556755685569557055715572557355745575557655775578557955805581558255835584558555865587558855895590559155925593559455955596559755985599560056015602560356045605560656075608560956105611561256135614561556165617561856195620562156225623562456255626562756285629563056315632563356345635563656375638563956405641564256435644564556465647564856495650565156525653565456555656565756585659566056615662566356645665566656675668566956705671567256735674567556765677567856795680568156825683568456855686568756885689569056915692569356945695569656975698569957005701570257035704570557065707570857095710571157125713571457155716571757185719572057215722572357245725572657275728572957305731573257335734573557365737573857395740574157425743574457455746574757485749575057515752575357545755575657575758575957605761576257635764576557665767576857695770577157725773577457755776577757785779578057815782578357845785578657875788578957905791579257935794579557965797579857995800580158025803580458055806580758085809581058115812581358145815581658175818581958205821582258235824582558265827582858295830583158325833583458355836583758385839584058415842584358445845584658475848584958505851585258535854585558565857585858595860586158625863586458655866586758685869587058715872587358745875587658775878587958805881588258835884588558865887588858895890589158925893589458955896589758985899590059015902590359045905590659075908590959105911591259135914591559165917591859195920592159225923592459255926592759285929593059315932593359345935593659375938593959405941594259435944594559465947594859495950595159525953595459555956595759585959596059615962596359645965596659675968596959705971597259735974597559765977597859795980598159825983598459855986598759885989599059915992599359945995599659975998599960006001600260036004600560066007600860096010601160126013601460156016601760186019602060216022602360246025602660276028602960306031603260336034603560366037603860396040604160426043604460456046604760486049605060516052605360546055605660576058605960606061606260636064606560666067606860696070607160726073607460756076607760786079608060816082608360846085608660876088608960906091609260936094609560966097609860996100610161026103610461056106610761086109611061116112611361146115611661176118611961206121612261236124612561266127612861296130613161326133613461356136613761386139614061416142614361446145614661476148614961506151615261536154615561566157615861596160616161626163616461656166616761686169617061716172617361746175617661776178617961806181618261836184618561866187618861896190619161926193619461956196619761986199620062016202620362046205620662076208620962106211621262136214621562166217621862196220622162226223622462256226622762286229623062316232623362346235623662376238623962406241624262436244624562466247624862496250625162526253625462556256625762586259626062616262626362646265626662676268626962706271627262736274627562766277627862796280628162826283628462856286628762886289629062916292629362946295629662976298629963006301630263036304630563066307630863096310631163126313631463156316631763186319632063216322632363246325632663276328632963306331633263336334633563366337633863396340634163426343634463456346634763486349635063516352635363546355635663576358635963606361636263636364636563666367636863696370637163726373637463756376637763786379638063816382638363846385638663876388638963906391639263936394639563966397639863996400640164026403640464056406640764086409641064116412641364146415641664176418641964206421642264236424642564266427642864296430643164326433643464356436643764386439644064416442644364446445644664476448644964506451645264536454645564566457645864596460646164626463646464656466646764686469647064716472647364746475647664776478647964806481648264836484648564866487648864896490649164926493649464956496649764986499650065016502650365046505650665076508650965106511651265136514651565166517651865196520652165226523652465256526652765286529653065316532653365346535653665376538653965406541654265436544654565466547654865496550655165526553655465556556655765586559656065616562656365646565656665676568656965706571657265736574657565766577657865796580658165826583658465856586658765886589659065916592659365946595659665976598659966006601660266036604660566066607660866096610661166126613661466156616661766186619662066216622662366246625662666276628662966306631663266336634663566366637663866396640664166426643664466456646664766486649665066516652665366546655665666576658665966606661666266636664666566666667666866696670667166726673667466756676667766786679668066816682668366846685668666876688668966906691669266936694669566966697669866996700670167026703670467056706670767086709671067116712671367146715671667176718671967206721672267236724672567266727672867296730673167326733673467356736673767386739674067416742674367446745674667476748674967506751675267536754675567566757675867596760676167626763676467656766676767686769677067716772677367746775677667776778677967806781678267836784678567866787678867896790679167926793679467956796679767986799680068016802680368046805680668076808680968106811681268136814681568166817681868196820682168226823682468256826682768286829683068316832683368346835683668376838683968406841684268436844684568466847684868496850685168526853685468556856685768586859686068616862686368646865686668676868686968706871687268736874687568766877687868796880688168826883688468856886688768886889689068916892689368946895689668976898689969006901690269036904690569066907690869096910691169126913691469156916691769186919692069216922692369246925692669276928692969306931693269336934693569366937693869396940694169426943694469456946694769486949695069516952695369546955695669576958695969606961696269636964696569666967696869696970697169726973697469756976697769786979698069816982698369846985698669876988698969906991699269936994699569966997699869997000700170027003700470057006700770087009701070117012701370147015701670177018701970207021702270237024702570267027702870297030703170327033703470357036703770387039704070417042704370447045704670477048704970507051705270537054705570567057705870597060706170627063706470657066706770687069707070717072707370747075707670777078707970807081708270837084708570867087708870897090709170927093709470957096709770987099710071017102710371047105710671077108710971107111711271137114711571167117711871197120712171227123712471257126712771287129713071317132713371347135713671377138713971407141714271437144714571467147714871497150715171527153715471557156715771587159716071617162716371647165716671677168716971707171717271737174717571767177717871797180718171827183718471857186718771887189719071917192719371947195719671977198719972007201720272037204720572067207720872097210721172127213721472157216721772187219722072217222722372247225722672277228722972307231723272337234723572367237723872397240724172427243724472457246724772487249725072517252725372547255725672577258725972607261726272637264726572667267726872697270727172727273727472757276727772787279728072817282728372847285728672877288728972907291729272937294729572967297729872997300730173027303730473057306730773087309731073117312731373147315731673177318731973207321732273237324732573267327732873297330733173327333733473357336733773387339734073417342734373447345734673477348734973507351735273537354735573567357735873597360736173627363736473657366736773687369737073717372737373747375737673777378737973807381738273837384738573867387738873897390739173927393739473957396739773987399740074017402740374047405740674077408740974107411741274137414741574167417741874197420742174227423742474257426742774287429743074317432743374347435743674377438743974407441744274437444744574467447744874497450745174527453745474557456745774587459746074617462746374647465746674677468746974707471747274737474747574767477747874797480748174827483748474857486748774887489749074917492749374947495749674977498749975007501750275037504750575067507750875097510751175127513751475157516751775187519752075217522752375247525752675277528752975307531753275337534753575367537753875397540754175427543754475457546754775487549755075517552755375547555755675577558755975607561756275637564756575667567756875697570757175727573757475757576757775787579758075817582758375847585758675877588758975907591759275937594759575967597759875997600760176027603760476057606760776087609761076117612761376147615761676177618761976207621762276237624762576267627762876297630763176327633763476357636763776387639764076417642764376447645764676477648764976507651765276537654765576567657765876597660766176627663766476657666766776687669767076717672767376747675767676777678767976807681768276837684768576867687768876897690769176927693769476957696769776987699770077017702770377047705770677077708770977107711771277137714771577167717771877197720772177227723772477257726772777287729773077317732773377347735773677377738773977407741774277437744774577467747774877497750775177527753775477557756775777587759776077617762776377647765776677677768776977707771777277737774777577767777777877797780778177827783778477857786778777887789779077917792779377947795779677977798779978007801780278037804780578067807780878097810781178127813781478157816781778187819782078217822782378247825782678277828782978307831783278337834783578367837783878397840784178427843784478457846784778487849785078517852785378547855785678577858785978607861786278637864786578667867786878697870787178727873787478757876787778787879788078817882788378847885788678877888788978907891789278937894789578967897789878997900790179027903790479057906790779087909791079117912791379147915791679177918791979207921792279237924792579267927792879297930793179327933793479357936793779387939794079417942794379447945794679477948794979507951795279537954795579567957795879597960796179627963796479657966796779687969797079717972797379747975797679777978797979807981798279837984798579867987798879897990799179927993799479957996799779987999800080018002800380048005800680078008800980108011801280138014801580168017801880198020802180228023802480258026802780288029803080318032803380348035803680378038803980408041804280438044804580468047804880498050805180528053805480558056805780588059806080618062806380648065806680678068806980708071807280738074807580768077807880798080808180828083808480858086808780888089809080918092809380948095809680978098809981008101810281038104810581068107810881098110811181128113811481158116811781188119812081218122812381248125812681278128812981308131813281338134813581368137813881398140814181428143814481458146814781488149815081518152815381548155815681578158815981608161816281638164816581668167816881698170817181728173817481758176817781788179818081818182818381848185818681878188818981908191819281938194819581968197819881998200820182028203820482058206820782088209821082118212821382148215821682178218821982208221822282238224822582268227822882298230823182328233823482358236823782388239824082418242824382448245824682478248824982508251825282538254825582568257825882598260826182628263826482658266826782688269827082718272827382748275827682778278827982808281828282838284828582868287828882898290829182928293829482958296829782988299830083018302830383048305830683078308830983108311831283138314831583168317831883198320832183228323832483258326832783288329833083318332833383348335833683378338833983408341834283438344834583468347834883498350835183528353835483558356835783588359836083618362836383648365836683678368836983708371837283738374837583768377837883798380838183828383838483858386838783888389839083918392839383948395839683978398839984008401840284038404840584068407840884098410841184128413841484158416841784188419842084218422842384248425842684278428842984308431843284338434843584368437843884398440844184428443844484458446844784488449845084518452845384548455845684578458845984608461846284638464846584668467846884698470847184728473847484758476847784788479848084818482848384848485848684878488848984908491849284938494849584968497849884998500850185028503850485058506850785088509851085118512851385148515851685178518851985208521852285238524852585268527852885298530853185328533853485358536853785388539854085418542854385448545854685478548854985508551855285538554855585568557855885598560856185628563856485658566856785688569857085718572857385748575857685778578857985808581858285838584858585868587858885898590859185928593859485958596859785988599860086018602860386048605860686078608860986108611861286138614861586168617861886198620862186228623862486258626862786288629863086318632863386348635863686378638863986408641864286438644864586468647864886498650865186528653865486558656865786588659866086618662866386648665866686678668866986708671867286738674867586768677867886798680868186828683868486858686868786888689869086918692869386948695869686978698869987008701870287038704870587068707870887098710871187128713871487158716871787188719872087218722872387248725872687278728872987308731873287338734873587368737873887398740874187428743874487458746874787488749875087518752875387548755875687578758875987608761876287638764876587668767876887698770877187728773877487758776877787788779878087818782878387848785878687878788878987908791879287938794879587968797879887998800880188028803880488058806880788088809881088118812881388148815881688178818881988208821882288238824882588268827882888298830883188328833883488358836883788388839884088418842884388448845884688478848884988508851885288538854885588568857885888598860886188628863886488658866886788688869887088718872887388748875887688778878887988808881888288838884888588868887888888898890889188928893889488958896889788988899890089018902890389048905890689078908890989108911891289138914891589168917891889198920892189228923892489258926892789288929893089318932893389348935893689378938893989408941894289438944894589468947894889498950895189528953895489558956895789588959896089618962896389648965896689678968896989708971897289738974897589768977897889798980898189828983898489858986898789888989899089918992899389948995899689978998899990009001900290039004900590069007900890099010901190129013901490159016901790189019902090219022902390249025902690279028902990309031903290339034903590369037903890399040904190429043904490459046904790489049905090519052905390549055905690579058905990609061906290639064906590669067906890699070907190729073907490759076907790789079908090819082908390849085908690879088908990909091909290939094909590969097909890999100910191029103910491059106910791089109911091119112911391149115911691179118911991209121912291239124912591269127912891299130913191329133913491359136913791389139914091419142914391449145914691479148914991509151915291539154915591569157915891599160916191629163916491659166916791689169917091719172917391749175917691779178917991809181918291839184918591869187918891899190919191929193919491959196919791989199920092019202920392049205920692079208920992109211921292139214921592169217921892199220922192229223922492259226922792289229923092319232923392349235923692379238923992409241924292439244924592469247924892499250925192529253925492559256925792589259926092619262926392649265926692679268926992709271927292739274927592769277927892799280928192829283928492859286928792889289929092919292929392949295929692979298929993009301930293039304930593069307930893099310931193129313931493159316931793189319932093219322932393249325932693279328932993309331933293339334933593369337933893399340934193429343934493459346934793489349935093519352935393549355935693579358935993609361936293639364936593669367936893699370937193729373937493759376937793789379938093819382938393849385938693879388938993909391939293939394939593969397939893999400940194029403940494059406940794089409941094119412941394149415941694179418941994209421942294239424942594269427942894299430943194329433943494359436943794389439944094419442944394449445944694479448944994509451945294539454945594569457945894599460946194629463946494659466946794689469947094719472947394749475947694779478947994809481948294839484948594869487948894899490949194929493949494959496949794989499950095019502950395049505950695079508950995109511951295139514951595169517951895199520952195229523952495259526952795289529953095319532953395349535953695379538953995409541954295439544954595469547954895499550955195529553955495559556955795589559956095619562956395649565956695679568956995709571957295739574957595769577957895799580958195829583958495859586958795889589959095919592959395949595959695979598959996009601960296039604960596069607960896099610961196129613961496159616961796189619962096219622962396249625962696279628962996309631963296339634963596369637963896399640964196429643964496459646964796489649965096519652965396549655965696579658965996609661966296639664966596669667966896699670967196729673967496759676967796789679968096819682968396849685968696879688968996909691969296939694969596969697969896999700970197029703970497059706970797089709971097119712971397149715971697179718971997209721972297239724972597269727972897299730973197329733973497359736973797389739974097419742974397449745974697479748974997509751975297539754975597569757975897599760976197629763976497659766976797689769977097719772977397749775977697779778977997809781978297839784978597869787978897899790979197929793979497959796979797989799980098019802980398049805980698079808980998109811981298139814981598169817981898199820982198229823982498259826982798289829983098319832983398349835983698379838983998409841984298439844984598469847984898499850985198529853985498559856985798589859986098619862986398649865986698679868986998709871987298739874987598769877987898799880988198829883988498859886988798889889989098919892989398949895989698979898989999009901990299039904990599069907990899099910991199129913991499159916991799189919992099219922992399249925992699279928992999309931993299339934993599369937993899399940994199429943994499459946994799489949995099519952995399549955995699579958995999609961996299639964996599669967996899699970997199729973997499759976997799789979998099819982998399849985998699879988998999909991999299939994999599969997999899991000010001100021000310004100051000610007100081000910010100111001210013100141001510016100171001810019100201002110022100231002410025100261002710028100291003010031100321003310034100351003610037100381003910040100411004210043100441004510046100471004810049100501005110052100531005410055100561005710058100591006010061100621006310064100651006610067100681006910070100711007210073100741007510076100771007810079100801008110082100831008410085100861008710088100891009010091100921009310094100951009610097100981009910100101011010210103101041010510106101071010810109101101011110112101131011410115101161011710118101191012010121101221012310124101251012610127101281012910130101311013210133101341013510136101371013810139101401014110142101431014410145101461014710148101491015010151101521015310154101551015610157101581015910160101611016210163101641016510166101671016810169101701017110172101731017410175101761017710178101791018010181101821018310184101851018610187101881018910190101911019210193101941019510196101971019810199102001020110202102031020410205102061020710208102091021010211102121021310214102151021610217102181021910220102211022210223102241022510226102271022810229102301023110232102331023410235102361023710238102391024010241102421024310244102451024610247102481024910250102511025210253102541025510256102571025810259102601026110262102631026410265102661026710268102691027010271102721027310274102751027610277102781027910280102811028210283102841028510286102871028810289102901029110292102931029410295102961029710298102991030010301103021030310304103051030610307103081030910310103111031210313103141031510316103171031810319103201032110322103231032410325103261032710328103291033010331103321033310334103351033610337103381033910340103411034210343103441034510346103471034810349103501035110352103531035410355103561035710358103591036010361103621036310364103651036610367103681036910370103711037210373103741037510376103771037810379103801038110382103831038410385103861038710388103891039010391103921039310394103951039610397103981039910400104011040210403104041040510406104071040810409104101041110412104131041410415104161041710418104191042010421104221042310424104251042610427104281042910430104311043210433104341043510436104371043810439104401044110442104431044410445104461044710448104491045010451104521045310454104551045610457104581045910460104611046210463104641046510466104671046810469104701047110472104731047410475104761047710478104791048010481104821048310484104851048610487104881048910490104911049210493104941049510496104971049810499105001050110502105031050410505105061050710508105091051010511105121051310514105151051610517105181051910520105211052210523105241052510526105271052810529105301053110532105331053410535105361053710538105391054010541105421054310544105451054610547105481054910550105511055210553105541055510556105571055810559105601056110562105631056410565105661056710568105691057010571105721057310574105751057610577105781057910580105811058210583105841058510586105871058810589105901059110592105931059410595105961059710598105991060010601106021060310604106051060610607106081060910610106111061210613106141061510616106171061810619106201062110622106231062410625106261062710628106291063010631106321063310634106351063610637106381063910640106411064210643106441064510646106471064810649106501065110652106531065410655106561065710658106591066010661106621066310664106651066610667106681066910670106711067210673106741067510676106771067810679106801068110682106831068410685106861068710688106891069010691106921069310694106951069610697106981069910700107011070210703107041070510706107071070810709107101071110712107131071410715107161071710718107191072010721107221072310724107251072610727107281072910730107311073210733107341073510736107371073810739107401074110742107431074410745107461074710748107491075010751107521075310754107551075610757107581075910760107611076210763107641076510766107671076810769107701077110772107731077410775107761077710778107791078010781107821078310784107851078610787107881078910790107911079210793107941079510796107971079810799108001080110802108031080410805108061080710808108091081010811108121081310814108151081610817108181081910820108211082210823108241082510826108271082810829108301083110832108331083410835108361083710838108391084010841108421084310844108451084610847108481084910850108511085210853108541085510856108571085810859108601086110862108631086410865108661086710868108691087010871108721087310874108751087610877108781087910880108811088210883108841088510886108871088810889108901089110892108931089410895108961089710898108991090010901109021090310904109051090610907109081090910910109111091210913109141091510916109171091810919109201092110922109231092410925109261092710928109291093010931109321093310934109351093610937109381093910940109411094210943109441094510946109471094810949109501095110952109531095410955109561095710958109591096010961109621096310964109651096610967109681096910970109711097210973109741097510976109771097810979109801098110982109831098410985109861098710988109891099010991109921099310994109951099610997109981099911000110011100211003110041100511006110071100811009110101101111012110131101411015110161101711018110191102011021110221102311024110251102611027110281102911030110311103211033110341103511036110371103811039110401104111042110431104411045110461104711048110491105011051110521105311054110551105611057110581105911060110611106211063110641106511066110671106811069110701107111072110731107411075110761107711078110791108011081110821108311084110851108611087110881108911090110911109211093110941109511096110971109811099111001110111102111031110411105111061110711108111091111011111111121111311114111151111611117111181111911120111211112211123111241112511126111271112811129111301113111132111331113411135111361113711138111391114011141111421114311144111451114611147111481114911150111511115211153111541115511156111571115811159111601116111162111631116411165111661116711168111691117011171111721117311174111751117611177111781117911180111811118211183111841118511186111871118811189111901119111192111931119411195111961119711198111991120011201112021120311204112051120611207112081120911210112111121211213112141121511216112171121811219112201122111222112231122411225112261122711228112291123011231112321123311234112351123611237112381123911240112411124211243112441124511246112471124811249112501125111252112531125411255112561125711258112591126011261112621126311264112651126611267112681126911270112711127211273112741127511276112771127811279112801128111282112831128411285112861128711288112891129011291112921129311294112951129611297112981129911300113011130211303113041130511306113071130811309113101131111312113131131411315113161131711318113191132011321113221132311324113251132611327113281132911330113311133211333113341133511336113371133811339113401134111342113431134411345113461134711348113491135011351113521135311354113551135611357113581135911360113611136211363113641136511366113671136811369113701137111372113731137411375113761137711378113791138011381113821138311384113851138611387113881138911390113911139211393113941139511396113971139811399114001140111402114031140411405114061140711408114091141011411114121141311414114151141611417114181141911420114211142211423114241142511426114271142811429114301143111432114331143411435114361143711438114391144011441114421144311444114451144611447114481144911450114511145211453114541145511456114571145811459114601146111462114631146411465114661146711468114691147011471114721147311474114751147611477114781147911480114811148211483114841148511486114871148811489114901149111492114931149411495114961149711498114991150011501115021150311504115051150611507115081150911510115111151211513115141151511516115171151811519115201152111522115231152411525115261152711528115291153011531115321153311534115351153611537115381153911540115411154211543115441154511546115471154811549115501155111552115531155411555115561155711558115591156011561115621156311564115651156611567115681156911570115711157211573115741157511576115771157811579115801158111582115831158411585115861158711588115891159011591115921159311594115951159611597115981159911600116011160211603116041160511606116071160811609116101161111612116131161411615116161161711618116191162011621116221162311624116251162611627116281162911630116311163211633116341163511636116371163811639116401164111642116431164411645116461164711648116491165011651116521165311654116551165611657116581165911660116611166211663116641166511666116671166811669116701167111672116731167411675116761167711678116791168011681116821168311684116851168611687116881168911690116911169211693116941169511696116971169811699117001170111702117031170411705117061170711708117091171011711117121171311714117151171611717117181171911720117211172211723117241172511726117271172811729117301173111732117331173411735117361173711738117391174011741117421174311744117451174611747117481174911750117511175211753117541175511756117571175811759117601176111762117631176411765117661176711768117691177011771117721177311774117751177611777117781177911780117811178211783117841178511786117871178811789117901179111792117931179411795117961179711798117991180011801118021180311804118051180611807118081180911810118111181211813118141181511816118171181811819118201182111822118231182411825118261182711828118291183011831118321183311834118351183611837118381183911840118411184211843118441184511846118471184811849118501185111852118531185411855118561185711858118591186011861118621186311864118651186611867118681186911870118711187211873118741187511876118771187811879118801188111882118831188411885118861188711888118891189011891118921189311894118951189611897118981189911900119011190211903119041190511906119071190811909119101191111912119131191411915119161191711918119191192011921119221192311924119251192611927119281192911930119311193211933119341193511936119371193811939119401194111942119431194411945119461194711948119491195011951119521195311954119551195611957119581195911960119611196211963119641196511966119671196811969119701197111972119731197411975119761197711978119791198011981119821198311984119851198611987119881198911990119911199211993119941199511996119971199811999120001200112002120031200412005120061200712008120091201012011120121201312014120151201612017120181201912020120211202212023120241202512026120271202812029120301203112032120331203412035120361203712038120391204012041120421204312044120451204612047120481204912050120511205212053120541205512056120571205812059120601206112062120631206412065120661206712068120691207012071120721207312074120751207612077120781207912080120811208212083120841208512086120871208812089120901209112092120931209412095120961209712098120991210012101121021210312104121051210612107121081210912110121111211212113121141211512116121171211812119121201212112122121231212412125121261212712128121291213012131121321213312134121351213612137121381213912140121411214212143121441214512146121471214812149121501215112152121531215412155121561215712158121591216012161121621216312164121651216612167121681216912170121711217212173121741217512176121771217812179121801218112182121831218412185121861218712188121891219012191121921219312194121951219612197121981219912200122011220212203122041220512206122071220812209122101221112212122131221412215122161221712218122191222012221122221222312224122251222612227122281222912230122311223212233122341223512236122371223812239122401224112242122431224412245122461224712248122491225012251122521225312254122551225612257122581225912260122611226212263122641226512266122671226812269122701227112272122731227412275122761227712278122791228012281122821228312284122851228612287122881228912290122911229212293122941229512296122971229812299123001230112302123031230412305123061230712308123091231012311123121231312314123151231612317123181231912320123211232212323123241232512326123271232812329123301233112332123331233412335123361233712338123391234012341123421234312344123451234612347123481234912350123511235212353123541235512356123571235812359123601236112362123631236412365123661236712368123691237012371123721237312374123751237612377123781237912380123811238212383123841238512386123871238812389123901239112392123931239412395123961239712398123991240012401124021240312404124051240612407124081240912410124111241212413124141241512416124171241812419124201242112422124231242412425124261242712428124291243012431124321243312434124351243612437124381243912440124411244212443124441244512446124471244812449124501245112452124531245412455124561245712458124591246012461124621246312464124651246612467124681246912470124711247212473124741247512476124771247812479124801248112482124831248412485124861248712488124891249012491124921249312494124951249612497124981249912500125011250212503125041250512506125071250812509125101251112512125131251412515125161251712518125191252012521125221252312524125251252612527125281252912530125311253212533125341253512536125371253812539125401254112542125431254412545125461254712548125491255012551125521255312554125551255612557125581255912560125611256212563125641256512566125671256812569125701257112572125731257412575125761257712578125791258012581125821258312584125851258612587125881258912590125911259212593125941259512596125971259812599126001260112602126031260412605126061260712608126091261012611126121261312614126151261612617126181261912620126211262212623126241262512626126271262812629126301263112632126331263412635126361263712638126391264012641126421264312644126451264612647126481264912650126511265212653126541265512656126571265812659126601266112662126631266412665126661266712668126691267012671126721267312674126751267612677126781267912680126811268212683126841268512686126871268812689126901269112692126931269412695126961269712698126991270012701127021270312704127051270612707127081270912710127111271212713127141271512716127171271812719127201272112722127231272412725127261272712728127291273012731127321273312734127351273612737127381273912740127411274212743127441274512746127471274812749127501275112752127531275412755127561275712758127591276012761127621276312764127651276612767127681276912770127711277212773127741277512776127771277812779127801278112782127831278412785127861278712788127891279012791127921279312794127951279612797127981279912800128011280212803128041280512806128071280812809128101281112812128131281412815128161281712818128191282012821128221282312824128251282612827128281282912830128311283212833128341283512836128371283812839128401284112842128431284412845128461284712848128491285012851128521285312854128551285612857128581285912860128611286212863128641286512866128671286812869128701287112872128731287412875128761287712878128791288012881128821288312884128851288612887128881288912890128911289212893128941289512896128971289812899129001290112902129031290412905129061290712908129091291012911129121291312914129151291612917129181291912920129211292212923129241292512926129271292812929129301293112932129331293412935129361293712938129391294012941129421294312944129451294612947129481294912950129511295212953129541295512956129571295812959129601296112962129631296412965129661296712968129691297012971129721297312974129751297612977129781297912980129811298212983129841298512986129871298812989129901299112992129931299412995129961299712998129991300013001130021300313004130051300613007130081300913010130111301213013130141301513016130171301813019130201302113022130231302413025130261302713028130291303013031130321303313034130351303613037130381303913040130411304213043130441304513046130471304813049130501305113052130531305413055130561305713058130591306013061130621306313064130651306613067130681306913070130711307213073130741307513076130771307813079130801308113082130831308413085130861308713088130891309013091130921309313094130951309613097130981309913100131011310213103131041310513106131071310813109131101311113112131131311413115131161311713118131191312013121131221312313124131251312613127131281312913130131311313213133131341313513136131371313813139131401314113142131431314413145131461314713148131491315013151131521315313154131551315613157131581315913160131611316213163131641316513166131671316813169131701317113172131731317413175131761317713178131791318013181131821318313184131851318613187131881318913190131911319213193131941319513196131971319813199132001320113202132031320413205132061320713208132091321013211132121321313214132151321613217132181321913220132211322213223132241322513226132271322813229132301323113232132331323413235132361323713238132391324013241132421324313244132451324613247
  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\ActShowContent;
  8. use App\Libs\Utils;
  9. use App\Models\MpGeneratePicTask;
  10. use App\Models\MpTaskCenter;
  11. use App\Services\AIGeneration\AIImageGenerationService;
  12. use App\Services\AIGeneration\AIVideoGenerationService;
  13. use App\Services\DeepSeek\DeepSeekService;
  14. use App\Services\PointsService;
  15. use App\Services\TaskCenterService;
  16. use Dflydev\DotAccessData\Util;
  17. use GuzzleHttp\Client;
  18. use Illuminate\Support\Facades\DB;
  19. use Illuminate\Support\Facades\Log;
  20. use Illuminate\Support\Facades\Redis;
  21. use OSS\Core\OssException;
  22. use OSS\OssClient;
  23. use PhpOffice\PhpSpreadsheet\IOFactory;
  24. class AnimeService
  25. {
  26. protected $aiImageGenerationService;
  27. protected $aiVideoGenerationService;
  28. protected $DeepSeekService;
  29. protected $pointsService;
  30. protected $taskCenterService;
  31. private $url;
  32. private $api_key;
  33. private $headers;
  34. public function __construct(
  35. AIImageGenerationService $aiImageGenerationService,
  36. AIVideoGenerationService $aiVideoGenerationService,
  37. DeepSeekService $DeepSeekService,
  38. PointsService $pointsService,
  39. TaskCenterService $taskCenterService
  40. ) {
  41. $this->aiImageGenerationService = $aiImageGenerationService;
  42. $this->aiVideoGenerationService = $aiVideoGenerationService;
  43. $this->DeepSeekService = $DeepSeekService;
  44. $this->pointsService = $pointsService;
  45. $this->taskCenterService = $taskCenterService;
  46. $this->url = 'https://api.deepseek.com/chat/completions';
  47. $this->api_key = env('DEEPSEEK_API_KEY');
  48. $this->headers = [
  49. 'Authorization' => 'Bearer '.$this->api_key,
  50. 'Content-Type' => 'application/json; charset=UTF-8'
  51. ];
  52. }
  53. /**
  54. * 构建统一的分镜数据结构(episodeInfo格式)
  55. * @param array $segments 分镜数据数组
  56. * @return array 返回包含acts和total_duration的数组
  57. */
  58. public function buildEpisodeSegmentsStructure($segments) {
  59. $acts = [];
  60. $totalDuration = 0; // 初始化总时长
  61. foreach($segments as $segment) {
  62. // 计算分镜时长,优先级:video_duration > audio_duration > 默认5秒
  63. $videoDuration = getProp($segment, 'video_duration');
  64. $audioDuration = getProp($segment, 'audio_duration');
  65. if (!empty($videoDuration) && is_numeric($videoDuration)) {
  66. $totalDuration += floatval($videoDuration);
  67. } elseif (!empty($audioDuration) && is_numeric($audioDuration)) {
  68. $totalDuration += floatval($audioDuration);
  69. } else {
  70. $totalDuration += 5; // 默认5秒
  71. }
  72. $segment_content = getProp($segment, 'segment_content');
  73. // 判断是否有尾帧描述,如果有则去掉这部分内容
  74. if (strpos($segment_content, '尾帧') !== false) {
  75. // 使用正则表达式匹配"尾帧"及其后面的内容并移除(s修饰符让.匹配换行符)
  76. $segment_content = preg_replace('/尾帧.*$/s', '', $segment_content);
  77. }
  78. // 构建分镜信息
  79. $segmentInfo = [
  80. 'segment_id' => getProp($segment, 'segment_id'),
  81. 'segment_number' => getProp($segment, 'segment_number'),
  82. 'segment_content' => $segment_content,
  83. 'description' => getProp($segment, 'description'),
  84. 'composition' => getProp($segment, 'composition'),
  85. 'camera_movement' => getProp($segment, 'camera_movement'),
  86. 'voice_actor' => getProp($segment, 'voice_actor'),
  87. 'dialogue' => getProp($segment, 'dialogue'),
  88. 'frame_type' => getProp($segment, 'frame_type'),
  89. 'scene' => getProp($segment, 'scene'),
  90. 'characters' => getProp($segment, 'characters'),
  91. 'tail_frame' => getProp($segment, 'tail_frame'),
  92. 'emotion' => getProp($segment, 'emotion'),
  93. 'emotion_type' => getProp($segment, 'emotion_type'),
  94. 'gender' => getProp($segment, 'gender'),
  95. 'speed_ratio' => getProp($segment, 'speed_ratio'),
  96. 'loudness_ratio' => getProp($segment, 'loudness_ratio'),
  97. 'emotion_scale' => getProp($segment, 'emotion_scale'),
  98. 'pitch' => getProp($segment, 'pitch'),
  99. 'voice_name' => getProp($segment, 'voice_name'),
  100. 'voice_type' => getProp($segment, 'voice_type'),
  101. 'voice_audio_url' => getProp($segment, 'voice_audio_url'),
  102. 'img_url' => getProp($segment, 'img_url'),
  103. 'audio_url' => getProp($segment, 'audio_url'),
  104. 'audio_duration' => getProp($segment, 'audio_duration', 0),
  105. 'video_url' => getProp($segment, 'video_url'),
  106. 'video_duration' => getProp($segment, 'video_duration', 0),
  107. 'video_time_point_start' => getProp($segment, 'video_time_point_start', 0),
  108. 'video_time_point_end' => getProp($segment, 'video_time_point_end', getProp($segment, 'video_duration', 0)),
  109. 'last_frame_url' => getProp($segment, 'last_frame_url'),
  110. 'current_type' => getProp($segment, 'current_type'),
  111. ];
  112. $actNumber = getProp($segment, 'act_number');
  113. if (isset($acts[$actNumber])) {
  114. $acts[$actNumber]['segments'][] = $segmentInfo;
  115. } else {
  116. $acts[$actNumber] = [
  117. 'act_number' => $actNumber,
  118. 'act_title' => getProp($segment, 'act_title'),
  119. 'act_duration' => getProp($segment, 'act_duration'),
  120. 'segments' => [$segmentInfo]
  121. ];
  122. }
  123. }
  124. return [
  125. 'acts' => array_values($acts),
  126. 'total_duration' => intval(round($totalDuration))
  127. ];
  128. }
  129. /**
  130. * 构建统一的分段数据结构(episodeInfoForAce格式)
  131. * @param array $segments 分段数据数组
  132. * @return array 返回包含acts和total_duration的数组
  133. */
  134. public function buildEpisodeActsStructureForAce($segments) {
  135. $acts = [];
  136. $totalDuration = 0; // 初始化总时长
  137. foreach($segments as $segment) {
  138. // 计算分镜时长,优先级:video_duration > act_duration > 默认5秒
  139. $videoDuration = getProp($segment, 'video_duration');
  140. $actDuration = getProp($segment, 'act_duration');
  141. if (!empty($videoDuration) && is_numeric($videoDuration)) {
  142. $totalDuration += floatval($videoDuration);
  143. } elseif (!empty($actDuration) && is_numeric($actDuration)) {
  144. $totalDuration += floatval($actDuration);
  145. } else {
  146. $totalDuration += 5; // 默认5秒
  147. }
  148. // 构建分镜信息
  149. $segmentInfo = [
  150. 'act_id' => getProp($segment, 'id'),
  151. 'act_number' => getProp($segment, 'act_number'),
  152. 'act_title' => getProp($segment, 'act_title'),
  153. 'act_duration' => getProp($segment, 'act_duration'),
  154. 'act_content' => getProp($segment, 'act_content'),
  155. 'video_url' => getProp($segment, 'video_url'),
  156. 'video_duration' => getProp($segment, 'video_duration', 0),
  157. 'video_time_point_start' => getProp($segment, 'video_time_point_start', 0),
  158. 'video_time_point_end' => getProp($segment, 'video_time_point_end', getProp($segment, 'video_duration', 0)),
  159. 'last_frame_url' => getProp($segment, 'last_frame_url'),
  160. 'current_type' => getProp($segment, 'current_type'),
  161. ];
  162. $acts[] = $segmentInfo;
  163. }
  164. return [
  165. 'acts' => array_values($acts),
  166. 'total_duration' => intval(round($totalDuration))
  167. ];
  168. }
  169. /**
  170. * 验证画面比例是否有效
  171. * @param string $ratio 画面比例
  172. * @return bool
  173. */
  174. public function validateRatio($ratio) {
  175. return isset(BaseConst::IMAGE_RATIOS[$ratio]);
  176. }
  177. /**
  178. * 获取画面比例对应的宽高
  179. * @param string $ratio 画面比例
  180. * @return array ['width' => int, 'height' => int]
  181. * @throws \Exception
  182. */
  183. private function getRatioDimensions($ratio) {
  184. if ($ratio && !$this->validateRatio($ratio)) {
  185. $validRatios = implode('、', array_keys(BaseConst::IMAGE_RATIOS));
  186. Utils::throwError("1002:画面比例选择不正确,只支持{$validRatios}");
  187. }
  188. return isset(BaseConst::IMAGE_RATIOS[$ratio]) ? BaseConst::IMAGE_RATIOS[$ratio] : ['width' => 1600, 'height' => 2848];
  189. }
  190. public function createAnime($data) {
  191. $uid = Site::getUid();
  192. $cpid = Site::getCpid();
  193. $input_art_style = getProp($data, 'art_style');
  194. $file = getProp($data, 'file');
  195. $content = getProp($data, 'content', '');
  196. $bid = getProp($data, 'bid', 0);
  197. $script_id = getProp($data, 'script_id', 0);
  198. $ace_mode = getProp($data, 'ace_mode', 0);
  199. $extra_products = getProp($data, 'products', []);
  200. if (is_string($extra_products)) $extra_products = json_decode($extra_products, true);
  201. if (!is_array($extra_products)) {
  202. Utils::throwError('20003:传入的资产格式不正确');
  203. }
  204. // 替换美术风格
  205. $mappedArtStyle = $this->DeepSeekService->getArtStylePromptByInput($input_art_style);
  206. // 提取文件内容
  207. if ($file) {
  208. $content = $this->DeepSeekService->extractFileContent($file);
  209. if (!$content) {
  210. Utils::throwError('20003:无法提取文件内容,请检查文件格式');
  211. }
  212. } elseif ($script_id) {
  213. $content = $this->DeepSeekService->getContentByScriptId($script_id);
  214. if (!$content) {
  215. Utils::throwError('20003:无法获取剧本内容,请检查剧本');
  216. }
  217. } elseif ($bid) {
  218. $content = $this->DeepSeekService->getContentByBid($bid);
  219. if (!$content) {
  220. Utils::throwError('20003:无法获取书籍内容,请检查书籍');
  221. }
  222. } elseif ($content) {
  223. $content = filterContent($content);
  224. }else {
  225. $content = '';
  226. }
  227. $anime_data = [
  228. 'user_id' => $uid,
  229. 'cpid' => $cpid,
  230. 'anime_name' => '新剧本策划',
  231. 'is_multi' => getProp($data, 'is_multi', 1),
  232. 'content' => $content,
  233. 'art_style_type' => $input_art_style,
  234. 'ace_mode' => $ace_mode,
  235. 'script_id' => $script_id,
  236. 'extra_products' => json_encode($extra_products, 256),
  237. 'created_at' => date('Y-m-d H:i:s'),
  238. 'updated_at' => date('Y-m-d H:i:s'),
  239. ];
  240. // 处理文本模型
  241. $model = getProp($data, 'model');
  242. if (!$model) {
  243. // 用户没有输入,使用默认值
  244. $model = 'deepseek-v4-pro';
  245. }
  246. // 验证模型是否在可用模型表中
  247. if (!DB::table('mp_text_models')->where('model', $model)->where('is_enabled', 1)->exists()) {
  248. $model = 'deepseek-v4-pro';
  249. }
  250. $anime_data['model'] = $model;
  251. if ($mappedArtStyle) $anime_data['art_style'] = $mappedArtStyle;
  252. return DB::table('mp_animes')->insertGetId($anime_data);
  253. }
  254. public function chatList($data) {
  255. $uid = Site::getUid();
  256. $anime_name = getProp($data, 'anime_name');
  257. $query = DB::table('mp_animes')->where('is_deleted', 0)->where('user_id', $uid);
  258. if ($anime_name) {
  259. $query->where('anime_name', 'like', "%$anime_name%");
  260. }
  261. return $query->orderBy('id', 'desc')->paginate();
  262. }
  263. public function chatHistory($data) {
  264. $anime_id = getProp($data, 'anime_id');
  265. $sequence = getProp($data, 'sequence', 0);
  266. if (!$anime_id) Utils::throwError('20003:请选择对话!');
  267. $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)
  268. ->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');
  269. return $query->orderBy('ar.id')->get()->map(function ($value) {
  270. $value = (array)$value;
  271. if ($value['role'] == 'assistant') $value['content'] = filterScriptContent($value['content']);
  272. $value['created_at'] = transDate($value['created_at']);
  273. $value['episode_created_at'] = transDate($value['episode_created_at']);
  274. return $value;
  275. })->toArray();
  276. }
  277. public function batchSetRoleImg($data) {
  278. $episode_id = getProp($data, 'episode_id');
  279. if (!$episode_id) Utils::throwError('1002:请选择分集');
  280. $episode = DB::table('mp_anime_episodes')->where('id', $episode_id)->first();
  281. $roles = json_decode(getProp($data, 'roles'), true) ?: [];
  282. $art_style = getProp($episode, 'art_style');
  283. $anime_id = getProp($episode, 'anime_id');
  284. $anime = DB::table('mp_animes')->where('id', $anime_id)->first();
  285. $art_style_type = getProp($anime, 'art_style_type');
  286. $character_prefix = '';
  287. $scene_prefix = '';
  288. if ($art_style_type) {
  289. $art_style_arr = $this->DeepSeekService->getArtStyleShortPromptByInput($art_style_type);
  290. $character_prefix = isset($art_style_arr['character_prefix']) ? $art_style_arr['character_prefix'] : '';
  291. $scene_prefix = isset($art_style_arr['scene_prefix']) ? $art_style_arr['scene_prefix'] : '';
  292. }
  293. foreach ($roles as &$role) {
  294. $role_name = getProp($role, 'role');
  295. if ($role_name == '旁白') continue;
  296. // 优先使用 pic_prompt,如果没有则使用 description
  297. $pic_prompt = getProp($role, 'pic_prompt');
  298. $description = !empty($pic_prompt) ? trim((string)$pic_prompt) : getProp($role, 'description');
  299. // if ($art_style) $description = "美术风格:\n{$art_style}\n主体描述:{$description}\n图片要求:图片侧重点是人物,不要出现场景或背景,并且只能生成一个人物";
  300. $description = buildStylePromptPrefix($character_prefix) . "主体描述:{$description}\n超高清,高细节,主体突出,构图合理,画面干净,无场景或背景,单人物,无文字,无水印,无字幕,电影级光影,视觉焦点明确";
  301. // 参考图地址
  302. $ref_img_url = getProp($role, 'url');
  303. if ($ref_img_url) continue; // 已有图片则跳过
  304. // 此处调用AIImageGenerationService的生成图片任务接口: createImageGenerationTask(注意使用默认参数,prompt使用角色描述),并返回任务id
  305. try {
  306. $params = [
  307. 'prompt' => $description,
  308. 'ref_img_urls' => !empty($ref_img_url) ? [$ref_img_url] : [],
  309. // 计费锚点(动漫/剧集/剧本),用于积分明细归属统计
  310. 'anime_id' => $anime_id,
  311. 'episode_id' => $episode_id,
  312. 'episode_number' => getProp($episode, 'episode_number'),
  313. ];
  314. $task = $this->aiImageGenerationService->createImageGenerationTask($params);
  315. $task_id = $task->id;
  316. if (!$task_id) {
  317. Utils::throwError("20003:角色({$role_name})生成图片失败");
  318. }
  319. $role['task_id'] = $task_id;
  320. $role['task_status'] = 'processing';
  321. } catch (\Exception $e) {
  322. logDB('anime', 'error', "角色({$role_name})生成图片失败", ['error' => $e->getMessage()]);
  323. Utils::throwError("20003:" . $e->getMessage());
  324. }
  325. }
  326. // 保存角色信息
  327. $boolen = DB::table('mp_anime_episodes')->where('id', $episode_id)->update([
  328. 'roles' => json_encode($roles, 256),
  329. 'generate_status' => '执行中',
  330. 'generate_at' => date('Y-m-d H:i:s'),
  331. 'updated_at' => date('Y-m-d H:i:s')
  332. ]);
  333. if (!$boolen) {
  334. Utils::throwError('20003:保存角色信息失败');
  335. }
  336. return $boolen;
  337. }
  338. public function batchSetSceneImg($data) {
  339. $episode_id = getProp($data, 'episode_id');
  340. if (!$episode_id) Utils::throwError('1002:请选择分集');
  341. $episode = DB::table('mp_anime_episodes')->where('id', $episode_id)->first();
  342. $scenes = json_decode(getProp($episode, 'scenes'), true);
  343. $art_style = getProp($episode, 'art_style');
  344. $target_scene = getProp($data, 'target_scene');
  345. $anime_id = getProp($episode, 'anime_id');
  346. $anime = DB::table('mp_animes')->where('id', $anime_id)->first();
  347. $art_style_type = getProp($anime, 'art_style_type');
  348. $character_prefix = '';
  349. $scene_prefix = '';
  350. if ($art_style_type) {
  351. $art_style_arr = $this->DeepSeekService->getArtStyleShortPromptByInput($art_style_type);
  352. $character_prefix = isset($art_style_arr['character_prefix']) ? $art_style_arr['character_prefix'] : '';
  353. $scene_prefix = isset($art_style_arr['scene_prefix']) ? $art_style_arr['scene_prefix'] : '';
  354. }
  355. foreach ($scenes as &$scene) {
  356. $scene_name = getProp($scene, 'scene');
  357. if ($scene_name != $target_scene) continue;
  358. // 优先使用 pic_prompt,如果没有则使用 description
  359. $pic_prompt = getProp($scene, 'pic_prompt');
  360. $description = !empty($pic_prompt) ? trim((string)$pic_prompt) : getProp($scene, 'description');
  361. // if ($art_style) $description = "美术风格:\n{$art_style}\n\n场景描述:{$description}\n图片要求: 图片侧重点是场景,生成的是场景环境图片,不要出现人物(此为第一优先要求)";
  362. $description = buildStylePromptPrefix($scene_prefix) . "场景描述:{$description}\n无人物,超高清,高细节,主体突出,构图合理,画面干净,无文字,无水印,无字幕,电影级光影,视觉焦点明确";
  363. // 参考图地址
  364. $ref_img_url = getProp($scene, 'url');
  365. if ($ref_img_url) continue; // 已有图片则跳过
  366. // 此处调用AIImageGenerationService的生成图片任务接口: createImageGenerationTask(注意使用默认参数,prompt使用角色描述),并返回任务id
  367. try {
  368. $params = [
  369. 'prompt' => $description,
  370. 'ref_img_urls' => !empty($ref_img_url) ? [$ref_img_url] : [],
  371. // 计费锚点(动漫/剧集/剧本),用于积分明细归属统计
  372. 'anime_id' => $anime_id,
  373. 'episode_id' => $episode_id,
  374. 'episode_number' => getProp($episode, 'episode_number'),
  375. ];
  376. $task = $this->aiImageGenerationService->createImageGenerationTask($params);
  377. $task_id = $task->id;
  378. if (!$task_id) {
  379. Utils::throwError("20003:场景({$scene_name})生成图片失败");
  380. }
  381. $scene['task_id'] = $task_id;
  382. $scene['task_status'] = 'processing';
  383. } catch (\Exception $e) {
  384. logDB('anime', 'error', "场景({$scene_name})生成图片失败", ['error' => $e->getMessage()]);
  385. Utils::throwError("20003:" . $e->getMessage());
  386. }
  387. }
  388. // 保存场景信息
  389. $boolen = DB::table('mp_anime_episodes')->where('id', $episode_id)->update([
  390. 'scenes' => json_encode($scenes, 256),
  391. 'generate_status' => '执行中',
  392. 'generate_at' => date('Y-m-d H:i:s'),
  393. 'updated_at' => date('Y-m-d H:i:s')
  394. ]);
  395. if (!$boolen) {
  396. Utils::throwError('20003:保存角色信息失败');
  397. }
  398. return $boolen;
  399. }
  400. public function editAnime($data) {
  401. $anime_id = getProp($data, 'anime_id');
  402. $anime_name = trim(getProp($data, 'anime_name'));
  403. // 确认对话名称唯一性
  404. if ($id = DB::table('mp_animes')->where('anime_name', $anime_name)->value('id')) {
  405. if ($id != $anime_id) $anime_name = $anime_name . '_' . date('YmdHis');
  406. }
  407. if (!$anime_id || !$anime_name) {
  408. Utils::throwError('20003:参数异常');
  409. }
  410. return DB::table('mp_animes')->where('id', $anime_id)->update([
  411. 'anime_name' => $anime_name,
  412. 'updated_at' => date('Y-m-d H:i:s')
  413. ]);
  414. // $script_arr =getProp($data, 'script', []);
  415. // if (!$script_arr) Utils::throwError('20003:剧本内容不能为空');
  416. // $start_episode_sequence = getProp($data, 'start_episode_sequence', 1);
  417. // $anime_id = getProp($data, 'anime_id');
  418. // try {
  419. // DB::beginTransaction();
  420. // $table_data = [
  421. // 'intro' => isset($script_arr['intro']) ? $script_arr['intro'] : '',
  422. // 'highlights' => isset($script_arr['highlights']) ? $script_arr['highlights'] : '',
  423. // 'role_relationship' => isset($script_arr['role_relationship']) ? $script_arr['role_relationship'] : '',
  424. // 'core_contradiction' => isset($script_arr['core_contradiction']) ? $script_arr['core_contradiction'] : '',
  425. // 'roles' => isset($script_arr['roles']) ? json_encode($script_arr['roles'], 256) : '',
  426. // 'art_style' => isset($script_arr['art_style']) ? $script_arr['art_style'] : '',
  427. // 'scenes' => isset($script_arr['scenes']) ? json_encode($script_arr['scenes'], 256) : '',
  428. // 'status' => 3,
  429. // 'start_episode_sequence' => $start_episode_sequence,
  430. // 'end_episode_sequence' => $start_episode_sequence + count($script_arr['episodes']) - 1,
  431. // 'episode_num' => count($script_arr['episodes']),
  432. // 'updated_at' => date('Y-m-d H:i:s')
  433. // ];
  434. // // 保存剧本内容
  435. // if (!empty($anime_id)) {
  436. // $boolen = DB::table('mp_animes')->where('id', $anime_id)->update($table_data);
  437. // if (!$boolen) {
  438. // dLog('anime')->info('对话保存失败', $table_data);
  439. // Utils::throwError('20003:对话保存失败');
  440. // }
  441. // }else {
  442. // $table['created_at'] = $table_data['updated_at'];
  443. // $anime_id = DB::table('mp_animes')->insertGetId($table_data);
  444. // if (!$anime_id) {
  445. // dLog('anime')->info('对话保存失败', $table_data);
  446. // Utils::throwError('20003:对话保存失败');
  447. // }
  448. // }
  449. // // 保存分集内容
  450. // // 删除历史分集内容
  451. // $boolen1 = DB::table('mp_anime_episodes')->where('anime_id', $anime_id)->delete();
  452. // $episodes = [];
  453. // $sequence = 1;
  454. // foreach ($script_arr['episodes'] as $episode) {
  455. // $segment_number = 1;
  456. // foreach($episode['segments'] as $segment) {
  457. // $episodes[] = [
  458. // 'anime_id' => $anime_id,
  459. // 'episode_number' => $episode['episode_number'],
  460. // 'title' => $episode['title'],
  461. // // 'content' => $episode['content'],
  462. // 'content' => '',
  463. // 'segment_number' => $segment_number,
  464. // 'segment_content' => $segment['segment_content'],
  465. // 'sequence' => $sequence,
  466. // 'created_at' => date('Y-m-d H:i:s'),
  467. // 'updated_at' => date('Y-m-d H:i:s')
  468. // ];
  469. // $sequence++;
  470. // $segment_number++;
  471. // }
  472. // }
  473. // $boolen2 = DB::table('mp_anime_episodes')->insert($episodes);
  474. // if (!$boolen2) {
  475. // dLog('deepseek')->info('分集内容保存失败', $episodes);
  476. // logDB('deepseek', 'error', '分集内容保存失败', ['episodes_count' => count($episodes)]);
  477. // Utils::throwError('20003:分集内容保存失败');
  478. // }
  479. // } catch (\Exception $e) {
  480. // DB::rollBack();
  481. // Utils::throwError('20003:'.$e->getMessage());
  482. // }
  483. // DB::commit();
  484. // return true;
  485. }
  486. public function delAnime($data) {
  487. $anime_id = getProp($data, 'anime_id');
  488. if (!$anime_id) {
  489. Utils::throwError('20003:请选择剧本');
  490. }
  491. return DB::table('mp_animes')->where('id', $anime_id)->update([
  492. 'is_deleted' => 1,
  493. 'updated_at' => date('Y-m-d H:i:s')
  494. ]);
  495. }
  496. public function animeDetail($data) {
  497. $uid = Site::getUid();
  498. $anime_id = getProp($data, 'anime_id');
  499. $anime = DB::table('mp_animes')->where('id', $anime_id)->where('is_deleted', 0)->where('user_id', $uid)
  500. ->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();
  501. if (!$anime) Utils::throwError('20003:权限不足');
  502. $anime = (array)$anime;
  503. $anime['roles'] = json_decode($anime['roles']);
  504. $anime['scenes'] = json_decode($anime['scenes']);
  505. // 获取分集信息
  506. $episodes = DB::table('mp_anime_episodes')->where('anime_id', $anime_id)->where('is_default', 1)
  507. ->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"))
  508. ->orderBy('episode_number')->get()->map(function ($value) {
  509. return (array)$value;
  510. })->toArray();
  511. $anime['episodes'] = $episodes;
  512. // 获取当前仍在批量生成中的剧集任务(只展示 episodes 中尚未出现的剧集序号)
  513. $episodeNumbers = array_map('intval', array_column($episodes, 'episode_number'));
  514. $episodeTasks = DB::table('mp_batch_episode_generation_details')
  515. ->where('anime_id', $anime_id)
  516. ->whereIn('status', ['pending', 'processing', 'failed']) // 只获取待生成/生成中任务,已完成或失败的不显示
  517. ->orderBy('episode_number')
  518. ->get()
  519. ->map(function ($task) use ($episodeNumbers) {
  520. if (in_array((int)$task->episode_number, $episodeNumbers, true)) {
  521. return null;
  522. }
  523. return [
  524. 'episode_number' => (int)$task->episode_number,
  525. 'status' => $task->status,
  526. 'error_message' => $task->status == 'failed' ? $task->error_message : '',
  527. ];
  528. })
  529. ->filter()
  530. ->values()
  531. ->toArray();
  532. $anime['episode_tasks'] = $episodeTasks;
  533. return $anime;
  534. }
  535. public function episodeInfo($data) {
  536. $uid = Site::getUid();
  537. $anime_id = getProp($data, 'anime_id');
  538. $episode_id = getProp($data, 'episode_id');
  539. if (!$anime_id || !$episode_id) {
  540. Utils::throwError('1002:请选择剧集');
  541. }
  542. // 验证用户权限
  543. $anime = DB::table('mp_animes')->where('id', $anime_id)->where('user_id', $uid)->where('is_deleted', 0)->first();
  544. if (!$anime) Utils::throwError('20003:权限不足');
  545. $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();
  546. if (!$episode) Utils::throwError('20003:该剧集不存在!');
  547. $episode = (array)$episode;
  548. $episode['roles'] = json_decode($episode['roles'], true);
  549. // foreach($episode['roles'] as &$item) {
  550. // if (isset($item['pic_prompt']) && mb_substr($item['pic_prompt'], 0, 11) != '写实。全景,正面拍摄。') $item['pic_prompt'] = '写实。全景,正面拍摄。'.$item['pic_prompt'];
  551. // }
  552. $episode['scenes'] = json_decode($episode['scenes'], true);
  553. // foreach($episode['scenes'] as &$item) {
  554. // if (isset($item['pic_prompt']) && mb_substr($item['pic_prompt'], 0, 3) != '写实。') $item['pic_prompt'] = '写实。'.$item['pic_prompt'];
  555. // }
  556. // 获取分镜信息
  557. $segments = DB::table('mp_episode_segments')->where('anime_id', $anime_id)->where('episode_id', getProp($episode, 'episode_id'))->orderBy('segment_number')
  558. ->select('*')->get()->map(function ($value) {
  559. return (array)$value;
  560. })->toArray();
  561. // 使用公共方法构建分镜结构
  562. $segmentsStructure = $this->buildEpisodeSegmentsStructure($segments);
  563. $episode['acts'] = $segmentsStructure['acts'];
  564. $episode['total_duration'] = $segmentsStructure['total_duration'];
  565. return $episode;
  566. }
  567. public function episodeInfoForAce($data) {
  568. $anime_id = getProp($data, 'anime_id');
  569. $episode_id = getProp($data, 'episode_id');
  570. if (!$anime_id || !$episode_id) {
  571. Utils::throwError('1002:请选择剧集');
  572. }
  573. $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();
  574. if (!$episode) Utils::throwError('20003:该剧集不存在!');
  575. $episode = (array)$episode;
  576. $episode['roles'] = json_decode($episode['roles'], true);
  577. // foreach($episode['roles'] as &$item) {
  578. // if (isset($item['pic_prompt']) && mb_substr($item['pic_prompt'], 0, 11) != '写实。全景,正面拍摄。') $item['pic_prompt'] = '写实。全景,正面拍摄。'.$item['pic_prompt'];
  579. // }
  580. $episode['scenes'] = json_decode($episode['scenes'], true);
  581. // foreach($episode['scenes'] as &$item) {
  582. // if (isset($item['pic_prompt']) && mb_substr($item['pic_prompt'], 0, 3) != '写实。') $item['pic_prompt'] = '写实。'.$item['pic_prompt'];
  583. // }
  584. $episode['props'] = $episode['props'] ? json_decode($episode['props'], true) : [];
  585. // 获取分镜信息
  586. $segments = DB::table('mp_episode_segments')->where('anime_id', $anime_id)->where('episode_id', getProp($episode, 'episode_id'))->orderBy('act_number')
  587. ->select('*')->get()->map(function ($value) {
  588. return (array)$value;
  589. })->toArray();
  590. $segmentsStructure = $this->buildEpisodeActsStructureForAce($segments);
  591. $episode['acts'] = $segmentsStructure['acts'];
  592. $episode['total_duration'] = $segmentsStructure['total_duration'];
  593. // 获取mp_animes表中的视频参数
  594. $anime = DB::table('mp_animes')->where('id', $anime_id)->first(['video_model', 'video_resolution', 'video_ratio']);
  595. $episode['video_params'] = [
  596. 'video_model' => getProp($anime, 'video_model'),
  597. 'video_resolution' => getProp($anime, 'video_resolution'),
  598. 'ratio' => getProp($anime, 'video_ratio'),
  599. ];
  600. return $episode;
  601. }
  602. public function segmentInfo($data) {
  603. $uid = Site::getUid();
  604. $segment_id = getProp($data, 'segment_id');
  605. if (!$segment_id) {
  606. Utils::throwError('1002:请选择分镜');
  607. }
  608. // 获取分镜信息
  609. $segment = DB::table('mp_episode_segments')->where('segment_id', $segment_id)->first();
  610. // 验证用户权限
  611. if ($segment) {
  612. $anime = DB::table('mp_animes')->where('id', getProp($segment, 'anime_id'))->where('user_id', $uid)->where('is_deleted', 0)->first();
  613. if (!$anime) Utils::throwError('20003:权限不足');
  614. }
  615. $result = [
  616. 'segment_id' => getProp($segment, 'segment_id'),
  617. 'segment_number' => getProp($segment, 'segment_number'),
  618. 'segment_content' => getProp($segment, 'segment_content'),
  619. 'description' => getProp($segment, 'description'),
  620. 'composition' => getProp($segment, 'composition'),
  621. 'camera_movement' => getProp($segment, 'camera_movement'),
  622. 'voice_actor' => getProp($segment, 'voice_actor'),
  623. 'dialogue' => getProp($segment, 'dialogue'),
  624. 'frame_type' => getProp($segment, 'frame_type'),
  625. 'scene' => getProp($segment, 'scene'),
  626. 'characters' => getProp($segment, 'characters'),
  627. 'tail_frame' => getProp($segment, 'tail_frame'),
  628. 'emotion' => getProp($segment, 'emotion'),
  629. 'emotion_type' => getProp($segment, 'emotion_type'),
  630. 'gender' => getProp($segment, 'gender'),
  631. 'speed_ratio' => getProp($segment, 'speed_ratio'),
  632. 'loudness_ratio' => getProp($segment, 'loudness_ratio'),
  633. 'emotion_scale' => getProp($segment, 'emotion_scale'),
  634. 'pitch' => getProp($segment, 'pitch'),
  635. 'voice_name' => getProp($segment, 'voice_name'),
  636. 'voice_type' => getProp($segment, 'voice_type'),
  637. 'voice_audio_url' => getProp($segment, 'voice_audio_url'),
  638. 'img_url' => getProp($segment, 'img_url'),
  639. 'video_url' => getProp($segment, 'video_url'),
  640. 'last_frame_url' => getProp($segment, 'last_frame_url'),
  641. ];
  642. return $result;
  643. }
  644. public function copyEpisodeVersion($data) {
  645. $episode_id = getProp($data, 'episode_id');
  646. $uid = Site::getUid();
  647. $cpid = Site::getCpid();
  648. $episode = DB::table('mp_anime_episodes')->where('id', $episode_id)->first();
  649. if (!$episode) Utils::throwError('20003:该剧集不存在');
  650. $episode = (array)$episode;
  651. $anime_id = $episode['anime_id'];
  652. $episode_number = $episode['episode_number'];
  653. $count = DB::table('mp_anime_episodes')->where('anime_id', $anime_id)->where('episode_number', $episode_number)->count('id');
  654. $sequence = $count + 1;
  655. unset($episode['id']);
  656. $now = date('Y-m-d H:i:s');
  657. $episode['created_at'] = $now;
  658. $episode['updated_at'] = $now;
  659. $episode['is_default'] = 1;
  660. // 获取版本中含有"(副本"字样的个数
  661. $copy_count = DB::table('mp_anime_episodes')->where('anime_id', $anime_id)->where('episode_number', $episode_number)->where('title', 'like', '%(副本%')->count('id');
  662. $episode['title'] = $copy_count > 0 ? $episode['title']."(副本{$copy_count})" : $episode['title']."(副本)"; // 生成带(副本)字样的标题
  663. $episode['sequence'] = $sequence;
  664. $episode['is_generated'] = 0;
  665. $episode['cpid'] = $cpid;
  666. // 获取ace_mode
  667. $ace_mode = DB::table('mp_animes')->where('id', $anime_id)->value('ace_mode');
  668. try {
  669. DB::beginTransaction();
  670. DB::table('mp_anime_episodes')->where('anime_id', $anime_id)->where('episode_number', $episode_number)->update(['is_default' => 0, 'updated_at'=>$now]);
  671. // 新增副本
  672. $new_episode_id = DB::table('mp_anime_episodes')->insertGetId($episode);
  673. if (!$new_episode_id) {
  674. Utils::throwError('20003:创建副本失败!');
  675. }
  676. // 获取分镜数据并准备插入
  677. $segments_for_insert = DB::table('mp_episode_segments')
  678. ->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')
  679. ->where('episode_id', $episode_id)->orderBy('segment_number')->get()->map(function($item) use ($new_episode_id,$ace_mode) {
  680. $item = (array)$item;
  681. $item['episode_id'] = $new_episode_id;
  682. if ((int)$ace_mode !== 1) $item['segment_id'] = date('YmdHis').mt_rand(1000,9999).str_pad($item['segment_number'], 3, "0", STR_PAD_LEFT);
  683. $item['created_at'] = $item['updated_at'] = date('Y-m-d H:i:s');
  684. return $item;
  685. })->toArray();
  686. // 写入分镜数据
  687. $boolen2 = DB::table('mp_episode_segments')->insert($segments_for_insert);
  688. if (!$boolen2) {
  689. Utils::throwError('20003:写入分镜数据失败!');
  690. }
  691. // 写入对话历史
  692. $records = [
  693. [
  694. 'uid' => $uid,
  695. 'anime_id' => $anime_id,
  696. 'role' => 'user',
  697. 'content' => '创建副本',
  698. 'sequence' => $episode_number,
  699. 'episode_id' => $new_episode_id,
  700. 'created_at' => $now,
  701. 'updated_at' => $now
  702. ],
  703. [
  704. 'uid' => $uid,
  705. 'anime_id' => $anime_id,
  706. 'role' => 'assistant',
  707. 'content' => '好的,已为您创建副本',
  708. 'sequence' => $episode_number,
  709. 'episode_id' => $new_episode_id,
  710. 'created_at' => $now,
  711. 'updated_at' => $now
  712. ]
  713. ];
  714. $boolen3 = DB::table('mp_anime_records')->insert($records);
  715. if (!$boolen3) {
  716. Utils::throwError('20003:对话记录保存失败');
  717. }
  718. }catch (\Exception $e) {
  719. DB::rollBack();
  720. Utils::throwError('20003:'.$e->getMessage());
  721. }
  722. DB::commit();
  723. // 构建与 episodeInfo 方法一致的返回数据结构
  724. $result = [
  725. 'episode_id' => $new_episode_id,
  726. 'anime_id' => $anime_id,
  727. 'episode_number' => $episode_number,
  728. 'title' => $episode['title'],
  729. 'intro' => $episode['intro'],
  730. 'art_style' => $episode['art_style'],
  731. 'roles' => json_decode($episode['roles'], true),
  732. 'scenes' => json_decode($episode['scenes'], true),
  733. 'is_generated' => (int)$episode['is_generated']
  734. ];
  735. if ((int)$ace_mode === 1) {
  736. // 获取分镜信息
  737. $segments = DB::table('mp_episode_segments')->where('anime_id', $anime_id)->where('episode_id', $new_episode_id)->orderBy('act_number')
  738. ->select('*')->get()->map(function ($value) {
  739. return (array)$value;
  740. })->toArray();
  741. $segmentsStructure = $this->buildEpisodeActsStructureForAce($segments);
  742. }else {
  743. // 复用已有的分镜数据,按 act 分组(避免重复查询数据库)
  744. $segmentsStructure = $this->buildEpisodeSegmentsStructure($segments_for_insert);
  745. }
  746. $result['acts'] = $segmentsStructure['acts'];
  747. $result['total_duration'] = $segmentsStructure['total_duration'];
  748. return $result;
  749. }
  750. public function episodeVersions($data) {
  751. $anime_id = getProp($data, 'anime_id');
  752. $episode_id = getProp($data, 'episode_id');
  753. if (!$anime_id || !$episode_id) {
  754. Utils::throwError('1002:请选择剧集');
  755. }
  756. $episode_number = DB::table('mp_anime_episodes')->where('anime_id', $anime_id)->where('id', $episode_id)->value('episode_number');
  757. $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) {
  758. return (array)$value;
  759. })->toArray();
  760. if (!$episodes) Utils::throwError('20003:该剧集不存在!');
  761. foreach($episodes as &$episode) {
  762. $episode['version'] = 'V'.$episode['sequence'];
  763. $episode['roles'] = json_decode($episode['roles'], true);
  764. $episode['scenes'] = json_decode($episode['scenes'], true);
  765. // 获取分镜信息
  766. $segments = DB::table('mp_episode_segments')->where('anime_id', $anime_id)->where('episode_id', getProp($episode, 'episode_id'))->orderBy('segment_number')
  767. ->select('*')->get()->map(function ($value) {
  768. return (array)$value;
  769. })->toArray();
  770. // 使用公共方法构建分镜结构
  771. $segmentsStructure = $this->buildEpisodeSegmentsStructure($segments);
  772. $episode['acts'] = $segmentsStructure['acts'];
  773. $episode['total_duration'] = $segmentsStructure['total_duration'];
  774. }
  775. return $episodes;
  776. }
  777. public function bindEpisodeVersion($data) {
  778. $episode_id = getProp($data, 'episode_id');
  779. $episode = DB::table('mp_anime_episodes')->where('id', $episode_id)->first();
  780. if (!$episode) Utils::throwError('20003:该剧集不存在');
  781. $episode = (array)$episode;
  782. if ((int)$episode['is_default'] === 1) return true;
  783. try {
  784. DB::beginTransaction();
  785. // 移除is_default标志
  786. $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')]);
  787. if (!$boolen) {
  788. Utils::throwError('20003:更新失败!');
  789. }
  790. // 绑定副本
  791. $boolen2 = DB::table('mp_anime_episodes')->where('id', $episode_id)->update(['is_default' => 1, 'updated_at'=>date('Y-m-d H:i:s')]);
  792. if (!$boolen2) {
  793. Utils::throwError('20003:绑定失败!');
  794. }
  795. }catch (\Exception $e) {
  796. DB::rollBack();
  797. Utils::throwError('20003:'.$e->getMessage());
  798. }
  799. DB::commit();
  800. return true;
  801. }
  802. public function chatChangeImg($data) {
  803. $segment_id = getProp($data, 'segment_id');
  804. $type = getProp($data, 'type', 1); // 类型: 1.对话改图 2.图片生成
  805. $prompt = getProp($data, 'prompt');
  806. if (!$prompt || !$segment_id) {
  807. Utils::throwError('1002:请输入提示词,并且选择分镜');
  808. }
  809. $segment = DB::table("mp_episode_segments")->where('segment_id', $segment_id)->first();
  810. if (!$segment) Utils::throwError('20003:该分镜不存在!');
  811. if ((int)$type === 1) $ref_img_url = getProp($segment, 'img_url');
  812. else $ref_img_url = '';
  813. // $ref_img_url = '';
  814. if (empty($prompt)) {
  815. if (empty($ref_img_url)) {
  816. $prompt = getProp($segment, 'segment_content');
  817. }else {
  818. $prompt = '请根据图片生成';
  819. }
  820. }
  821. $anime_id = getProp($segment, 'anime_id');
  822. $episode_id = getProp($segment, 'episode_id');
  823. $episode_number = getProp($segment, 'episode_number');
  824. $episode = DB::table('mp_anime_episodes')->where('id', $episode_id)->first();
  825. $ratio = getProp($data, 'ratio');
  826. if (!$ratio) {
  827. $ratio = getProp($episode, 'ratio');
  828. if (!$ratio) $ratio = '9:16';
  829. }
  830. $art_style = getProp($episode, 'art_style');
  831. if ($art_style) {
  832. $prompt = "美术风格:{$art_style}\n{$prompt}";
  833. }
  834. $dimensions = $this->getRatioDimensions($ratio);
  835. $width = $dimensions['width'];
  836. $height = $dimensions['height'];
  837. try {
  838. $params = [
  839. 'alias_segment_id' => $segment_id,
  840. 'prompt' => $prompt,
  841. 'ref_img_urls' => !empty($ref_img_url) ? [$ref_img_url] : [],
  842. 'width' => $width,
  843. 'height' => $height
  844. ];
  845. // 优化提示词(不要生成字幕)
  846. $params['prompt'] = "前置要求:图片中不要带有任何对话台词或字幕信息\n".$params['prompt'];
  847. $task = $this->aiImageGenerationService->createImageGenerationTask($params);
  848. $task_id = $task->id;
  849. if (!$task_id) {
  850. Utils::throwError("20003:生成图片失败");
  851. }
  852. // 更新任务ID
  853. $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')]);
  854. if (!$boolen) Utils::throwError('20003:更新任务ID失败');
  855. } catch (\Exception $e) {
  856. Utils::throwError("20003:" . $e->getMessage());
  857. }
  858. // 创建任务之后先暂停10s等待异步任务完成
  859. sleep(10);
  860. $img_url = $this->loopGetPicTaskResult($task_id);
  861. if (!$img_url) Utils::throwError('20003:图片生成中,请稍后刷新');
  862. // 图片生成后新增对话记录
  863. try {
  864. $uid = Site::getUid();
  865. $now = date('Y-m-d H:i:s');
  866. // 使用AI反推图片提示词
  867. $pic_prompt = $this->generateImagePromptFromUrl($img_url);
  868. // 保存对话记录
  869. $records = [
  870. [
  871. 'uid' => $uid,
  872. 'anime_id' => $anime_id,
  873. 'sequence' => $episode_number,
  874. 'role' => 'user',
  875. 'content' => $prompt,
  876. 'segment_id' => $segment_id,
  877. 'pic_task_id' => $task_id,
  878. 'image_url' => '',
  879. 'created_at' => $now,
  880. 'updated_at' => $now
  881. ],
  882. [
  883. 'uid' => $uid,
  884. 'anime_id' => $anime_id,
  885. 'sequence' => $episode_number,
  886. 'role' => 'assistant',
  887. 'content' => $pic_prompt,
  888. 'segment_id' => $segment_id,
  889. 'pic_task_id' => $task_id,
  890. 'image_url' => $img_url,
  891. 'created_at' => $now,
  892. 'updated_at' => $now
  893. ]
  894. ];
  895. DB::table('mp_anime_records')->insert($records);
  896. } catch (\Exception $e) {
  897. // 记录日志但不影响主流程
  898. dLog('anime')->error('保存对话记录失败: ' . $e->getMessage(), [
  899. 'segment_id' => $segment_id,
  900. 'img_url' => $img_url
  901. ]);
  902. logDB('anime', 'error', '保存对话记录失败', [
  903. 'segment_id' => $segment_id,
  904. 'img_url' => $img_url,
  905. 'error' => $e->getMessage()
  906. ]);
  907. }
  908. return $img_url;
  909. }
  910. public function segmentChatHistory($data) {
  911. $segment_id = getProp($data, 'segment_id');
  912. if (!$segment_id) Utils::throwError('20003:请选择分镜!');
  913. $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');
  914. $chat = $query->orderBy('id')->get()->map(function ($value) {
  915. $value = (array)$value;
  916. $value['created_at'] = transDate($value['created_at']);
  917. return $value;
  918. })->toArray();
  919. // 获取历史图片
  920. $url = [];
  921. $pic_history = DB::table('mp_generate_pic_tasks')->where('alias_segment_id', $segment_id)->where('status', 'success')->orderBy('created_at', 'desc')->get();
  922. foreach($pic_history as $task) {
  923. $result_url = getProp($task, 'result_url');
  924. if (is_json($result_url)) {
  925. $url = array_merge($url, json_decode($result_url, true));
  926. }else {
  927. $url[] = $result_url;
  928. }
  929. }
  930. // 获取历史视频
  931. $video_history = DB::table('mp_generate_video_tasks')->where('alias_segment_id', $segment_id)->where('status', 'success')->orderBy('created_at', 'desc')->get();
  932. foreach($video_history as $task) {
  933. $result_url = getProp($task, 'compressed_url');
  934. if (is_json($result_url)) {
  935. $url = array_merge($url, json_decode($result_url, true));
  936. }else {
  937. $url[] = $result_url;
  938. }
  939. }
  940. return compact('chat', 'url');
  941. }
  942. public function changeEpisodeRoles($data) {
  943. $anime_id = getProp($data, 'anime_id');
  944. $episode_id = getProp($data, 'episode_id');
  945. $target_roles = getProp($data, 'roles');
  946. // 删除标志优先取最外层入参 is_deleted,兼容角色对象内部(roles.is_deleted)的传参
  947. $is_deleted = getProp($data, 'is_deleted', getProp($target_roles, 'is_deleted', 0));
  948. // 控制字段不随角色内容写入分集roles存储
  949. if (is_array($target_roles)) {
  950. unset($target_roles['is_deleted']);
  951. }
  952. // 参数验证
  953. if (!$anime_id) Utils::throwError('20003:请提供动漫ID');
  954. if (!$episode_id) Utils::throwError('20003:请提供剧集ID');
  955. if (!$target_roles) Utils::throwError('20003:请提供角色信息');
  956. // 验证剧集是否存在
  957. $episode = DB::table('mp_anime_episodes')
  958. ->where('anime_id', $anime_id)
  959. ->where('id', $episode_id)
  960. ->first();
  961. if (!$episode) Utils::throwError('20003:该剧集不存在');
  962. $roles = json_decode(getProp($episode, 'roles'), true);
  963. // 获取anime信息,检查是否有关联的script_id
  964. $anime = DB::table('mp_animes')->where('id', $anime_id)->first();
  965. if (!$anime) Utils::throwError('20003:动漫不存在');
  966. $script_id = getProp($anime, 'script_id');
  967. $episode_number = getProp($episode, 'episode_number', 1);
  968. $uid = Site::getUid();
  969. $cpid = Site::getCpid();
  970. try {
  971. $target_role_name = getProp($target_roles, 'role');
  972. if (empty($target_role_name)) {
  973. Utils::throwError('20003:角色名称不能为空');
  974. }
  975. // 如果是删除操作
  976. if ($is_deleted == 1) {
  977. // 从角色列表中移除该角色
  978. $roles = array_values(array_filter($roles, function($role) use ($target_role_name) {
  979. return getProp($role, 'role') !== $target_role_name;
  980. }));
  981. // 更新角色列表
  982. $result = DB::table('mp_anime_episodes')
  983. ->where('anime_id', $anime_id)
  984. ->where('id', $episode_id)
  985. ->update([
  986. 'roles' => json_encode($roles, 256),
  987. 'updated_at' => date('Y-m-d H:i:s')
  988. ]);
  989. if ($result === false) {
  990. Utils::throwError('20003:删除角色失败');
  991. }
  992. } else {
  993. // 新增或更新操作
  994. $role_found = false;
  995. $is_new_role = false;
  996. // 查找并更新已存在的角色
  997. foreach($roles as &$role) {
  998. if (getProp($role, 'role') === $target_role_name) {
  999. $role = $target_roles;
  1000. $role_found = true;
  1001. break;
  1002. }
  1003. }
  1004. // 如果角色不存在,则新增
  1005. if (!$role_found) {
  1006. $roles[] = $target_roles;
  1007. $is_new_role = true;
  1008. }
  1009. // 更新角色列表
  1010. $result = DB::table('mp_anime_episodes')
  1011. ->where('anime_id', $anime_id)
  1012. ->where('id', $episode_id)
  1013. ->update([
  1014. 'roles' => json_encode($roles, 256),
  1015. 'updated_at' => date('Y-m-d H:i:s')
  1016. ]);
  1017. if ($result === false) {
  1018. Utils::throwError('20003:更新角色列表失败');
  1019. }
  1020. // 同步更新分镜表中对应主体的音色信息
  1021. $voice_name = getProp($target_roles, 'voice_name');
  1022. $voice_type = getProp($target_roles, 'voice_type');
  1023. $voice_audio_url = getProp($target_roles, 'voice_audio_url');
  1024. DB::table('mp_episode_segments')
  1025. ->where('anime_id', $anime_id)
  1026. ->where('episode_id', $episode_id)
  1027. ->where('voice_actor', $target_role_name)
  1028. ->update([
  1029. 'voice_name' => $voice_name,
  1030. 'voice_type' => $voice_type,
  1031. 'voice_audio_url' => $voice_audio_url,
  1032. 'updated_at' => date('Y-m-d H:i:s')
  1033. ]);
  1034. // 如果有关联的script_id,则同步到mp_products表
  1035. if ($script_id) {
  1036. // 查询剧本信息(仅同步属于当前用户的剧本,不属于则跳过后续资产同步)
  1037. $script = DB::table('mp_scripts')
  1038. ->where('id', $script_id)
  1039. ->where('user_id', $uid)
  1040. ->where('is_deleted', 0)
  1041. ->first();
  1042. if ($script) {
  1043. $script_name = $script->script_name ?? 'script_' . $script_id;
  1044. $product_name = getProp($target_roles, 'role');
  1045. $pic_prompt = getProp($target_roles, 'pic_prompt', '');
  1046. $url = getProp($target_roles, 'url', '');
  1047. $three_view_image_url = trim(getProp($target_roles, 'three_view_image_url', ''));
  1048. $timbre_url = trim(getProp($target_roles, 'timbre_url', ''));
  1049. // 兼容 versions 传入数组或 JSON 字符串
  1050. $versions = getProp($target_roles, 'versions', null);
  1051. if (is_string($versions) && $versions !== '') {
  1052. $decoded_versions = json_decode($versions, true);
  1053. if (is_array($decoded_versions)) {
  1054. $versions = $decoded_versions;
  1055. }
  1056. }
  1057. $product_type = 1; // 1=角色
  1058. // 查找或创建以script_name命名的文件夹
  1059. $folder = DB::table('mp_products')
  1060. ->where('cpid', $cpid)
  1061. ->where('type', 2) // 文件夹类型
  1062. ->where('product', $product_type) // 角色类型
  1063. ->where('product_name', $script_name)
  1064. ->where('parent_id', 0)
  1065. ->where('is_deleted', 0)
  1066. ->first();
  1067. if (!$folder) {
  1068. // 创建文件夹
  1069. $folder_id = DB::table('mp_products')->insertGetId([
  1070. 'user_id' => $uid,
  1071. 'cpid' => $cpid,
  1072. 'type' => 2, // 文件夹
  1073. 'product' => $product_type, // 角色类型
  1074. 'parent_id' => 0,
  1075. 'level' => 1,
  1076. 'product_name' => $script_name,
  1077. 'sort_order' => time(),
  1078. 'is_deleted' => 0,
  1079. 'created_at' => date('Y-m-d H:i:s'),
  1080. 'updated_at' => date('Y-m-d H:i:s')
  1081. ]);
  1082. } else {
  1083. $folder_id = $folder->id;
  1084. }
  1085. // 查找该文件夹下是否已存在同名资产
  1086. $existing_product = DB::table('mp_products')
  1087. ->where('cpid', $cpid)
  1088. ->where('type', 1) // 资产类型
  1089. ->where('product', $product_type)
  1090. ->where('parent_id', $folder_id)
  1091. ->where('product_name', $product_name)
  1092. ->where('is_deleted', 0)
  1093. ->first();
  1094. if ($existing_product) {
  1095. // 更新已存在的资产
  1096. $updateData = [
  1097. 'pic_task_status' => '生成成功',
  1098. ];
  1099. if ($pic_prompt) $updateData['pic_prompt'] = $pic_prompt;
  1100. if ($url) $updateData['url'] = $url;
  1101. // 显式传入三视图(含空值)时同步写入,空值表示当前版本没有三视图
  1102. if (is_array($target_roles) && array_key_exists('three_view_image_url', $target_roles)) {
  1103. $updateData['three_view_image_url'] = trim(getProp($target_roles, 'three_view_image_url', ''));
  1104. }
  1105. // 显式传入音色(含空值)时同步写入,空值表示清除该资产的音色
  1106. if (is_array($target_roles) && array_key_exists('timbre_url', $target_roles)) {
  1107. $updateData['timbre_url'] = trim(getProp($target_roles, 'timbre_url', ''));
  1108. }
  1109. // 处理versions字段,显式传入数组(含空数组)时覆盖
  1110. if (is_array($versions)) {
  1111. $updateData['versions'] = json_encode($versions, 256);
  1112. }
  1113. $updateData['updated_at'] = date('Y-m-d H:i:s');
  1114. DB::table('mp_products')
  1115. ->where('id', $existing_product->id)
  1116. ->update($updateData);
  1117. $product_id = $existing_product->id;
  1118. } else {
  1119. // 创建新资产
  1120. $product_id = DB::table('mp_products')->insertGetId([
  1121. 'user_id' => $uid,
  1122. 'cpid' => $cpid,
  1123. 'type' => 1, // 资产
  1124. 'product' => $product_type, // 角色
  1125. 'parent_id' => $folder_id,
  1126. 'level' => 2,
  1127. 'product_name' => $product_name,
  1128. 'url' => $url,
  1129. 'three_view_image_url' => $three_view_image_url,
  1130. 'timbre_url' => $timbre_url,
  1131. 'pic_prompt' => $pic_prompt,
  1132. 'versions' => is_array($versions) ? json_encode($versions, 256) : '[]',
  1133. 'sort_order' => time(),
  1134. 'is_deleted' => 0,
  1135. 'pic_task_status' => '生成成功',
  1136. 'created_at' => date('Y-m-d H:i:s'),
  1137. 'updated_at' => date('Y-m-d H:i:s')
  1138. ]);
  1139. }
  1140. // 建立或更新绑定关系
  1141. $existing_mapping = DB::table('mp_script_product_mappings')
  1142. ->where('script_id', $script_id)
  1143. ->where('product_id', $product_id)
  1144. ->where('episode_number', $episode_number)
  1145. ->first();
  1146. if (!$existing_mapping) {
  1147. // 创建绑定关系
  1148. DB::table('mp_script_product_mappings')->insert([
  1149. 'script_id' => $script_id,
  1150. 'product_id' => $product_id,
  1151. 'episode_number' => $episode_number,
  1152. 'created_at' => date('Y-m-d H:i:s'),
  1153. 'updated_at' => date('Y-m-d H:i:s')
  1154. ]);
  1155. }
  1156. }
  1157. }
  1158. }
  1159. } catch (\Exception $e) {
  1160. dLog('anime')->error('更新剧集角色失败', [
  1161. 'anime_id' => $anime_id,
  1162. 'episode_id' => $episode_id,
  1163. 'error' => $e->getMessage()
  1164. ]);
  1165. Utils::throwError('20003:更新角色列表失败 ' . $e->getMessage());
  1166. }
  1167. return true;
  1168. }
  1169. public function changeEpisodeScenes($data) {
  1170. $anime_id = getProp($data, 'anime_id');
  1171. $episode_id = getProp($data, 'episode_id');
  1172. $target_scenes = getProp($data, 'scenes');
  1173. // 删除标志优先取最外层入参 is_deleted,兼容场景对象内部(scenes.is_deleted)的传参
  1174. $is_deleted = getProp($data, 'is_deleted', getProp($target_scenes, 'is_deleted', 0));
  1175. // 控制字段不随场景内容写入分集scenes存储
  1176. if (is_array($target_scenes)) {
  1177. unset($target_scenes['is_deleted']);
  1178. }
  1179. // 参数验证
  1180. if (!$anime_id) Utils::throwError('20003:请提供动漫ID');
  1181. if (!$episode_id) Utils::throwError('20003:请提供剧集ID');
  1182. if (!$target_scenes) Utils::throwError('20003:请提供场景信息');
  1183. // 验证剧集是否存在
  1184. $episode = DB::table('mp_anime_episodes')
  1185. ->where('anime_id', $anime_id)
  1186. ->where('id', $episode_id)
  1187. ->first();
  1188. if (!$episode) Utils::throwError('20003:该剧集不存在');
  1189. $scenes = json_decode(getProp($episode, 'scenes'), true);
  1190. // 获取anime信息,检查是否有关联的script_id
  1191. $anime = DB::table('mp_animes')->where('id', $anime_id)->first();
  1192. if (!$anime) Utils::throwError('20003:动漫不存在');
  1193. $script_id = getProp($anime, 'script_id');
  1194. $episode_number = getProp($episode, 'episode_number', 1);
  1195. $uid = Site::getUid();
  1196. $cpid = Site::getCpid();
  1197. try {
  1198. $target_scene_name = getProp($target_scenes, 'scene');
  1199. if (empty($target_scene_name)) {
  1200. Utils::throwError('20003:场景名称不能为空');
  1201. }
  1202. // 如果是删除操作
  1203. if ($is_deleted == 1) {
  1204. // 从场景列表中移除该场景
  1205. $scenes = array_values(array_filter($scenes, function($scene) use ($target_scene_name) {
  1206. return getProp($scene, 'scene') !== $target_scene_name;
  1207. }));
  1208. // 更新场景列表
  1209. $result = DB::table('mp_anime_episodes')
  1210. ->where('anime_id', $anime_id)
  1211. ->where('id', $episode_id)
  1212. ->update([
  1213. 'scenes' => json_encode($scenes, 256),
  1214. 'updated_at' => date('Y-m-d H:i:s')
  1215. ]);
  1216. if ($result === false) {
  1217. Utils::throwError('20003:删除场景失败');
  1218. }
  1219. } else {
  1220. // 新增或更新操作
  1221. $scene_found = false;
  1222. $is_new_scene = false;
  1223. // 查找并更新已存在的场景
  1224. foreach($scenes as &$scene) {
  1225. if (getProp($scene, 'scene') === $target_scene_name) {
  1226. $scene = $target_scenes;
  1227. $scene_found = true;
  1228. break;
  1229. }
  1230. }
  1231. // 如果场景不存在,则新增
  1232. if (!$scene_found) {
  1233. $scenes[] = $target_scenes;
  1234. $is_new_scene = true;
  1235. }
  1236. // 更新场景列表
  1237. $result = DB::table('mp_anime_episodes')
  1238. ->where('anime_id', $anime_id)
  1239. ->where('id', $episode_id)
  1240. ->update([
  1241. 'scenes' => json_encode($scenes, 256),
  1242. 'updated_at' => date('Y-m-d H:i:s')
  1243. ]);
  1244. if ($result === false) {
  1245. Utils::throwError('20003:更新场景列表失败');
  1246. }
  1247. // 如果有关联的script_id,则同步到mp_products表
  1248. if ($script_id) {
  1249. // 查询剧本信息(仅同步属于当前用户的剧本,不属于则跳过后续资产同步)
  1250. $script = DB::table('mp_scripts')
  1251. ->where('id', $script_id)
  1252. ->where('user_id', $uid)
  1253. ->where('is_deleted', 0)
  1254. ->first();
  1255. if ($script) {
  1256. $script_name = $script->script_name ?? 'script_' . $script_id;
  1257. $product_name = getProp($target_scenes, 'scene');
  1258. $pic_prompt = getProp($target_scenes, 'pic_prompt', '');
  1259. $url = getProp($target_scenes, 'url', '');
  1260. $three_view_image_url = trim(getProp($target_scenes, 'three_view_image_url', ''));
  1261. $timbre_url = trim(getProp($target_scenes, 'timbre_url', ''));
  1262. // 兼容 versions 传入数组或 JSON 字符串
  1263. $versions = getProp($target_scenes, 'versions', null);
  1264. if (is_string($versions) && $versions !== '') {
  1265. $decoded_versions = json_decode($versions, true);
  1266. if (is_array($decoded_versions)) {
  1267. $versions = $decoded_versions;
  1268. }
  1269. }
  1270. $product_type = 2; // 2=场景
  1271. // 查找或创建以script_name命名的文件夹
  1272. $folder = DB::table('mp_products')
  1273. ->where('cpid', $cpid)
  1274. ->where('type', 2) // 文件夹类型
  1275. ->where('product', $product_type) // 场景类型
  1276. ->where('product_name', $script_name)
  1277. ->where('parent_id', 0)
  1278. ->where('is_deleted', 0)
  1279. ->first();
  1280. if (!$folder) {
  1281. // 创建文件夹
  1282. $folder_id = DB::table('mp_products')->insertGetId([
  1283. 'user_id' => $uid,
  1284. 'cpid' => $cpid,
  1285. 'type' => 2, // 文件夹
  1286. 'product' => $product_type, // 场景类型
  1287. 'parent_id' => 0,
  1288. 'level' => 1,
  1289. 'product_name' => $script_name,
  1290. 'sort_order' => time(),
  1291. 'is_deleted' => 0,
  1292. 'created_at' => date('Y-m-d H:i:s'),
  1293. 'updated_at' => date('Y-m-d H:i:s')
  1294. ]);
  1295. } else {
  1296. $folder_id = $folder->id;
  1297. }
  1298. // 查找该文件夹下是否已存在同名资产
  1299. $existing_product = DB::table('mp_products')
  1300. ->where('cpid', $cpid)
  1301. ->where('type', 1) // 资产类型
  1302. ->where('product', $product_type)
  1303. ->where('parent_id', $folder_id)
  1304. ->where('product_name', $product_name)
  1305. ->where('is_deleted', 0)
  1306. ->first();
  1307. if ($existing_product) {
  1308. // 更新已存在的资产
  1309. $updateData = [
  1310. 'pic_task_status' => '生成成功'
  1311. ];
  1312. if ($pic_prompt) $updateData['pic_prompt'] = $pic_prompt;
  1313. if ($url) $updateData['url'] = $url;
  1314. // 显式传入三视图(含空值)时同步写入,空值表示当前版本没有三视图
  1315. if (is_array($target_scenes) && array_key_exists('three_view_image_url', $target_scenes)) {
  1316. $updateData['three_view_image_url'] = trim(getProp($target_scenes, 'three_view_image_url', ''));
  1317. }
  1318. // 显式传入音色(含空值)时同步写入,空值表示清除该资产的音色
  1319. if (is_array($target_scenes) && array_key_exists('timbre_url', $target_scenes)) {
  1320. $updateData['timbre_url'] = trim(getProp($target_scenes, 'timbre_url', ''));
  1321. }
  1322. // 处理versions字段,显式传入数组(含空数组)时覆盖
  1323. if (is_array($versions)) {
  1324. $updateData['versions'] = json_encode($versions, 256);
  1325. }
  1326. $updateData['updated_at'] = date('Y-m-d H:i:s');
  1327. DB::table('mp_products')
  1328. ->where('id', $existing_product->id)
  1329. ->update($updateData);
  1330. $product_id = $existing_product->id;
  1331. } else {
  1332. // 创建新资产
  1333. $product_id = DB::table('mp_products')->insertGetId([
  1334. 'user_id' => $uid,
  1335. 'cpid' => $cpid,
  1336. 'type' => 1, // 资产
  1337. 'product' => $product_type, // 场景
  1338. 'parent_id' => $folder_id,
  1339. 'level' => 2,
  1340. 'product_name' => $product_name,
  1341. 'url' => $url,
  1342. 'three_view_image_url' => $three_view_image_url,
  1343. 'timbre_url' => $timbre_url,
  1344. 'pic_prompt' => $pic_prompt,
  1345. 'versions' => is_array($versions) ? json_encode($versions, 256) : '[]',
  1346. 'sort_order' => time(),
  1347. 'is_deleted' => 0,
  1348. 'pic_task_status' => '生成成功',
  1349. 'created_at' => date('Y-m-d H:i:s'),
  1350. 'updated_at' => date('Y-m-d H:i:s')
  1351. ]);
  1352. }
  1353. // 建立或更新绑定关系
  1354. $existing_mapping = DB::table('mp_script_product_mappings')
  1355. ->where('script_id', $script_id)
  1356. ->where('product_id', $product_id)
  1357. ->where('episode_number', $episode_number)
  1358. ->first();
  1359. if (!$existing_mapping) {
  1360. // 创建绑定关系
  1361. DB::table('mp_script_product_mappings')->insert([
  1362. 'script_id' => $script_id,
  1363. 'product_id' => $product_id,
  1364. 'episode_number' => $episode_number,
  1365. 'created_at' => date('Y-m-d H:i:s'),
  1366. 'updated_at' => date('Y-m-d H:i:s')
  1367. ]);
  1368. }
  1369. }
  1370. }
  1371. }
  1372. } catch (\Exception $e) {
  1373. dLog('anime')->error('更新剧集场景失败', [
  1374. 'anime_id' => $anime_id,
  1375. 'episode_id' => $episode_id,
  1376. 'error' => $e->getMessage()
  1377. ]);
  1378. Utils::throwError('20003:更新场景列表失败 ' . $e->getMessage());
  1379. }
  1380. return true;
  1381. }
  1382. public function changeEpisodeProps($data) {
  1383. $anime_id = getProp($data, 'anime_id');
  1384. $episode_id = getProp($data, 'episode_id');
  1385. $target_props = getProp($data, 'props');
  1386. // 删除标志优先取最外层入参 is_deleted,兼容道具对象内部(props.is_deleted)的传参
  1387. $is_deleted = getProp($data, 'is_deleted', getProp($target_props, 'is_deleted', 0));
  1388. // 控制字段不随道具内容写入分集props存储
  1389. if (is_array($target_props)) {
  1390. unset($target_props['is_deleted']);
  1391. }
  1392. // 参数验证
  1393. if (!$anime_id) Utils::throwError('20003:请提供动漫ID');
  1394. if (!$episode_id) Utils::throwError('20003:请提供剧集ID');
  1395. if (!$target_props) Utils::throwError('20003:请提供道具信息');
  1396. // 验证剧集是否存在
  1397. $episode = DB::table('mp_anime_episodes')
  1398. ->where('anime_id', $anime_id)
  1399. ->where('id', $episode_id)
  1400. ->first();
  1401. if (!$episode) Utils::throwError('20003:该剧集不存在');
  1402. $props = json_decode(getProp($episode, 'props'), true);
  1403. // 获取anime信息,检查是否有关联的script_id
  1404. $anime = DB::table('mp_animes')->where('id', $anime_id)->first();
  1405. if (!$anime) Utils::throwError('20003:动漫不存在');
  1406. $script_id = getProp($anime, 'script_id');
  1407. $episode_number = getProp($episode, 'episode_number', 1);
  1408. $uid = Site::getUid();
  1409. $cpid = Site::getCpid();
  1410. try {
  1411. $target_prop_name = getProp($target_props, 'prop');
  1412. if (empty($target_prop_name)) {
  1413. Utils::throwError('20003:道具名称不能为空');
  1414. }
  1415. // 如果是删除操作
  1416. if ($is_deleted == 1) {
  1417. // 从道具列表中移除该道具
  1418. $props = array_values(array_filter($props, function($prop) use ($target_prop_name) {
  1419. return getProp($prop, 'prop') !== $target_prop_name;
  1420. }));
  1421. // 更新道具列表
  1422. $result = DB::table('mp_anime_episodes')
  1423. ->where('anime_id', $anime_id)
  1424. ->where('id', $episode_id)
  1425. ->update([
  1426. 'props' => json_encode($props, 256),
  1427. 'updated_at' => date('Y-m-d H:i:s')
  1428. ]);
  1429. if ($result === false) {
  1430. Utils::throwError('20003:删除道具失败');
  1431. }
  1432. } else {
  1433. // 新增或更新操作
  1434. $prop_found = false;
  1435. $is_new_prop = false;
  1436. // 查找并更新已存在的道具
  1437. foreach($props as &$prop) {
  1438. if (getProp($prop, 'prop') === $target_prop_name) {
  1439. $prop = $target_props;
  1440. $prop_found = true;
  1441. break;
  1442. }
  1443. }
  1444. // 如果道具不存在,则新增
  1445. if (!$prop_found) {
  1446. $props[] = $target_props;
  1447. $is_new_prop = true;
  1448. }
  1449. // 更新道具列表
  1450. $result = DB::table('mp_anime_episodes')
  1451. ->where('anime_id', $anime_id)
  1452. ->where('id', $episode_id)
  1453. ->update([
  1454. 'props' => json_encode($props, 256),
  1455. 'updated_at' => date('Y-m-d H:i:s')
  1456. ]);
  1457. if ($result === false) {
  1458. Utils::throwError('20003:更新道具列表失败');
  1459. }
  1460. // 如果有关联的script_id,则同步到mp_products表
  1461. if ($script_id) {
  1462. // 查询剧本信息(仅同步属于当前用户的剧本,不属于则跳过后续资产同步)
  1463. $script = DB::table('mp_scripts')
  1464. ->where('id', $script_id)
  1465. ->where('user_id', $uid)
  1466. ->where('is_deleted', 0)
  1467. ->first();
  1468. if ($script) {
  1469. $script_name = $script->script_name ?? 'script_' . $script_id;
  1470. $product_name = getProp($target_props, 'prop');
  1471. $pic_prompt = getProp($target_props, 'pic_prompt', '');
  1472. $url = getProp($target_props, 'url', '');
  1473. $three_view_image_url = trim(getProp($target_props, 'three_view_image_url', ''));
  1474. $timbre_url = trim(getProp($target_props, 'timbre_url', ''));
  1475. // 兼容 versions 传入数组或 JSON 字符串
  1476. $versions = getProp($target_props, 'versions', null);
  1477. if (is_string($versions) && $versions !== '') {
  1478. $decoded_versions = json_decode($versions, true);
  1479. if (is_array($decoded_versions)) {
  1480. $versions = $decoded_versions;
  1481. }
  1482. }
  1483. $product_type = 3; // 3=道具
  1484. // 查找或创建以script_name命名的文件夹
  1485. $folder = DB::table('mp_products')
  1486. ->where('cpid', $cpid)
  1487. ->where('type', 2) // 文件夹类型
  1488. ->where('product', $product_type) // 道具类型
  1489. ->where('product_name', $script_name)
  1490. ->where('parent_id', 0)
  1491. ->where('is_deleted', 0)
  1492. ->first();
  1493. if (!$folder) {
  1494. // 创建文件夹
  1495. $folder_id = DB::table('mp_products')->insertGetId([
  1496. 'user_id' => $uid,
  1497. 'cpid' => $cpid,
  1498. 'type' => 2, // 文件夹
  1499. 'product' => $product_type, // 道具类型
  1500. 'parent_id' => 0,
  1501. 'level' => 1,
  1502. 'product_name' => $script_name,
  1503. 'sort_order' => time(),
  1504. 'is_deleted' => 0,
  1505. 'created_at' => date('Y-m-d H:i:s'),
  1506. 'updated_at' => date('Y-m-d H:i:s')
  1507. ]);
  1508. } else {
  1509. $folder_id = $folder->id;
  1510. }
  1511. // 查找该文件夹下是否已存在同名资产
  1512. $existing_product = DB::table('mp_products')
  1513. ->where('cpid', $cpid)
  1514. ->where('type', 1) // 资产类型
  1515. ->where('product', $product_type)
  1516. ->where('parent_id', $folder_id)
  1517. ->where('product_name', $product_name)
  1518. ->where('is_deleted', 0)
  1519. ->first();
  1520. if ($existing_product) {
  1521. // 更新已存在的资产
  1522. $updateData = [
  1523. 'pic_task_status' => '生成成功'
  1524. ];
  1525. if ($pic_prompt) $updateData['pic_prompt'] = $pic_prompt;
  1526. if ($url) $updateData['url'] = $url;
  1527. // 显式传入三视图(含空值)时同步写入,空值表示当前版本没有三视图
  1528. if (is_array($target_props) && array_key_exists('three_view_image_url', $target_props)) {
  1529. $updateData['three_view_image_url'] = trim(getProp($target_props, 'three_view_image_url', ''));
  1530. }
  1531. // 显式传入音色(含空值)时同步写入,空值表示清除该资产的音色
  1532. if (is_array($target_props) && array_key_exists('timbre_url', $target_props)) {
  1533. $updateData['timbre_url'] = trim(getProp($target_props, 'timbre_url', ''));
  1534. }
  1535. // 处理versions字段,显式传入数组(含空数组)时覆盖
  1536. if (is_array($versions)) {
  1537. $updateData['versions'] = json_encode($versions, 256);
  1538. }
  1539. $updateData['updated_at'] = date('Y-m-d H:i:s');
  1540. DB::table('mp_products')
  1541. ->where('id', $existing_product->id)
  1542. ->update($updateData);
  1543. $product_id = $existing_product->id;
  1544. } else {
  1545. // 创建新资产
  1546. $product_id = DB::table('mp_products')->insertGetId([
  1547. 'user_id' => $uid,
  1548. 'cpid' => $cpid,
  1549. 'type' => 1, // 资产
  1550. 'product' => $product_type, // 道具
  1551. 'parent_id' => $folder_id,
  1552. 'level' => 2,
  1553. 'product_name' => $product_name,
  1554. 'url' => $url,
  1555. 'three_view_image_url' => $three_view_image_url,
  1556. 'timbre_url' => $timbre_url,
  1557. 'pic_prompt' => $pic_prompt,
  1558. 'versions' => is_array($versions) ? json_encode($versions, 256) : '[]',
  1559. 'sort_order' => time(),
  1560. 'is_deleted' => 0,
  1561. 'pic_task_status' => '生成成功',
  1562. 'created_at' => date('Y-m-d H:i:s'),
  1563. 'updated_at' => date('Y-m-d H:i:s')
  1564. ]);
  1565. }
  1566. // 建立或更新绑定关系
  1567. $existing_mapping = DB::table('mp_script_product_mappings')
  1568. ->where('script_id', $script_id)
  1569. ->where('product_id', $product_id)
  1570. ->where('episode_number', $episode_number)
  1571. ->first();
  1572. if (!$existing_mapping) {
  1573. // 创建绑定关系
  1574. DB::table('mp_script_product_mappings')->insert([
  1575. 'script_id' => $script_id,
  1576. 'product_id' => $product_id,
  1577. 'episode_number' => $episode_number,
  1578. 'created_at' => date('Y-m-d H:i:s'),
  1579. 'updated_at' => date('Y-m-d H:i:s')
  1580. ]);
  1581. }
  1582. }
  1583. }
  1584. }
  1585. } catch (\Exception $e) {
  1586. dLog('anime')->error('更新剧集道具失败', [
  1587. 'anime_id' => $anime_id,
  1588. 'episode_id' => $episode_id,
  1589. 'error' => $e->getMessage()
  1590. ]);
  1591. Utils::throwError('20003:更新道具列表失败 ' . $e->getMessage());
  1592. }
  1593. return true;
  1594. }
  1595. public function editSegment($data) {
  1596. $segment_id = getProp($data, 'segment_id');
  1597. $segment_content = getProp($data, 'segment_content');
  1598. $image_url = getProp($data, 'image_url');
  1599. $video_url = getProp($data, 'video_url');
  1600. // 参数验证
  1601. if (!$segment_id) Utils::throwError('20003:请提供分镜ID');
  1602. // 验证分镜是否存在
  1603. $segment = DB::table('mp_episode_segments')
  1604. ->where('segment_id', $segment_id)
  1605. ->first();
  1606. if (!$segment) Utils::throwError('20003:该分镜不存在');
  1607. $dubTaskId = 0;
  1608. try {
  1609. DB::beginTransaction();
  1610. // 准备更新数据
  1611. $update_data = [
  1612. 'updated_at' => date('Y-m-d H:i:s')
  1613. ];
  1614. if ($segment_content) {
  1615. // 先将segment_content赋值到update_data
  1616. $update_data['segment_content'] = $segment_content;
  1617. // 使用现有方法分析segment_content,提取各个字段
  1618. $this->handleSegmentContent($update_data);
  1619. // 如果有对话内容,创建视频配音合成任务
  1620. $dialogue = getProp($update_data, 'dialogue');
  1621. if (!empty($dialogue)) {
  1622. $now = date('Y-m-d H:i:s');
  1623. $generate_json = [
  1624. 'text' => $dialogue,
  1625. 'role' => getProp($update_data, 'voice_actor'),
  1626. 'voice_type' => getProp($update_data, 'voice_type'),
  1627. 'voice_name' => getProp($update_data, 'voice_name'),
  1628. 'emotion' => getProp($update_data, 'emotion'),
  1629. 'emotion_type' => getProp($update_data, 'emotion_type'),
  1630. 'gender' => getProp($update_data, 'gender'),
  1631. 'speed_ratio' => getProp($update_data, 'speed_ratio', 0),
  1632. 'loudness_ratio' => getProp($update_data, 'loudness_ratio', 0),
  1633. 'emotion_scale' => getProp($update_data, 'emotion_scale', 0),
  1634. 'pitch' => getProp($update_data, 'pitch', 0),
  1635. ];
  1636. // 插入视频配音合成任务
  1637. $dubTaskId = DB::table('mp_dub_video_tasks')->insertGetId([
  1638. 'alias_segment_id' => $segment_id,
  1639. 'generate_status' => '执行中',
  1640. 'audio_url' => '',
  1641. 'generate_json' => json_encode($generate_json, 256),
  1642. 'created_at' => $now,
  1643. 'updated_at' => $now,
  1644. ]);
  1645. if (!$dubTaskId) {
  1646. Utils::throwError('20003:创建配音任务失败!');
  1647. }
  1648. $update_data['audio_url'] = '';
  1649. } else {
  1650. // dialogue为空时,直接写入默认音频信息
  1651. $update_data['audio_url'] = 'https://zw-audiobook.tos-cn-beijing.volces.com/effects/ellipses_2s.mp3';
  1652. $update_data['audio_duration'] = 2.0;
  1653. $update_data['subtitle_info'] = json_encode(['duration' => 2.0, 'words' => []], 256);
  1654. }
  1655. }
  1656. if ($image_url) {
  1657. $update_data['img_url'] = $image_url;
  1658. // 同时写入一个简单的图片生成任务
  1659. $pic_task = [
  1660. 'alias_segment_id' => $segment_id,
  1661. 'ref_img_url' => json_encode([]),
  1662. 'status' => 'success',
  1663. 'result_url' => json_encode([$image_url], 256),
  1664. 'model' => '',
  1665. 'created_at' => date('Y-m-d H:i:s'),
  1666. 'updated_at' => date('Y-m-d H:i:s'),
  1667. ];
  1668. DB::table('mp_generate_pic_tasks')->insert($pic_task);
  1669. }
  1670. if ($video_url) {
  1671. $update_data['origin_video_url'] = $video_url;
  1672. $compressed_video_url = compressVideo($video_url);
  1673. $update_data['current_type'] = 2;
  1674. $update_data['video_url'] = $compressed_video_url ?: $video_url;
  1675. // 同时写入一个简单的视频生成任务
  1676. $video_task = [
  1677. 'alias_segment_id' => $segment_id,
  1678. 'status' => 'success',
  1679. 'result_url' => $update_data['origin_video_url'],
  1680. 'compressed_url' => $update_data['video_url'],
  1681. 'created_at' => date('Y-m-d H:i:s'),
  1682. 'updated_at' => date('Y-m-d H:i:s'),
  1683. ];
  1684. DB::table('mp_generate_video_tasks')->insert($video_task);
  1685. }
  1686. // 更新分镜信息
  1687. $result = DB::table('mp_episode_segments')
  1688. ->where('segment_id', $segment_id)
  1689. ->update($update_data);
  1690. if ($result === false) {
  1691. Utils::throwError('20003:更新分镜剧本失败');
  1692. }
  1693. DB::commit();
  1694. // 如果有创建音频生成任务则调用API
  1695. if ($dubTaskId) {
  1696. // 请求远程服务器执行生成
  1697. $client = new Client(['timeout' => 300, 'verify' => false]);
  1698. $result = $client->get("http://122.9.129.83:5000/api/anime/genAudio?taskId={$dubTaskId}");
  1699. $response = $result->getBody()->getContents();
  1700. $response_arr = json_decode($response, true);
  1701. if (!isset($response_arr['code']) || (int)$response_arr['code'] !== 0) {
  1702. $error_msg = isset($response_arr['msg']) ? $response_arr['msg'] : '未知错误';
  1703. dLog('anime')->error('火山生成音频失败', ['error' => $error_msg, 'task_id' => $dubTaskId, 'segment_id'=>$segment_id]);
  1704. logDB('anime', 'error', '火山生成音频失败', ['error' => $error_msg, 'task_id' => $dubTaskId, 'segment_id'=>$segment_id]);
  1705. Utils::throwError('20003:火山生成音频失败');
  1706. }
  1707. }
  1708. return true;
  1709. } catch (\Exception $e) {
  1710. DB::rollBack();
  1711. dLog('anime')->error('更新分镜剧本失败', [
  1712. 'segment_id' => $segment_id,
  1713. 'error' => $e->getMessage()
  1714. ]);
  1715. Utils::throwError('20003:更新分镜剧本失败 ' . $e->getMessage());
  1716. }
  1717. }
  1718. public function batchSetSegmentPics($data) {
  1719. $anime_id = getProp($data, 'anime_id');
  1720. $episode_id = getProp($data, 'episode_id');
  1721. $ratio = getProp($data, 'ratio');
  1722. $dimensions = $this->getRatioDimensions($ratio);
  1723. $width = $dimensions['width'];
  1724. $height = $dimensions['height'];
  1725. if (!$anime_id || !$episode_id) {
  1726. Utils::throwError('1002:请选择剧集');
  1727. }
  1728. // 获取剧集信息
  1729. $episode = DB::table('mp_anime_episodes')
  1730. ->where('anime_id', $anime_id)
  1731. ->where('id', $episode_id)
  1732. ->where('is_default', 1)
  1733. ->select('id as episode_id', 'anime_id', 'episode_number', 'roles', 'scenes', 'image_model')
  1734. ->first();
  1735. if (!$episode) {
  1736. Utils::throwError('20003:该剧集不存在');
  1737. }
  1738. $model = getProp($data, 'model');
  1739. if (!$model) {
  1740. $model = getProp($episode, 'image_model');
  1741. if (!$model) {
  1742. // episode表也没有,使用默认值
  1743. $model = 'gpt-image-2';
  1744. }
  1745. }
  1746. // 验证模型是否在可用模型表中
  1747. if (!DB::table('mp_image_models')->where('model', $model)->where('is_enabled', 1)->exists()) {
  1748. $model = 'gpt-image-2';
  1749. }
  1750. $roles = json_decode(getProp($episode, 'roles'), true);
  1751. if (!$roles) {
  1752. Utils::throwError('20003:角色信息格式错误');
  1753. }
  1754. // 构建角色名称到参考图的映射
  1755. $role_map = [];
  1756. foreach ($roles as $role) {
  1757. $role_name = getProp($role, 'role');
  1758. $role_url = getProp($role, 'url');
  1759. if (!empty($role_name) && !empty($role_url)) {
  1760. // // 处理角色名称,去除装扮后缀(如:许芸-校服装 -> 许芸)- 修复中文乱码问题(弃用,容易产生重复图片)
  1761. // $base_name = preg_replace('/[--].*$/u', '', $role_name);
  1762. // $role_map[$base_name] = $role_url;
  1763. // 同时保存完整名称的映射
  1764. $role_map[$role_name] = $role_url;
  1765. }
  1766. }
  1767. $scenes = json_decode(getProp($episode, 'roles'), true);
  1768. if (!$scenes) {
  1769. Utils::throwError('20003:场景信息格式错误');
  1770. }
  1771. // 构建角色名称到参考图的映射
  1772. $scene_map = [];
  1773. foreach ($scenes as $scene) {
  1774. $scene_name = getProp($scene, 'scene');
  1775. $scene_url = getProp($scene, 'url');
  1776. if (!empty($scene_name) && !empty($scene_url)) {
  1777. $scene_map[$scene_name] = $scene_url;
  1778. }
  1779. }
  1780. // 获取所有分镜信息
  1781. $segments = DB::table('mp_episode_segments')
  1782. ->where('anime_id', $anime_id)
  1783. ->where('episode_id', $episode_id)
  1784. ->whereNotIn('pic_task_status', ['已完成', '生成中'])
  1785. ->orderBy('segment_number')
  1786. ->get()
  1787. ->toArray();
  1788. if (empty($segments)) {
  1789. Utils::throwError('20003:所有分镜图片已完成或正在生成中');
  1790. }
  1791. // 保存图片比例
  1792. DB::table('mp_anime_episodes')->where('id', $episode_id)->update(['ratio' => $ratio, 'updated_at' => date('Y-m-d H:i:s')]);
  1793. $updated_segments = [];
  1794. $failed_segments = [];
  1795. // 批量为每个分镜生成图片任务
  1796. foreach ($segments as $segment) {
  1797. $segment_id = $segment->segment_id;
  1798. $segment_content = $segment->segment_content;
  1799. if (empty($segment_content)) {
  1800. $failed_segments[] = [
  1801. 'segment_id' => $segment_id,
  1802. 'error' => '分镜内容为空'
  1803. ];
  1804. continue;
  1805. }
  1806. try {
  1807. $dubTaskId = 0;
  1808. // 解析分镜内容,提取画面描述作为主要提示词
  1809. $prompt = $segment_content;
  1810. $ref_img_urls = [];
  1811. // 分镜场景
  1812. $scene = getProp($segment, 'scene');
  1813. $matched_scene = '';
  1814. if (isset($scene_map[$scene])) {
  1815. $img_index = count($ref_img_urls) + 1;
  1816. $prompt = "场景:$scene(图$img_index)\n$prompt";
  1817. $ref_img_urls[] = $scene_map[$scene];
  1818. $matched_scene = $scene;
  1819. }
  1820. // 分镜角色
  1821. $characters = getProp($segment, 'characters');
  1822. $characters = str_replace(['、', ',', ';'], ',', $characters);
  1823. $roles = explode(',', $characters);
  1824. // 从分镜内容中提取涉及的角色
  1825. $segment_characters = $this->extractCharactersFromSegment($segment_content, array_keys($role_map), $roles);
  1826. // 获取匹配角色的参考图
  1827. foreach ($segment_characters as $character) {
  1828. if (isset($role_map[$character])) {
  1829. // 将$prompt中出现的角色替换成角色(图1、2、3,序号是$ref_img_urls的个数加1)
  1830. $img_index = count($ref_img_urls) + 1;
  1831. $prompt = str_replace($character, $character . '(图' . $img_index . ')', $prompt);
  1832. $ref_img_urls[] = $role_map[$character];
  1833. }
  1834. }
  1835. // 如果没有找到匹配的角色参考图,不使用参考图
  1836. if (empty($ref_img_urls)) {
  1837. $ref_img_urls = [];
  1838. }
  1839. // 准备生成任务参数
  1840. $params = [
  1841. 'model' => $model,
  1842. 'alias_segment_id' => $segment_id,
  1843. 'prompt' => $prompt,
  1844. 'ref_img_urls' => $ref_img_urls,
  1845. 'width' => $width,
  1846. 'height' => $height,
  1847. ];
  1848. // 优化提示词(不要生成字幕)
  1849. $params['prompt'] = "前置要求:图片中不要带有任何对话台词或字幕信息\n".$params['prompt'];
  1850. // $task_id = mt_rand(100000, 999999);
  1851. // 调用AI图片生成服务
  1852. $task = $this->aiImageGenerationService->createImageGenerationTask($params);
  1853. $task_id = $task->id;
  1854. if (!$task_id) {
  1855. $failed_segments[] = [
  1856. 'segment_id' => $segment_id,
  1857. 'error' => '创建生成任务失败'
  1858. ];
  1859. continue;
  1860. }
  1861. $update_data = [
  1862. 'pic_task_id' => $task_id,
  1863. 'pic_task_status' => '生成中',
  1864. 'audio_url' => '',
  1865. 'updated_at' => date('Y-m-d H:i:s')
  1866. ];
  1867. // 如果有对话内容,创建视频配音合成任务
  1868. $dialogue = getProp($segment, 'dialogue');
  1869. if (!empty($dialogue)) {
  1870. $now = date('Y-m-d H:i:s');
  1871. $generate_json = [
  1872. 'text' => $dialogue,
  1873. 'role' => getProp($segment, 'voice_actor'),
  1874. 'voice_type' => getProp($segment, 'voice_type'),
  1875. 'voice_name' => getProp($segment, 'voice_name'),
  1876. 'emotion' => getProp($segment, 'emotion'),
  1877. 'emotion_type' => getProp($segment, 'emotion_type'),
  1878. 'gender' => getProp($segment, 'gender'),
  1879. 'speed_ratio' => getProp($segment, 'speed_ratio', 0),
  1880. 'loudness_ratio' => getProp($segment, 'loudness_ratio', 0),
  1881. 'emotion_scale' => getProp($segment, 'emotion_scale', 0),
  1882. 'pitch' => getProp($segment, 'pitch', 0),
  1883. ];
  1884. // 插入视频配音合成任务
  1885. $dubTaskId = DB::table('mp_dub_video_tasks')->insertGetId([
  1886. 'alias_segment_id' => $segment_id,
  1887. 'generate_status' => '执行中',
  1888. 'audio_url' => '',
  1889. 'generate_json' => json_encode($generate_json, 256),
  1890. 'created_at' => $now,
  1891. 'updated_at' => $now,
  1892. ]);
  1893. if (!$dubTaskId) {
  1894. dLog('anime')->error('火山生成音频失败', ['segment_id' => $segment_id, 'generate_json'=>$generate_json]);
  1895. logDB('anime', 'error', '火山生成音频失败', ['segment_id' => $segment_id, 'generate_json'=>$generate_json]);
  1896. // Utils::throwError('20003:创建配音任务失败!');
  1897. }
  1898. } else {
  1899. // dialogue为空时,直接写入默认音频信息到分镜表
  1900. $update_data['audio_url'] = 'https://zw-audiobook.tos-cn-beijing.volces.com/effects/ellipses_2s.mp3';
  1901. $update_data['audio_duration'] = 2.0;
  1902. $update_data['subtitle_info'] = json_encode(['duration' => 2.0, 'words' => []], 256);
  1903. }
  1904. // 更新分镜的任务信息
  1905. $update_result = DB::table('mp_episode_segments')
  1906. ->where('segment_id', $segment_id)
  1907. ->update($update_data);
  1908. // 如果是第一集的首帧图片,则存入待更新数组
  1909. if ($update_result && (int)getProp($segment, 'episode_number') === 1 && (int)getProp($segment, 'segment_number') === 1) {
  1910. Redis::sadd('anime_first_frame_urls', $segment_id);
  1911. }
  1912. if ($update_result) {
  1913. $updated_segments[] = [
  1914. 'segment_id' => $segment_id,
  1915. 'task_id' => $task_id,
  1916. 'status' => '生成中',
  1917. 'matched_scenes' => $matched_scene,
  1918. 'matched_roles' => $segment_characters,
  1919. 'ref_urls_count' => count($ref_img_urls)
  1920. ];
  1921. } else {
  1922. $failed_segments[] = [
  1923. 'segment_id' => $segment_id,
  1924. 'error' => '更新分镜任务状态失败'
  1925. ];
  1926. }
  1927. if ($dubTaskId) {
  1928. sleep(1);
  1929. // 请求远程服务器执行生成
  1930. $client = new Client(['timeout' => 300, 'verify' => false]);
  1931. $result = $client->get("http://122.9.129.83:5000/api/anime/genAudio?taskId={$dubTaskId}");
  1932. $response = $result->getBody()->getContents();
  1933. $response_arr = json_decode($response, true);
  1934. if (!isset($response_arr['code']) || (int)$response_arr['code'] !== 0) {
  1935. $error_msg = isset($response_arr['msg']) ? $response_arr['msg'] : '未知错误';
  1936. dLog('anime')->error('火山生成音频失败', ['error' => $error_msg, 'task_id' => $dubTaskId, 'segment_id' => $segment_id]);
  1937. logDB('anime', 'error', '火山生成音频失败', ['error' => $error_msg, 'task_id' => $dubTaskId, 'segment_id' => $segment_id]);
  1938. }
  1939. }
  1940. } catch (\Exception $e) {
  1941. $failed_segments[] = [
  1942. 'segment_id' => $segment_id,
  1943. 'error' => $e->getMessage()
  1944. ];
  1945. }
  1946. }
  1947. // 更新剧集生成状态
  1948. if (!empty($updated_segments)) {
  1949. DB::table('mp_anime_episodes')
  1950. ->where('id', $episode_id)
  1951. ->update([
  1952. 'is_generated' => 1,
  1953. 'updated_at' => date('Y-m-d H:i:s')
  1954. ]);
  1955. }
  1956. return [
  1957. 'success_count' => count($updated_segments),
  1958. 'failed_count' => count($failed_segments),
  1959. 'success_segments' => $updated_segments,
  1960. 'failed_segments' => $failed_segments,
  1961. 'total_segments' => count($segments)
  1962. ];
  1963. }
  1964. public function reGenerateSegment($data) {
  1965. $segment_id = getProp($data, 'segment_id');
  1966. $segment = DB::table('mp_episode_segments')->where('segment_id', $segment_id)->first();
  1967. $anime_id = getProp($segment, 'anime_id');
  1968. $episode_id = getProp($segment, 'episode_id');
  1969. $episode_number = getProp($segment, 'episode_number');
  1970. $segment_content = getProp($data, 'segment_content');
  1971. $ratio = getProp($data, 'ratio');
  1972. if (!$ratio) {
  1973. $ratio = DB::table('mp_anime_episodes')->where('id', $episode_id)->value('ratio');
  1974. if (!$ratio) $ratio = '9:16';
  1975. }
  1976. $dimensions = $this->getRatioDimensions($ratio);
  1977. $width = $dimensions['width'];
  1978. $height = $dimensions['height'];
  1979. if (!$anime_id || !$episode_id) {
  1980. Utils::throwError('1002:请选择分镜');
  1981. }
  1982. // 使用文生文模型重新解析segment_content
  1983. if (!empty($segment_content)) {
  1984. $segment_content = $this->parseSegmentContentWithAI($segment_content);
  1985. }
  1986. // 获取动漫的角色信息(包含参考图)
  1987. $anime = DB::table('mp_animes')
  1988. ->where('id', $anime_id)
  1989. ->select('roles', 'scenes')
  1990. ->first();
  1991. if (!$anime || !$anime->roles) {
  1992. Utils::throwError('20003:未找到角色信息');
  1993. }
  1994. $roles = json_decode($anime->roles, true);
  1995. if (!$roles) {
  1996. Utils::throwError('20003:角色信息格式错误');
  1997. }
  1998. // 构建角色名称到参考图的映射
  1999. $role_map = [];
  2000. foreach ($roles as $role) {
  2001. $role_name = getProp($role, 'role');
  2002. $role_url = getProp($role, 'url');
  2003. if (!empty($role_name) && !empty($role_url)) {
  2004. $role_map[$role_name] = $role_url;
  2005. }
  2006. }
  2007. $scenes = json_decode($anime->scenes, true);
  2008. if (!$scenes) {
  2009. Utils::throwError('20003:角色信息格式错误');
  2010. }
  2011. // 构建角色名称到参考图的映射
  2012. $scene_map = [];
  2013. foreach ($scenes as $scene) {
  2014. $scene_name = getProp($scene, 'scene');
  2015. $scene_url = getProp($scene, 'url');
  2016. if (!empty($scene_name) && !empty($scene_url)) {
  2017. $scene_map[$scene_name] = $scene_url;
  2018. }
  2019. }
  2020. $segment_id = $segment->segment_id;
  2021. $original_segment_content = $segment->segment_content;
  2022. // 如果传入了新的segment_content,使用新的内容,否则使用原有内容
  2023. $final_segment_content = !empty($segment_content) ? $segment_content : $original_segment_content;
  2024. if (empty($final_segment_content)) {
  2025. Utils::throwError('20003:分镜内容不存在,请填写内容后重试');
  2026. }
  2027. try {
  2028. $dubTaskId = 0;
  2029. // 分镜剧本数组
  2030. $update_data = [
  2031. 'segment_content' => $final_segment_content,
  2032. 'pic_task_status' => '生成中',
  2033. 'updated_at' => date('Y-m-d H:i:s')
  2034. ];
  2035. // 解析分镜内容,提取画面描述作为主要提示词
  2036. $prompt = $final_segment_content;
  2037. $ref_img_urls = [];
  2038. // 分镜场景
  2039. $scene = getProp($data, 'scene');
  2040. if ($scene) {
  2041. $matched_scene = '';
  2042. if (isset($scene_map[$scene])) {
  2043. $img_index = count($ref_img_urls) + 1;
  2044. $prompt = "场景:$scene(图$img_index)\n$prompt";
  2045. $ref_img_urls[] = $scene_map[$scene];
  2046. $matched_scene = $scene;
  2047. }
  2048. $update_data['scene'] = $scene;
  2049. }
  2050. // 分镜角色
  2051. $characters = getProp($data, 'characters');
  2052. if ($characters) {
  2053. $update_data['characters'] = $characters;
  2054. $characters = str_replace(['、', ',', ';'], ',', $characters);
  2055. $characters = explode(',', $characters);
  2056. // 从分镜内容中提取涉及的角色
  2057. $segment_characters = $this->extractCharactersFromSegment($final_segment_content, array_keys($role_map), $characters);
  2058. // 获取匹配角色的参考图
  2059. foreach ($segment_characters as $character) {
  2060. if (isset($role_map[$character])) {
  2061. // 将$prompt中出现的角色替换成角色(图1、2、3,序号是$ref_img_urls的个数加1)
  2062. $img_index = count($ref_img_urls) + 1;
  2063. $prompt = str_replace($character, $character . '(图' . $img_index . ')', $prompt);
  2064. $ref_img_urls[] = $role_map[$character];
  2065. }
  2066. }
  2067. }
  2068. // 如果没有找到匹配的角色参考图,不使用参考图
  2069. if (empty($ref_img_urls)) {
  2070. $ref_img_urls = [];
  2071. }
  2072. // 准备生成任务参数
  2073. $params = [
  2074. 'alias_segment_id' => $segment_id,
  2075. 'prompt' => $prompt,
  2076. 'ref_img_urls' => $ref_img_urls,
  2077. 'width' => $width,
  2078. 'height' => $height,
  2079. ];
  2080. // 优化提示词(不要生成字幕)
  2081. $params['prompt'] = "前置要求:图片中不要带有任何对话台词或字幕信息\n".$params['prompt'];
  2082. // 调用AI图片生成服务
  2083. $task = $this->aiImageGenerationService->createImageGenerationTask($params);
  2084. $task_id = $task->id;
  2085. if (!$task_id) {
  2086. Utils::throwError('20003:创建生成任务失败!');
  2087. }
  2088. $update_data['pic_task_id'] = $task_id;
  2089. // 更新分镜剧本信息
  2090. $this->handleSegmentContent($update_data);
  2091. // 如果有对话内容,创建视频配音合成任务(有更改分镜内容时创建)
  2092. if ($segment_content) {
  2093. $dialogue = getProp($update_data, 'dialogue');
  2094. if (!empty($dialogue)) {
  2095. $now = date('Y-m-d H:i:s');
  2096. $generate_json = [
  2097. 'text' => $dialogue,
  2098. 'role' => getProp($update_data, 'voice_actor'),
  2099. 'voice_type' => getProp($update_data, 'voice_type'),
  2100. 'voice_name' => getProp($update_data, 'voice_name'),
  2101. 'emotion' => getProp($update_data, 'emotion'),
  2102. 'emotion_type' => getProp($update_data, 'emotion_type'),
  2103. 'gender' => getProp($update_data, 'gender'),
  2104. 'speed_ratio' => getProp($update_data, 'speed_ratio', 0),
  2105. 'loudness_ratio' => getProp($update_data, 'loudness_ratio', 0),
  2106. 'emotion_scale' => getProp($update_data, 'emotion_scale', 0),
  2107. 'pitch' => getProp($update_data, 'pitch', 0),
  2108. ];
  2109. // 插入视频配音合成任务
  2110. $dubTaskId = DB::table('mp_dub_video_tasks')->insertGetId([
  2111. 'alias_segment_id' => $segment_id,
  2112. 'generate_status' => '执行中',
  2113. 'audio_url' => '',
  2114. 'generate_json' => json_encode($generate_json, 256),
  2115. 'created_at' => date('Y-m-d H:i:s'),
  2116. 'updated_at' => date('Y-m-d H:i:s'),
  2117. ]);
  2118. if (!$dubTaskId) {
  2119. Utils::throwError('20003:创建配音任务失败!');
  2120. }
  2121. $update_data['audio_url'] = '';
  2122. } else {
  2123. // dialogue为空时,直接写入默认音频信息
  2124. $update_data['audio_url'] = 'https://zw-audiobook.tos-cn-beijing.volces.com/effects/ellipses_2s.mp3';
  2125. $update_data['audio_duration'] = 2.0;
  2126. $update_data['subtitle_info'] = json_encode(['duration' => 2.0, 'words' => []], 256);
  2127. }
  2128. }
  2129. $boolen = DB::table('mp_episode_segments')
  2130. ->where('segment_id', $segment_id)
  2131. ->update($update_data);
  2132. // 如果是第一集的首帧图片,则存入待更新数组
  2133. if ($boolen && (int)getProp($segment, 'episode_number') === 1 && (int)getProp($segment, 'segment_number') === 1) {
  2134. Redis::sadd('anime_first_frame_urls', $segment_id);
  2135. }
  2136. if ($dubTaskId) {
  2137. // 请求远程服务器执行生成
  2138. $client = new Client(['timeout' => 300, 'verify' => false]);
  2139. $result = $client->get("http://122.9.129.83:5000/api/anime/genAudio?taskId={$dubTaskId}");
  2140. $response = $result->getBody()->getContents();
  2141. $response_arr = json_decode($response, true);
  2142. if (!isset($response_arr['code']) || (int)$response_arr['code'] !== 0) {
  2143. $error_msg = isset($response_arr['msg']) ? $response_arr['msg'] : '未知错误';
  2144. dLog('anime')->error('火山生成音频失败', ['error' => $error_msg, 'task_id' => $dubTaskId]);
  2145. logDB('anime', 'error', '火山生成音频失败', ['error' => $error_msg, 'task_id' => $dubTaskId]);
  2146. Utils::throwError('20003:火山生成音频失败');
  2147. }
  2148. }
  2149. } catch (\Exception $e) {
  2150. $failed_segments[] = [
  2151. 'segment_id' => $segment_id,
  2152. 'error' => $e->getMessage()
  2153. ];
  2154. }
  2155. // 创建任务之后先暂停10s等待异步任务完成
  2156. sleep(10);
  2157. $img_url = $this->loopGetPicTaskResult($task_id);
  2158. if (!$img_url) Utils::throwError('20003:图片生成中,请稍后刷新');
  2159. // 图片生成后新增对话记录
  2160. try {
  2161. $uid = Site::getUid();
  2162. $now = date('Y-m-d H:i:s');
  2163. // 使用AI反推图片提示词
  2164. $pic_prompt = $this->generateImagePromptFromUrl($img_url);
  2165. // 保存对话记录
  2166. $records = [
  2167. [
  2168. 'uid' => $uid,
  2169. 'anime_id' => $anime_id,
  2170. 'sequence' => $episode_number,
  2171. 'role' => 'user',
  2172. 'content' => '重新生成',
  2173. 'segment_id' => $segment_id,
  2174. 'pic_task_id' => $task_id,
  2175. 'image_url' => '',
  2176. 'created_at' => $now,
  2177. 'updated_at' => $now
  2178. ],
  2179. [
  2180. 'uid' => $uid,
  2181. 'anime_id' => $anime_id,
  2182. 'sequence' => $episode_number,
  2183. 'role' => 'assistant',
  2184. 'content' => $pic_prompt,
  2185. 'segment_id' => $segment_id,
  2186. 'pic_task_id' => $task_id,
  2187. 'image_url' => $img_url,
  2188. 'created_at' => $now,
  2189. 'updated_at' => $now
  2190. ]
  2191. ];
  2192. DB::table('mp_anime_records')->insert($records);
  2193. } catch (\Exception $e) {
  2194. // 记录日志但不影响主流程
  2195. dLog('anime')->error('保存对话记录失败: ' . $e->getMessage(), [
  2196. 'segment_id' => $segment_id,
  2197. 'img_url' => $img_url
  2198. ]);
  2199. }
  2200. return $img_url;
  2201. }
  2202. public function addSegment($data) {
  2203. $prev_segment_id = getProp($data, 'prev_segment_id');
  2204. $img_url = getProp($data, 'img_url');
  2205. $video_url = getProp($data, 'video_url');
  2206. $segment = DB::table('mp_episode_segments')->where('segment_id', $prev_segment_id)->first();
  2207. if (!$segment) Utils::throwError('20003:该分镜不存在');
  2208. $anime_id = getProp($segment, 'anime_id');
  2209. $episode_id = getProp($segment, 'episode_id');
  2210. $episode_number = getProp($segment, 'episode_number');
  2211. $segment_number = getProp($segment, 'segment_number');
  2212. $new_segment_number = $segment_number + 1;
  2213. $segment_id = date('YmdHis') . mt_rand(1000, 9999) . str_pad($new_segment_number, 3, "0", STR_PAD_LEFT);
  2214. // 分镜剧本数组
  2215. $insert_data = [
  2216. 'anime_id' => $anime_id,
  2217. 'episode_id' => $episode_id,
  2218. 'episode_number' => $episode_number,
  2219. 'act_number' => getProp($segment, 'act_number'),
  2220. 'act_title' => getProp($segment, 'act_title'),
  2221. 'segment_id' => $segment_id,
  2222. 'segment_number' => $new_segment_number,
  2223. 'segment_content' => '',
  2224. 'img_url' => '',
  2225. 'video_url' => '',
  2226. 'created_at' => date('Y-m-d H:i:s'),
  2227. 'updated_at' => date('Y-m-d H:i:s')
  2228. ];
  2229. if ($img_url) $insert_data['img_url'] = $img_url;
  2230. if ($video_url) {
  2231. $insert_data['origin_video_url'] = $video_url;
  2232. $insert_data['current_type'] = 2;
  2233. $compressed_video_url = compressVideo($video_url);
  2234. $insert_data['video_url'] = $compressed_video_url ?: $video_url;
  2235. }
  2236. try {
  2237. DB::beginTransaction();
  2238. // 先更新序号
  2239. DB::table('mp_episode_segments')->where('anime_id', $anime_id)->where('episode_id', $episode_id)->where('segment_number', '>', $segment_number)->increment('segment_number');
  2240. $id = DB::table('mp_episode_segments')->insertGetId($insert_data);
  2241. if (!$id) {
  2242. Utils::throwError('20003:新增分镜失败!');
  2243. }
  2244. }catch (\Exception $e) {
  2245. DB::rollBack();
  2246. Utils::throwError('20003:'.$e->getMessage());
  2247. }
  2248. DB::commit();
  2249. $segment = DB::table('mp_episode_segments')->where('id', $id)->first();
  2250. $segment = $segment ? (array)$segment : [];
  2251. return $segment;
  2252. // 以下代码暂弃用
  2253. $anime_id = getProp($segment, 'anime_id');
  2254. $episode_id = getProp($segment, 'episode_id');
  2255. $episode_number = getProp($segment, 'episode_number');
  2256. $segment_number = getProp($segment, 'segment_number');
  2257. $segment_content = getProp($data, 'segment_content');
  2258. $img_url = getProp($data, 'img_url');
  2259. $video_url = getProp($data, 'video_url');
  2260. $ratio = getProp($data, 'ratio');
  2261. $dimensions = $this->getRatioDimensions($ratio);
  2262. $width = $dimensions['width'];
  2263. $height = $dimensions['height'];
  2264. if (!$anime_id || !$episode_id) {
  2265. Utils::throwError('1002:请选择分镜');
  2266. }
  2267. // 使用文生文模型重新解析segment_content
  2268. if (!empty($segment_content)) {
  2269. $segment_content = $this->parseSegmentContentWithAI($segment_content);
  2270. }
  2271. // 获取动漫的角色信息(包含参考图)
  2272. $anime = DB::table('mp_animes')
  2273. ->where('id', $anime_id)
  2274. ->select('roles', 'scenes')
  2275. ->first();
  2276. if (!$anime || !$anime->roles) {
  2277. Utils::throwError('20003:未找到角色信息');
  2278. }
  2279. $roles = json_decode($anime->roles, true);
  2280. if (!$roles) {
  2281. Utils::throwError('20003:角色信息格式错误');
  2282. }
  2283. // 构建角色名称到参考图的映射
  2284. $role_map = [];
  2285. foreach ($roles as $role) {
  2286. $role_name = getProp($role, 'role');
  2287. $role_url = getProp($role, 'url');
  2288. if (!empty($role_name) && !empty($role_url)) {
  2289. $role_map[$role_name] = $role_url;
  2290. }
  2291. }
  2292. $scenes = json_decode($anime->scenes, true);
  2293. if (!$scenes) {
  2294. Utils::throwError('20003:角色信息格式错误');
  2295. }
  2296. // 构建角色名称到参考图的映射
  2297. $scene_map = [];
  2298. foreach ($scenes as $scene) {
  2299. $scene_name = getProp($scene, 'scene');
  2300. $scene_url = getProp($scene, 'url');
  2301. if (!empty($scene_name) && !empty($scene_url)) {
  2302. $scene_map[$scene_name] = $scene_url;
  2303. }
  2304. }
  2305. $segment_id = $segment->segment_id;
  2306. $original_segment_content = $segment->segment_content;
  2307. // 如果传入了新的segment_content,使用新的内容,否则使用原有内容
  2308. $final_segment_content = !empty($segment_content) ? $segment_content : $original_segment_content;
  2309. if (empty($final_segment_content)) {
  2310. Utils::throwError('20003:分镜内容不存在,请填写内容后重试');
  2311. }
  2312. try {
  2313. $dubTaskId = 0;
  2314. DB::beginTransaction();
  2315. $new_segment_number = $segment_number + 1;
  2316. $segment_id = date('YmdHis') . mt_rand(1000, 9999) . str_pad($new_segment_number, 3, "0", STR_PAD_LEFT);
  2317. // 分镜剧本数组
  2318. $insert_data = [
  2319. 'anime_id' => $anime_id,
  2320. 'episode_id' => $episode_id,
  2321. 'episode_number' => $episode_number,
  2322. 'act_number' => getProp($segment, 'act_number'),
  2323. 'act_title' => getProp($segment, 'act_title'),
  2324. 'segment_id' => $segment_id,
  2325. 'segment_number' => $new_segment_number,
  2326. 'segment_content' => $final_segment_content,
  2327. 'img_url' => $img_url,
  2328. 'video_url' => $video_url,
  2329. 'created_at' => date('Y-m-d H:i:s'),
  2330. 'updated_at' => date('Y-m-d H:i:s')
  2331. ];
  2332. // 更新分镜剧本信息
  2333. $this->handleSegmentContent($insert_data);
  2334. // 如果有对话内容,创建视频配音合成任务
  2335. $dialogue = getProp($insert_data, 'dialogue');
  2336. if (!empty($dialogue)) {
  2337. $now = date('Y-m-d H:i:s');
  2338. $generate_json = [
  2339. 'text' => $dialogue,
  2340. 'role' => getProp($insert_data, 'voice_actor'),
  2341. 'voice_type' => getProp($insert_data, 'voice_type'),
  2342. 'voice_name' => getProp($insert_data, 'voice_name'),
  2343. 'emotion' => getProp($insert_data, 'emotion'),
  2344. 'emotion_type' => getProp($insert_data, 'emotion_type'),
  2345. 'gender' => getProp($insert_data, 'gender'),
  2346. 'speed_ratio' => getProp($insert_data, 'speed_ratio', 0),
  2347. 'loudness_ratio' => getProp($insert_data, 'loudness_ratio', 0),
  2348. 'emotion_scale' => getProp($insert_data, 'emotion_scale', 0),
  2349. 'pitch' => getProp($insert_data, 'pitch', 0),
  2350. ];
  2351. // 插入视频配音合成任务
  2352. $dubTaskId = DB::table('mp_dub_video_tasks')->insertGetId([
  2353. 'alias_segment_id' => $segment_id,
  2354. 'generate_status' => '执行中',
  2355. 'audio_url' => '',
  2356. 'generate_json' => json_encode($generate_json, 256),
  2357. 'created_at' => $now,
  2358. 'updated_at' => $now,
  2359. ]);
  2360. if (!$dubTaskId) {
  2361. Utils::throwError('20003:创建配音任务失败!');
  2362. }
  2363. $insert_data['audio_url'] = '';
  2364. } else {
  2365. // dialogue为空时,直接写入默认音频信息
  2366. $insert_data['audio_url'] = 'https://zw-audiobook.tos-cn-beijing.volces.com/effects/ellipses_2s.mp3';
  2367. $insert_data['audio_duration'] = 2.0;
  2368. $insert_data['subtitle_info'] = json_encode(['duration' => 2.0, 'words' => []], 256);
  2369. }
  2370. // 如果没有上传图片则使用当前描述进行生成
  2371. if (!$img_url) {
  2372. // 解析分镜内容,提取画面描述作为主要提示词
  2373. $prompt = $final_segment_content;
  2374. $ref_img_urls = [];
  2375. // 分镜场景
  2376. $scene = getProp($insert_data, 'scene');
  2377. if ($scene) {
  2378. $matched_scene = '';
  2379. if (isset($scene_map[$scene])) {
  2380. $img_index = count($ref_img_urls) + 1;
  2381. $prompt = "场景:$scene(图$img_index)\n$prompt";
  2382. $ref_img_urls[] = $scene_map[$scene];
  2383. $matched_scene = $scene;
  2384. }
  2385. $update_data['scene'] = $scene;
  2386. }
  2387. // 分镜角色
  2388. $characters = getProp($insert_data, 'characters');
  2389. if ($characters) {
  2390. $update_data['characters'] = $characters;
  2391. $characters = str_replace(['、', ',', ';'], ',', $characters);
  2392. $characters = explode(',', $characters);
  2393. // 从分镜内容中提取涉及的角色
  2394. $segment_characters = $this->extractCharactersFromSegment($final_segment_content, array_keys($role_map), $characters);
  2395. // 获取匹配角色的参考图
  2396. foreach ($segment_characters as $character) {
  2397. if (isset($role_map[$character])) {
  2398. // 将$prompt中出现的角色替换成角色(图1、2、3,序号是$ref_img_urls的个数加1)
  2399. $img_index = count($ref_img_urls) + 1;
  2400. $prompt = str_replace($character, $character . '(图' . $img_index . ')', $prompt);
  2401. $ref_img_urls[] = $role_map[$character];
  2402. }
  2403. }
  2404. }
  2405. // 如果没有找到匹配的角色参考图,不使用参考图
  2406. if (empty($ref_img_urls)) {
  2407. $ref_img_urls = [];
  2408. }
  2409. // 准备生成任务参数
  2410. $params = [
  2411. 'alias_segment_id' => $segment_id,
  2412. 'prompt' => $prompt,
  2413. 'ref_img_urls' => $ref_img_urls,
  2414. 'width' => $width,
  2415. 'height' => $height,
  2416. ];
  2417. // 调用AI图片生成服务
  2418. $task = $this->aiImageGenerationService->createImageGenerationTask($params);
  2419. $task_id = $task->id;
  2420. // $task_id = 'whatever';
  2421. if (!$task_id) {
  2422. Utils::throwError('20003:创建生成任务失败!');
  2423. }
  2424. $insert_data['pic_task_status'] = '生成中';
  2425. $insert_data['pic_task_id'] = $task_id;
  2426. }
  2427. // 先更新序号
  2428. DB::table('mp_episode_segments')->where('anime_id', $anime_id)->where('episode_id', $episode_id)->where('segment_number', '>', $segment_number)->increment('segment_number');
  2429. $boolen = DB::table('mp_episode_segments')->insert($insert_data);
  2430. if (!$boolen) {
  2431. Utils::throwError('20003:新增分镜失败!');
  2432. }
  2433. // 如果是第一集的首帧图片,则存入待更新数组
  2434. if ($boolen && (int)$episode_number === 1 && (int)$new_segment_number === 1) {
  2435. Redis::sadd('anime_first_frame_urls', $segment_id);
  2436. }
  2437. if ($dubTaskId) {
  2438. // 请求远程服务器执行生成
  2439. $client = new Client(['timeout' => 300, 'verify' => false]);
  2440. $result = $client->get("http://122.9.129.83:5000/api/anime/genAudio?taskId={$dubTaskId}");
  2441. $response = $result->getBody()->getContents();
  2442. $response_arr = json_decode($response, true);
  2443. if (!isset($response_arr['code']) || (int)$response_arr['code'] !== 0) {
  2444. $error_msg = isset($response_arr['msg']) ? $response_arr['msg'] : '未知错误';
  2445. dLog('anime')->error('火山生成音频失败', ['error' => $error_msg, 'task_id' => $dubTaskId]);
  2446. Utils::throwError('20003:火山生成音频失败');
  2447. }
  2448. }
  2449. } catch (\Exception $e) {
  2450. DB::rollBack();
  2451. Utils::throwError('20003:'.$e->getMessage());
  2452. }
  2453. DB::commit();
  2454. // 创建任务之后先暂停10s等待异步任务完成
  2455. sleep(10);
  2456. if (isset($task_id)) $img_url = $this->loopGetPicTaskResult($task_id);
  2457. if (!$img_url) Utils::throwError('20003:图片生成中,请稍后刷新');
  2458. $segment = DB::table('mp_episode_segments')->where('segment_id', $segment_id)->first();
  2459. $segment = $segment ? (array)$segment : [];
  2460. return $segment;
  2461. }
  2462. public function copySegment($data) {
  2463. $segment_id = getProp($data, 'segment_id');
  2464. $segment = DB::table('mp_episode_segments')->where('segment_id', $segment_id)->first();
  2465. if (!$segment) Utils::throwError('20003:请选择分镜');
  2466. $anime_id = getProp($segment, 'anime_id');
  2467. $episode_id = getProp($segment, 'episode_id');
  2468. $episode_number = getProp($segment, 'episode_number');
  2469. $segment_number = getProp($segment, 'segment_number');
  2470. $new_segment_id = 0;
  2471. try {
  2472. DB::beginTransaction();
  2473. $segment = (array)$segment;
  2474. unset($segment['id']);
  2475. $segment['segment_number'] += 1;
  2476. $segment['segment_id'] = date('YmdHis') . mt_rand(1000, 9999) . str_pad($segment['segment_number'], 3, "0", STR_PAD_LEFT);
  2477. // $segment['pic_task_id'] = $segment['pic_task_status'] = $segment['video_task_id'] = $segment['video_task_status'] = '';
  2478. $segment['created_at'] = $segment['updated_at'] = date('Y-m-d H:i:s');
  2479. // 更新其他分镜序号
  2480. DB::table('mp_episode_segments')->where('anime_id', $anime_id)->where('episode_id', $episode_id)->where('segment_number', '>', $segment_number)->increment('segment_number');
  2481. // 复制分镜
  2482. $id = DB::table('mp_episode_segments')->insertGetId($segment);
  2483. if (!$id) {
  2484. Utils::throwError('20003:复制分镜失败');
  2485. }
  2486. }catch (\Exception $e) {
  2487. DB::rollBack();
  2488. Utils::throwError('20003:'.$e->getMessage());
  2489. }
  2490. DB::commit();
  2491. $segment = DB::table('mp_episode_segments')->where('id', $id)->first();
  2492. $segment = $segment ? (array)$segment : [];
  2493. return $segment;
  2494. }
  2495. public function moveSegment($data) {
  2496. $segment_id = getProp($data, 'segment_id');
  2497. $target_segment_id = getProp($data, 'target_segment_id');
  2498. // 获取源分镜信息
  2499. $source_segment = DB::table('mp_episode_segments')->where('segment_id', $segment_id)->first();
  2500. if (!$source_segment) Utils::throwError('20003:请选择分镜');
  2501. // 获取目标分镜信息
  2502. $target_segment = DB::table('mp_episode_segments')->where('segment_id', $target_segment_id)->first();
  2503. if (!$target_segment) Utils::throwError('20003:目标分镜不存在');
  2504. $anime_id = getProp($source_segment, 'anime_id');
  2505. $episode_id = getProp($source_segment, 'episode_id');
  2506. $episode_number = getProp($source_segment, 'episode_number');
  2507. $source_segment_number = getProp($source_segment, 'segment_number');
  2508. $target_segment_number = getProp($target_segment, 'segment_number');
  2509. // 验证源分镜和目标分镜必须属于同一个动漫的同一集
  2510. $target_anime_id = getProp($target_segment, 'anime_id');
  2511. $target_episode_number = getProp($target_segment, 'episode_number');
  2512. if ($anime_id != $target_anime_id || $episode_number != $target_episode_number) {
  2513. Utils::throwError('20003:只能在同一动漫的同一集内移动分镜');
  2514. }
  2515. // 如果源分镜和目标分镜相同,无需移动
  2516. if ($source_segment_number == $target_segment_number) {
  2517. return true;
  2518. }
  2519. try {
  2520. DB::beginTransaction();
  2521. if ($source_segment_number < $target_segment_number) {
  2522. // 向后移动:源分镜移动到目标分镜之后
  2523. // 1. 将源分镜和目标分镜之间的所有分镜序号减1
  2524. DB::table('mp_episode_segments')
  2525. ->where('anime_id', $anime_id)
  2526. ->where('episode_id', $episode_id)
  2527. ->where('segment_number', '>', $source_segment_number)
  2528. ->where('segment_number', '<=', $target_segment_number)
  2529. ->decrement('segment_number');
  2530. // 2. 将源分镜移动到目标分镜之后
  2531. $new_segment_number = $target_segment_number;
  2532. } else {
  2533. // 向前移动:源分镜移动到目标分镜之后
  2534. // 1. 将目标分镜之后到源分镜之前的所有分镜序号加1
  2535. DB::table('mp_episode_segments')
  2536. ->where('anime_id', $anime_id)
  2537. ->where('episode_id', $episode_id)
  2538. ->where('segment_number', '>', $target_segment_number)
  2539. ->where('segment_number', '<', $source_segment_number)
  2540. ->increment('segment_number');
  2541. // 2. 将源分镜移动到目标分镜之后
  2542. $new_segment_number = $target_segment_number + 1;
  2543. }
  2544. // 3. 更新源分镜的序号
  2545. $update_result = DB::table('mp_episode_segments')
  2546. ->where('segment_id', $segment_id)
  2547. ->update([
  2548. 'segment_number' => $new_segment_number,
  2549. 'updated_at' => date('Y-m-d H:i:s')
  2550. ]);
  2551. if (!$update_result) {
  2552. Utils::throwError('20003:更新分镜序号失败');
  2553. }
  2554. DB::commit();
  2555. return true;
  2556. } catch (\Exception $e) {
  2557. DB::rollBack();
  2558. Utils::throwError('20003:' . $e->getMessage());
  2559. }
  2560. }
  2561. public function delSegment($data) {
  2562. $segment_id = getProp($data, 'segment_id');
  2563. $segment = DB::table('mp_episode_segments')->where('segment_id', $segment_id)->first();
  2564. if (!$segment) Utils::throwError('20003:请选择分镜');
  2565. $anime_id = getProp($segment, 'anime_id');
  2566. $episode_id = getProp($segment, 'episode_id');
  2567. $episode_number = getProp($segment, 'episode_number');
  2568. $segment_number = getProp($segment, 'segment_number');
  2569. try {
  2570. DB::beginTransaction();
  2571. // 删除分镜
  2572. $boolen = DB::table('mp_episode_segments')->where('segment_id', $segment_id)->delete();
  2573. if (!$boolen) {
  2574. Utils::throwError('20003:删除分镜失败');
  2575. }
  2576. // 更新其他分镜序号
  2577. DB::table('mp_episode_segments')->where('anime_id', $anime_id)->where('episode_id', $episode_id)->where('segment_number', '>', $segment_number)->decrement('segment_number');
  2578. }catch (\Exception $e) {
  2579. DB::rollBack();
  2580. Utils::throwError('20003:'.$e->getMessage());
  2581. }
  2582. DB::commit();
  2583. return true;
  2584. }
  2585. public function applySegment($data) {
  2586. $segment_id = getProp($data, 'segment_id');
  2587. $url = getProp($data, 'url');
  2588. if (!$segment_id) Utils::throwError('20003:请选择分镜');
  2589. if (!$url) Utils::throwError('20003:URL不能为空');
  2590. // 获取URL的文件扩展名
  2591. $urlPath = parse_url($url, PHP_URL_PATH);
  2592. $extension = strtolower(pathinfo($urlPath, PATHINFO_EXTENSION));
  2593. // 定义图片和视频的扩展名
  2594. $imageExtensions = ['jpg', 'jpeg', 'png', 'gif', 'bmp', 'webp', 'svg'];
  2595. $videoExtensions = ['mp4', 'avi', 'mov', 'wmv', 'flv', 'mkv', 'webm', 'm4v'];
  2596. // 判断是图片还是视频
  2597. $updateData = ['updated_at' => date('Y-m-d H:i:s')];
  2598. if (in_array($extension, $imageExtensions)) {
  2599. // 图片类型
  2600. $updateData['img_url'] = $url;
  2601. $updateData['current_type'] = 1;
  2602. } elseif (in_array($extension, $videoExtensions)) {
  2603. // 视频类型
  2604. $updateData['video_url'] = $url;
  2605. $updateData['current_type'] = 2;
  2606. } else {
  2607. Utils::throwError('20003:不支持的文件类型');
  2608. }
  2609. // 更新分镜表
  2610. $result = DB::table('mp_episode_segments')
  2611. ->where('segment_id', $segment_id)
  2612. ->update($updateData);
  2613. if (!$result) {
  2614. Utils::throwError('20003:更新分镜失败');
  2615. }
  2616. return true;
  2617. }
  2618. public function segmentHistory($data) {
  2619. $segment_id = getProp($data, 'segment_id');
  2620. // 获取历史图片
  2621. $pics = [];
  2622. $pic_history = DB::table('mp_generate_pic_tasks')->where('alias_segment_id', $segment_id)->where('status', 'success')->orderBy('created_at', 'desc')->get();
  2623. foreach($pic_history as $task) {
  2624. $result_url = getProp($task, 'result_url');
  2625. if (is_json($result_url)) {
  2626. $pics = array_merge($pics, json_decode($result_url, true));
  2627. }else {
  2628. $pics[] = $result_url;
  2629. }
  2630. }
  2631. // 获取历史视频
  2632. $videos = [];
  2633. $video_history = DB::table('mp_generate_video_tasks')->where('alias_segment_id', $segment_id)->where('status', 'success')->orderBy('created_at', 'desc')->get();
  2634. foreach($video_history as $task) {
  2635. $result_url = getProp($task, 'result_url');
  2636. if (is_json($result_url)) {
  2637. $videos = array_merge($videos, json_decode($result_url, true));
  2638. }else {
  2639. $videos[] = $result_url;
  2640. }
  2641. }
  2642. return compact('pics', 'videos');
  2643. }
  2644. public function addAct($data) {
  2645. $prev_act_id = getProp($data, 'prev_act_id');
  2646. $act_title = getProp($data, 'act_title', '');
  2647. $act_content = getProp($data, 'act_content', '');
  2648. $act_duration = getProp($data, 'act_duration', 5);
  2649. $video_url = getProp($data, 'video_url');
  2650. // 根据prev_act_id获取记录
  2651. $prev_segment = DB::table('mp_episode_segments')->where('id', $prev_act_id)->first();
  2652. if (!$prev_segment) Utils::throwError('20003:该片段不存在');
  2653. $anime_id = getProp($prev_segment, 'anime_id');
  2654. $episode_id = getProp($prev_segment, 'episode_id');
  2655. $episode_number = getProp($prev_segment, 'episode_number');
  2656. $prev_act_number = getProp($prev_segment, 'act_number');
  2657. // 获取新的act_number
  2658. $new_act_number = $prev_act_number + 1;
  2659. try {
  2660. DB::beginTransaction();
  2661. // 更新后续所有act的act_number(全能模式下每个act只有一条记录)
  2662. DB::table('mp_episode_segments')
  2663. ->where('anime_id', $anime_id)
  2664. ->where('episode_id', $episode_id)
  2665. ->where('act_number', '>', $prev_act_number)
  2666. ->increment('act_number');
  2667. // 插入新片段记录
  2668. $insert_data = [
  2669. 'anime_id' => $anime_id,
  2670. 'episode_id' => $episode_id,
  2671. 'episode_number' => $episode_number,
  2672. 'act_number' => $new_act_number,
  2673. 'created_at' => date('Y-m-d H:i:s'),
  2674. 'updated_at' => date('Y-m-d H:i:s')
  2675. ];
  2676. if ($act_title) {
  2677. $insert_data['act_title'] = $act_title;
  2678. }
  2679. if ($act_content) {
  2680. $insert_data['act_content'] = $act_content;
  2681. }
  2682. if ($act_duration) {
  2683. $insert_data['act_duration'] = $act_duration;
  2684. }
  2685. if ($video_url) {
  2686. $insert_data['origin_video_url'] = $video_url;
  2687. $insert_data['current_type'] = 2;
  2688. $compressed_video_url = compressVideo($video_url);
  2689. $insert_data['video_url'] = $compressed_video_url ?: $video_url;
  2690. }
  2691. $id = DB::table('mp_episode_segments')->insertGetId($insert_data);
  2692. if (!$id) {
  2693. Utils::throwError('20003:新增片段失败!');
  2694. }
  2695. DB::commit();
  2696. }catch (\Exception $e) {
  2697. DB::rollBack();
  2698. Utils::throwError('20003:'.$e->getMessage());
  2699. }
  2700. $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();
  2701. $segment = $segment ? (array)$segment : [];
  2702. return $segment;
  2703. }
  2704. public function editAct($data) {
  2705. $act_id = getProp($data, 'act_id');
  2706. $act_content = getProp($data, 'act_content');
  2707. $act_duration = getProp($data, 'act_duration');
  2708. $act_title = getProp($data, 'act_title');
  2709. $image_url = getProp($data, 'image_url');
  2710. $video_url = getProp($data, 'video_url');
  2711. // 参数验证
  2712. if (!$act_id) Utils::throwError('20003:请提供片段ID');
  2713. // 验证片段是否存在(全能模式下每个act只有一条记录)
  2714. $segment = DB::table('mp_episode_segments')
  2715. ->where('id', $act_id)
  2716. ->first();
  2717. if (!$segment) Utils::throwError('20003:该片段不存在');
  2718. try {
  2719. DB::beginTransaction();
  2720. // 准备更新数据
  2721. $update_data = [
  2722. 'updated_at' => date('Y-m-d H:i:s')
  2723. ];
  2724. // 更新act相关字段
  2725. if (!empty($act_content)) {
  2726. $update_data['act_show_content'] = $act_content;
  2727. $update_data['act_content'] = str_replace(["@", "{", "}"], "", $act_content);
  2728. // 处理【镜头X】或【分镜X】重新编号为从1开始的连续整数【镜头X】
  2729. $shot_counter = 0;
  2730. $update_data['act_show_content'] = preg_replace_callback(
  2731. '/【(?:镜头|分镜)(\d+)】/u',
  2732. function($matches) use (&$shot_counter) {
  2733. $shot_counter++;
  2734. return '【镜头' . $shot_counter . '】';
  2735. },
  2736. $update_data['act_show_content']
  2737. );
  2738. }
  2739. if (!empty($act_duration)) {
  2740. $update_data['act_duration'] = $act_duration;
  2741. }
  2742. if (!empty($act_title)) {
  2743. $update_data['act_title'] = $act_title;
  2744. }
  2745. // 处理图片上传
  2746. if ($image_url) {
  2747. $update_data['img_url'] = $image_url;
  2748. $update_data['current_type'] = 1;
  2749. // 同时写入一个图片生成任务记录
  2750. if ($act_id) {
  2751. $pic_task = [
  2752. 'alias_act_id' => $act_id,
  2753. 'ref_img_url' => json_encode([]),
  2754. 'status' => 'success',
  2755. 'result_url' => json_encode([$image_url], 256),
  2756. 'model' => '',
  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_pic_tasks')->insert($pic_task);
  2761. }
  2762. }
  2763. // 处理视频上传
  2764. if ($video_url) {
  2765. $update_data['origin_video_url'] = $video_url;
  2766. $compressed_video_url = compressVideo($video_url);
  2767. $update_data['current_type'] = 2;
  2768. $update_data['video_url'] = $compressed_video_url ?: $video_url;
  2769. // 同时写入一个视频生成任务记录
  2770. if ($act_id) {
  2771. $video_task = [
  2772. 'alias_act_id' => $act_id,
  2773. 'status' => 'success',
  2774. 'result_url' => $update_data['origin_video_url'],
  2775. 'compressed_url' => $update_data['video_url'],
  2776. 'created_at' => date('Y-m-d H:i:s'),
  2777. 'updated_at' => date('Y-m-d H:i:s'),
  2778. ];
  2779. DB::table('mp_generate_video_tasks')->insert($video_task);
  2780. }
  2781. }
  2782. // 更新片段信息
  2783. $result = DB::table('mp_episode_segments')
  2784. ->where('id', $act_id)
  2785. ->update($update_data);
  2786. if ($result === false) {
  2787. Utils::throwError('20003:更新片段失败');
  2788. }
  2789. DB::commit();
  2790. // 返回新复制的记录
  2791. $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();
  2792. $new_segment = (array)$new_segment;
  2793. return $new_segment;
  2794. } catch (\Exception $e) {
  2795. DB::rollBack();
  2796. dLog('anime')->error('更新片段失败', [
  2797. 'act_id' => $act_id,
  2798. 'error' => $e->getMessage()
  2799. ]);
  2800. Utils::throwError('20003:更新片段失败 ' . $e->getMessage());
  2801. }
  2802. }
  2803. public function copyAct($data) {
  2804. $act_id = getProp($data, 'act_id');
  2805. // 根据act_id获取记录(全能模式下每个act只有一条记录)
  2806. $source_segment = DB::table('mp_episode_segments')->where('id', $act_id)->first();
  2807. if (!$source_segment) Utils::throwError('20003:请选择片段');
  2808. $anime_id = getProp($source_segment, 'anime_id');
  2809. $episode_id = getProp($source_segment, 'episode_id');
  2810. $episode_number = getProp($source_segment, 'episode_number');
  2811. $act_number = getProp($source_segment, 'act_number');
  2812. try {
  2813. DB::beginTransaction();
  2814. // 新act的编号
  2815. $new_act_number = $act_number + 1;
  2816. // 更新后续所有act的act_number
  2817. DB::table('mp_episode_segments')
  2818. ->where('anime_id', $anime_id)
  2819. ->where('episode_id', $episode_id)
  2820. ->where('act_number', '>', $act_number)
  2821. ->increment('act_number');
  2822. // 复制该片段记录
  2823. $segment_data = (array)$source_segment;
  2824. unset($segment_data['id']);
  2825. $segment_data['video_url'] = '';
  2826. $segment_data['video_task_id'] = '';
  2827. $segment_data['video_task_status'] = '';
  2828. $segment_data['act_number'] = $new_act_number;
  2829. $segment_data['created_at'] = $segment_data['updated_at'] = date('Y-m-d H:i:s');
  2830. $id = DB::table('mp_episode_segments')->insertGetId($segment_data);
  2831. if (!$id) {
  2832. Utils::throwError('20003:复制片段失败');
  2833. }
  2834. DB::commit();
  2835. }catch (\Exception $e) {
  2836. DB::rollBack();
  2837. Utils::throwError('20003:'.$e->getMessage());
  2838. }
  2839. // 返回新复制的记录
  2840. $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();
  2841. $new_segment = $new_segment ? (array)$new_segment : [];
  2842. $new_segment['act_id'] = $id;
  2843. return $new_segment;
  2844. }
  2845. public function moveAct($data) {
  2846. $act_id = getProp($data, 'act_id');
  2847. $target_act_id = getProp($data, 'target_act_id');
  2848. // 获取源片段信息
  2849. $source_segment = DB::table('mp_episode_segments')->where('id', $act_id)->first();
  2850. if (!$source_segment) Utils::throwError('20003:请选择片段');
  2851. // 获取目标片段信息
  2852. $target_segment = DB::table('mp_episode_segments')->where('id', $target_act_id)->first();
  2853. if (!$target_segment) Utils::throwError('20003:目标片段不存在');
  2854. $anime_id = getProp($source_segment, 'anime_id');
  2855. $episode_id = getProp($source_segment, 'episode_id');
  2856. $source_act_number = getProp($source_segment, 'act_number');
  2857. $target_act_number = getProp($target_segment, 'act_number');
  2858. // 验证源片段和目标片段必须属于同一个动漫的同一集
  2859. $target_anime_id = getProp($target_segment, 'anime_id');
  2860. $target_episode_id = getProp($target_segment, 'episode_id');
  2861. if ($anime_id != $target_anime_id || $episode_id != $target_episode_id) {
  2862. Utils::throwError('20003:只能在同一动漫的同一集内移动片段');
  2863. }
  2864. // 如果源片段和目标片段相同,无需移动
  2865. if ($source_act_number == $target_act_number) {
  2866. return true;
  2867. }
  2868. try {
  2869. DB::beginTransaction();
  2870. if ($source_act_number < $target_act_number) {
  2871. // 向后移动:源片段移动到目标片段之后
  2872. // 1. 将源片段和目标片段之间的所有片段编号减1
  2873. DB::table('mp_episode_segments')
  2874. ->where('anime_id', $anime_id)
  2875. ->where('episode_id', $episode_id)
  2876. ->where('act_number', '>', $source_act_number)
  2877. ->where('act_number', '<=', $target_act_number)
  2878. ->decrement('act_number');
  2879. // 2. 将源片段移动到目标片段之后
  2880. $new_act_number = $target_act_number;
  2881. } else {
  2882. // 向前移动:源片段移动到目标片段之后
  2883. // 1. 将目标片段之后到源片段之前的所有片段编号加1
  2884. DB::table('mp_episode_segments')
  2885. ->where('anime_id', $anime_id)
  2886. ->where('episode_id', $episode_id)
  2887. ->where('act_number', '>', $target_act_number)
  2888. ->where('act_number', '<', $source_act_number)
  2889. ->increment('act_number');
  2890. // 2. 将源片段移动到目标片段之后
  2891. $new_act_number = $target_act_number + 1;
  2892. }
  2893. // 3. 更新源片段的编号
  2894. $update_result = DB::table('mp_episode_segments')
  2895. ->where('id', $act_id)
  2896. ->update([
  2897. 'act_number' => $new_act_number,
  2898. 'updated_at' => date('Y-m-d H:i:s')
  2899. ]);
  2900. if (!$update_result) {
  2901. Utils::throwError('20003:更新片段编号失败');
  2902. }
  2903. DB::commit();
  2904. return true;
  2905. } catch (\Exception $e) {
  2906. DB::rollBack();
  2907. Utils::throwError('20003:' . $e->getMessage());
  2908. }
  2909. }
  2910. public function delAct($data) {
  2911. $act_id = getProp($data, 'act_id');
  2912. // 根据act_id获取记录(全能模式下每个act只有一条记录)
  2913. $segment = DB::table('mp_episode_segments')->where('id', $act_id)->first();
  2914. if (!$segment) Utils::throwError('20003:请选择片段');
  2915. $anime_id = getProp($segment, 'anime_id');
  2916. $episode_id = getProp($segment, 'episode_id');
  2917. $act_number = getProp($segment, 'act_number');
  2918. try {
  2919. DB::beginTransaction();
  2920. // 删除该片段记录
  2921. $deleted = DB::table('mp_episode_segments')->where('id', $act_id)->delete();
  2922. if (!$deleted) {
  2923. Utils::throwError('20003:删除片段失败');
  2924. }
  2925. // 更新后续act的编号
  2926. DB::table('mp_episode_segments')
  2927. ->where('anime_id', $anime_id)
  2928. ->where('episode_id', $episode_id)
  2929. ->where('act_number', '>', $act_number)
  2930. ->decrement('act_number');
  2931. DB::commit();
  2932. }catch (\Exception $e) {
  2933. DB::rollBack();
  2934. Utils::throwError('20003:'.$e->getMessage());
  2935. }
  2936. return true;
  2937. }
  2938. public function applyAct($data) {
  2939. $act_id = getProp($data, 'act_id');
  2940. $url = getProp($data, 'url');
  2941. if (!$act_id) Utils::throwError('20003:请选择片段');
  2942. if (!$url) Utils::throwError('20003:URL不能为空');
  2943. // 获取URL的文件扩展名
  2944. $urlPath = parse_url($url, PHP_URL_PATH);
  2945. $extension = strtolower(pathinfo($urlPath, PATHINFO_EXTENSION));
  2946. // 定义图片和视频的扩展名
  2947. $imageExtensions = ['jpg', 'jpeg', 'png', 'gif', 'bmp', 'webp', 'svg'];
  2948. $videoExtensions = ['mp4', 'avi', 'mov', 'wmv', 'flv', 'mkv', 'webm', 'm4v'];
  2949. // 判断是图片还是视频
  2950. $updateData = ['updated_at' => date('Y-m-d H:i:s')];
  2951. if (in_array($extension, $imageExtensions)) {
  2952. // 图片类型
  2953. $updateData['img_url'] = $url;
  2954. $updateData['current_type'] = 1;
  2955. } elseif (in_array($extension, $videoExtensions)) {
  2956. // 视频类型
  2957. $updateData['video_url'] = $url;
  2958. $updateData['current_type'] = 2;
  2959. } else {
  2960. Utils::throwError('20003:不支持的文件类型');
  2961. }
  2962. // 更新片段记录(全能模式下每个act只有一条记录)
  2963. $result = DB::table('mp_episode_segments')
  2964. ->where('id', $act_id)
  2965. ->update($updateData);
  2966. if (!$result) {
  2967. Utils::throwError('20003:更新片段失败');
  2968. }
  2969. return true;
  2970. }
  2971. public function actChatHistory($data) {
  2972. $act_id = getProp($data, 'act_id');
  2973. if (!$act_id) Utils::throwError('20003:请选择片段!');
  2974. $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');
  2975. $chat = $query->orderBy('id')->get()->map(function ($value) {
  2976. $value = (array)$value;
  2977. $value['created_at'] = transDate($value['created_at']);
  2978. if ($value['reference_images']) $value['reference_images'] = json_decode($value['reference_images'], 256);
  2979. else $value['reference_images'] = [];
  2980. return $value;
  2981. })->toArray();
  2982. // 获取历史图片
  2983. $url = [];
  2984. $pic_history = DB::table('mp_generate_pic_tasks')->where('alias_act_id', $act_id)->where('status', 'success')->orderBy('created_at', 'desc')->get();
  2985. foreach($pic_history as $task) {
  2986. $result_url = getProp($task, 'result_url');
  2987. if (is_json($result_url)) {
  2988. $url = array_merge($url, json_decode($result_url, true));
  2989. }else {
  2990. $url[] = $result_url;
  2991. }
  2992. }
  2993. // 获取历史视频
  2994. $video_history = DB::table('mp_generate_video_tasks')->where('alias_act_id', $act_id)->where('status', 'success')->orderBy('created_at', 'desc')->get();
  2995. foreach($video_history as $task) {
  2996. $result_url = getProp($task, 'result_url');
  2997. if (is_json($result_url)) {
  2998. $url = array_merge($url, json_decode($result_url, true));
  2999. }else {
  3000. $url[] = $result_url;
  3001. }
  3002. }
  3003. // 获取资产库
  3004. $products = [];
  3005. // 通过act_id查询片段信息获取episode_id
  3006. $segment = DB::table('mp_episode_segments')->where('id', $act_id)->first();
  3007. if ($segment) {
  3008. $episode_id = getProp($segment, 'episode_id');
  3009. // 查询剧集信息获取roles、scenes和extra_products
  3010. $episode = DB::table('mp_anime_episodes')->where('id', $episode_id)->first();
  3011. if ($episode) {
  3012. $roles = json_decode(getProp($episode, 'roles', '[]'), true) ?: [];
  3013. $scenes = json_decode(getProp($episode, 'scenes', '[]'), true) ?: [];
  3014. $props = json_decode(getProp($episode, 'props', '[]'), true) ?: [];
  3015. $extra_products = json_decode(getProp($episode, 'extra_products', '[]'), true) ?: [];
  3016. // 先合并roles、scenes和props
  3017. // 处理角色数组
  3018. foreach ($roles as $role) {
  3019. $product = $role;
  3020. // 将role字段重命名为product_name
  3021. if (is_array($product) && !empty($product['role'] ?? null)) {
  3022. $product['product_name'] = $product['role'];
  3023. unset($product['role']);
  3024. $product['product'] = 1; // 标记类型为角色
  3025. $products[$product['product_name']] = $product; // 使用product_name作为key便于后续覆盖
  3026. }
  3027. }
  3028. // 处理场景数组
  3029. foreach ($scenes as $scene) {
  3030. $product = $scene;
  3031. // 将scene字段重命名为product_name
  3032. if (is_array($product) && !empty($product['scene'] ?? null)) {
  3033. $product['product_name'] = $product['scene'];
  3034. unset($product['scene']);
  3035. $product['product'] = 2; // 标记类型为场景
  3036. $products[$product['product_name']] = $product; // 使用product_name作为key便于后续覆盖
  3037. }
  3038. }
  3039. // 处理道具数组
  3040. foreach ($props as $prop) {
  3041. $product = $prop;
  3042. // 将prop字段重命名为product_name
  3043. if (is_array($product) && !empty($product['prop'] ?? null)) {
  3044. $product['product_name'] = $product['prop'];
  3045. unset($product['prop']);
  3046. $product['product'] = 3; // 标记类型为道具
  3047. $products[$product['product_name']] = $product; // 使用product_name作为key便于后续覆盖
  3048. }
  3049. }
  3050. // extra_products优先级更高,直接覆盖同名的roles和scenes
  3051. foreach ($extra_products as $extra_product) {
  3052. $product_name = getProp($extra_product, 'product_name');
  3053. if ($product_name) {
  3054. $products[$product_name] = $extra_product; // 覆盖同名数据
  3055. }
  3056. }
  3057. // 重新索引数组(去除key)
  3058. $products = array_values($products);
  3059. }
  3060. }
  3061. // 获取执行中的任务
  3062. $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) {
  3063. $value = (array)$value;
  3064. if ($value['ref_image_url']) $value['ref_image_url'] = json_decode($value['ref_image_url'], true);
  3065. else $value['ref_image_url'] = [];
  3066. $value['status'] = $value['status'] == 'pending' ? '视频待生成' : '视频生成中';
  3067. // 处理prompt:删除人物音色部分,保留【镜头】开始的内容,并去掉<图片X>标记
  3068. if (!empty($value['prompt'])) {
  3069. $prompt = $value['prompt'];
  3070. // 查找第一个【镜头】的位置
  3071. if (preg_match('/【镜头\d+】/u', $prompt, $matches, PREG_OFFSET_CAPTURE)) {
  3072. // 从【镜头】开始截取
  3073. $prompt = substr($prompt, $matches[0][1]);
  3074. }
  3075. // 去除所有<图片X>格式的标记(X可以是任意数字)
  3076. $prompt = preg_replace('/<图片\d+>/u', '', $prompt);
  3077. $value['prompt'] = $prompt;
  3078. }
  3079. return $value;
  3080. })->toArray();
  3081. return compact('chat', 'url', 'products', 'tasks');
  3082. }
  3083. public function applyAudioData($data) {
  3084. $segment_id = getProp($data, 'segment_id');
  3085. $global_data = getProp($data, 'global_data');
  3086. $segment_data = getProp($data, 'segment_data');
  3087. if (!$segment_id) Utils::throwError('20003:请选择分镜');
  3088. $global_data = is_array($global_data) ? $global_data : [];
  3089. $segment_data = is_array($segment_data) ? $segment_data : [];
  3090. // dialogue只能在segment_data中,如果在global_data中则移到segment_data
  3091. $dialogue_item = null;
  3092. foreach ($global_data as $key => $item) {
  3093. if (trim((string)getProp($item, 'name')) === 'dialogue') {
  3094. $dialogue_item = $item;
  3095. unset($global_data[$key]);
  3096. break;
  3097. }
  3098. }
  3099. if ($dialogue_item) {
  3100. $segment_data[] = $dialogue_item;
  3101. }
  3102. // 特殊参数: audio_url,audio_duration,subtitle_info
  3103. // 这些特殊参数必须同时存在才对当前分镜有效,直接保存但不创建音频任务
  3104. // 如果不是全部存在,则仍需创建音频任务
  3105. $special_fields = ['audio_url', 'audio_duration', 'subtitle_info'];
  3106. $special_update_data = [];
  3107. $has_all_special_params = false;
  3108. // 从segment_data中提取特殊参数
  3109. $filtered_segment_data = [];
  3110. foreach ($segment_data as $item) {
  3111. $field_name = trim((string)getProp($item, 'name'));
  3112. if (in_array($field_name, $special_fields)) {
  3113. $special_update_data[$field_name] = getProp($item, 'value');
  3114. } else {
  3115. // 非特殊参数保留,继续后续处理
  3116. $filtered_segment_data[] = $item;
  3117. }
  3118. }
  3119. // 检查是否三个特殊参数都存在
  3120. if (count($special_update_data) === 3 &&
  3121. isset($special_update_data['audio_url']) &&
  3122. isset($special_update_data['audio_duration']) &&
  3123. isset($special_update_data['subtitle_info'])) {
  3124. $has_all_special_params = true;
  3125. // 立即更新到当前分镜
  3126. $special_update_data['updated_at'] = date('Y-m-d H:i:s');
  3127. DB::table('mp_episode_segments')
  3128. ->where('segment_id', $segment_id)
  3129. ->update($special_update_data);
  3130. }
  3131. // 使用过滤后的segment_data继续处理其他参数
  3132. $segment_data = $filtered_segment_data;
  3133. $allow_fields = ['dialogue', 'voice_type', 'speed_ratio', 'loudness_ratio', 'emotion_scale', 'pitch'];
  3134. $global_update_data = [];
  3135. $segment_update_data = [];
  3136. $global_voice_type = '';
  3137. $target_segment = DB::table('mp_episode_segments')->where('segment_id', $segment_id)->first();
  3138. if (!$target_segment) Utils::throwError('20003:分镜不存在');
  3139. $episode_id = getProp($target_segment, 'episode_id');
  3140. $target_voice_actor = trim((string)getProp($target_segment, 'voice_actor'));
  3141. $episode = DB::table('mp_anime_episodes')->where('id', $episode_id)->first();
  3142. if (!$episode) Utils::throwError('20003:分集不存在');
  3143. foreach ($global_data as $item) {
  3144. $field_name = trim((string)getProp($item, 'name'));
  3145. if (!$field_name || !in_array($field_name, $allow_fields)) {
  3146. continue;
  3147. }
  3148. $global_update_data[$field_name] = getProp($item, 'value');
  3149. if ($field_name === 'voice_type') {
  3150. $global_voice_type = trim((string)getProp($item, 'value'));
  3151. }
  3152. }
  3153. foreach ($segment_data as $item) {
  3154. $field_name = trim((string)getProp($item, 'name'));
  3155. if (!$field_name || !in_array($field_name, $allow_fields)) {
  3156. continue;
  3157. }
  3158. $segment_update_data[$field_name] = getProp($item, 'value');
  3159. }
  3160. if ($global_voice_type) {
  3161. $timbre_info = DB::table('mp_timbres')
  3162. ->where('timbre_type', $global_voice_type)
  3163. ->select('audio_url', 'timbre_name')
  3164. ->first();
  3165. if ($timbre_info) {
  3166. $global_update_data['voice_audio_url'] = getProp($timbre_info, 'audio_url');
  3167. $global_update_data['voice_name'] = str_replace('(多情感)', '', getProp($timbre_info, 'timbre_name'));
  3168. }
  3169. }
  3170. try {
  3171. DB::beginTransaction();
  3172. // 收集需要创建音频合成任务的segment_id和对应的分镜数据
  3173. $segment_ids_to_create_task = [];
  3174. $segments_data = [];
  3175. // 如果有全局更新,获取该角色的所有分镜数据并检查是否有变化
  3176. if (!empty($global_update_data)) {
  3177. // 如果角色不存在,则只更新当前分镜
  3178. if (!$target_voice_actor) {
  3179. // 只处理当前分镜
  3180. $affected_segments = DB::table('mp_episode_segments')
  3181. ->where('segment_id', $segment_id)
  3182. ->select('segment_id', 'audio_url', 'voice_actor', 'dialogue', 'voice_type', 'voice_name', 'voice_audio_url', 'emotion', 'emotion_type', 'gender', 'speed_ratio', 'loudness_ratio', 'emotion_scale', 'pitch')
  3183. ->get();
  3184. } else {
  3185. // 获取该角色的所有分镜
  3186. $affected_segments = DB::table('mp_episode_segments')
  3187. ->where('episode_id', $episode_id)
  3188. ->where('voice_actor', $target_voice_actor)
  3189. ->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')
  3190. ->get();
  3191. }
  3192. foreach ($affected_segments as $seg) {
  3193. $seg = (array)$seg;
  3194. $sid = getProp($seg, 'segment_id');
  3195. // 检查参数是否发生变化
  3196. $has_changed = false;
  3197. foreach ($global_update_data as $field => $new_value) {
  3198. $old_value = getProp($seg, $field);
  3199. if ($old_value != $new_value) {
  3200. $has_changed = true;
  3201. break;
  3202. }
  3203. }
  3204. if ($has_changed) {
  3205. $segment_ids_to_create_task[] = $sid;
  3206. $segments_data[$sid] = $seg;
  3207. }
  3208. }
  3209. // 只有在有变化的分镜时才更新
  3210. if (!empty($segment_ids_to_create_task)) {
  3211. $global_segment_update_data = $global_update_data;
  3212. $global_segment_update_data['audio_url'] = ''; // 清空音频URL
  3213. $global_segment_update_data['updated_at'] = date('Y-m-d H:i:s');
  3214. DB::table('mp_episode_segments')
  3215. ->where('episode_id', $episode_id)
  3216. ->where('voice_actor', $target_voice_actor)
  3217. ->whereIn('segment_id', $segment_ids_to_create_task)
  3218. ->update($global_segment_update_data);
  3219. }
  3220. if ($global_voice_type) {
  3221. $episode_roles = json_decode((string)getProp($episode, 'roles'), true);
  3222. $episode_roles = is_array($episode_roles) ? $episode_roles : [];
  3223. $roles_updated = false;
  3224. foreach ($episode_roles as &$role) {
  3225. // 通过 role 字段匹配角色名,而不是 voice_name
  3226. if (trim((string)getProp($role, 'role')) !== $target_voice_actor) {
  3227. continue;
  3228. }
  3229. $role['voice_type'] = $global_voice_type;
  3230. $role['voice_audio_url'] = getProp($global_update_data, 'voice_audio_url');
  3231. $role['voice_name'] = getProp($global_update_data, 'voice_name');
  3232. $roles_updated = true;
  3233. }
  3234. unset($role);
  3235. if ($roles_updated) {
  3236. DB::table('mp_anime_episodes')->where('id', $episode_id)->update([
  3237. 'roles' => json_encode($episode_roles, 256),
  3238. 'updated_at' => date('Y-m-d H:i:s'),
  3239. ]);
  3240. }
  3241. }
  3242. }
  3243. // 如果有单个分镜更新,检查是否有变化
  3244. if (!empty($segment_update_data)) {
  3245. // 获取当前分镜数据
  3246. $current_segment = DB::table('mp_episode_segments')
  3247. ->where('segment_id', $segment_id)
  3248. ->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')
  3249. ->first();
  3250. if ($current_segment) {
  3251. $current_segment = (array)$current_segment;
  3252. // 检查参数是否发生变化
  3253. $has_changed = false;
  3254. foreach ($segment_update_data as $field => $new_value) {
  3255. $old_value = getProp($current_segment, $field);
  3256. if ($old_value != $new_value) {
  3257. $has_changed = true;
  3258. break;
  3259. }
  3260. }
  3261. if ($has_changed) {
  3262. // 如果该分镜还未在列表中,添加进去
  3263. if (!in_array($segment_id, $segment_ids_to_create_task)) {
  3264. $segment_ids_to_create_task[] = $segment_id;
  3265. $segments_data[$segment_id] = $current_segment;
  3266. }
  3267. // 更新分镜数据并清空音频URL
  3268. $segment_update_data['audio_url'] = '';
  3269. $segment_update_data['updated_at'] = date('Y-m-d H:i:s');
  3270. DB::table('mp_episode_segments')->where('segment_id', $segment_id)->update($segment_update_data);
  3271. }
  3272. }
  3273. }
  3274. // 为所有有变化的分镜创建音频合成任务
  3275. // 但如果当前分镜同时设置了全部三个特殊参数(audio_url, audio_duration, subtitle_info),则跳过该分镜
  3276. if (!empty($segment_ids_to_create_task)) {
  3277. foreach ($segment_ids_to_create_task as $sid) {
  3278. // 如果当前分镜同时设置了全部三个特殊参数,则跳过音频任务创建
  3279. if ($sid === $segment_id && $has_all_special_params) {
  3280. continue;
  3281. }
  3282. // 重新获取更新后的分镜数据
  3283. $updated_segment = DB::table('mp_episode_segments')
  3284. ->where('segment_id', $sid)
  3285. ->select('voice_actor', 'dialogue', 'voice_type', 'voice_name', 'emotion', 'emotion_type', 'gender', 'speed_ratio', 'loudness_ratio', 'emotion_scale', 'pitch')
  3286. ->first();
  3287. if (!$updated_segment) continue;
  3288. $updated_segment = (array)$updated_segment;
  3289. // 检查dialogue是否为空
  3290. $dialogue = getProp($updated_segment, 'dialogue');
  3291. if (empty($dialogue)) {
  3292. // dialogue为空时,直接写入默认音频信息
  3293. DB::table('mp_episode_segments')->where('segment_id', $sid)->update([
  3294. 'audio_url' => 'https://zw-audiobook.tos-cn-beijing.volces.com/effects/ellipses_2s.mp3',
  3295. 'audio_duration' => 2.0,
  3296. 'subtitle_info' => json_encode(['duration' => 2.0, 'words' => []], 256),
  3297. 'updated_at' => date('Y-m-d H:i:s')
  3298. ]);
  3299. continue;
  3300. }
  3301. $generate_json = [
  3302. 'text' => $dialogue,
  3303. 'role' => getProp($updated_segment, 'voice_actor'),
  3304. 'voice_type' => getProp($updated_segment, 'voice_type'),
  3305. 'voice_name' => getProp($updated_segment, 'voice_name'),
  3306. 'emotion' => getProp($updated_segment, 'emotion'),
  3307. 'emotion_type' => getProp($updated_segment, 'emotion_type'),
  3308. 'gender' => getProp($updated_segment, 'gender'),
  3309. 'speed_ratio' => getProp($updated_segment, 'speed_ratio', 0),
  3310. 'loudness_ratio' => getProp($updated_segment, 'loudness_ratio', 0),
  3311. 'emotion_scale' => getProp($updated_segment, 'emotion_scale', 0),
  3312. 'pitch' => getProp($updated_segment, 'pitch', 0),
  3313. ];
  3314. // 插入视频配音合成任务
  3315. $dubTaskId = DB::table('mp_dub_video_tasks')->insertGetId([
  3316. 'alias_segment_id' => $sid,
  3317. 'generate_status' => '执行中',
  3318. 'audio_url' => '',
  3319. 'generate_json' => json_encode($generate_json, 256),
  3320. 'created_at' => date('Y-m-d H:i:s'),
  3321. 'updated_at' => date('Y-m-d H:i:s'),
  3322. ]);
  3323. if (!$dubTaskId) {
  3324. dLog('anime')->error('创建配音任务失败', ['segment_id' => $sid]);
  3325. continue;
  3326. }
  3327. // 将任务ID添加到Redis列表中
  3328. Redis::lpush('dub_video_task_queue', $dubTaskId);
  3329. // 请求远程服务器执行生成
  3330. try {
  3331. sleep(1);
  3332. $client = new Client(['timeout' => 300, 'verify' => false]);
  3333. $result = $client->get("http://122.9.129.83:5000/api/anime/genAudio?taskId={$dubTaskId}");
  3334. $response = $result->getBody()->getContents();
  3335. $response_arr = json_decode($response, true);
  3336. if (!isset($response_arr['code']) || (int)$response_arr['code'] !== 0) {
  3337. $error_msg = isset($response_arr['msg']) ? $response_arr['msg'] : '未知错误';
  3338. dLog('anime')->error('火山生成音频失败', ['error' => $error_msg, 'task_id' => $dubTaskId, 'segment_id' => $sid]);
  3339. logDB('anime', 'error', '火山生成音频失败', ['error' => $error_msg, 'task_id' => $dubTaskId, 'segment_id' => $sid]);
  3340. }
  3341. } catch (\Exception $e) {
  3342. dLog('anime')->error('调用音频生成API失败', ['error' => $e->getMessage(), 'task_id' => $dubTaskId, 'segment_id' => $sid]);
  3343. logDB('anime', 'error', '调用音频生成API失败', ['error' => $e->getMessage(), 'task_id' => $dubTaskId, 'segment_id' => $sid]);
  3344. }
  3345. }
  3346. }
  3347. DB::commit();
  3348. } catch (\Exception $e) {
  3349. DB::rollBack();
  3350. Utils::throwError('20003:'.$e->getMessage());
  3351. }
  3352. return true;
  3353. }
  3354. public function episodePicsInfo($data) {
  3355. $anime_id = getProp($data, 'anime_id');
  3356. $episode_id = getProp($data, 'episode_id');
  3357. // 参数验证
  3358. if (!$anime_id && !$episode_id) {
  3359. Utils::throwError('20003:请提供动漫ID或分集ID');
  3360. }
  3361. // 根据参数获取数据源
  3362. if ($episode_id) {
  3363. // 从剧集表获取
  3364. $source = DB::table('mp_anime_episodes')->where('id', $episode_id)->first();
  3365. if (!$source) Utils::throwError('20003:该剧集不存在');
  3366. $table_name = 'mp_anime_episodes';
  3367. $id_field = 'id';
  3368. $id_value = $episode_id;
  3369. // 获取剧集的anime_id用于继承全局数据
  3370. $anime_id = getProp($source, 'anime_id');
  3371. } else {
  3372. // 从动漫表获取
  3373. $source = DB::table('mp_animes')->where('id', $anime_id)->where('is_deleted', 0)->first();
  3374. if (!$source) Utils::throwError('20003:该动漫不存在');
  3375. $table_name = 'mp_animes';
  3376. $id_field = 'id';
  3377. $id_value = $anime_id;
  3378. }
  3379. $source = (array)$source;
  3380. $roles = json_decode(getProp($source, 'roles', '[]'), true) ?: [];
  3381. $scenes = json_decode(getProp($source, 'scenes', '[]'), true) ?: [];
  3382. $props = json_decode(getProp($source, 'props', '[]'), true) ?: [];
  3383. // 如果是分集数据,需要处理继承和任务创建逻辑
  3384. if ($episode_id) {
  3385. $this->processEpisodeRolesAndScenes($episode_id, $anime_id, $roles, $scenes, $source);
  3386. }
  3387. // 返回生成器函数,用于 SSE 流式输出
  3388. return function() use ($roles, $scenes, $props, $table_name, $id_field, $id_value) {
  3389. $startTime = time();
  3390. $maxDuration = 600; // 10分钟超时
  3391. $checkInterval = 3; // 每3秒检查一次
  3392. // Redis 缓存键
  3393. $cacheKey = "anime:pics_info:{$table_name}:{$id_value}";
  3394. // 生成当前数据的哈希值用于比较
  3395. $generateHash = function($roles, $scenes, $props) {
  3396. return md5(json_encode(['roles' => $roles, 'scenes' => $scenes, 'props' => $props], JSON_UNESCAPED_UNICODE));
  3397. };
  3398. // 发送初始数据
  3399. $currentHash = $generateHash($roles, $scenes, $props);
  3400. Redis::setex($cacheKey, 600, $currentHash); // 缓存10分钟
  3401. echo "data: " . json_encode([
  3402. 'type' => 'init',
  3403. 'data' => [
  3404. 'roles' => $roles,
  3405. 'scenes' => $scenes,
  3406. 'props' => $props,
  3407. 'start_time' => $startTime
  3408. ]
  3409. ], JSON_UNESCAPED_UNICODE) . "\n\n";
  3410. if (ob_get_level() > 0) {
  3411. ob_flush();
  3412. }
  3413. flush();
  3414. // 持续轮询任务状态
  3415. while (time() - $startTime < $maxDuration) {
  3416. $hasProcessing = false;
  3417. $updated = false;
  3418. // 检查角色任务状态
  3419. foreach ($roles as $index => &$role) {
  3420. $task_id = getProp($role, 'task_id');
  3421. $task_status = getProp($role, 'task_status');
  3422. $existing_url = getProp($role, 'url');
  3423. // 只处理有任务ID且状态为processing的角色,或者状态为processing但没有URL的角色
  3424. if ($task_id && ($task_status === 'processing' || (in_array($task_status, ['success', 'completed']) && empty($existing_url)))) {
  3425. $hasProcessing = ($task_status === 'processing');
  3426. // 查询任务状态
  3427. $task = DB::table('mp_generate_pic_tasks')
  3428. ->where('id', $task_id)
  3429. ->select('id', 'status', 'result_url', 'error_message')
  3430. ->first();
  3431. if ($task) {
  3432. $task = (array)$task;
  3433. $status = getProp($task, 'status');
  3434. // 如果任务完成或失败
  3435. if (in_array($status, ['success', 'failed'])) {
  3436. $role['task_status'] = $status;
  3437. if ($status === 'success') {
  3438. $result_url = getProp($task, 'result_url');
  3439. if ($result_url) {
  3440. $result_urls = is_json($result_url) ? json_decode($result_url, true) : [$result_url];
  3441. if (is_array($result_urls) && !empty($result_urls[0])) {
  3442. $role['url'] = $result_urls[0];
  3443. }
  3444. }
  3445. }
  3446. $updated = true;
  3447. } else if ($status === 'processing') {
  3448. $hasProcessing = true;
  3449. }
  3450. }
  3451. }
  3452. }
  3453. // 检查场景任务状态
  3454. foreach ($scenes as $index => &$scene) {
  3455. $task_id = getProp($scene, 'task_id');
  3456. $task_status = getProp($scene, 'task_status');
  3457. $existing_url = getProp($scene, 'url');
  3458. // 只处理有任务ID且状态为processing的场景,或者状态为success但没有URL的场景
  3459. if ($task_id && ($task_status === 'processing' || (in_array($task_status, ['success', 'completed']) && empty($existing_url)))) {
  3460. $hasProcessing = ($task_status === 'processing');
  3461. // 查询任务状态
  3462. $task = DB::table('mp_generate_pic_tasks')
  3463. ->where('id', $task_id)
  3464. ->select('id', 'status', 'result_url', 'error_message')
  3465. ->first();
  3466. if ($task) {
  3467. $task = (array)$task;
  3468. $status = getProp($task, 'status');
  3469. // 如果任务完成或失败
  3470. if (in_array($status, ['success', 'failed'])) {
  3471. $scene['task_status'] = $status;
  3472. if ($status === 'success') {
  3473. $result_url = getProp($task, 'result_url');
  3474. if ($result_url) {
  3475. $result_urls = is_json($result_url) ? json_decode($result_url, true) : [$result_url];
  3476. if (is_array($result_urls) && !empty($result_urls[0])) {
  3477. $scene['url'] = $result_urls[0];
  3478. }
  3479. }
  3480. }
  3481. $updated = true;
  3482. } else if ($status === 'processing') {
  3483. $hasProcessing = true;
  3484. }
  3485. }
  3486. }
  3487. }
  3488. // 检查道具任务状态
  3489. foreach ($props as $index => &$prop) {
  3490. $task_id = getProp($prop, 'task_id');
  3491. $task_status = getProp($prop, 'task_status');
  3492. $existing_url = getProp($prop, 'url');
  3493. // 只处理有任务ID且状态为processing的道具,或者状态为success但没有URL的道具
  3494. if ($task_id && ($task_status === 'processing' || (in_array($task_status, ['success', 'completed']) && empty($existing_url)))) {
  3495. $hasProcessing = ($task_status === 'processing');
  3496. // 查询任务状态
  3497. $task = DB::table('mp_generate_pic_tasks')
  3498. ->where('id', $task_id)
  3499. ->select('id', 'status', 'result_url', 'error_message')
  3500. ->first();
  3501. if ($task) {
  3502. $task = (array)$task;
  3503. $status = getProp($task, 'status');
  3504. // 如果任务完成或失败
  3505. if (in_array($status, ['success', 'failed'])) {
  3506. $prop['task_status'] = $status;
  3507. if ($status === 'success') {
  3508. $result_url = getProp($task, 'result_url');
  3509. if ($result_url) {
  3510. $result_urls = is_json($result_url) ? json_decode($result_url, true) : [$result_url];
  3511. if (is_array($result_urls) && !empty($result_urls[0])) {
  3512. $prop['url'] = $result_urls[0];
  3513. }
  3514. }
  3515. }
  3516. $updated = true;
  3517. } else if ($status === 'processing') {
  3518. $hasProcessing = true;
  3519. }
  3520. }
  3521. }
  3522. }
  3523. // 如果有更新,检查数据是否真的变化了(通过哈希对比)
  3524. if ($updated) {
  3525. $newHash = $generateHash($roles, $scenes, $props);
  3526. $cachedHash = Redis::get($cacheKey);
  3527. // 只有当数据真正变化时才更新数据库和发送事件
  3528. if ($newHash !== $cachedHash) {
  3529. try {
  3530. // 更新数据库
  3531. DB::table($table_name)->where($id_field, $id_value)->update([
  3532. 'roles' => json_encode($roles, JSON_UNESCAPED_UNICODE),
  3533. 'scenes' => json_encode($scenes, JSON_UNESCAPED_UNICODE),
  3534. 'props' => json_encode($props, JSON_UNESCAPED_UNICODE),
  3535. 'updated_at' => date('Y-m-d H:i:s')
  3536. ]);
  3537. // 更新缓存
  3538. Redis::setex($cacheKey, 600, $newHash);
  3539. // 发送更新事件
  3540. echo "data: " . json_encode([
  3541. 'type' => 'update',
  3542. 'data' => [
  3543. 'roles' => $roles,
  3544. 'scenes' => $scenes,
  3545. 'props' => $props,
  3546. 'elapsed_time' => time() - $startTime
  3547. ]
  3548. ], JSON_UNESCAPED_UNICODE) . "\n\n";
  3549. if (ob_get_level() > 0) {
  3550. ob_flush();
  3551. }
  3552. flush();
  3553. } catch (\Exception $e) {
  3554. dLog('anime')->error('更新角色/场景/道具信息失败: ' . $e->getMessage());
  3555. }
  3556. } else {
  3557. // 即使哈希相同,如果有URL更新也要发送事件
  3558. $hasUrlUpdate = false;
  3559. foreach ($roles as $role) {
  3560. if (!empty(getProp($role, 'url')) && getProp($role, 'task_status') === 'success') {
  3561. $hasUrlUpdate = true;
  3562. break;
  3563. }
  3564. }
  3565. if (!$hasUrlUpdate) {
  3566. foreach ($scenes as $scene) {
  3567. if (!empty(getProp($scene, 'url')) && getProp($scene, 'task_status') === 'success') {
  3568. $hasUrlUpdate = true;
  3569. break;
  3570. }
  3571. }
  3572. }
  3573. if (!$hasUrlUpdate) {
  3574. foreach ($props as $prop) {
  3575. if (!empty(getProp($prop, 'url')) && getProp($prop, 'task_status') === 'success') {
  3576. $hasUrlUpdate = true;
  3577. break;
  3578. }
  3579. }
  3580. }
  3581. if ($hasUrlUpdate) {
  3582. // 强制更新数据库和发送事件
  3583. try {
  3584. DB::table($table_name)->where($id_field, $id_value)->update([
  3585. 'roles' => json_encode($roles, JSON_UNESCAPED_UNICODE),
  3586. 'scenes' => json_encode($scenes, JSON_UNESCAPED_UNICODE),
  3587. 'props' => json_encode($props, JSON_UNESCAPED_UNICODE),
  3588. 'updated_at' => date('Y-m-d H:i:s')
  3589. ]);
  3590. // 更新缓存
  3591. Redis::setex($cacheKey, 600, $newHash);
  3592. // 发送更新事件
  3593. echo "data: " . json_encode([
  3594. 'type' => 'update',
  3595. 'data' => [
  3596. 'roles' => $roles,
  3597. 'scenes' => $scenes,
  3598. 'props' => $props,
  3599. 'elapsed_time' => time() - $startTime
  3600. ]
  3601. ], JSON_UNESCAPED_UNICODE) . "\n\n";
  3602. if (ob_get_level() > 0) {
  3603. ob_flush();
  3604. }
  3605. flush();
  3606. } catch (\Exception $e) {
  3607. dLog('anime')->error('强制更新角色/场景/道具信息失败: ' . $e->getMessage());
  3608. }
  3609. }
  3610. }
  3611. }
  3612. // 如果所有任务都已完成,发送完成事件并退出
  3613. if (!$hasProcessing) {
  3614. // 查询数据库中的最终数据,确保返回最新的完整数据
  3615. try {
  3616. $finalSource = DB::table($table_name)->where($id_field, $id_value)->first();
  3617. if ($finalSource) {
  3618. $finalSource = (array)$finalSource;
  3619. $finalRoles = json_decode(getProp($finalSource, 'roles', '[]'), true) ?: [];
  3620. $finalScenes = json_decode(getProp($finalSource, 'scenes', '[]'), true) ?: [];
  3621. $finalProps = json_decode(getProp($finalSource, 'props', '[]'), true) ?: [];
  3622. // 使用数据库中的最终数据
  3623. $roles = $finalRoles;
  3624. $scenes = $finalScenes;
  3625. $props = $finalProps;
  3626. }
  3627. } catch (\Exception $e) {
  3628. dLog('anime')->error('查询最终数据失败: ' . $e->getMessage());
  3629. // 如果查询失败,继续使用内存中的数据
  3630. }
  3631. // 清理缓存
  3632. Redis::del($cacheKey);
  3633. echo "data: " . json_encode([
  3634. 'type' => 'completed',
  3635. 'data' => [
  3636. 'roles' => $roles,
  3637. 'scenes' => $scenes,
  3638. 'props' => $props,
  3639. 'total_time' => time() - $startTime
  3640. ]
  3641. ], JSON_UNESCAPED_UNICODE) . "\n\n";
  3642. if (ob_get_level() > 0) {
  3643. ob_flush();
  3644. }
  3645. flush();
  3646. break;
  3647. }
  3648. // 等待下次检查
  3649. sleep($checkInterval);
  3650. }
  3651. // 超时处理
  3652. if (time() - $startTime >= $maxDuration) {
  3653. // 查询数据库中的最终数据,即使超时也要返回最新数据
  3654. try {
  3655. $finalSource = DB::table($table_name)->where($id_field, $id_value)->first();
  3656. if ($finalSource) {
  3657. $finalSource = (array)$finalSource;
  3658. $finalRoles = json_decode(getProp($finalSource, 'roles', '[]'), true) ?: [];
  3659. $finalScenes = json_decode(getProp($finalSource, 'scenes', '[]'), true) ?: [];
  3660. $finalProps = json_decode(getProp($finalSource, 'props', '[]'), true) ?: [];
  3661. // 使用数据库中的最终数据
  3662. $roles = $finalRoles;
  3663. $scenes = $finalScenes;
  3664. $props = $finalProps;
  3665. }
  3666. } catch (\Exception $e) {
  3667. dLog('anime')->error('超时时查询最终数据失败: ' . $e->getMessage());
  3668. // 如果查询失败,继续使用内存中的数据
  3669. }
  3670. // 清理缓存
  3671. Redis::del($cacheKey);
  3672. echo "data: " . json_encode([
  3673. 'type' => 'timeout',
  3674. 'message' => '轮询超时,请刷新页面查看最新状态',
  3675. 'data' => [
  3676. 'roles' => $roles,
  3677. 'scenes' => $scenes,
  3678. 'props' => $props
  3679. ]
  3680. ], JSON_UNESCAPED_UNICODE) . "\n\n";
  3681. if (ob_get_level() > 0) {
  3682. ob_flush();
  3683. }
  3684. flush();
  3685. }
  3686. };
  3687. }
  3688. public function clipSegmentVideo($data) {
  3689. $segment_id = getProp($data, 'segment_id');
  3690. $video_time_point_start = getProp($data, 'video_time_point_start');
  3691. $video_time_point_end = getProp($data, 'video_time_point_end');
  3692. if (!$segment_id || !$video_time_point_start || !$video_time_point_end) {
  3693. Utils::throwError('20003:参数异常');
  3694. }
  3695. if (!DB::table('mp_episode_segments')->where('segment_id', $segment_id)->value('video_url')) {
  3696. Utils::throwError('20003:该分镜没有视频,无法裁剪');
  3697. }
  3698. $video_duration = $video_time_point_end - $video_time_point_start;
  3699. if (!$video_duration < 0) Utils::throwError('20003:参数异常');
  3700. return DB::table('mp_episode_segments')->where('segment_id', $segment_id)->update([
  3701. 'video_duration' => $video_duration,
  3702. 'video_time_point_start' => $video_time_point_start,
  3703. 'video_time_point_end' => $video_time_point_end,
  3704. 'updated_at' => date('Y-m-d H:i:s')
  3705. ]);
  3706. }
  3707. // 轮训获取图片任务结果
  3708. private function loopGetPicTaskResult($task_id) {
  3709. $task = MpGeneratePicTask::where('id', $task_id)->first();
  3710. if (!$task) {
  3711. return '';
  3712. }
  3713. // 检查任务模型类型(火山模型和GPT模型都支持直接检查任务状态)
  3714. $model = getProp($task, 'model');
  3715. $isVolcModel = in_array($model, \App\Consts\BaseConst::VOLC_PIC_MODELS);
  3716. $isGptModel = in_array($model, \App\Consts\BaseConst::GPT_IMAGE2_MODELS);
  3717. $isSyncModel = $isVolcModel || $isGptModel;
  3718. // 轮询查询任务状态(火山API和即梦AI都需要轮询)
  3719. $start_count = 0;
  3720. $img_url = '';
  3721. while ($start_count <= 60) { // 循环20次请求,每3s一次
  3722. sleep(3);
  3723. $task = MpGeneratePicTask::where('id', $task_id)->first();
  3724. // 如果任务已经完成,直接返回结果
  3725. if ($task->status === 'success' && $task->result_url) {
  3726. $result_urls = is_array($task->result_url) ? $task->result_url : json_decode($task->result_url, true);
  3727. return is_array($result_urls) ? $result_urls[0] : $task->result_url;
  3728. }
  3729. // 如果任务已失败,返回空
  3730. if ($task->status === 'failed') {
  3731. return '';
  3732. }
  3733. if ($isSyncModel) continue;
  3734. // 查询任务状态
  3735. $statusInfo = $this->aiImageGenerationService->queryTaskStatus($task);
  3736. if ($statusInfo['status'] === 'success') {
  3737. $task->updateStatus('success', [
  3738. 'result_url' => $statusInfo['result_url'],
  3739. 'result_json' => $statusInfo['result_json'] ?? []
  3740. ]);
  3741. // 同步调整分镜图片状态和结果
  3742. if (getProp($task, 'alias_segment_id')) {
  3743. DB::table('mp_episode_segments')->where('segment_id', getProp($task, 'alias_segment_id'))->update([
  3744. 'img_url' => $statusInfo['result_url'][0],
  3745. 'pic_task_status' => '已完成',
  3746. ]);
  3747. }
  3748. $img_url = $statusInfo['result_url'][0];
  3749. break;
  3750. } elseif ($statusInfo['status'] === 'failed') {
  3751. $task->updateStatus('failed', [
  3752. 'error_message' => $statusInfo['error_message'],
  3753. 'result_json' => $statusInfo['result_json'] ?? []
  3754. ]);
  3755. if (getProp($task, 'alias_segment_id')) {
  3756. DB::table('mp_episode_segments')->where('segment_id', getProp($task, 'alias_segment_id'))->update([
  3757. 'pic_task_status' => '失败',
  3758. ]);
  3759. }
  3760. break;
  3761. }
  3762. $start_count++;
  3763. }
  3764. return $img_url;
  3765. }
  3766. /**
  3767. * 从分镜内容中提取涉及的角色
  3768. */
  3769. private function extractCharactersFromSegment($segment_content, $available_characters, $roles) {
  3770. $found_characters = [];
  3771. foreach ($available_characters as $character) {
  3772. // 检查角色名称是否在分镜内容中出现
  3773. if (strpos($segment_content, $character) !== false) {
  3774. $found_characters[] = $character;
  3775. }
  3776. }
  3777. if (!$found_characters) {
  3778. foreach ($roles as $character) {
  3779. // 检查角色名称是否在分镜内容中出现
  3780. if (strpos($segment_content, $character) !== false) {
  3781. $found_characters[] = $character;
  3782. }
  3783. }
  3784. }
  3785. return array_unique($found_characters);
  3786. }
  3787. // 从分镜剧本中提取关键字段
  3788. private function handleSegmentContent(&$data) {
  3789. $segmentContent = getProp($data, 'segment_content');
  3790. // 解析分镜详细信息 - 与 Helpers.php 中 handleEpisodeContent 的 segmentData 结构保持一致
  3791. $segmentData = [
  3792. 'description' => '',
  3793. 'composition' => '',
  3794. 'camera_movement' => '',
  3795. 'voice_actor' => '',
  3796. 'dialogue' => '',
  3797. 'frame_type' => '',
  3798. 'scene' => '', // 场景
  3799. 'characters' => '', // 出镜角色
  3800. 'tail_frame' => '', // 尾帧描述
  3801. 'emotion' => '中性', // 情感
  3802. 'gender' => '0', // 性别(0未知,1男,2女)
  3803. 'speed_ratio' => 0, // 语速
  3804. 'loudness_ratio' => 0, // 音量
  3805. 'emotion_scale' => 4, // 情感强度
  3806. 'pitch' => 0, // 音调
  3807. ];
  3808. // 用于存储需要从 segment_content 中移除的匹配项
  3809. $replaceEmptyArr = [];
  3810. // 提取各个字段 - 兼容中文冒号和英文冒号,支持多种表达方式
  3811. if (preg_match('/(?:画面描述|镜头描述|场景描述)[::]\s*([^\n]+)/u', $segmentContent, $descMatch)) {
  3812. $segmentData['description'] = trim($descMatch[1]);
  3813. $data['description'] = trim($descMatch[1]);
  3814. }
  3815. if (preg_match('/(?:构图设计|构图|镜头构图)[::]\s*([^\n]+)/u', $segmentContent, $compMatch)) {
  3816. $segmentData['composition'] = trim($compMatch[1]);
  3817. $data['composition'] = trim($compMatch[1]);
  3818. }
  3819. if (preg_match('/(?:运镜调度|运镜|镜头运动|摄影机运动)[::]\s*([^\n]+)/u', $segmentContent, $cameraMatch)) {
  3820. $segmentData['camera_movement'] = trim($cameraMatch[1]);
  3821. $data['camera_movement'] = trim($cameraMatch[1]);
  3822. }
  3823. if (preg_match('/(?:配音角色|配音|角色|声优)[::]\s*([^\n]+)/u', $segmentContent, $voiceMatch)) {
  3824. $segmentData['voice_actor'] = trim($voiceMatch[1]);
  3825. $data['voice_actor'] = trim($voiceMatch[1]);
  3826. }
  3827. if (preg_match('/(?:台词内容|台词|对白|对话)[::]\s*([^\n]+)/u', $segmentContent, $dialogueMatch)) {
  3828. $segmentData['dialogue'] = trim($dialogueMatch[1]);
  3829. $data['dialogue'] = trim($dialogueMatch[1]);
  3830. }
  3831. if (preg_match('/(?:画面类型|镜头类型|类型)[::]\s*([^\n]+)/u', $segmentContent, $frameMatch)) {
  3832. $segmentData['frame_type'] = trim($frameMatch[1]);
  3833. $data['frame_type'] = trim($frameMatch[1]);
  3834. }
  3835. // 场景字段
  3836. if (preg_match('/(?:场景|拍摄场景|背景场景|环境)[::]\s*([^\n]+)/u', $segmentContent, $sceneMatch)) {
  3837. $segmentData['scene'] = trim($sceneMatch[1]);
  3838. $data['scene'] = trim($sceneMatch[1]);
  3839. }
  3840. // 出镜角色字段
  3841. if (preg_match('/(?:出镜角色|角色出镜|登场角色|人物)[::]\s*([^\n]+)/u', $segmentContent, $charactersMatch)) {
  3842. $segmentData['characters'] = trim($charactersMatch[1]);
  3843. $data['characters'] = trim($charactersMatch[1]);
  3844. }
  3845. // 尾帧描述字段
  3846. if (preg_match('/(?:尾帧描述|尾帧|结束帧|最后一帧|结尾画面|结束画面)[::]\s*([^\n]+)/u', $segmentContent, $tailFrameMatch)) {
  3847. $segmentData['tail_frame'] = trim($tailFrameMatch[1]);
  3848. $data['tail_frame'] = trim($tailFrameMatch[1]);
  3849. }
  3850. // 情感字段
  3851. if (preg_match('/(?:情感|情绪|感情)[::]\s*([^\n]+)/u', $segmentContent, $emotionMatch)) {
  3852. $replaceEmptyArr[] = trim($emotionMatch[0]);
  3853. $segmentData['emotion'] = trim($emotionMatch[1]);
  3854. $data['emotion'] = trim($emotionMatch[1]);
  3855. }
  3856. // 性别字段
  3857. if (preg_match('/(?:性别)[::]\s*([^\n]+)/u', $segmentContent, $genderMatch)) {
  3858. $replaceEmptyArr[] = trim($genderMatch[0]);
  3859. $genderStr = trim($genderMatch[1]);
  3860. if (strpos($genderStr, '男') !== false || $genderStr === '1') {
  3861. $segmentData['gender'] = '1';
  3862. $data['gender'] = '1';
  3863. } elseif (strpos($genderStr, '女') !== false || $genderStr === '2') {
  3864. $segmentData['gender'] = '2';
  3865. $data['gender'] = '2';
  3866. } else {
  3867. $segmentData['gender'] = '0';
  3868. $data['gender'] = '0';
  3869. }
  3870. }
  3871. // 语速字段
  3872. if (preg_match('/(?:语速|说话速度)[::]\s*([-+]?[0-9]*\.?[0-9]+)/u', $segmentContent, $speedMatch)) {
  3873. $replaceEmptyArr[] = trim($speedMatch[0]);
  3874. $segmentData['speed_ratio'] = (float)trim($speedMatch[1]);
  3875. $data['speed_ratio'] = (float)trim($speedMatch[1]);
  3876. }
  3877. // 音量字段
  3878. if (preg_match('/(?:音量|声音大小)[::]\s*([-+]?[0-9]*\.?[0-9]+)/u', $segmentContent, $loudnessMatch)) {
  3879. $replaceEmptyArr[] = trim($loudnessMatch[0]);
  3880. $segmentData['loudness_ratio'] = (float)trim($loudnessMatch[1]);
  3881. $data['loudness_ratio'] = (float)trim($loudnessMatch[1]);
  3882. }
  3883. // 情感强度字段
  3884. if (preg_match('/(?:情感强度|情绪强度)[::]\s*([0-9]+)/u', $segmentContent, $scaleMatch)) {
  3885. $replaceEmptyArr[] = trim($scaleMatch[0]);
  3886. $segmentData['emotion_scale'] = (int)trim($scaleMatch[1]);
  3887. $data['emotion_scale'] = (int)trim($scaleMatch[1]);
  3888. }
  3889. // 音调字段
  3890. if (preg_match('/(?:音调|音高)[::]\s*([-+]?[0-9]+)/u', $segmentContent, $pitchMatch)) {
  3891. $replaceEmptyArr[] = trim($pitchMatch[0]);
  3892. $segmentData['pitch'] = (int)trim($pitchMatch[1]);
  3893. $data['pitch'] = (int)trim($pitchMatch[1]);
  3894. }
  3895. // 从 segment_content 中移除已提取的配音参数字段
  3896. if (!empty($replaceEmptyArr)) {
  3897. $data['segment_content'] = str_replace($replaceEmptyArr, '', $segmentContent);
  3898. }
  3899. // 如果有配音角色,查询音色信息并验证情感
  3900. $voice_actor = $segmentData['voice_actor'];
  3901. if (!empty($voice_actor) && $voice_actor !== '旁白') {
  3902. // 从当前分镜所属的剧集或动漫中查找角色音色信息
  3903. $anime_id = getProp($data, 'anime_id');
  3904. $episode_id = getProp($data, 'episode_id');
  3905. // 优先从剧集的角色列表中查找
  3906. $roles = [];
  3907. if ($episode_id) {
  3908. $episode = DB::table('mp_anime_episodes')->where('id', $episode_id)->first();
  3909. if ($episode && getProp($episode, 'roles')) {
  3910. $roles = json_decode(getProp($episode, 'roles'), true) ?: [];
  3911. }
  3912. }
  3913. // 如果剧集中没有,从动漫的角色列表中查找
  3914. if (empty($roles) && $anime_id) {
  3915. $anime = DB::table('mp_animes')->where('id', $anime_id)->first();
  3916. if ($anime && getProp($anime, 'roles')) {
  3917. $roles = json_decode(getProp($anime, 'roles'), true) ?: [];
  3918. }
  3919. }
  3920. // 查找匹配的角色音色信息
  3921. $timbre_info = null;
  3922. foreach ($roles as $role) {
  3923. if (getProp($role, 'role') === $voice_actor) {
  3924. $timbre_info = $role;
  3925. break;
  3926. }
  3927. }
  3928. // 如果找到音色信息,添加到数据中
  3929. if ($timbre_info) {
  3930. $voice_type = getProp($timbre_info, 'voice_type');
  3931. $voice_name = getProp($timbre_info, 'voice_name');
  3932. $voice_audio_url = getProp($timbre_info, 'voice_audio_url');
  3933. if ($voice_type) {
  3934. $data['voice_type'] = $voice_type;
  3935. $segmentData['voice_type'] = $voice_type;
  3936. }
  3937. if ($voice_name) {
  3938. $data['voice_name'] = $voice_name;
  3939. $segmentData['voice_name'] = $voice_name;
  3940. }
  3941. if ($voice_audio_url) {
  3942. $data['voice_audio_url'] = $voice_audio_url;
  3943. $segmentData['voice_audio_url'] = $voice_audio_url;
  3944. }
  3945. // 验证情感是否在音色支持的情感列表中
  3946. if ($voice_type) {
  3947. $timbre_emotion = DB::table('mp_timbres')->where('timbre_type', $voice_type)->value('emotion');
  3948. if ($timbre_emotion) {
  3949. $timbre_emotion = explode(',', $timbre_emotion);
  3950. } else {
  3951. $timbre_emotion = [];
  3952. }
  3953. $emotion = getProp($segmentData, 'emotion', '中性');
  3954. if (!in_array($emotion, $timbre_emotion)) {
  3955. $emotion = '中性';
  3956. }
  3957. $emotion_list = DB::table('mp_emotion_list')->where('is_enabled', 1)->pluck('emotion_name', 'emotion_code')->toArray();
  3958. $emotion_list = array_flip($emotion_list);
  3959. $emotion_type = isset($emotion_list[$emotion]) ? $emotion_list[$emotion] : 'neutral';
  3960. $data['emotion_type'] = $emotion_type;
  3961. $segmentData['emotion_type'] = $emotion_type;
  3962. }
  3963. }
  3964. }
  3965. return $segmentData;
  3966. }
  3967. public function createSegmentVideoTask($data) {
  3968. $segment_id = getProp($data, 'segment_id');
  3969. $tail_frame = getProp($data, 'tail_frame');
  3970. $first_frame_url = getProp($data, 'first_frame_url');
  3971. $tail_frame_url = getProp($data, 'tail_frame_url');
  3972. $generate_audio = getProp($data, 'generate_audio', 0);
  3973. if (!$segment_id) {
  3974. Utils::throwError('1002:分镜ID不能为空');
  3975. }
  3976. // 获取分镜信息
  3977. $segment = DB::table('mp_episode_segments')->where('segment_id', $segment_id)->first();
  3978. if (!$segment) {
  3979. Utils::throwError('20003:分镜不存在');
  3980. }
  3981. $segment = (array)$segment;
  3982. $episode_id = getProp($segment, 'episode_id');
  3983. $ratio = DB::table('mp_anime_episodes')->where('id', $episode_id)->value('ratio');
  3984. if (!$ratio) $ratio = '9:16';
  3985. // 获取分镜内容
  3986. $segmentContent = getProp($segment, 'segment_content', '');
  3987. // 检查 $segmentContent 中是否已有尾帧描述
  3988. $contentHasTailFrame = preg_match('/(?:尾帧描述|尾帧)[::]\s*([^\n]+)/u', $segmentContent, $contentTailFrameMatch);
  3989. // 确定最终使用的尾帧描述(优先级:用户输入 > segmentContent自带 > 分镜表字段)
  3990. $finalTailFrame = '';
  3991. if ($tail_frame) {
  3992. // 用户输入了尾帧描述,优先使用
  3993. $finalTailFrame = $tail_frame;
  3994. // 如果 segmentContent 中已有尾帧描述,需要替换
  3995. if ($contentHasTailFrame) {
  3996. $segmentContent = preg_replace('/(?:尾帧描述|尾帧)[::]\s*[^\n]+/u', "尾帧描述:$tail_frame", $segmentContent);
  3997. }
  3998. } elseif ($contentHasTailFrame) {
  3999. // segmentContent 中有尾帧描述,使用它
  4000. $finalTailFrame = trim($contentTailFrameMatch[1]);
  4001. } else {
  4002. // 两者都没有,使用分镜表中的尾帧描述
  4003. $finalTailFrame = getProp($segment, 'tail_frame', '');
  4004. }
  4005. // 判断 $segmentContent 是否有台词内容,如果有则确保使用中文左右双引号
  4006. $hasDialogue = false;
  4007. if (preg_match('/(?:台词内容|台词|对白|对话)[::]\s*([^\n]+)/u', $segmentContent, $dialogueMatch)) {
  4008. $dialogue = trim($dialogueMatch[1]);
  4009. // 如果台词不为空且不是"无"
  4010. if (!empty($dialogue) && $dialogue !== '无') {
  4011. // 过滤掉所有符号(引号、标点、空格等),只保留文字内容来判断是否有实际台词
  4012. $dialogueFiltered = preg_replace('/[""\'\',。!?、;:…—\-\s\p{P}\p{S}]/u', '', $dialogue);
  4013. if (!empty($dialogueFiltered) && $dialogueFiltered !== '无') {
  4014. $hasDialogue = true;
  4015. }
  4016. $dialogue = preg_replace('/^["”]/u', '“', $dialogue); // 替换句首英文双引号或中文右双引号
  4017. $dialogue = preg_replace('/["“]$/u', '”', $dialogue); // 替换句尾英文双引号或中文左双引号
  4018. // 句首或句尾没有中文双引号,则分别添加中文左右双引号
  4019. if (!preg_match('/^[“]/', $dialogue)) {
  4020. $dialogue = '“' . $dialogue;
  4021. }
  4022. if (!preg_match('/[”]$/', $dialogue)) {
  4023. $dialogue .= '”';
  4024. }
  4025. // 将修改后的台词替换回 $segmentContent
  4026. $originalDialogue = $dialogueMatch[1];
  4027. $segmentContent = str_replace($originalDialogue, $dialogue, $segmentContent);
  4028. }
  4029. }
  4030. // 构建完整的提示词
  4031. $fullPrompt = $segmentContent;
  4032. if ($finalTailFrame && !$contentHasTailFrame) {
  4033. // 只有当 segmentContent 中没有尾帧描述时才追加
  4034. $fullPrompt .= "\n尾帧描述:$finalTailFrame";
  4035. }
  4036. // 去除多余的换行符(将连续多个换行符替换为单个换行符)
  4037. $fullPrompt = preg_replace('/\n{2,}/', "\n", $fullPrompt);
  4038. $fullPrompt = trim($fullPrompt);
  4039. // 当前是否启用音效同出(没台词强制关闭音效同出,节省资源收费)
  4040. $current_generate_audio = $hasDialogue ? $generate_audio : 0;
  4041. // 智能选择视频时长
  4042. // $videoDuration = $this->calculateOptimalVideoDuration($segmentContent, $tail_frame);
  4043. $videoDuration = -1;
  4044. // 处理视频模型
  4045. $model = getProp($data, 'model');
  4046. if (!$model) {
  4047. // 用户没有输入,从episode表获取
  4048. $episode = DB::table('mp_anime_episodes')->where('id', getProp($segment, 'episode_id'))->first();
  4049. $model = getProp($episode, 'video_model');
  4050. if (!$model) {
  4051. // episode表也没有,使用默认值
  4052. $model = 'doubao-seedance-1-5-pro-251215';
  4053. }
  4054. }
  4055. // 验证模型是否在可用模型表中
  4056. if (!DB::table('mp_video_models')->where('model', $model)->where('is_enabled', 1)->exists()) {
  4057. $model = 'doubao-seedance-1-5-pro-251215';
  4058. }
  4059. // 保存到episode表
  4060. $episode_id = getProp($segment, 'episode_id');
  4061. DB::table('mp_anime_episodes')->where('id', $episode_id)->update([
  4062. 'video_model' => $model,
  4063. 'updated_at' => date('Y-m-d H:i:s')
  4064. ]);
  4065. // 构建视频生成参数
  4066. $videoParams = [
  4067. 'model' => $model,
  4068. 'alias_segment_id' => $segment_id,
  4069. 'prompt' => trim($fullPrompt),
  4070. 'video_duration' => $videoDuration,
  4071. 'video_resolution' => '720P',
  4072. 'seed' => -1,
  4073. 'ratio' => $ratio,
  4074. 'generate_audio' => (int)$current_generate_audio === 0 ? false : true,
  4075. 'draft' => false,
  4076. 'watermark' => false,
  4077. 'camera_fixed' => false,
  4078. // 'callback_url' => 'http://mpaudio.yqsd.cn/api/video/seedanceCallback'
  4079. ];
  4080. // 如果分镜有图片,作为首帧
  4081. $hasImage = !empty(getProp($segment, 'img_url')) || $first_frame_url;
  4082. $hasVideo = !empty(getProp($segment, 'video_url'));
  4083. if ($hasImage) {
  4084. if ($first_frame_url) {
  4085. $videoParams['first_frame_url'] = $first_frame_url;
  4086. }else {
  4087. $videoParams['first_frame_url'] = getProp($segment, 'img_url');
  4088. }
  4089. if ($tail_frame_url) $videoParams['tail_frame_url'] = $tail_frame_url;
  4090. }
  4091. // 构建content数组
  4092. $videoParams['content'] = [
  4093. [
  4094. 'type' => 'text',
  4095. 'text' => $videoParams['prompt'],
  4096. ]
  4097. ];
  4098. // 如果有首帧图片,添加到content中
  4099. if ($hasImage) {
  4100. 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'])) {
  4101. $videoParams['content'][] = [
  4102. 'type' => 'image_url',
  4103. 'image_url' => [
  4104. 'url' => $videoParams['first_frame_url'],
  4105. ],
  4106. 'role' => 'reference_image',
  4107. ];
  4108. if (isset($videoParams['tail_frame_url'])) {
  4109. $videoParams['content'][] = [
  4110. 'type' => 'image_url',
  4111. 'image_url' => [
  4112. 'url' => $videoParams['tail_frame_url'],
  4113. ],
  4114. 'role' => 'reference_image',
  4115. ];
  4116. }
  4117. }else {
  4118. $videoParams['content'][] = [
  4119. 'type' => 'image_url',
  4120. 'image_url' => [
  4121. 'url' => $videoParams['first_frame_url'],
  4122. ],
  4123. 'role' => 'first_frame',
  4124. ];
  4125. if (isset($videoParams['tail_frame_url'])) {
  4126. $videoParams['content'][] = [
  4127. 'type' => 'image_url',
  4128. 'image_url' => [
  4129. 'url' => $videoParams['tail_frame_url'],
  4130. ],
  4131. 'role' => 'last_frame',
  4132. ];
  4133. }
  4134. }
  4135. }
  4136. // 获取配音音频URL
  4137. $audioUrl = getProp($segment, 'audio_url');
  4138. $audioDuration = getProp($segment, 'audio_duration');
  4139. // 音频传入的前提:必须有至少一张图片或一个视频
  4140. $canUseAudio = ($hasImage || $hasVideo) && !empty($audioUrl);
  4141. // 余额预检:按预估时长计算所需积分,不足直接报错
  4142. $chargeDuration = (int)ceil((float)$audioDuration);
  4143. if ($chargeDuration <= 0) {
  4144. $chargeDuration = 5; // 无音频时长时按默认5秒预估
  4145. }
  4146. $this->pointsService->checkUserPointsEnough(
  4147. $this->pointsService->getVideoChargePoints([
  4148. 'model' => $model,
  4149. 'video_resolution' => strtolower($videoParams['video_resolution'] ?? '720P'),
  4150. 'video_duration' => $chargeDuration,
  4151. 'ratio' => $ratio,
  4152. 'generate_audio' => $current_generate_audio,
  4153. ])
  4154. );
  4155. // dd($videoParams);
  4156. // 根据模型选择不同的视频生成方法
  4157. if (strpos($model, 'jimeng') !== false) {
  4158. // 即梦模型参数调整
  4159. $videoParams['video_duration'] = $audioDuration > 5 ? 10 : 5; // 即梦只支持5s或10s
  4160. unset($videoParams['content']); // 即梦不使用content格式
  4161. $task = $this->aiVideoGenerationService->createJimengTask($videoParams);
  4162. } elseif (strpos($model, 'kling') !== false) {
  4163. // Keling模型参数调整
  4164. $videoParams['video_duration'] = max(3, min(15, ceil($audioDuration))); // Keling支持3-15秒
  4165. $videoParams['aspect_ratio'] = $videoParams['ratio']; // Keling使用aspect_ratio
  4166. unset($videoParams['ratio']);
  4167. unset($videoParams['content']); // Keling不使用content格式
  4168. $task = $this->aiVideoGenerationService->createKelingOmniTask($videoParams);
  4169. } elseif (strpos($model, 'zhizhen') !== false) {
  4170. // 智帧20等新模型使用统一API
  4171. // 构建统一API参数
  4172. $unifiedParams = [
  4173. 'model_code' => $model,
  4174. 'alias_segment_id' => $segment_id,
  4175. 'prompt' => trim($fullPrompt),
  4176. 'video_duration' => $audioDuration > 0 ? max(5, min(15, ceil($audioDuration))) : 5,
  4177. 'video_resolution' => strtolower($videoParams['video_resolution']),
  4178. 'video_ratio' => $ratio,
  4179. 'seed' => -1,
  4180. ];
  4181. // 构建parameters参数
  4182. $parameters = [
  4183. 'seconds' => $unifiedParams['video_duration'],
  4184. 'resolution' => $unifiedParams['video_resolution'],
  4185. 'ratio' => $ratio,
  4186. // 'video_mode' => 'multi_image',
  4187. // 'mode' => 'multi_image',
  4188. 'generate_audio' => (int)$current_generate_audio === 1 ? true : false,
  4189. ];
  4190. $hasImage = false;
  4191. // 处理首帧和尾帧(智帧20模型必须要有首帧图片)
  4192. if ($hasImage) {
  4193. $parameters['first_frame_url'] = $videoParams['first_frame_url'];
  4194. if (isset($videoParams['tail_frame_url'])) {
  4195. $parameters['last_frame_url'] = $videoParams['tail_frame_url'];
  4196. }
  4197. // 只有在有图片的情况下才能添加参考音频
  4198. if ($audioUrl) {
  4199. // $parameters['reference_audios'] = [$audioUrl];
  4200. }
  4201. } else {
  4202. // 没有图片时,记录错误日志
  4203. logDB('anime', 'error', '智帧20模型缺少首帧图片', [
  4204. 'segment_id' => $segment_id,
  4205. 'model' => $model
  4206. ]);
  4207. }
  4208. $unifiedParams['parameters'] = $parameters;
  4209. // 调用统一API创建任务
  4210. $task = $this->aiVideoGenerationService->createUnifiedApiTask($unifiedParams);
  4211. } else {
  4212. // Seedance模型(默认)
  4213. // 快快AI Seedance 2.0/2.5:配音音频需先上传为素材,走聚合网关 /v1/video/generations
  4214. if ($this->isKuaikuaiSeedanceModel($model)) {
  4215. $videoParams['gateway_base_url'] = env('KUAIKUAI_AI_BASE_URL', 'https://ai-api.kkidc.com');
  4216. if ($canUseAudio && $audioUrl) {
  4217. // 上传配音音频为素材(上传失败时同步清理提示词中的<音频N>标记,不阻断任务)
  4218. $reference_audio_assets = $this->aiVideoGenerationService->processReferenceAudiosToKuaikuaiAssets([$audioUrl], $fullPrompt);
  4219. $videoParams['reference_audio_assets'] = $reference_audio_assets;
  4220. // 优化提示词,增加音频相关描述
  4221. $audioPrompt = "全程使用音频1作为视频配音。" . $fullPrompt;
  4222. $videoParams['prompt'] = $audioPrompt;
  4223. } elseif ($audioDuration) { // 有音频时长则需将视频时长设置为比音频时长更长的整数
  4224. $videoParams['video_duration'] = max(4, min(12, ceil($audioDuration)));
  4225. }
  4226. $task = $this->aiVideoGenerationService->createKuaikuaiVideoTask($videoParams);
  4227. } 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'])) {
  4228. // 检查是否为 Seedance 2.0 模型,如果是则需要处理配音音频
  4229. // 添加配音音频到content中
  4230. $videoParams['content'][] = [
  4231. 'type' => 'audio_url',
  4232. 'audio_url' => [
  4233. 'url' => $audioUrl,
  4234. ],
  4235. 'role' => 'reference_audio',
  4236. ];
  4237. // 优化提示词,增加音频相关描述
  4238. $audioPrompt = "全程使用音频1作为视频配音。" . $fullPrompt;
  4239. $videoParams['prompt'] = $audioPrompt;
  4240. $videoParams['content'][0]['text'] = $audioPrompt;
  4241. } else {
  4242. if ($audioDuration) { // 有音频时长则需将视频时长设置为比音频时长更长的整数
  4243. $videoParams['video_duration'] = max(4, min(12, ceil($audioDuration))); // seedance支持2-12s
  4244. }
  4245. $task = $this->aiVideoGenerationService->createSeedanceTask($videoParams);
  4246. }
  4247. }
  4248. // 更新分镜表的视频任务信息
  4249. DB::table('mp_episode_segments')->where('segment_id', $segment_id)->update([
  4250. 'video_task_id' => $task->id,
  4251. 'video_task_status' => '生成中',
  4252. 'generate_audio' => $generate_audio,
  4253. 'updated_at' => date('Y-m-d H:i:s')
  4254. ]);
  4255. return [
  4256. 'task_id' => $task->id,
  4257. 'status' => $task->status,
  4258. 'segment_id' => $segment_id,
  4259. 'video_duration' => $videoDuration
  4260. ];
  4261. }
  4262. /**
  4263. * 是否为快快AI Seedance 2.0/2.5 系列模型
  4264. * 快快AI平台模型ID:seed-2-fast / seed-2-mini / seed-2.5 / seed-2
  4265. *
  4266. * @param string $model
  4267. * @return bool
  4268. */
  4269. public function isKuaikuaiSeedanceModel(string $model): bool
  4270. {
  4271. return in_array($model, ['seed-2-fast', 'seed-2-mini', 'seed-2.5', 'seed-2'], true);
  4272. }
  4273. /**
  4274. * 是否为百度AI网关Seedance 2.0系列模型(系统内使用 baidu- 前缀名,请求网关时映射为 doubao- 原名)
  4275. *
  4276. * @param string $model
  4277. * @return bool
  4278. */
  4279. public function isBaiduSeedanceModel(string $model): bool
  4280. {
  4281. return in_array($model, [
  4282. 'baidu-doubao-seedance-2-0-260128',
  4283. 'baidu-doubao-seedance-2-0-fast-260128',
  4284. 'baidu-doubao-seedance-2-0-mini-260615',
  4285. 'baidu-doubao-seedance-2-5-260628',
  4286. ], true);
  4287. }
  4288. /**
  4289. * 是否为海外百度Seedance(dreamina真人素材空间)模型
  4290. * 系统内使用 baidu-dreamina- 前缀名,请求网关时映射为 dreamina-* 原名
  4291. *
  4292. * @param string $model
  4293. * @return bool
  4294. */
  4295. public function isOverseasBaiduSeedanceModel(string $model): bool
  4296. {
  4297. return in_array($model, [
  4298. 'baidu-dreamina-seedance-2-0-260128',
  4299. 'baidu-dreamina-seedance-2-0-fast-260128',
  4300. 'baidu-dreamina-seedance-2-0-mini-260615',
  4301. 'baidu-dreamina-seedance-2-5-260628',
  4302. ], true);
  4303. }
  4304. /**
  4305. * 是否为 Seedance 2.0 系列模型(百度 doubao-seedance-2.0 / baidu-doubao-* / baidu-dreamina-* / 快快AI seed-2 系列)
  4306. * 供单条与批量生成入口统一判断,避免各入口各自维护模型白名单
  4307. *
  4308. * @param string $model
  4309. * @return bool
  4310. */
  4311. public function isSeedance20SeriesModel(string $model): bool
  4312. {
  4313. return strpos($model, 'doubao-seedance-2.0') !== false
  4314. || $this->isKuaikuaiSeedanceModel($model)
  4315. || $this->isBaiduSeedanceModel($model)
  4316. || $this->isOverseasBaiduSeedanceModel($model);
  4317. }
  4318. public function createActVideoTask($data) {
  4319. $act_id = getProp($data, 'act_id');
  4320. $first_frame_url = getProp($data, 'first_frame_url');
  4321. $tail_frame_url = getProp($data, 'tail_frame_url');
  4322. $generate_audio = getProp($data, 'generate_audio', 1);
  4323. $video_duration = getProp($data, 'video_duration');
  4324. $video_resolution = getProp($data, 'video_resolution');
  4325. $ratio = getProp($data, 'ratio');
  4326. $products = getProp($data, 'products', []);
  4327. $reference_images = array_unique(getProp($data, 'reference_images', []));
  4328. if (!is_array($reference_images) || !is_array($products)) {
  4329. Utils::throwError('20003:传入的参考图或资产格式不正确');
  4330. }
  4331. if (!$act_id) {
  4332. Utils::throwError('1002:片段ID不能为空');
  4333. }
  4334. // 获取片段信息
  4335. $act = DB::table('mp_episode_segments')->where('id', $act_id)->first();
  4336. if (!$act) {
  4337. Utils::throwError('20003:片段不存在');
  4338. }
  4339. $act = (array)$act;
  4340. $anime_id = getProp($act, 'anime_id');
  4341. $episode_id = getProp($act, 'episode_id');
  4342. $anime = DB::table('mp_animes')->where('id', $anime_id)->first();
  4343. $ace_mode = getProp($anime, 'ace_mode');
  4344. $art_style_type = getProp($anime, 'art_style_type');
  4345. $art_style = getProp($anime, 'art_style');
  4346. $episode = DB::table('mp_anime_episodes')->where('id', $episode_id)->first();
  4347. if (!$ratio) $ratio = getProp($episode, 'ratio', '9:16');
  4348. if (!$video_resolution) $video_resolution = getProp($episode, 'video_resolution', '720p');
  4349. // 将资产中新出现的资产放到extra_products中
  4350. // 满足以下要求: 遍历传入的$products,将product_name与$episode中的roles、scenes和props做比对,如果不在其中,则与$episode中的extra_products做比对,如果有同名的则覆盖,没有则新增后存入$episode中的extra_products字段中
  4351. if (!empty($products) && $episode) {
  4352. // 获取剧集中的角色、场景和道具列表
  4353. $roles = json_decode(getProp($episode, 'roles', '[]'), true) ?: [];
  4354. $scenes = json_decode(getProp($episode, 'scenes', '[]'), true) ?: [];
  4355. $props = json_decode(getProp($episode, 'props', '[]'), true) ?: [];
  4356. $extra_products = json_decode(getProp($episode, 'extra_products', '[]'), true) ?: [];
  4357. // 构建角色名称列表
  4358. $role_names = array_column($roles, 'role');
  4359. // 构建场景名称列表
  4360. $scene_names = array_column($scenes, 'scene');
  4361. // 构建道具名称列表
  4362. $prop_names = array_column($props, 'prop');
  4363. // 遍历传入的products
  4364. foreach ($products as $product) {
  4365. $product_name = getProp($product, 'product_name');
  4366. // 如果product_name不在roles、scenes和props中
  4367. if (!in_array($product_name, $role_names) && !in_array($product_name, $scene_names) && !in_array($product_name, $prop_names)) {
  4368. // 查找是否在extra_products中存在同名的
  4369. $found = false;
  4370. foreach ($extra_products as $key => $extra_product) {
  4371. if (getProp($extra_product, 'product_name') === $product_name) {
  4372. // 有同名的则覆盖
  4373. $extra_products[$key] = $product;
  4374. $found = true;
  4375. break;
  4376. }
  4377. }
  4378. // 没有则新增
  4379. if (!$found) {
  4380. $extra_products[] = $product;
  4381. }
  4382. }
  4383. }
  4384. if ($extra_products) {
  4385. // 保存到数据库
  4386. DB::table('mp_anime_episodes')
  4387. ->where('id', $episode_id)
  4388. ->update([
  4389. 'extra_products' => json_encode($extra_products, 256),
  4390. 'updated_at' => date('Y-m-d H:i:s')
  4391. ]);
  4392. }
  4393. }
  4394. // 获取分镜内容
  4395. $actContent = getProp($act, 'act_show_content', '');
  4396. // 音效同出(默认使用)
  4397. $current_generate_audio = $generate_audio ? 1 : 0;
  4398. // 处理视频模型(需在构建提示词之前解析:决定角色音色是否使用参考音频)
  4399. $model = getProp($data, 'model');
  4400. if (!$model) {
  4401. $model = getProp($episode, 'video_model');
  4402. if (!$model) {
  4403. // episode表也没有,使用默认值
  4404. $model = 'seed-2';
  4405. }
  4406. }
  4407. // 验证模型是否在可用模型表中(全能模式片段转视频仅允许 ace_mode=1 的模型)
  4408. $valid_models = DB::table('mp_video_models')->where('ace_mode', 1)->select('model')->pluck('model')->toArray();
  4409. if (!in_array($model, $valid_models)) {
  4410. $model = 'seed-2';
  4411. }
  4412. // 构建完整的提示词
  4413. // 参考音频开关:调用方传 enable_reference_audio 优先,未传则读 ENABLE_REFERENCE_AUDIO(默认开启)
  4414. $supportAudioReference = $this->isReferenceAudioEnabled($data) && $this->isActReferenceAudioSupported($model);
  4415. // 先在提示词转换之前完成参考音频校验与截断(超出模型段数/时长上限的角色回退使用音色提示词)
  4416. $audioPlan = $supportAudioReference
  4417. ? $this->resolveActReferenceAudios($actContent, $products, $model)
  4418. : ['allowed' => [], 'excluded' => [], 'total_duration' => 0];
  4419. // 资产参考图同样先按模型上限(2.0=9张、2.5=30张)截断,保证提示词中的<图片N>与实际素材一一对应
  4420. $imagePlan = $this->resolveActReferenceImages($actContent, $products, $model);
  4421. $processResult = $this->processActContentWithProducts($actContent, $products, $supportAudioReference, $audioPlan['allowed'], $imagePlan['allowed']);
  4422. $fullPrompt = $processResult['content'];
  4423. // if ($art_style_type == '3D真人风格') $fullPrompt = "美术风格: $art_style\n\n".$fullPrompt;
  4424. // 参考图合并:资产参考图(已按模型上限截断)优先,调用方显式传入的参考图按剩余额度补充,超出时优先截断调用方传入的图
  4425. $asset_reference_images = $processResult['reference_images'];
  4426. $frontend_reference_images_all = array_values(array_unique(array_filter($reference_images)));
  4427. $frontend_reference_images = $frontend_reference_images_all;
  4428. if (!empty($imagePlan['limit'])) {
  4429. $remaining = max(0, $imagePlan['limit'] - count($asset_reference_images));
  4430. $frontend_reference_images = array_slice($frontend_reference_images, 0, $remaining);
  4431. }
  4432. $reference_images = array_values(array_unique(array_filter(array_merge($asset_reference_images, $frontend_reference_images))));
  4433. // 任务记录用:截断前的完整合并数组(正文内出现的资产图 + 调用方传入的参考图),便于追溯前端入参
  4434. $reference_images_all = array_values(array_unique(array_filter(array_merge(
  4435. $processResult['reference_images_all'] ?? $asset_reference_images,
  4436. $frontend_reference_images_all
  4437. ))));
  4438. // 角色音色参考音频(顺序与提示词中的<音频N>标记一一对应)
  4439. $reference_audios = $supportAudioReference ? ($processResult['reference_audios'] ?? []) : [];
  4440. $videoDuration = $video_duration ? $video_duration : getProp($act, 'act_duration');
  4441. // 保存到episode表(仅在专用方法中更新模型)
  4442. // DB::table('mp_anime_episodes')->where('id', $episode_id)->update([
  4443. // 'video_model' => $model,
  4444. // 'updated_at' => date('Y-m-d H:i:s')
  4445. // ]);
  4446. // 余额预检:按预估时长计算所需积分,不足直接报错
  4447. $chargeDuration = (int)$videoDuration;
  4448. if ($chargeDuration <= 0) {
  4449. $chargeDuration = 5; // 无时长时按默认5秒预估
  4450. }
  4451. $this->pointsService->checkUserPointsEnough(
  4452. $this->pointsService->getVideoChargePoints([
  4453. 'model' => $model,
  4454. 'video_resolution' => strtolower($video_resolution ?? '720p'),
  4455. 'video_duration' => $chargeDuration,
  4456. 'ratio' => $ratio,
  4457. 'generate_audio' => $current_generate_audio,
  4458. ])
  4459. );
  4460. // 构建视频生成参数
  4461. $videoParams = [
  4462. 'model' => $model,
  4463. 'alias_act_id' => $act_id,
  4464. 'prompt' => trim($fullPrompt),
  4465. 'video_duration' => $videoDuration,
  4466. 'video_resolution' => $video_resolution,
  4467. 'seed' => -1,
  4468. 'ratio' => $ratio,
  4469. 'generate_audio' => (int)$current_generate_audio === 0 ? false : true,
  4470. 'draft' => false,
  4471. 'watermark' => false,
  4472. 'camera_fixed' => false,
  4473. // 'callback_url' => 'http://mpaudio.yqsd.cn/api/video/seedanceCallback'
  4474. ];
  4475. // 如果分镜有图片,作为首帧
  4476. $hasImage = !empty(getProp($act, 'img_url')) || $first_frame_url;
  4477. $hasVideo = !empty(getProp($act, 'video_url'));
  4478. if ($hasImage) {
  4479. if ($first_frame_url) {
  4480. $videoParams['first_frame_url'] = $first_frame_url;
  4481. }else {
  4482. $videoParams['first_frame_url'] = getProp($act, 'img_url');
  4483. }
  4484. if ($tail_frame_url) $videoParams['tail_frame_url'] = $tail_frame_url;
  4485. }
  4486. // 构建content数组
  4487. $videoParams['content'] = [
  4488. [
  4489. 'type' => 'text',
  4490. 'text' => $videoParams['prompt'],
  4491. ]
  4492. ];
  4493. // 如果有首帧图片,添加到content中
  4494. if ($hasImage) {
  4495. 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'])) {
  4496. $videoParams['content'][] = [
  4497. 'type' => 'image_url',
  4498. 'image_url' => [
  4499. 'url' => $videoParams['first_frame_url'],
  4500. ],
  4501. 'role' => 'reference_image',
  4502. ];
  4503. if (isset($videoParams['tail_frame_url'])) {
  4504. $videoParams['content'][] = [
  4505. 'type' => 'image_url',
  4506. 'image_url' => [
  4507. 'url' => $videoParams['tail_frame_url'],
  4508. ],
  4509. 'role' => 'reference_image',
  4510. ];
  4511. }
  4512. }else {
  4513. $videoParams['content'][] = [
  4514. 'type' => 'image_url',
  4515. 'image_url' => [
  4516. 'url' => $videoParams['first_frame_url'],
  4517. ],
  4518. 'role' => 'first_frame',
  4519. ];
  4520. if (isset($videoParams['tail_frame_url'])) {
  4521. $videoParams['content'][] = [
  4522. 'type' => 'image_url',
  4523. 'image_url' => [
  4524. 'url' => $videoParams['tail_frame_url'],
  4525. ],
  4526. 'role' => 'last_frame',
  4527. ];
  4528. }
  4529. }
  4530. }
  4531. // dd($videoParams);
  4532. // 根据模型选择不同的视频生成方法
  4533. try {
  4534. if (strpos($model, 'jimeng') !== false) {
  4535. // 即梦模型参数调整
  4536. unset($videoParams['content']); // 即梦不使用content格式
  4537. $task = $this->aiVideoGenerationService->createJimengTask($videoParams);
  4538. } elseif (strpos($model, 'kling') !== false) {
  4539. // Keling模型参数调整
  4540. $videoParams['aspect_ratio'] = $videoParams['ratio']; // Keling使用aspect_ratio
  4541. unset($videoParams['ratio']);
  4542. unset($videoParams['content']); // Keling不使用content格式
  4543. $task = $this->aiVideoGenerationService->createKelingOmniTask($videoParams);
  4544. } elseif (strpos($model, 'zhizhen') !== false) {
  4545. // 智帧20等新模型使用统一API
  4546. // 构建统一API参数
  4547. $unifiedParams = [
  4548. 'model_code' => $model,
  4549. 'alias_act_id' => $act_id,
  4550. 'prompt' => trim($fullPrompt),
  4551. 'video_duration' => $videoDuration,
  4552. 'video_resolution' => strtolower($videoParams['video_resolution']),
  4553. 'video_ratio' => $ratio,
  4554. 'seed' => -1,
  4555. ];
  4556. // 构建parameters参数
  4557. $parameters = [
  4558. 'seconds' => $unifiedParams['video_duration'],
  4559. 'resolution' => $unifiedParams['video_resolution'],
  4560. 'ratio' => $ratio,
  4561. // 'video_mode' => 'multi_image',
  4562. // 'mode' => 'multi_image',
  4563. 'generate_audio' => (int)$current_generate_audio === 1 ? true : false,
  4564. ];
  4565. $hasImage = false;
  4566. // 处理首帧和尾帧(智帧20模型必须要有首帧图片)
  4567. if ($hasImage) {
  4568. $parameters['first_frame_url'] = $videoParams['first_frame_url'];
  4569. if (isset($videoParams['tail_frame_url'])) {
  4570. $parameters['last_frame_url'] = $videoParams['tail_frame_url'];
  4571. }
  4572. } else {
  4573. // 没有图片时,记录错误日志
  4574. logDB('anime', 'error', '智帧20模型缺少首帧图片', [
  4575. 'act_id' => $act_id,
  4576. 'model' => $model
  4577. ]);
  4578. }
  4579. if ($reference_images) {
  4580. // 参考图按模型上限截断(Seedance 2.0 系列=9张,2.5=30张)
  4581. $imageLimit = $this->getActReferenceImageLimit($model);
  4582. if ($imageLimit > 0) {
  4583. $reference_images = array_slice($reference_images, 0, $imageLimit);
  4584. }
  4585. // 任务记录用:保存截断前的完整参考图(含调用方传入),便于追溯前端入参
  4586. $unifiedParams['reference_images'] = $reference_images_all;
  4587. // 实际提交给大模型的参考图(截断后)
  4588. $unifiedParams['ref_image_url'] = json_encode($reference_images, 256);
  4589. $reference_images = $this->aiImageGenerationService->processReferenceImagesToAssets($reference_images, $unifiedParams['prompt']);
  4590. $parameters['reference_images'] = $reference_images;
  4591. $parameters['video_mode'] = 'multi_image';
  4592. $parameters['mode'] = 'multi_image';
  4593. }
  4594. // 角色音色参考音频:上传为素材并传入统一API(上传失败时清理提示词中的<音频N>标记)
  4595. if ($reference_audios) {
  4596. $unifiedParams['ref_audio_url'] = json_encode($reference_audios, 256);
  4597. // 任务记录:参考图与参考音频一起存入 ref_image_url
  4598. $unifiedParams['ref_image_url'] = $this->mergeReferenceAudiosIntoRefImageUrl($unifiedParams['ref_image_url'] ?? '', $reference_audios);
  4599. $reference_audio_assets = $this->processActReferenceAudiosToAssets($reference_audios, $model, $unifiedParams['prompt']);
  4600. $parameters['reference_audios'] = $reference_audio_assets;
  4601. // 音频素材上传失败的角色回退到音色提示词
  4602. $unifiedParams['prompt'] = $this->applyAudioVoiceFallbacks($unifiedParams['prompt'], $processResult['audio_voice_fallbacks'] ?? []);
  4603. $unifiedParams['prompt'] = trim($unifiedParams['prompt']);
  4604. }
  4605. $unifiedParams['parameters'] = $parameters;
  4606. // 调用统一API创建任务
  4607. $task = $this->aiVideoGenerationService->createUnifiedApiTask($unifiedParams);
  4608. } elseif ($this->isSeedance20SeriesModel($model)) {
  4609. // 豆包Seedance 2.0(百度AI网关)/ 快快AI Seedance 2.0/2.5:图片需要先上传为素材
  4610. $isKuaikuai = $this->isKuaikuaiSeedanceModel($model);
  4611. $isDreamina = $this->isOverseasBaiduSeedanceModel($model);
  4612. // 任务记录用:保存截断前的完整合并数组(正文内资产图 + 调用方传入的参考图),便于追溯前端入参
  4613. $videoParams['reference_images'] = $reference_images_all;
  4614. if ($reference_images) {
  4615. // 参考图按模型上限截断(Seedance 2.0 系列=9张,2.5=30张)
  4616. $imageLimit = $this->getActReferenceImageLimit($model);
  4617. if ($imageLimit > 0) {
  4618. $reference_images = array_slice($reference_images, 0, $imageLimit);
  4619. }
  4620. // 维护ref_image_url字段(参考图URL,JSON数组,与智帧分支保持一致)
  4621. $videoParams['ref_image_url'] = json_encode($reference_images, 256);
  4622. // 参考图上传为素材(国内百度/海外百度dreamina/快快AI),上传失败时同步清理提示词中的<图片N>标记
  4623. $reference_image_assets = $isKuaikuai
  4624. ? $this->aiVideoGenerationService->processReferenceImagesToKuaikuaiAssets($reference_images, $fullPrompt)
  4625. : ($isDreamina
  4626. ? $this->aiVideoGenerationService->processReferenceImagesToBaiduDreaminaAssets($reference_images, $fullPrompt)
  4627. : $this->aiVideoGenerationService->processReferenceImagesToSeedance20Assets($reference_images, $fullPrompt));
  4628. // 素材上传失败后提示词可能被清理,同步更新视频参数中的提示词
  4629. $videoParams['prompt'] = trim($fullPrompt);
  4630. $videoParams['content'][0]['text'] = trim($fullPrompt);
  4631. $videoParams['reference_image_assets'] = $reference_image_assets;
  4632. }
  4633. // 角色音色参考音频:上传为素材并传入网关(上传失败时清理提示词中的<音频N>标记)
  4634. if ($reference_audios) {
  4635. $videoParams['ref_audio_url'] = json_encode($reference_audios, 256);
  4636. // 任务记录:参考图与参考音频一起存入 ref_image_url
  4637. $videoParams['ref_image_url'] = $this->mergeReferenceAudiosIntoRefImageUrl($videoParams['ref_image_url'] ?? '', $reference_audios);
  4638. $reference_audio_assets = $this->processActReferenceAudiosToAssets($reference_audios, $model, $fullPrompt);
  4639. // 音频素材上传失败的角色回退到音色提示词
  4640. $fullPrompt = $this->applyAudioVoiceFallbacks($fullPrompt, $processResult['audio_voice_fallbacks'] ?? []);
  4641. $videoParams['prompt'] = trim($fullPrompt);
  4642. $videoParams['content'][0]['text'] = trim($fullPrompt);
  4643. $videoParams['reference_audio_assets'] = $reference_audio_assets;
  4644. }
  4645. // 快快AI走聚合网关 /v1/video/generations(火山豆包格式)
  4646. if ($isKuaikuai) {
  4647. $videoParams['gateway_base_url'] = env('KUAIKUAI_AI_BASE_URL', 'https://ai-api.kkidc.com');
  4648. $task = $this->aiVideoGenerationService->createKuaikuaiVideoTask($videoParams);
  4649. } else {
  4650. $task = $this->aiVideoGenerationService->createSeedance20Task($videoParams);
  4651. }
  4652. } else {
  4653. $task = $this->aiVideoGenerationService->createSeedanceTask($videoParams);
  4654. }
  4655. } catch (ApiException $e) {
  4656. // 上游调用抛出的网关异常统一做友好化处理;本地业务错误(非1001)保持原提示不变
  4657. if ($e->getCode() === 1001) {
  4658. Utils::throwError('1001:' . mapErrorMessage($e->getMessage()));
  4659. }
  4660. throw $e;
  4661. } catch (\Exception $e) {
  4662. // 其他未包装的异常,同样只对报错信息做格式化,便于前端展示友好提示
  4663. Utils::throwError('20003:' . mapErrorMessage($e->getMessage()));
  4664. }
  4665. // 更新分镜表的视频任务信息
  4666. DB::table('mp_episode_segments')->where('id', $act_id)->update([
  4667. 'video_task_id' => $task->id,
  4668. 'video_task_status' => '生成中',
  4669. 'generate_audio' => $generate_audio,
  4670. 'updated_at' => date('Y-m-d H:i:s')
  4671. ]);
  4672. // 如果是全能模式,并且是第一集的第一个片段,将act_id存入Redis
  4673. $episode_number = getProp($act, 'episode_number');
  4674. $act_number = getProp($act, 'act_number');
  4675. if ((int)$ace_mode === 1 && (int)$episode_number === 1 && (int)$act_number === 1) {
  4676. Redis::sadd('anime_act_first_frame_urls', $act_id);
  4677. }
  4678. $result = [
  4679. 'task_id' => $task->id,
  4680. 'status' => $task->status,
  4681. 'act_id' => $act_id,
  4682. 'video_duration' => $videoDuration
  4683. ];
  4684. // 仅当任务提交阶段就已失败时,附带格式化后的错误信息;正常返回结构不受影响
  4685. if ($task->status === 'failed' && !empty($task->error_message)) {
  4686. $result['error_message'] = mapErrorMessage($task->error_message);
  4687. }
  4688. return $result;
  4689. }
  4690. /**
  4691. * 文生视频通用方法
  4692. * 支持传入视频参数、提示词、参考图等信息,不支持products入参
  4693. * 用户提示词不做任何处理,直接组装参数后根据模型调用
  4694. *
  4695. * @param array $data 请求参数
  4696. * @return array
  4697. */
  4698. public function generateVideo($data) {
  4699. $prompt = getProp($data, 'prompt');
  4700. if (empty($prompt)) {
  4701. Utils::throwError('20003:提示词不能为空');
  4702. }
  4703. $model = getProp($data, 'model');
  4704. if (!$model) {
  4705. $model = 'baidu-doubao-seedance-2-0-260128';
  4706. }
  4707. // 验证模型是否在可用模型表中
  4708. if (!DB::table('mp_video_models')->where('model', $model)->where('is_enabled', 1)->exists()) {
  4709. Utils::throwError('20003:该模型已不可用,请更换!');
  4710. }
  4711. $video_duration = getProp($data, 'video_duration', 5);
  4712. // 默认超分720p档(按480p生成后本地超分到720p);480p为原始档需前端显式指定
  4713. $video_resolution = getProp($data, 'video_resolution', 'sr_720p');
  4714. $ratio = getProp($data, 'ratio', '9:16');
  4715. $generate_audio = getProp($data, 'generate_audio', 1);
  4716. $seed = getProp($data, 'seed', -1);
  4717. $first_frame_url = getProp($data, 'first_frame_url');
  4718. $tail_frame_url = getProp($data, 'tail_frame_url');
  4719. // 参考图(支持数组或JSON字符串,最多9张)
  4720. $reference_images = getProp($data, 'reference_images', []);
  4721. if (is_string($reference_images)) {
  4722. $reference_images = json_decode($reference_images, true) ?: [];
  4723. }
  4724. if (!is_array($reference_images)) {
  4725. Utils::throwError('20003:参考图格式不正确');
  4726. }
  4727. $reference_images = array_values(array_unique(array_filter($reference_images)));
  4728. $reference_images = array_slice($reference_images, 0, 9);
  4729. // 参考视频(支持数组或JSON字符串,最多3个)
  4730. $reference_videos = getProp($data, 'reference_videos', []);
  4731. if (is_string($reference_videos)) {
  4732. $reference_videos = json_decode($reference_videos, true) ?: [];
  4733. }
  4734. if (!is_array($reference_videos)) {
  4735. Utils::throwError('20003:参考视频格式不正确');
  4736. }
  4737. $reference_videos = array_values(array_unique(array_filter($reference_videos)));
  4738. if (count($reference_videos) > 3) {
  4739. Utils::throwError('20003:参考视频最多选择3个');
  4740. }
  4741. $reference_videos = array_slice($reference_videos, 0, 3);
  4742. // 参考音频:以传入的 reference_audios 为准,有值即视为启用,无值即关闭
  4743. $reference_audios = getProp($data, 'reference_audios', []);
  4744. if (is_string($reference_audios)) {
  4745. $reference_audios = json_decode($reference_audios, true) ?: [];
  4746. }
  4747. if (!is_array($reference_audios)) {
  4748. Utils::throwError('20003:参考音频格式不正确');
  4749. }
  4750. $reference_audios = array_values(array_unique(array_filter($reference_audios)));
  4751. $audioLimits = $this->getActAudioLimits($model);
  4752. if ($audioLimits) {
  4753. $reference_audios = $this->filterActReferenceAudios($reference_audios, $audioLimits);
  4754. } else {
  4755. // 非多模态参考音频模型:保留原有最多3段的限制
  4756. $reference_audios = array_slice($reference_audios, 0, 3);
  4757. }
  4758. // 余额预检:按预估时长计算所需积分,不足直接报错
  4759. $chargeDuration = (int)ceil((float)$video_duration);
  4760. if ($chargeDuration <= 0) {
  4761. $chargeDuration = 5; // 无时长时按默认5秒预估
  4762. }
  4763. $this->pointsService->checkUserPointsEnough(
  4764. $this->pointsService->getVideoChargePoints([
  4765. 'model' => $model,
  4766. 'video_resolution' => strtolower($video_resolution ?? '720p'),
  4767. 'video_duration' => $chargeDuration,
  4768. 'ratio' => $ratio,
  4769. 'generate_audio' => (int)$generate_audio,
  4770. ])
  4771. );
  4772. // 构建视频生成参数(用户参数直接透传,提示词不做处理)
  4773. $videoParams = [
  4774. 'model' => $model,
  4775. 'prompt' => $prompt,
  4776. 'video_duration' => $video_duration,
  4777. 'video_resolution' => $video_resolution,
  4778. 'seed' => $seed,
  4779. 'ratio' => $ratio,
  4780. 'generate_audio' => (int)$generate_audio === 1 ? true : false,
  4781. 'draft' => getProp($data, 'draft', false),
  4782. 'watermark' => getProp($data, 'watermark', false),
  4783. 'camera_fixed' => getProp($data, 'camera_fixed', false),
  4784. ];
  4785. if ($first_frame_url) $videoParams['first_frame_url'] = $first_frame_url;
  4786. if ($tail_frame_url) $videoParams['tail_frame_url'] = $tail_frame_url;
  4787. // 构建content数组
  4788. $videoParams['content'] = [
  4789. [
  4790. 'type' => 'text',
  4791. 'text' => $prompt,
  4792. ]
  4793. ];
  4794. // 根据模型选择不同的视频生成方法
  4795. if (strpos($model, 'jimeng') !== false) {
  4796. // 即梦模型参数调整
  4797. unset($videoParams['content']); // 即梦不使用content格式
  4798. $task = $this->aiVideoGenerationService->createJimengTask($videoParams);
  4799. } elseif (strpos($model, 'kling') !== false) {
  4800. // 可灵模型参数调整
  4801. $videoParams['aspect_ratio'] = $videoParams['ratio']; // 可灵使用aspect_ratio
  4802. unset($videoParams['ratio']);
  4803. unset($videoParams['content']); // 可灵不使用content格式
  4804. $task = $this->aiVideoGenerationService->createKelingOmniTask($videoParams);
  4805. } elseif (strpos($model, 'zhizhen') !== false) {
  4806. // 智帧等新模型使用统一API
  4807. $unifiedParams = [
  4808. 'model_code' => $model,
  4809. 'prompt' => $prompt,
  4810. 'video_duration' => $video_duration,
  4811. 'video_resolution' => strtolower($video_resolution),
  4812. 'video_ratio' => $ratio,
  4813. 'seed' => $seed,
  4814. ];
  4815. // 构建parameters参数
  4816. $parameters = [
  4817. 'seconds' => $unifiedParams['video_duration'],
  4818. 'resolution' => $unifiedParams['video_resolution'],
  4819. 'ratio' => $ratio,
  4820. 'generate_audio' => (int)$generate_audio === 1 ? true : false,
  4821. ];
  4822. // 首帧和尾帧
  4823. if ($first_frame_url) $parameters['first_frame_url'] = $first_frame_url;
  4824. if ($tail_frame_url) $parameters['last_frame_url'] = $tail_frame_url;
  4825. // 维护ref_image_url字段(参考图+参考视频+参考音频URL,JSON数组,与参考图处理方式一致)
  4826. $refImageUrls = array_merge($reference_images, $reference_videos, $reference_audios);
  4827. if ($refImageUrls) {
  4828. $unifiedParams['ref_image_url'] = json_encode(array_values(array_filter($refImageUrls)), 256);
  4829. }
  4830. // 参考图处理
  4831. if ($reference_images) {
  4832. $reference_images = $this->aiImageGenerationService->processReferenceImagesToAssets($reference_images, $unifiedParams['prompt']);
  4833. $parameters['reference_images'] = $reference_images;
  4834. $parameters['video_mode'] = 'multi_image';
  4835. $parameters['mode'] = 'multi_image';
  4836. }
  4837. // 参考视频和参考音频(与参考图一致,先上传为智帧素材)
  4838. if ($reference_videos) {
  4839. $reference_videos = $this->aiImageGenerationService->processReferenceVideosToAssets($reference_videos, $unifiedParams['prompt']);
  4840. $parameters['reference_videos'] = $reference_videos;
  4841. }
  4842. if ($reference_audios) {
  4843. $reference_audios = $this->aiImageGenerationService->processReferenceAudiosToAssets($reference_audios, $unifiedParams['prompt']);
  4844. $parameters['reference_audios'] = $reference_audios;
  4845. }
  4846. $unifiedParams['parameters'] = $parameters;
  4847. // 调用统一API创建任务
  4848. $task = $this->aiVideoGenerationService->createUnifiedApiTask($unifiedParams);
  4849. } elseif ($this->isSeedance20SeriesModel($model)) {
  4850. // 豆包Seedance 2.0(百度AI网关)/ 快快AI Seedance 2.0/2.5:图片/视频/音频需要先上传为素材
  4851. $isKuaikuai = $this->isKuaikuaiSeedanceModel($model);
  4852. $isDreamina = $this->isOverseasBaiduSeedanceModel($model);
  4853. $videoParams['reference_images'] = $reference_images;
  4854. // 维护ref_image_url字段(参考图+参考视频+参考音频URL,JSON数组)
  4855. $refImageUrls = array_merge($reference_images, $reference_videos, $reference_audios);
  4856. if ($refImageUrls) {
  4857. $videoParams['ref_image_url'] = json_encode(array_values(array_filter($refImageUrls)), 256);
  4858. }
  4859. if ($reference_images) {
  4860. // 参考图上传为素材(国内百度/海外百度dreamina/快快AI)
  4861. $reference_image_assets = $isKuaikuai
  4862. ? $this->aiVideoGenerationService->processReferenceImagesToKuaikuaiAssets($reference_images, $videoParams['prompt'])
  4863. : ($isDreamina
  4864. ? $this->aiVideoGenerationService->processReferenceImagesToBaiduDreaminaAssets($reference_images, $videoParams['prompt'])
  4865. : $this->aiVideoGenerationService->processReferenceImagesToSeedance20Assets($reference_images, $videoParams['prompt']));
  4866. $videoParams['reference_image_assets'] = $reference_image_assets;
  4867. }
  4868. // 参考视频上传为素材(国内百度/海外百度dreamina/快快AI)
  4869. if ($reference_videos) {
  4870. $reference_video_assets = $isKuaikuai
  4871. ? $this->aiVideoGenerationService->processReferenceVideosToKuaikuaiAssets($reference_videos, $videoParams['prompt'])
  4872. : ($isDreamina
  4873. ? $this->aiVideoGenerationService->processReferenceVideosToBaiduDreaminaAssets($reference_videos, $videoParams['prompt'])
  4874. : $this->aiVideoGenerationService->processReferenceVideosToSeedance20Assets($reference_videos, $videoParams['prompt']));
  4875. $videoParams['reference_video_assets'] = $reference_video_assets;
  4876. }
  4877. // 参考音频上传为素材(国内百度/海外百度dreamina/快快AI)
  4878. if ($reference_audios) {
  4879. $reference_audio_assets = $isKuaikuai
  4880. ? $this->aiVideoGenerationService->processReferenceAudiosToKuaikuaiAssets($reference_audios, $videoParams['prompt'])
  4881. : ($isDreamina
  4882. ? $this->aiVideoGenerationService->processReferenceAudiosToBaiduDreaminaAssets($reference_audios, $videoParams['prompt'])
  4883. : $this->aiVideoGenerationService->processReferenceAudiosToSeedance20Assets($reference_audios, $videoParams['prompt']));
  4884. $videoParams['reference_audio_assets'] = $reference_audio_assets;
  4885. }
  4886. // 参考素材上传失败时可能清理提示词中的素材标记,需要同步回content文本
  4887. if ($reference_images || $reference_videos || $reference_audios) {
  4888. $videoParams['content'][0]['text'] = $videoParams['prompt'];
  4889. }
  4890. // 快快AI走聚合网关 /v1/video/generations(火山豆包格式)
  4891. if ($isKuaikuai) {
  4892. $videoParams['gateway_base_url'] = env('KUAIKUAI_AI_BASE_URL', 'https://ai-api.kkidc.com');
  4893. $task = $this->aiVideoGenerationService->createKuaikuaiVideoTask($videoParams);
  4894. } else {
  4895. $task = $this->aiVideoGenerationService->createSeedance20Task($videoParams);
  4896. }
  4897. } else {
  4898. // 官方Seedance模型:兼容参考视频和参考音频(content直接透传公网URL)
  4899. // 维护ref_image_url字段(参考图+参考视频+参考音频URL,JSON数组)
  4900. $refImageUrls = array_merge($reference_images, $reference_videos, $reference_audios);
  4901. if ($refImageUrls) {
  4902. $videoParams['ref_image_url'] = json_encode(array_values(array_filter($refImageUrls)), 256);
  4903. }
  4904. if ($reference_videos) {
  4905. foreach ($reference_videos as $videoUrl) {
  4906. $videoParams['content'][] = [
  4907. 'type' => 'video_url',
  4908. 'video_url' => [
  4909. 'url' => $videoUrl,
  4910. ],
  4911. 'role' => 'reference_video',
  4912. ];
  4913. }
  4914. }
  4915. if ($reference_audios) {
  4916. foreach ($reference_audios as $audioUrl) {
  4917. $videoParams['content'][] = [
  4918. 'type' => 'audio_url',
  4919. 'audio_url' => [
  4920. 'url' => $audioUrl,
  4921. ],
  4922. 'role' => 'reference_audio',
  4923. ];
  4924. }
  4925. }
  4926. $task = $this->aiVideoGenerationService->createSeedanceTask($videoParams);
  4927. }
  4928. return [
  4929. 'task_id' => $task->id,
  4930. 'status' => $task->status,
  4931. 'model' => $model,
  4932. 'video_duration' => $video_duration,
  4933. 'video_resolution' => $video_resolution,
  4934. 'ratio' => $ratio
  4935. ];
  4936. }
  4937. /**
  4938. * 预估生成所需积分(mode=chat/image/video,支持多数量总额)
  4939. *
  4940. * chat : count(默认1,AI对话单次10积分);批量分集可传 anime_id + generate_episode_number 按实际待创建集数估算
  4941. * image : model 必传;resolution(1k/2k/4k)或 width/height 自动归一化;image_num(默认1)
  4942. * video : model 必传;video_resolution(默认720p);video_duration(默认5秒);count(默认1);scene(默认video_generation)
  4943. *
  4944. * @param array $data
  4945. * @return array
  4946. */
  4947. public function previewCharge(array $data): array
  4948. {
  4949. $mode = (string)getProp($data, 'mode', '');
  4950. if (!in_array($mode, ['chat', 'image', 'video'])) {
  4951. Utils::throwError('1003:请传入mode参数(chat/image/video)');
  4952. }
  4953. // 视频计费场景(video_generation/video_to_video),默认视频生成
  4954. $scene = (string)getProp($data, 'scene', 'video_generation');
  4955. // 未显式传scene且带参考视频时,自动按video_to_video定价
  4956. if ($mode === 'video' && !array_key_exists('scene', $data) && !empty(getProp($data, 'reference_videos', []))) {
  4957. $scene = 'video_to_video';
  4958. }
  4959. $items = [];
  4960. $model = '';
  4961. $resolution = '';
  4962. if ($mode === 'video') {
  4963. // 通用视频预估:单价/秒 × 时长 × 数量(多个视频计算总额)
  4964. $model = (string)getProp($data, 'model', '');
  4965. if (!$model) {
  4966. Utils::throwError('1002:model参数不能为空');
  4967. }
  4968. $resolution = strtolower((string)getProp($data, 'video_resolution', '720p'));
  4969. $duration = (int)getProp($data, 'video_duration', 5);
  4970. if ($duration <= 0) {
  4971. $duration = 5;
  4972. }
  4973. $count = max(1, (int)getProp($data, 'count', 1));
  4974. $pointsPerVideo = $this->pointsService->getVideoChargePoints([
  4975. 'model' => $model,
  4976. 'video_resolution' => $resolution,
  4977. 'video_duration' => $duration,
  4978. 'mode' => $scene,
  4979. ]);
  4980. $points = $pointsPerVideo * $count;
  4981. $items[] = [
  4982. 'type' => 'video',
  4983. 'model' => $model,
  4984. 'video_resolution' => $resolution,
  4985. 'video_duration' => $duration,
  4986. 'count' => $count,
  4987. 'points' => $points,
  4988. ];
  4989. } elseif ($mode === 'image') {
  4990. // 通用图片预估:单张价格 × 张数(resolution 可直传,或传 width/height 自动归一化)
  4991. $model = (string)getProp($data, 'model', '');
  4992. if (!$model) {
  4993. Utils::throwError('1002:model参数不能为空');
  4994. }
  4995. $resolution = strtolower((string)getProp($data, 'resolution', ''));
  4996. if (!$resolution) {
  4997. $width = (int)getProp($data, 'width', 0);
  4998. $height = (int)getProp($data, 'height', 0);
  4999. if ($width <= 0 || $height <= 0) {
  5000. $width = 1600;
  5001. $height = 2848;
  5002. }
  5003. $resolution = $this->pointsService->normalizeImageResolutionKey($width, $height);
  5004. }
  5005. $imageNum = max(1, (int)getProp($data, 'image_num', 1));
  5006. $points = $this->pointsService->getImageChargePoints([
  5007. 'model' => $model,
  5008. 'resolution' => $resolution,
  5009. ]) * $imageNum;
  5010. $items[] = [
  5011. 'type' => 'image',
  5012. 'model' => $model,
  5013. 'resolution' => $resolution,
  5014. 'image_num' => $imageNum,
  5015. 'points' => $points,
  5016. ];
  5017. } else {
  5018. // AI对话预估:按 price_type 档位取价(special 默认10 / normal 3);
  5019. // 批量生成分集传 anime_id + generate_episode_number 时按实际待创建集数估算(该场景实际扣费固定 special 档)
  5020. $priceType = (string)getProp($data, 'price_type', 'special');
  5021. if (!in_array($priceType, ['special', 'normal'], true)) {
  5022. Utils::throwError('1003:price_type参数仅支持special或normal');
  5023. }
  5024. $count = max(1, (int)getProp($data, 'count', 1));
  5025. $animeId = getProp($data, 'anime_id');
  5026. $generateEpisodes = (int)getProp($data, 'generate_episode_number', 0);
  5027. if ($animeId && $generateEpisodes > 0) {
  5028. // 批量生成分集按 special 档预估,与实际扣费口径一致
  5029. $priceType = 'special';
  5030. $currentMaxEpisode = DB::table('mp_anime_episodes')
  5031. ->where('anime_id', $animeId)
  5032. ->where('is_default', 1)
  5033. ->max('episode_number');
  5034. $currentMaxEpisode = $currentMaxEpisode ?: 0;
  5035. $startEpisodeNumber = $currentMaxEpisode + 1;
  5036. $endEpisodeNumber = $startEpisodeNumber + $generateEpisodes - 1;
  5037. $existingSkipped = DB::table('mp_batch_episode_generation_details')
  5038. ->where('anime_id', $animeId)
  5039. ->whereBetween('episode_number', [$startEpisodeNumber, $endEpisodeNumber])
  5040. ->whereIn('status', ['pending', 'processing', 'completed'])
  5041. ->count();
  5042. $count = ($endEpisodeNumber - $startEpisodeNumber + 1) - $existingSkipped;
  5043. if ($count < 0) {
  5044. $count = 0;
  5045. }
  5046. }
  5047. $points = $this->pointsService->getChatChargePoints((string)$model, $priceType) * $count;
  5048. $items[] = [
  5049. 'type' => 'chat',
  5050. 'count' => $count,
  5051. 'price_type' => $priceType,
  5052. 'points' => $points,
  5053. ];
  5054. }
  5055. $totalPoints = 0;
  5056. foreach ($items as $item) {
  5057. $totalPoints += $item['points'];
  5058. }
  5059. return [
  5060. 'mode' => $mode,
  5061. 'total_points' => $totalPoints,
  5062. 'items' => $items,
  5063. 'points_balance' => $this->pointsService->getUserPointsBalance(),
  5064. 'remark' => '积分为预估值,实际扣费以生成完成后的实际消耗为准',
  5065. ];
  5066. }
  5067. /**
  5068. * 根据提示词内容智能计算最优视频时长
  5069. *
  5070. * @param string $segmentContent 分镜内容
  5071. * @param string $tailFrame 尾帧描述
  5072. * @return int 视频时长(2-12秒)
  5073. */
  5074. public function calculateOptimalVideoDuration($segmentContent, $tailFrame = '') {
  5075. // 合并所有文本内容
  5076. $fullText = trim($segmentContent . ' ' . $tailFrame);
  5077. // 如果没有内容,返回默认时长
  5078. if (empty($fullText)) {
  5079. return 5;
  5080. }
  5081. // 计算文本长度(中文字符按2个字符计算)
  5082. $textLength = mb_strlen($fullText, 'UTF-8');
  5083. $chineseCharCount = preg_match_all('/[\x{4e00}-\x{9fff}]/u', $fullText);
  5084. $adjustedLength = $textLength + $chineseCharCount; // 中文字符权重更高
  5085. // 分析内容复杂度
  5086. $complexityScore = $this->analyzeContentComplexity($fullText);
  5087. // 基础时长计算(根据文本长度)
  5088. $baseDuration = 3; // 默认2秒
  5089. // if ($adjustedLength <= 20) {
  5090. // $baseDuration = 3;
  5091. // } elseif ($adjustedLength <= 40) {
  5092. // $baseDuration = 4;
  5093. // } elseif ($adjustedLength <= 60) {
  5094. // $baseDuration = 5;
  5095. // } elseif ($adjustedLength <= 80) {
  5096. // $baseDuration = 6;
  5097. // } elseif ($adjustedLength <= 100) {
  5098. // $baseDuration = 7;
  5099. // } elseif ($adjustedLength <= 120) {
  5100. // $baseDuration = 8;
  5101. // } else {
  5102. // $baseDuration = 9;
  5103. // }
  5104. // 根据内容复杂度调整时长
  5105. $finalDuration = $baseDuration + $complexityScore;
  5106. // 确保时长在2-12秒范围内
  5107. return max(4, min(12, $finalDuration));
  5108. }
  5109. /**
  5110. * 分析内容复杂度,返回时长调整值
  5111. *
  5112. * @param string $text 文本内容
  5113. * @return int 调整值(-2到+3)
  5114. */
  5115. private function analyzeContentComplexity($text) {
  5116. $score = 0;
  5117. // 动作关键词(需要更长时间展现)
  5118. $actionKeywords = [
  5119. '跑步', '奔跑', '飞行', '跳跃', '战斗', '打斗', '追逐', '逃跑', '舞蹈', '表演',
  5120. '变化', '变身', '爆炸', '崩塌', '建造', '制作', '烹饪', '绘画', '写字',
  5121. '移动', '旋转', '翻滚', '攀爬', '游泳', '潜水', '滑行', '飞翔'
  5122. ];
  5123. // 静态关键词(可以用较短时间)
  5124. $staticKeywords = [
  5125. '站立', '坐着', '躺着', '静止', '凝视', '思考', '沉思', '观察', '等待',
  5126. '睡觉', '休息', '静坐', '冥想', '阅读', '听音乐'
  5127. ];
  5128. // 复杂场景关键词(需要更长时间)
  5129. $complexSceneKeywords = [
  5130. '人群', '聚会', '会议', '战争', '庆典', '仪式', '表演', '比赛', '竞技',
  5131. '多人', '群体', '团队', '合作', '互动', '对话', '争论', '讨论'
  5132. ];
  5133. // 情感关键词(需要适中时间表现)
  5134. $emotionKeywords = [
  5135. '哭泣', '笑容', '愤怒', '惊讶', '恐惧', '悲伤', '喜悦', '兴奋', '紧张',
  5136. '感动', '震惊', '困惑', '失望', '希望', '绝望', '温柔', '严肃'
  5137. ];
  5138. // 检查动作关键词
  5139. foreach ($actionKeywords as $keyword) {
  5140. if (strpos($text, $keyword) !== false) {
  5141. $score += 1;
  5142. break; // 避免重复加分
  5143. }
  5144. }
  5145. // 检查静态关键词
  5146. foreach ($staticKeywords as $keyword) {
  5147. if (strpos($text, $keyword) !== false) {
  5148. $score -= 1;
  5149. break;
  5150. }
  5151. }
  5152. // 检查复杂场景关键词
  5153. foreach ($complexSceneKeywords as $keyword) {
  5154. if (strpos($text, $keyword) !== false) {
  5155. $score += 1;
  5156. break;
  5157. }
  5158. }
  5159. // 检查情感关键词
  5160. foreach ($emotionKeywords as $keyword) {
  5161. if (strpos($text, $keyword) !== false) {
  5162. $score += 1;
  5163. break;
  5164. }
  5165. }
  5166. // 检查时间相关词汇
  5167. if (preg_match('/缓慢|慢慢|渐渐|逐渐|慢动作/', $text)) {
  5168. $score += 1;
  5169. }
  5170. if (preg_match('/快速|迅速|急速|瞬间|立刻|马上/', $text)) {
  5171. $score -= 1;
  5172. }
  5173. // 检查转场词汇
  5174. if (preg_match('/然后|接着|随后|紧接着|同时|与此同时/', $text)) {
  5175. $score += 1;
  5176. }
  5177. // 检查环境描述(复杂环境需要更多时间)
  5178. if (preg_match('/风景|景色|环境|背景|氛围|光线|阴影|色彩|细节/', $text)) {
  5179. $score += 1;
  5180. }
  5181. // 检查对话内容(对话需要更多时间)
  5182. if (preg_match('/说|讲|告诉|回答|询问|问|对话|交谈/', $text)) {
  5183. $score += 1;
  5184. }
  5185. // 限制调整范围
  5186. return max(-1, min(4, $score));
  5187. }
  5188. /**
  5189. * 创建完整视频合成任务
  5190. *
  5191. * @param array $data
  5192. * @return array
  5193. */
  5194. public function createCompleteVideoTask($data)
  5195. {
  5196. $animeId = getProp($data, 'anime_id');
  5197. $episodeId = getProp($data, 'episode_id');
  5198. // 验证参数
  5199. if (!$animeId || !$episodeId) {
  5200. Utils::throwError('20003:anime_id 和 episode_id 不能为空');
  5201. }
  5202. // 检查是否已存在处理中的任务
  5203. $existingTask = DB::table('mp_complete_video_tasks')
  5204. ->where('anime_id', $animeId)
  5205. ->where('episode_id', $episodeId)
  5206. ->whereIn('generate_status', ['执行中'])
  5207. ->first();
  5208. if ($existingTask) {
  5209. Utils::throwError('20003:该剧集已有正在处理的视频合成任务');
  5210. }
  5211. // 获取全能模式状态
  5212. $ace_mode = DB::table('mp_animes')->where('id', $animeId)->value('ace_mode');
  5213. if ((int)$ace_mode === 1) {
  5214. // 获取所有片段的配音视频,按 act_number 排序
  5215. $segments = DB::table('mp_episode_segments')
  5216. ->where('anime_id', $animeId)
  5217. ->where('episode_id', $episodeId)
  5218. ->orderBy('segment_number')
  5219. ->select('id as act_id', 'act_number', 'video_url', 'audio_url', 'video_time_point_start', 'video_time_point_end')
  5220. ->get();
  5221. // 检查是否所有片段都有视频
  5222. $missingVideos = $segments->filter(function($segment) {
  5223. return empty($segment->video_url);
  5224. });
  5225. if ($missingVideos->isNotEmpty()) {
  5226. Utils::throwError('20003:存在未完成视频的片段,请确保所有片段都已完成配音');
  5227. }
  5228. }else {
  5229. // 获取所有分镜的配音视频,按 segment_number 排序
  5230. $segments = DB::table('mp_episode_segments')
  5231. ->where('anime_id', $animeId)
  5232. ->where('episode_id', $episodeId)
  5233. ->orderBy('segment_number')
  5234. ->select('segment_id', 'segment_number', 'video_url', 'audio_url', 'video_time_point_start', 'video_time_point_end')
  5235. ->get();
  5236. // 检查是否所有分镜都有配音和视频
  5237. $missingVideos = $segments->filter(function($segment) {
  5238. return empty($segment->audio_url) || empty($segment->video_url);
  5239. });
  5240. if ($missingVideos->isNotEmpty()) {
  5241. Utils::throwError('20003:存在未完成配音或视频的分镜,请确保所有分镜都已完成配音或视频');
  5242. }
  5243. }
  5244. if ($segments->isEmpty()) {
  5245. Utils::throwError('20003:未找到该剧集的分镜数据');
  5246. }
  5247. // 获取当前完整视频url
  5248. $completeVideoUrl = DB::table('mp_anime_episodes')
  5249. ->where('anime_id', $animeId)
  5250. ->where('id', $episodeId)
  5251. ->value('complete_video_url');
  5252. // 构建 generate_json
  5253. $generateJson = [];
  5254. $sequence = 1;
  5255. foreach ($segments as $segment) {
  5256. if ((int)$ace_mode === 1) {
  5257. $generateJson[] = [
  5258. 'sequence' => $sequence++,
  5259. 'video_url' => $segment->video_url,
  5260. 'video_time_point_start' => $segment->video_time_point_start,
  5261. 'video_time_point_end' => $segment->video_time_point_end
  5262. ];
  5263. }else {
  5264. $generateJson[] = [
  5265. 'sequence' => $sequence++,
  5266. 'video_url' => $segment->video_url,
  5267. 'audio_url' => $segment->audio_url,
  5268. 'video_time_point_start' => $segment->video_time_point_start,
  5269. 'video_time_point_end' => $segment->video_time_point_end
  5270. ];
  5271. }
  5272. }
  5273. // 创建任务
  5274. $now = date('Y-m-d H:i:s');
  5275. $taskId = DB::table('mp_complete_video_tasks')->insertGetId([
  5276. 'anime_id' => $animeId,
  5277. 'episode_id' => $episodeId,
  5278. 'generate_json' => json_encode($generateJson, 256),
  5279. 'generate_status' => '执行中',
  5280. 'complete_video_url' => '',
  5281. 'created_at' => $now,
  5282. 'updated_at' => $now
  5283. ]);
  5284. if (!$taskId) {
  5285. Utils::throwError('20003:创建任务失败');
  5286. }
  5287. // 更新剧集表的任务ID和状态
  5288. $boolen = DB::table('mp_anime_episodes')
  5289. ->where('anime_id', $animeId)
  5290. ->where('id', $episodeId)
  5291. ->update([
  5292. 'complete_video_task_id' => $taskId,
  5293. 'complete_video_task_status' => '执行中',
  5294. 'updated_at' => $now
  5295. ]);
  5296. if (!$boolen) {
  5297. Utils::throwError('20003:更新剧集表失败');
  5298. }
  5299. dLog('anime')->info('创建完整视频合成任务', [
  5300. 'task_id' => $taskId,
  5301. 'anime_id' => $animeId,
  5302. 'episode_id' => $episodeId,
  5303. 'segment_count' => count($generateJson)
  5304. ]);
  5305. // 请求远程服务器执行生成
  5306. $client = new Client(['timeout' => 600, 'verify' => false]);
  5307. try {
  5308. $result = $client->get("http://122.9.129.83:5000/api/anime/genVideo?taskId={$taskId}");
  5309. $response = $result->getBody()->getContents();
  5310. $response_arr = json_decode($response, true);
  5311. if (!isset($response_arr['code']) || (int)$response_arr['code'] !== 0) {
  5312. $error_msg = isset($response_arr['msg']) ? $response_arr['msg'] : '未知错误';
  5313. dLog('anime')->error('火山合成完整视频失败', ['error' => $error_msg, 'task_id' => $taskId]);
  5314. // // 更新任务状态为失败
  5315. // DB::table('mp_complete_video_tasks')
  5316. // ->where('id', $taskId)
  5317. // ->update([
  5318. // 'generate_status' => '执行失败',
  5319. // 'error_message' => $error_msg,
  5320. // 'updated_at' => date('Y-m-d H:i:s')
  5321. // ]);
  5322. // // 同步更新剧集表状态
  5323. // DB::table('mp_anime_episodes')
  5324. // ->where('complete_video_task_id', $taskId)
  5325. // ->update([
  5326. // 'complete_video_task_status' => '执行失败',
  5327. // 'updated_at' => date('Y-m-d H:i:s')
  5328. // ]);
  5329. Utils::throwError('20003:火山合成完整视频失败: ' . $error_msg);
  5330. }
  5331. } catch (\Exception $e) {
  5332. dLog('anime')->error('调用远程服务器失败', ['error' => $e->getMessage(), 'task_id' => $taskId]);
  5333. // 更新任务状态为失败
  5334. DB::table('mp_complete_video_tasks')
  5335. ->where('id', $taskId)
  5336. ->update([
  5337. 'generate_status' => '执行失败',
  5338. 'error_message' => $e->getMessage(),
  5339. 'updated_at' => date('Y-m-d H:i:s')
  5340. ]);
  5341. // 同步更新剧集表状态
  5342. DB::table('mp_anime_episodes')
  5343. ->where('complete_video_task_id', $taskId)
  5344. ->update([
  5345. 'complete_video_task_status' => '执行失败',
  5346. 'updated_at' => date('Y-m-d H:i:s')
  5347. ]);
  5348. Utils::throwError('20003:调用远程服务器失败: ' . $e->getMessage());
  5349. }
  5350. // 开始轮询任务状态
  5351. $maxAttempts = 60; // 5分钟 = 60次 * 5秒
  5352. $pollInterval = 5; // 每5秒轮询一次
  5353. $attempt = 0;
  5354. dLog('anime')->info('开始轮询任务状态', ['task_id' => $taskId]);
  5355. while ($attempt < $maxAttempts) {
  5356. sleep($pollInterval);
  5357. $attempt++;
  5358. // 查询任务状态
  5359. $task = DB::table('mp_complete_video_tasks')
  5360. ->where('id', $taskId)
  5361. ->first();
  5362. if (!$task) {
  5363. dLog('anime')->error('任务不存在', ['task_id' => $taskId]);
  5364. Utils::throwError('20003:任务不存在');
  5365. }
  5366. dLog('anime')->info('轮询任务状态', [
  5367. 'task_id' => $taskId,
  5368. 'attempt' => $attempt,
  5369. 'status' => $task->generate_status
  5370. ]);
  5371. // 检查任务是否完成
  5372. if ($task->generate_status === '执行成功') {
  5373. // 同步更新剧集表状态
  5374. $boolen3 = DB::table('mp_anime_episodes')
  5375. ->where('anime_id', $animeId)
  5376. ->where('id', $episodeId)
  5377. ->update([
  5378. 'complete_video_url' => $task->complete_video_url,
  5379. 'complete_video_task_status' => '执行成功',
  5380. 'updated_at' => date('Y-m-d H:i:s')
  5381. ]);
  5382. dLog('anime')->info('视频合成任务完成', [
  5383. 'task_id' => $taskId,
  5384. 'video_url' => $task->complete_video_url,
  5385. 'attempts' => $attempt
  5386. ]);
  5387. // 如果更新成功则远程删除之前的文件
  5388. if ($boolen3 && $completeVideoUrl) {
  5389. $encode_url = urlencode($completeVideoUrl);
  5390. $client = new Client(['timeout' => 300, 'verify' => false]);
  5391. // 根据ID通过API通知合成音频
  5392. // $result = $client->get("http://47.240.171.155:5000/api/fileDelete?url={$encode_url}");
  5393. $result = $client->get("http://122.9.129.83:5000/api/fileDelete?url={$encode_url}");
  5394. $response = $result->getBody()->getContents();
  5395. $response_arr = json_decode($response, true);
  5396. Log::info('火山删除音频返回: '.$response);
  5397. if (!isset($response_arr['status']) || (int)$response_arr['status'] !== 0) {
  5398. $error_msg = isset($response_arr['msg']) ? $response_arr['msg'] : '未知错误';
  5399. Log::info('火山删除音频失败: '.$error_msg);
  5400. // Utils::throwError('20003:火山删除音频失败');
  5401. }
  5402. }
  5403. return [
  5404. 'task_id' => $taskId,
  5405. 'anime_id' => $animeId,
  5406. 'episode_id' => $episodeId,
  5407. 'segment_count' => count($generateJson),
  5408. 'generate_status' => '执行成功',
  5409. 'complete_video_url' => $task->complete_video_url,
  5410. ];
  5411. }
  5412. // 检查任务是否失败
  5413. if ($task->generate_status === '执行失败') {
  5414. // 同步更新剧集表状态
  5415. DB::table('mp_anime_episodes')
  5416. ->where('anime_id', $animeId)
  5417. ->where('id', $episodeId)
  5418. ->update([
  5419. 'complete_video_task_status' => '执行失败',
  5420. 'updated_at' => date('Y-m-d H:i:s')
  5421. ]);
  5422. $errorMessage = $task->error_message ?? '未知错误';
  5423. dLog('anime')->error('视频合成任务失败', [
  5424. 'task_id' => $taskId,
  5425. 'error' => $errorMessage,
  5426. 'attempts' => $attempt
  5427. ]);
  5428. return [
  5429. 'task_id' => $taskId,
  5430. 'anime_id' => $animeId,
  5431. 'episode_id' => $episodeId,
  5432. 'segment_count' => count($generateJson),
  5433. 'generate_status' => '执行失败',
  5434. 'error_message' => $errorMessage
  5435. ];
  5436. }
  5437. }
  5438. // 超时处理
  5439. dLog('anime')->warning('视频合成任务超时', [
  5440. 'task_id' => $taskId,
  5441. 'max_attempts' => $maxAttempts,
  5442. 'timeout_seconds' => $maxAttempts * $pollInterval
  5443. ]);
  5444. // 更新任务状态为超时
  5445. DB::table('mp_complete_video_tasks')
  5446. ->where('id', $taskId)
  5447. ->update([
  5448. 'generate_status' => '超时',
  5449. 'error_message' => '任务执行超时(5分钟)',
  5450. 'updated_at' => date('Y-m-d H:i:s')
  5451. ]);
  5452. return [
  5453. 'task_id' => $taskId,
  5454. 'anime_id' => $animeId,
  5455. 'episode_id' => $episodeId,
  5456. 'segment_count' => count($generateJson),
  5457. 'generate_status' => '超时',
  5458. 'error_message' => '任务执行超时,请稍后查询任务状态'
  5459. ];
  5460. }
  5461. /**
  5462. * 根据 inner_prompt_type 附加内置提示词
  5463. *
  5464. * @param string $prompt 用户提示词
  5465. * @param int $innerPromptType 内置提示词类型(1=三视图, 2=九宫格)
  5466. * @return string 合并后的提示词
  5467. */
  5468. public static function appendInnerPrompt($prompt, $innerPromptType = 0)
  5469. {
  5470. $innerPromptMap = [
  5471. 1 => '基于参考图生成主体的标准正面、侧面、后面三视图,主体完整。在最左侧添加主体正视图的特写,特写大小为标准一寸照,人物不要带表情。右侧是全身的三视图,其中正面、侧面的三视图给人脸打白色码、不显示五官。主体清晰完整。背景修改成纯白色,整体保持与参考图一致的美术风格和色彩搭配。画面无说明文字。',
  5472. 2 => '基于参考图及提示词内容,生成9张连贯的系列图片:9张图片围绕同一主体展开,保持角色形象、美术风格和色彩搭配完全一致,画面内容依次衔接、情节连贯,整体构成一组完整的系列图。每张图片主体完整清晰,构图合理,画面干净,无文字、无水印、无字幕。',
  5473. ];
  5474. if (!isset($innerPromptMap[$innerPromptType])) {
  5475. return $prompt;
  5476. }
  5477. return trim((string)$prompt) . "\n" . $innerPromptMap[$innerPromptType];
  5478. }
  5479. /**
  5480. * 根据 inner_prompt_type 获取生成图片数量
  5481. *
  5482. * @param int $innerPromptType 内置提示词类型
  5483. * @param int $imageNum 传入的图片张数
  5484. * @return int 图片数量
  5485. */
  5486. public static function getInnerImageNum($innerPromptType = 0, $imageNum)
  5487. {
  5488. return (int)$innerPromptType === 2 ? 9 : $imageNum;
  5489. }
  5490. /**
  5491. * 提取图片生成结果URL
  5492. *
  5493. * @param mixed $resultUrl 任务结果URL(数组、JSON字符串或普通字符串)
  5494. * @param int $innerPromptType 内置提示词类型
  5495. * @return mixed 类型2返回全部URL数组,其它类型返回首个URL
  5496. */
  5497. public static function extractResultUrls($resultUrl, $innerPromptType = 0)
  5498. {
  5499. $resultUrls = is_array($resultUrl) ? $resultUrl : json_decode((string)$resultUrl, true);
  5500. if (is_array($resultUrls) && !empty($resultUrls)) {
  5501. $resultUrls = array_values($resultUrls);
  5502. return (int)$innerPromptType === 2 ? $resultUrls : $resultUrls[0];
  5503. }
  5504. if (!empty($resultUrl)) {
  5505. return (int)$innerPromptType === 2 ? [$resultUrl] : $resultUrl;
  5506. }
  5507. return (int)$innerPromptType === 2 ? [] : '';
  5508. }
  5509. public function generateImg($data, $onTaskCreated = null, $onPoll = null) {
  5510. $prompt = getProp($data, 'prompt');
  5511. $episode_id = getProp($data, 'episode_id');
  5512. $ref_img_urls = getProp($data, 'ref_img_urls');
  5513. $ratio = getProp($data, 'ratio', '9:16');
  5514. $resolution = getProp($data, 'resolution', '2k');
  5515. $inner_prompt_type = getProp($data, 'inner_prompt_type', 0);
  5516. $imageNum = (int)getProp($data, 'image_num', 1);
  5517. // 分辨率档位与尺寸映射统一从 BaseConst 获取
  5518. $sizeMap = BaseConst::IMAGE_RESOLUTION_SIZE_MAP;
  5519. // 参数验证
  5520. $resolution = strtolower($resolution);
  5521. if (!isset($sizeMap[$resolution])) {
  5522. Utils::throwError('20003:分辨率参数错误,仅支持 2k、3k、4k');
  5523. }
  5524. if (!isset($sizeMap[$resolution][$ratio])) {
  5525. Utils::throwError('20003:宽高比参数错误,该分辨率下不支持 ' . $ratio . ' 比例');
  5526. }
  5527. // 根据 ratio 和 resolution 确定宽高
  5528. $width = $sizeMap[$resolution][$ratio]['width'];
  5529. $height = $sizeMap[$resolution][$ratio]['height'];
  5530. if (!is_array($ref_img_urls) && !empty($ref_img_urls)) {
  5531. if (is_json($ref_img_urls)) {
  5532. $ref_img_urls = json_decode($ref_img_urls, true);
  5533. }else {
  5534. $ref_img_urls = explode(',', $ref_img_urls);
  5535. }
  5536. }
  5537. // 处理图片模型
  5538. $model = getProp($data, 'model');
  5539. if (!$model) {
  5540. // 用户没有输入,从episode表获取
  5541. if ($episode_id) {
  5542. $episode = DB::table('mp_anime_episodes')->where('id', $episode_id)->first();
  5543. $model = getProp($episode, 'image_model');
  5544. }
  5545. if (!$model) {
  5546. // episode表也没有,使用默认值
  5547. $model = 'gpt-image-2';
  5548. }
  5549. }
  5550. // 验证模型是否在可用模型表中
  5551. if (!DB::table('mp_image_models')->where('model', $model)->where('is_enabled', 1)->exists()) {
  5552. // $model = 'gpt-image-2';
  5553. Utils::throwError('20003:该模型已不可用,请更换!');
  5554. }
  5555. // 保存到episode表
  5556. if ($episode_id) {
  5557. DB::table('mp_anime_episodes')->where('id', $episode_id)->update([
  5558. 'image_model' => $model,
  5559. 'updated_at' => date('Y-m-d H:i:s')
  5560. ]);
  5561. }
  5562. // 参数验证
  5563. if (!$prompt) Utils::throwError('20003:请提供提示词');
  5564. // 根据 inner_prompt_type 附加内置提示词并确定生成图片数量
  5565. $prompt = self::appendInnerPrompt($prompt, $inner_prompt_type);
  5566. $imageNum = self::getInnerImageNum($inner_prompt_type, $imageNum);
  5567. try {
  5568. // 创建图片生成任务
  5569. $params = [
  5570. 'prompt' => $prompt,
  5571. 'model' => $model,
  5572. 'ref_img_urls' => '',
  5573. 'width' => $width,
  5574. 'height' => $height,
  5575. 'image_num' => $imageNum,
  5576. // 计费锚点(动漫/剧集/剧本),上下文没有时不记录
  5577. 'anime_id' => getProp($data, 'anime_id'),
  5578. 'episode_id' => $episode_id,
  5579. ];
  5580. if ($ref_img_urls) $params['ref_img_urls'] = is_array($ref_img_urls) ? $ref_img_urls : [$ref_img_urls];
  5581. $task = $this->aiImageGenerationService->createImageGenerationTask($params);
  5582. $task_id = $task->id;
  5583. if (!$task_id) {
  5584. Utils::throwError('20003:创建图片生成任务失败');
  5585. }
  5586. // 创建任务中心记录并关联图片任务ID
  5587. $taskCenter = $this->taskCenterService->createTask('image', [
  5588. 'title' => '文生图',
  5589. 'ref_task_id' => $task_id,
  5590. // 'prompt' => $prompt,
  5591. // 'params' => json_encode($data, JSON_UNESCAPED_UNICODE),
  5592. ]);
  5593. $taskCenterId = $taskCenter->id;
  5594. // 组装本次任务信息(用于init消息,类似generateVideo)
  5595. $taskInfo = [
  5596. 'task_id' => $task_id,
  5597. 'status' => getProp($task, 'status', 'processing'),
  5598. 'model' => $model,
  5599. 'ratio' => $ratio,
  5600. 'resolution' => $resolution,
  5601. 'image_num' => $imageNum,
  5602. ];
  5603. // 创建图片任务后立即回调(类似generateVideo的init消息,返回任务中心ID和任务信息)
  5604. if (is_callable($onTaskCreated)) {
  5605. $onTaskCreated($taskCenterId, $taskInfo);
  5606. }
  5607. // 检查任务模型类型(火山模型和GPT模型都支持直接检查任务状态)
  5608. $model = getProp($task, 'model');
  5609. $isVolcModel = in_array($model, \App\Consts\BaseConst::VOLC_PIC_MODELS);
  5610. $isGptModel = in_array($model, \App\Consts\BaseConst::GPT_IMAGE2_MODELS);
  5611. $isSyncModel = $isVolcModel || $isGptModel;
  5612. // 任务需要轮询获取结果(15分钟超时,每3秒查询一次)
  5613. $start_time = time();
  5614. $timeout = 900; // 15分钟
  5615. $img_url = '';
  5616. $img_urls = [];
  5617. $lastQueueMessageTime = $start_time; // 记录上次发送队列消息的时间
  5618. $queueMessageInterval = 60; // 队列消息发送间隔(秒)
  5619. while (time() - $start_time < $timeout) {
  5620. sleep(3);
  5621. // 每分钟发送一次队列状态消息(仅流式模式)
  5622. if (is_callable($onPoll)) {
  5623. $currentTime = time();
  5624. if ($currentTime - $lastQueueMessageTime >= $queueMessageInterval) {
  5625. $onPoll($taskCenterId, $task_id, $currentTime - $start_time);
  5626. $lastQueueMessageTime = $currentTime;
  5627. }
  5628. }
  5629. // 火山API和GPT-Image2 API是同步返回结果的,直接检查任务状态
  5630. if ($isSyncModel) {
  5631. // 刷新任务状态
  5632. $task = MpGeneratePicTask::where('id', $task_id)->first();
  5633. if ($task->status === 'success' && $task->result_url) {
  5634. $resultUrls = is_array($task->result_url) ? $task->result_url : json_decode((string)$task->result_url, true);
  5635. $resultUrls = is_array($resultUrls) ? array_values(array_filter($resultUrls)) : [];
  5636. if (!empty($resultUrls)) {
  5637. $img_urls = $resultUrls;
  5638. $img_url = $resultUrls[0];
  5639. } else {
  5640. $img_url = (string)$task->result_url;
  5641. }
  5642. break;
  5643. } elseif ($task->status === 'failed') {
  5644. $errorMsg = mapErrorMessage($task->error_message ?? '');
  5645. Utils::throwError('20003:图片生成失败,' . $errorMsg);
  5646. }
  5647. // // 如果还在处理中,提示用户稍后查看
  5648. // Utils::throwError('20003:图片生成中,请稍后刷新查看结果');
  5649. }else {
  5650. $task = MpGeneratePicTask::where('id', $task_id)->first();
  5651. $statusInfo = $this->aiImageGenerationService->queryTaskStatus($task);
  5652. if ($statusInfo['status'] === 'success') {
  5653. $task->updateStatus('success', [
  5654. 'result_url' => $statusInfo['result_url'],
  5655. 'result_json' => $statusInfo['result_json'] ?? []
  5656. ]);
  5657. $resultUrls = is_array($statusInfo['result_url']) ? $statusInfo['result_url'] : json_decode((string)$statusInfo['result_url'], true);
  5658. $resultUrls = is_array($resultUrls) ? array_values(array_filter($resultUrls)) : [];
  5659. if (!empty($resultUrls)) {
  5660. $img_urls = $resultUrls;
  5661. $img_url = $resultUrls[0];
  5662. } else {
  5663. $img_url = (string)$statusInfo['result_url'];
  5664. }
  5665. break;
  5666. } elseif ($statusInfo['status'] === 'failed') {
  5667. $task->updateStatus('failed', [
  5668. 'error_message' => $statusInfo['error_message'],
  5669. 'result_json' => $statusInfo['result_json'] ?? []
  5670. ]);
  5671. dLog('anime')->error('图片生成失败,', [
  5672. 'error' => $statusInfo['error_message'] ?? '未知错误'
  5673. ]);
  5674. $errorMsg = mapErrorMessage($statusInfo['error_message'] ?? '');
  5675. Utils::throwError('20003:图片生成失败,' . $errorMsg);
  5676. }
  5677. }
  5678. }
  5679. if (empty($img_url)) {
  5680. Utils::throwError('20003:图片生成超时,请稍后重试');
  5681. }
  5682. // 多张图片返回全部URL数组(配合控制器输出image_urls字段)
  5683. if (count($img_urls) > 1) {
  5684. return [
  5685. 'img_url' => $img_url,
  5686. 'image_urls' => $img_urls,
  5687. 'task_id' => $taskCenterId,
  5688. ];
  5689. }
  5690. return [
  5691. 'img_url' => $img_url,
  5692. 'task_id' => $taskCenterId,
  5693. ];
  5694. } catch (\Exception $e) {
  5695. dLog('anime')->error('更新角色或场景失败', [
  5696. 'error' => $e->getMessage()
  5697. ]);
  5698. logDB('anime', 'error', '更新角色或场景失败', ['error' => $e->getMessage()]);
  5699. Utils::throwError('20003:' . $e->getMessage());
  5700. }
  5701. }
  5702. /**
  5703. * 使用文生文模型解析分镜内容
  5704. */
  5705. private function parseSegmentContentWithAI($segment_content) {
  5706. try {
  5707. // 使用DeepSeek服务的公开方法解析分镜内容
  5708. return $this->DeepSeekService->parseSegmentContent($segment_content);
  5709. } catch (\Exception $e) {
  5710. // 如果AI解析失败,记录日志并返回原内容
  5711. dLog('anime')->error('AI解析分镜内容失败: ' . $e->getMessage());
  5712. return $segment_content;
  5713. }
  5714. }
  5715. /**
  5716. * 处理分集的角色和场景数据(继承全局数据或创建新任务)
  5717. *
  5718. * @param int $episode_id 分集ID
  5719. * @param int $anime_id 动漫ID
  5720. * @param array $roles 分集角色数组(引用传递)
  5721. * @param array $scenes 分集场景数组(引用传递)
  5722. * @param array $episode 分集数据
  5723. */
  5724. private function processEpisodeRolesAndScenes($episode_id, $anime_id, &$roles, &$scenes, $episode) {
  5725. // 获取全局动漫的角色和场景数据
  5726. $anime = DB::table('mp_animes')->where('id', $anime_id)->first();
  5727. if (!$anime) return;
  5728. $art_style_type = getProp($anime, 'art_style_type');
  5729. $character_prefix = '';
  5730. $scene_prefix = '';
  5731. if ($art_style_type) {
  5732. $art_style_arr = $this->DeepSeekService->getArtStyleShortPromptByInput($art_style_type);
  5733. $character_prefix = isset($art_style_arr['character_prefix']) ? $art_style_arr['character_prefix'] : '';
  5734. $scene_prefix = isset($art_style_arr['scene_prefix']) ? $art_style_arr['scene_prefix'] : '';
  5735. }
  5736. $global_roles = json_decode(getProp($anime, 'roles'), true) ?: [];
  5737. $global_scenes = json_decode(getProp($anime, 'scenes'), true) ?: [];
  5738. $roles_updated = false;
  5739. $scenes_updated = false;
  5740. // 处理角色
  5741. foreach ($roles as &$role) {
  5742. $role_name = getProp($role, 'role');
  5743. $role_description = getProp($role, 'description');
  5744. $role_pic_prompt = getProp($role, 'pic_prompt');
  5745. $role_url = getProp($role, 'url');
  5746. $role_task_id = getProp($role, 'task_id');
  5747. // 如果已有URL或已有任务ID,跳过
  5748. if (!empty($role_url) || !empty($role_task_id) || $role_name === '旁白') {
  5749. continue;
  5750. }
  5751. $url_inherited = false;
  5752. // 尝试从全局数据中继承
  5753. foreach ($global_roles as $global_role) {
  5754. $global_role_name = getProp($global_role, 'role');
  5755. $global_role_description = getProp($global_role, 'description');
  5756. $global_role_pic_prompt = getProp($global_role, 'pic_prompt');
  5757. $global_role_url = getProp($global_role, 'url');
  5758. $global_role_task_id = getProp($global_role, 'task_id');
  5759. $global_role_task_status = getProp($global_role, 'task_status');
  5760. // 满足条件:角色名相同、描述相同、pic_prompt相同、全局有URL
  5761. if ($role_name === $global_role_name
  5762. && $role_description === $global_role_description
  5763. && $role_pic_prompt === $global_role_pic_prompt
  5764. && !empty($global_role_url)) {
  5765. // 继承 task_id、task_status 和 url
  5766. $role['task_id'] = $global_role_task_id;
  5767. $role['task_status'] = $global_role_task_status;
  5768. $role['url'] = $global_role_url;
  5769. $roles_updated = true;
  5770. $url_inherited = true;
  5771. dLog('anime')->info("分集ID:{$episode_id} 角色:{$role_name} 继承全局数据");
  5772. break;
  5773. }
  5774. }
  5775. // 如果无法继承且没有任务ID,创建新任务
  5776. if (!$url_inherited && empty($role_task_id)) {
  5777. try {
  5778. $art_style = getProp($episode, 'art_style');
  5779. // 优先使用 pic_prompt,如果没有则使用 description
  5780. $description = !empty($role_pic_prompt) ? trim((string)$role_pic_prompt) : $role_description;
  5781. // if ($art_style) {
  5782. // // $description = "美术风格:\n{$art_style}\n主体描述:{$description}\n图片要求:图片侧重点是人物,不要出现场景或背景,并且只能生成一个人物";
  5783. // $description = "主体描述:{$description}\n图片要求:图片侧重点是人物,不要出现场景或背景,并且只能生成一个人物";
  5784. // }
  5785. $description = buildStylePromptPrefix($character_prefix) . "主体描述:{$description}\n超高清,高细节,主体突出,构图合理,画面干净,无场景或背景,单人物,无文字,无水印,无字幕,电影级光影,视觉焦点明确";
  5786. $params = [
  5787. 'prompt' => $description,
  5788. 'ref_img_urls' => [],
  5789. // 计费锚点(动漫/剧集/剧本),用于积分明细归属统计
  5790. 'anime_id' => $anime_id,
  5791. 'episode_id' => $episode_id,
  5792. 'episode_number' => getProp($episode, 'episode_number'),
  5793. ];
  5794. $task = $this->aiImageGenerationService->createImageGenerationTask($params);
  5795. $task_id = $task->id;
  5796. if ($task_id) {
  5797. $role['task_id'] = $task_id;
  5798. $role['task_status'] = 'processing';
  5799. $roles_updated = true;
  5800. dLog('anime')->info("分集ID:{$episode_id} 角色:{$role_name} 创建图片生成任务,任务ID:{$task_id}");
  5801. }
  5802. } catch (\Exception $e) {
  5803. dLog('anime')->error("分集ID:{$episode_id} 角色:{$role_name} 创建图片生成任务失败: " . $e->getMessage());
  5804. }
  5805. }
  5806. }
  5807. // 处理场景
  5808. foreach ($scenes as &$scene) {
  5809. $scene_name = getProp($scene, 'scene');
  5810. $scene_description = getProp($scene, 'description');
  5811. $scene_pic_prompt = getProp($scene, 'pic_prompt');
  5812. $scene_url = getProp($scene, 'url');
  5813. $scene_task_id = getProp($scene, 'task_id');
  5814. // 如果已有URL或已有任务ID,跳过
  5815. if (!empty($scene_url) || !empty($scene_task_id)) {
  5816. continue;
  5817. }
  5818. $url_inherited = false;
  5819. // 尝试从全局数据中继承
  5820. foreach ($global_scenes as $global_scene) {
  5821. $global_scene_name = getProp($global_scene, 'scene');
  5822. $global_scene_description = getProp($global_scene, 'description');
  5823. $global_scene_pic_prompt = getProp($global_scene, 'pic_prompt');
  5824. $global_scene_url = getProp($global_scene, 'url');
  5825. $global_scene_task_id = getProp($global_scene, 'task_id');
  5826. $global_scene_task_status = getProp($global_scene, 'task_status');
  5827. // 满足条件:场景名相同、描述相同、pic_prompt相同、全局有URL
  5828. if ($scene_name === $global_scene_name
  5829. && $scene_description === $global_scene_description
  5830. && $scene_pic_prompt === $global_scene_pic_prompt
  5831. && !empty($global_scene_url)) {
  5832. // 继承 task_id、task_status 和 url
  5833. $scene['task_id'] = $global_scene_task_id;
  5834. $scene['task_status'] = $global_scene_task_status;
  5835. $scene['url'] = $global_scene_url;
  5836. $scenes_updated = true;
  5837. $url_inherited = true;
  5838. dLog('anime')->info("分集ID:{$episode_id} 场景:{$scene_name} 继承全局数据");
  5839. break;
  5840. }
  5841. }
  5842. // 如果无法继承且没有任务ID,创建新任务
  5843. if (!$url_inherited && empty($scene_task_id)) {
  5844. try {
  5845. $art_style = getProp($episode, 'art_style');
  5846. // 优先使用 pic_prompt,如果没有则使用 description
  5847. $description = !empty($scene_pic_prompt) ? trim((string)$scene_pic_prompt) : $scene_description;
  5848. // if ($art_style) {
  5849. // // $description = "美术风格:\n{$art_style}\n场景描述:{$description}\n图片要求: 图片侧重点是场景,生成的是场景环境图片,不要出现人物(此为第一优先要求)";
  5850. // $description = "场景描述:{$description}\n图片要求: 图片侧重点是场景,生成的是场景环境图片,不要出现人物(此为第一优先要求)";
  5851. // }
  5852. $description = buildStylePromptPrefix($scene_prefix) . "场景描述:{$description}\n无人物,超高清,高细节,主体突出,构图合理,画面干净,无文字,无水印,无字幕,电影级光影,视觉焦点明确";
  5853. $params = [
  5854. 'prompt' => $description,
  5855. 'ref_img_urls' => [],
  5856. // 计费锚点(动漫/剧集/剧本),用于积分明细归属统计
  5857. 'anime_id' => $anime_id,
  5858. 'episode_id' => $episode_id,
  5859. 'episode_number' => getProp($episode, 'episode_number'),
  5860. ];
  5861. $task = $this->aiImageGenerationService->createImageGenerationTask($params);
  5862. $task_id = $task->id;
  5863. if ($task_id) {
  5864. $scene['task_id'] = $task_id;
  5865. $scene['task_status'] = 'processing';
  5866. $scenes_updated = true;
  5867. dLog('anime')->info("分集ID:{$episode_id} 场景:{$scene_name} 创建图片生成任务,任务ID:{$task_id}");
  5868. }
  5869. } catch (\Exception $e) {
  5870. dLog('anime')->error("分集ID:{$episode_id} 场景:{$scene_name} 创建图片生成任务失败: " . $e->getMessage());
  5871. }
  5872. }
  5873. }
  5874. // 如果有更新,保存到数据库
  5875. if ($roles_updated || $scenes_updated) {
  5876. $update_data = ['updated_at' => date('Y-m-d H:i:s')];
  5877. if ($roles_updated) {
  5878. $update_data['roles'] = json_encode($roles, JSON_UNESCAPED_UNICODE);
  5879. }
  5880. if ($scenes_updated) {
  5881. $update_data['scenes'] = json_encode($scenes, JSON_UNESCAPED_UNICODE);
  5882. }
  5883. DB::table('mp_anime_episodes')->where('id', $episode_id)->update($update_data);
  5884. dLog('anime')->info("分集ID:{$episode_id} 角色和场景数据已更新");
  5885. }
  5886. }
  5887. /**
  5888. * 根据图片URL使用AI反推图片提示词
  5889. *
  5890. * @param string $img_url 图片URL
  5891. * @return string 反推的提示词
  5892. */
  5893. private function generateImagePromptFromUrl($img_url) {
  5894. try {
  5895. // 获取默认模型
  5896. $model = 'doubao-seed-2-0-mini-260215';
  5897. // 构建messages参数
  5898. $messages = [
  5899. [
  5900. 'role' => 'user',
  5901. 'content' => [
  5902. [
  5903. 'type' => 'text',
  5904. 'text' => '请解析这张参考图,并直接输出一段专业中文反推提示词。提示词用于短剧分镜图片生成,必须聚焦角色和场景本身,可包含姿态、镜头视角、构图、画风、色彩氛围、光线、景深或光圈质感等要素。不要输出解释、标题、列表或无关背景,只输出可直接用于文生图的分镜图片提示词'
  5905. ],
  5906. [
  5907. 'type' => 'image_url',
  5908. 'image_url' => [
  5909. 'url' => $img_url
  5910. ]
  5911. ]
  5912. ]
  5913. ]
  5914. ];
  5915. // 构建请求参数
  5916. $params = [
  5917. 'model' => $model,
  5918. 'messages' => $messages,
  5919. 'stream' => false,
  5920. 'thinking' => ['type' => 'disabled'] // 不使用思考模式
  5921. ];
  5922. // 调用DeepSeek服务的volcEngineChatCompletion方法(非流式)
  5923. $result = $this->DeepSeekService->volcEngineChatCompletion($params);
  5924. // 仅记录 token 使用明细(不扣积分)
  5925. $uid = 0;
  5926. try {
  5927. $uid = (int)Site::getUid();
  5928. } catch (\Throwable $e) {
  5929. // 非请求上下文(如命令行)下可能无法获取用户ID,置为0跳过记录
  5930. }
  5931. $this->pointsService->recordTokenOnlyDetail(
  5932. $uid,
  5933. $this->pointsService->getTokensFromUsage($result['usage'] ?? []),
  5934. [
  5935. 'model' => $model,
  5936. 'img_url' => $img_url,
  5937. 'source' => 'generateImagePromptFromUrl',
  5938. ],
  5939. 'chat',
  5940. $model,
  5941. ''
  5942. );
  5943. // 返回生成的内容
  5944. return getProp($result, 'fullContent', '图片描述生成失败');
  5945. } catch (\Exception $e) {
  5946. dLog('anime')->error('AI反推图片提示词失败: ' . $e->getMessage(), [
  5947. 'img_url' => $img_url
  5948. ]);
  5949. logDB('anime', 'error', 'AI反推图片提示词失败', [
  5950. 'error' => $e->getMessage(),
  5951. 'img_url' => $img_url
  5952. ]);
  5953. return '图片描述生成失败: ' . $e->getMessage();
  5954. }
  5955. }
  5956. /**
  5957. * 音频试听接口
  5958. * 创建音频任务并轮询获取结果
  5959. *
  5960. * @param array $data 参数数组
  5961. * @return array 返回音频URL或错误信息
  5962. */
  5963. public function previewAudio($data) {
  5964. $dialogue = getProp($data, 'dialogue');
  5965. // 必填参数验证
  5966. if (!$dialogue) Utils::throwError('20003:dialogue不能为空');
  5967. // 获取参数,优先使用传入的参数,否则使用分镜中的参数
  5968. $voice_type = getProp($data, 'voice_type');
  5969. $voice_name = getProp($data, 'voice_name');
  5970. $voice_actor = getProp($data, 'voice_actor');
  5971. $emotion_type = getProp($data, 'emotion_type');
  5972. $gender = getProp($data, 'gender', 0);
  5973. $emotion = getProp($data, 'emotion');
  5974. $speed_ratio = getProp($data, 'speed_ratio', 0);
  5975. $loudness_ratio = getProp($data, 'loudness_ratio', 0);
  5976. $emotion_scale = getProp($data, 'emotion_scale', 0);
  5977. $pitch = getProp($data, 'pitch', 0);
  5978. try {
  5979. $now = date('Y-m-d H:i:s');
  5980. // 构建生成参数
  5981. $generate_json = json_encode([
  5982. 'text' => $dialogue,
  5983. 'role' => $voice_actor,
  5984. 'voice_type' => $voice_type,
  5985. 'voice_name' => $voice_name,
  5986. 'emotion' => $emotion,
  5987. 'emotion_type' => $emotion_type,
  5988. 'gender' => $gender,
  5989. 'speed_ratio' => $speed_ratio,
  5990. 'loudness_ratio' => $loudness_ratio,
  5991. 'emotion_scale' => $emotion_scale,
  5992. 'pitch' => $pitch,
  5993. ], 256);
  5994. // 请求远程服务器执行生成
  5995. $client = new Client(['timeout' => 600, 'verify' => false]);
  5996. $result = $client->get("http://122.9.129.83:5000/api/anime/audioPreview?generateJson={$generate_json}");
  5997. $response = $result->getBody()->getContents();
  5998. $response_arr = json_decode($response, true);
  5999. if (!isset($response_arr['code']) || (int)$response_arr['code'] !== 0) {
  6000. $error_msg = isset($response_arr['msg']) ? $response_arr['msg'] : '未知错误';
  6001. dLog('anime')->error('音频试听任务创建失败', ['error' => $error_msg, 'response_arr' => $response_arr]);
  6002. Utils::throwError('20003:音频试听任务创建失败: ' . $error_msg);
  6003. }
  6004. $arr = $response_arr['data'];
  6005. $subtitle_info = $arr['subtitle_info'];
  6006. $audio_duration = json_decode($subtitle_info, true)['duration'];
  6007. if (!isset($arr['url']) || !$audio_duration || !$subtitle_info) Utils::throwError('20003:音频参数生成异常');
  6008. return [
  6009. 'audio_url' => $arr['url'],
  6010. 'subtitle_info' => $subtitle_info,
  6011. 'audio_duration' => round($audio_duration, 2)
  6012. ];
  6013. } catch (\Exception $e) {
  6014. dLog('anime')->error('音频试听失败', ['error' => $e->getMessage()]);
  6015. Utils::throwError('20003:' . $e->getMessage());
  6016. }
  6017. }
  6018. /**
  6019. * 获取角色库列表(支持文件夹递归查询)
  6020. * @param array $data 包含 parent_id(父文件夹ID,默认0表示最外层)、role(搜索关键词)、is_public(筛选类型)
  6021. * @return array 返回当前目录下的所有子目录和角色列表(递归)
  6022. */
  6023. public function globalProducts($data) {
  6024. $uid = Site::getUid();
  6025. $cpid = Site::getCpid();
  6026. $role = Site::getRole();
  6027. $id = getProp($data, 'id', 0);
  6028. $parent_id = getProp($data, 'parent_id', 0);
  6029. $product_name = getProp($data, 'product_name');
  6030. $product = getProp($data, 'product'); // 1.角色 2.场景 3.道具
  6031. $is_public = getProp($data, 'public_type', 2); // 0=仅个人库 1=仅公共库 2=个人库+公共库
  6032. if (!$product) {
  6033. Utils::throwError('20003:请选择产品类型');
  6034. }
  6035. // 根据角色和is_public参数确定查询范围
  6036. // admin角色:获取所有个人库+公共库(忽略is_public参数)
  6037. // user角色:根据is_public参数筛选
  6038. $query_user_ids = [];
  6039. if ($role === 'admin') {
  6040. // admin获取所有个人库和公共库
  6041. $query_user_ids = [$uid, 0];
  6042. } else {
  6043. // user角色根据is_public参数筛选
  6044. if ($is_public == 2) {
  6045. // 个人库+公共库
  6046. $query_user_ids = [$uid, 0];
  6047. } elseif ($is_public == 0) {
  6048. // 仅个人库
  6049. $query_user_ids = [$uid];
  6050. } elseif ($is_public == 1) {
  6051. // 仅公共库
  6052. $query_user_ids = [0];
  6053. }
  6054. }
  6055. // 如果有搜索条件(product_name 或 id),按条件搜索文件夹和产品
  6056. if ($id || $product_name) {
  6057. $query = DB::table('mp_products')
  6058. ->where('cpid', $cpid)
  6059. ->whereIn('user_id', $query_user_ids)
  6060. ->where('is_deleted', 0);
  6061. // 如果指定了 id,按 id 精确查询
  6062. if ($id) {
  6063. $query->where('id', $id);
  6064. }
  6065. // 如果指定了 product_name,按名称模糊查询
  6066. if ($product_name) {
  6067. $query->where('product_name', 'like', "%{$product_name}%");
  6068. }
  6069. // 如果指定了 product,添加筛选条件
  6070. if ($product) {
  6071. $query->where('product', $product);
  6072. }
  6073. $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')
  6074. ->orderByRaw('type DESC, CASE WHEN user_id = '.$uid.' THEN 0 ELSE 1 END ASC, sort_order DESC, created_at DESC')
  6075. ->get()
  6076. ->map(function($value) {
  6077. $value = (array)$value;
  6078. $value['created_at'] = transDate($value['created_at'], 'Y-m-d');
  6079. $value['type'] = (int)$value['type'];
  6080. $value['parent_id'] = (int)$value['parent_id'];
  6081. $value['level'] = (int)$value['level'];
  6082. $value['product'] = (int)($value['product'] ?? 1);
  6083. $value['is_public'] = (int)$value['user_id'] === 0 ? 1 : 0;
  6084. $value['timbre_url'] = $value['timbre_url'] ?? '';
  6085. $value['versions'] = json_decode($value['versions'], true) ?: [];
  6086. unset($value['user_id']);
  6087. return $value;
  6088. })
  6089. ->toArray();
  6090. return $result;
  6091. }
  6092. // 递归获取所有子目录和角色
  6093. return $this->getChildrenRecursive($cpid, $parent_id, $product, $query_user_ids, $uid);
  6094. }
  6095. /**
  6096. * 递归获取指定目录下的所有子目录和角色
  6097. * @param int $cpid 公司ID
  6098. * @param int $parent_id 父目录ID
  6099. * @param int|null $product 产品类型筛选 1.角色 2.场景 3.道具
  6100. * @param array $query_user_ids 用户ID数组(支持多个)
  6101. * @param int $current_uid 当前用户ID(用于排序)
  6102. * @return array
  6103. */
  6104. private function getChildrenRecursive($cpid, $parent_id, $product = null, $query_user_ids = [], $current_uid = 0) {
  6105. // 查询当前层级的所有项(文件夹和角色)
  6106. $query = DB::table('mp_products')
  6107. ->where('cpid', $cpid)
  6108. ->where('is_deleted', 0)
  6109. ->where('parent_id', $parent_id);
  6110. // 添加用户ID验证(支持多个user_id)
  6111. if (!empty($query_user_ids)) {
  6112. $query->whereIn('user_id', $query_user_ids);
  6113. }
  6114. // 如果指定了 product,添加筛选条件(文件夹和角色都需要筛选)
  6115. if ($product) {
  6116. $query->where('product', $product);
  6117. }
  6118. // 排序规则:
  6119. // 1. 文件夹在前(type DESC)
  6120. // 2. 个人库在前,公共库在后(CASE WHEN user_id = current_uid)
  6121. // 3. 其他排序规则
  6122. $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')
  6123. ->orderByRaw('type DESC, CASE WHEN user_id = '.$current_uid.' THEN 0 ELSE 1 END ASC, sort_order DESC, created_at DESC')
  6124. ->get();
  6125. $result = [];
  6126. foreach ($items as $item) {
  6127. $itemArray = [
  6128. 'id' => $item->id,
  6129. 'type' => (int)$item->type,
  6130. 'parent_id' => (int)$item->parent_id,
  6131. 'level' => (int)$item->level,
  6132. 'product_name' => $item->product_name,
  6133. 'url' => $item->url,
  6134. 'pic_prompt' => $item->pic_prompt ?? '',
  6135. 'three_view_image_url' => $item->three_view_image_url,
  6136. 'timbre_url' => $item->timbre_url ?? '',
  6137. 'product' => (int)($item->product ?? 1),
  6138. 'is_public' => (int)$item->user_id === 0 ? 1 : 0,
  6139. 'created_at' => transDate($item->created_at, 'Y-m-d')
  6140. ];
  6141. $itemArray['versions'] = json_decode($item->versions, true) ?: [];
  6142. // 如果是文件夹,递归获取其子项
  6143. if ($item->type == 2) {
  6144. $children = $this->getChildrenRecursive($cpid, $item->id, $product, $query_user_ids, $current_uid);
  6145. if (!empty($children)) {
  6146. $itemArray['children'] = $children;
  6147. }
  6148. }
  6149. $result[] = $itemArray;
  6150. }
  6151. return $result;
  6152. }
  6153. /**
  6154. * 创建文件夹
  6155. * @param array $data 包含 parent_id(父文件夹ID)、product_name(文件夹名称)、product(产品类型)
  6156. * @return int 返回新建文件夹ID
  6157. */
  6158. public function createFolder($data) {
  6159. $uid = Site::getUid();
  6160. $cpid = Site::getCpid();
  6161. $role = Site::getRole();
  6162. $parent_id = getProp($data, 'parent_id', 0);
  6163. $folder_name = getProp($data, 'product_name', '新建文件夹');
  6164. $is_public = getProp($data, 'is_public', 0); // 0=个人资产库 1=公共资产库
  6165. // 如果是公共库操作,需要admin权限
  6166. if ($is_public && $role !== 'admin') {
  6167. Utils::throwError('20003:只有管理员才能操作公共资产库');
  6168. }
  6169. // 根据is_public参数确定存储的user_id(公共库user_id=0,cpid保持不变)
  6170. $store_uid = $is_public ? 0 : $uid;
  6171. // 获取 product 字段:1.角色 2.场景 3.道具,默认为1
  6172. $product = getProp($data, 'product');
  6173. if (!in_array($product, [1, 2, 3])) {
  6174. // Utils::throwError('20003:product 参数错误,只能是 1(角色)、2(场景) 或 3(道具)');
  6175. }
  6176. // 验证父文件夹
  6177. $parent_level = 0;
  6178. if ($parent_id > 0) {
  6179. $parent = DB::table('mp_products')
  6180. ->where('id', $parent_id)
  6181. ->where('cpid', $cpid)
  6182. ->where('user_id', $store_uid)
  6183. ->where('type', 2)
  6184. ->where('is_deleted', 0)
  6185. ->first();
  6186. if (!$parent) {
  6187. Utils::throwError('20003:父文件夹不存在');
  6188. }
  6189. // 检查父文件夹的 product 类型是否一致
  6190. if ($parent->product != $product) {
  6191. Utils::throwError('20003:文件夹类型必须与父文件夹一致');
  6192. }
  6193. $parent_level = $parent->level;
  6194. // 检查层级限制(最多3层)
  6195. if ($parent_level >= 3) {
  6196. Utils::throwError('20003:文件夹层级不能超过3层');
  6197. }
  6198. }
  6199. // 检查当前目录下是否已存在空白文件夹
  6200. $empty_folder_exists = DB::table('mp_products')
  6201. ->where('parent_id', $parent_id)
  6202. ->where('cpid', $cpid)
  6203. ->where('user_id', $store_uid)
  6204. ->where('type', 2)
  6205. ->where('product', $product)
  6206. ->where('product_name', '新建文件夹')
  6207. ->where('is_deleted', 0)
  6208. ->exists();
  6209. if ($empty_folder_exists && $folder_name == '新建文件夹') {
  6210. Utils::throwError('20003:不允许创建多个空白文件夹,请先重命名现有文件夹');
  6211. }
  6212. // 创建文件夹
  6213. $folder_id = DB::table('mp_products')->insertGetId([
  6214. 'user_id' => $store_uid,
  6215. 'cpid' => $cpid,
  6216. 'type' => 2,
  6217. 'parent_id' => $parent_id,
  6218. 'level' => $parent_level + 1,
  6219. 'product_name' => $folder_name,
  6220. 'product' => $product,
  6221. 'sort_order' => time(), // 使用时间戳作为排序权重
  6222. 'is_deleted' => 0,
  6223. 'created_at' => date('Y-m-d H:i:s'),
  6224. 'updated_at' => date('Y-m-d H:i:s')
  6225. ]);
  6226. return [
  6227. 'id' => $folder_id,
  6228. 'type' => 2,
  6229. 'parent_id' => $parent_id,
  6230. 'level' => $parent_level + 1,
  6231. 'product_name' => $folder_name,
  6232. 'product' => $product,
  6233. ];
  6234. }
  6235. /**
  6236. * 重命名文件夹或角色
  6237. * @param array $data 包含 id、product_name(新名称)
  6238. * @return bool
  6239. */
  6240. public function renameFolder($data) {
  6241. $uid = Site::getUid();
  6242. $cpid = Site::getCpid();
  6243. $role = Site::getRole();
  6244. $id = getProp($data, 'id');
  6245. $new_name = getProp($data, 'product_name');
  6246. $is_public = getProp($data, 'is_public', 0); // 0=个人资产库 1=公共资产库
  6247. if (!$id || !$new_name) {
  6248. Utils::throwError('20003:参数不完整');
  6249. }
  6250. // 根据is_public参数确定查询的user_id(公共库user_id=0,cpid保持不变)
  6251. $query_uid = $is_public ? 0 : $uid;
  6252. // 如果是公共库操作,需要admin权限
  6253. if ($is_public && $role !== 'admin') {
  6254. Utils::throwError('20003:只有管理员才能操作公共资产库');
  6255. }
  6256. // 检查是否存在
  6257. $item = DB::table('mp_products')
  6258. ->where('id', $id)
  6259. ->where('cpid', $cpid)
  6260. ->where('user_id', $query_uid)
  6261. ->where('is_deleted', 0)
  6262. ->first();
  6263. if (!$item) {
  6264. Utils::throwError('20003:项目不存在');
  6265. }
  6266. return DB::table('mp_products')
  6267. ->where('id', $id)
  6268. ->where('cpid', $cpid)
  6269. ->where('user_id', $query_uid)
  6270. ->update([
  6271. 'product_name' => $new_name,
  6272. 'updated_at' => date('Y-m-d H:i:s')
  6273. ]);
  6274. }
  6275. /**
  6276. * 移动角色或文件夹到指定文件夹
  6277. * @param array $data 包含 id(要移动的项目ID)、target_parent_id(目标父文件夹ID)
  6278. * @return bool
  6279. */
  6280. public function moveProductOrFolder($data) {
  6281. $uid = Site::getUid();
  6282. $cpid = Site::getCpid();
  6283. $role = Site::getRole();
  6284. $id = getProp($data, 'id');
  6285. $target_parent_id = getProp($data, 'target_parent_id', 0);
  6286. $is_public = getProp($data, 'is_public', 0); // 0=个人资产库 1=公共资产库
  6287. if (!$id) {
  6288. Utils::throwError('20003:请选择要移动的项目');
  6289. }
  6290. // 根据is_public参数确定查询的user_id(公共库user_id=0,cpid保持不变)
  6291. $query_uid = $is_public ? 0 : $uid;
  6292. // 如果是公共库操作,需要admin权限
  6293. if ($is_public && $role !== 'admin') {
  6294. Utils::throwError('20003:只有管理员才能操作公共资产库');
  6295. }
  6296. // 检查要移动的项目
  6297. $item = DB::table('mp_products')
  6298. ->where('id', $id)
  6299. ->where('cpid', $cpid)
  6300. ->where('user_id', $query_uid)
  6301. ->where('is_deleted', 0)
  6302. ->first();
  6303. if (!$item) {
  6304. Utils::throwError('20003:项目不存在');
  6305. }
  6306. // 验证目标文件夹
  6307. $target_level = 0;
  6308. $target_product = $item->product; // 默认使用当前项目的 product
  6309. if ($target_parent_id > 0) {
  6310. $target_parent = DB::table('mp_products')
  6311. ->where('id', $target_parent_id)
  6312. ->where('cpid', $cpid)
  6313. ->where('user_id', $query_uid)
  6314. ->where('type', 2)
  6315. ->where('is_deleted', 0)
  6316. ->first();
  6317. if (!$target_parent) {
  6318. Utils::throwError('20003:目标文件夹不存在');
  6319. }
  6320. // 检查 product 类型是否一致
  6321. if ($target_parent->product != $item->product) {
  6322. Utils::throwError('20003:不能移动到不同类型的文件夹下');
  6323. }
  6324. $target_level = $target_parent->level;
  6325. $target_product = $target_parent->product;
  6326. // 如果移动的是文件夹,需要检查层级
  6327. if ($item->type == 2) {
  6328. // 计算移动后的最大层级
  6329. $max_child_level = $this->getMaxChildLevel($id);
  6330. $depth = $max_child_level - $item->level;
  6331. if ($target_level + 1 + $depth > 3) {
  6332. Utils::throwError('20003:移动后文件夹层级将超过3层限制');
  6333. }
  6334. // 不能移动到自己或自己的子文件夹下
  6335. if ($this->isDescendant($target_parent_id, $id)) {
  6336. Utils::throwError('20003:不能移动到自己或子文件夹下');
  6337. }
  6338. }
  6339. }
  6340. // 更新父文件夹和层级
  6341. $new_level = $target_level + 1;
  6342. DB::table('mp_products')
  6343. ->where('id', $id)
  6344. ->update([
  6345. 'parent_id' => $target_parent_id,
  6346. 'level' => $new_level,
  6347. 'updated_at' => date('Y-m-d H:i:s')
  6348. ]);
  6349. // 如果是文件夹,需要递归更新所有子项的层级
  6350. if ($item->type == 2) {
  6351. $this->updateChildrenLevel($id, $new_level);
  6352. }
  6353. return true;
  6354. }
  6355. /**
  6356. * 获取文件夹下最大子层级
  6357. * @param int $folder_id
  6358. * @return int
  6359. */
  6360. private function getMaxChildLevel($folder_id) {
  6361. $max_level = DB::table('mp_products')
  6362. ->where('parent_id', $folder_id)
  6363. ->where('is_deleted', 0)
  6364. ->max('level');
  6365. if (!$max_level) {
  6366. return DB::table('mp_products')->where('id', $folder_id)->value('level');
  6367. }
  6368. // 递归查找子文件夹
  6369. $children = DB::table('mp_products')
  6370. ->where('parent_id', $folder_id)
  6371. ->where('type', 2)
  6372. ->where('is_deleted', 0)
  6373. ->pluck('id');
  6374. foreach ($children as $child_id) {
  6375. $child_max = $this->getMaxChildLevel($child_id);
  6376. if ($child_max > $max_level) {
  6377. $max_level = $child_max;
  6378. }
  6379. }
  6380. return $max_level;
  6381. }
  6382. /**
  6383. * 检查 target_id 是否是 folder_id 的后代
  6384. * @param int $target_id
  6385. * @param int $folder_id
  6386. * @return bool
  6387. */
  6388. private function isDescendant($target_id, $folder_id) {
  6389. if ($target_id == $folder_id) {
  6390. return true;
  6391. }
  6392. $parent = DB::table('mp_products')
  6393. ->where('id', $target_id)
  6394. ->where('is_deleted', 0)
  6395. ->first();
  6396. if (!$parent || $parent->parent_id == 0) {
  6397. return false;
  6398. }
  6399. return $this->isDescendant($parent->parent_id, $folder_id);
  6400. }
  6401. /**
  6402. * 递归更新子项层级
  6403. * @param int $parent_id
  6404. * @param int $parent_level
  6405. */
  6406. private function updateChildrenLevel($parent_id, $parent_level) {
  6407. $children = DB::table('mp_products')
  6408. ->where('parent_id', $parent_id)
  6409. ->where('is_deleted', 0)
  6410. ->get();
  6411. foreach ($children as $child) {
  6412. $new_level = $parent_level + 1;
  6413. DB::table('mp_products')
  6414. ->where('id', $child->id)
  6415. ->update([
  6416. 'level' => $new_level,
  6417. 'updated_at' => date('Y-m-d H:i:s')
  6418. ]);
  6419. // 如果是文件夹,继续递归
  6420. if ($child->type == 2) {
  6421. $this->updateChildrenLevel($child->id, $new_level);
  6422. }
  6423. }
  6424. }
  6425. /**
  6426. * 获取文件夹路径(面包屑导航)
  6427. * @param array $data 包含 folder_id
  6428. * @return array 返回路径数组
  6429. */
  6430. public function getFolderPath($data) {
  6431. $uid = Site::getUid();
  6432. $cpid = Site::getCpid();
  6433. $folder_id = getProp($data, 'id', 0);
  6434. $is_public = getProp($data, 'is_public', 0); // 0=个人资产库 1=公共资产库
  6435. if ($folder_id == 0) {
  6436. return [
  6437. ['id' => 0, 'name' => '根目录']
  6438. ];
  6439. }
  6440. // 根据is_public参数确定查询的user_id(公共库user_id=0,cpid保持不变)
  6441. $query_uid = $is_public ? 0 : $uid;
  6442. $path = [];
  6443. $current_id = $folder_id;
  6444. while ($current_id > 0) {
  6445. $folder = DB::table('mp_products')
  6446. ->where('id', $current_id)
  6447. ->where('cpid', $cpid)
  6448. ->where('user_id', $query_uid)
  6449. ->where('type', 2)
  6450. ->where('is_deleted', 0)
  6451. ->first();
  6452. if (!$folder) {
  6453. break;
  6454. }
  6455. array_unshift($path, [
  6456. 'id' => $folder->id,
  6457. 'name' => $folder->product_name
  6458. ]);
  6459. $current_id = $folder->parent_id;
  6460. }
  6461. // 添加根目录
  6462. array_unshift($path, ['id' => 0, 'name' => '根目录']);
  6463. return $path;
  6464. }
  6465. public function createProduct($data) {
  6466. $uid = Site::getUid();
  6467. $cpid = Site::getCpid();
  6468. $role = Site::getRole();
  6469. $is_public = getProp($data, 'is_public', 0); // 0=个人资产库 1=公共资产库
  6470. // 如果是公共库操作,需要admin权限
  6471. if ($is_public && $role !== 'admin') {
  6472. Utils::throwError('20003:只有管理员才能操作公共资产库');
  6473. }
  6474. // 根据is_public参数确定存储的user_id(公共库user_id=0,cpid保持不变)
  6475. $store_uid = $is_public ? 0 : $uid;
  6476. // 新增参数:剧本ID和剧集序号(支持数组传参,多个序号也可用英文逗号隔开)
  6477. $script_id = (int)getProp($data, 'script_id', 0);
  6478. $episode_numbers = $this->normalizeEpisodeNumbers(getProp($data, 'episode_number', []));
  6479. if ($script_id && empty($episode_numbers)) {
  6480. Utils::throwError('20003:剧集序号不能为空');
  6481. }
  6482. if (!$script_id && !empty($episode_numbers)) {
  6483. Utils::throwError('20003:请提供剧本ID');
  6484. }
  6485. $product_name = trim(getProp($data, 'product_name'));
  6486. if (!$product_name) Utils::throwError('20003:名称不能为空');
  6487. $product_name = preg_replace('/^[\s*\[\]【】[]{}{}\x{3000}]+|[\s*\[\]【】[]{}{}\x{3000}]+$/u', '', $product_name);
  6488. // $exists_id = DB::table('mp_products')->where('cpid', $cpid)->where('type', 1)->where('product_name', $product_name)->where('is_deleted', 0)->value('id');
  6489. // if ($exists_id) Utils::throwError('20003:名称不能重复,请修改');
  6490. $url = trim(getProp($data, 'url'));
  6491. if (!$url) Utils::throwError('20003:图片地址不能为空');
  6492. $versions = getProp($data, 'versions');
  6493. // 检查是否是正确的图片格式
  6494. $allowedExtensions = ['jpg', 'jpeg', 'png', 'gif', 'webp', 'bmp'];
  6495. $urlPath = parse_url($url, PHP_URL_PATH);
  6496. $extension = strtolower(pathinfo($urlPath, PATHINFO_EXTENSION));
  6497. if (!in_array($extension, $allowedExtensions)) {
  6498. Utils::throwError('20003:图片格式不正确,仅支持 jpg、jpeg、png、gif、webp、bmp 格式');
  6499. }
  6500. // 选填三视图图片地址,格式校验与 url 一致
  6501. $three_view_image_url = trim(getProp($data, 'three_view_image_url', ''));
  6502. if ($three_view_image_url) {
  6503. $threeViewPath = parse_url($three_view_image_url, PHP_URL_PATH);
  6504. $threeViewExtension = strtolower(pathinfo($threeViewPath, PATHINFO_EXTENSION));
  6505. if (!in_array($threeViewExtension, $allowedExtensions)) {
  6506. Utils::throwError('20003:三视图图片格式不正确,仅支持 jpg、jpeg、png、gif、webp、bmp 格式');
  6507. }
  6508. }
  6509. // 选填音色音频地址(兼容 timbre_url/audio_url/timbre 传参)
  6510. $timbre_url = $this->getProductTimbreUrl($data);
  6511. if ($timbre_url) {
  6512. $this->validateProductAudioUrl($timbre_url);
  6513. }
  6514. $pic_prompt = trim(getProp($data, 'pic_prompt'));
  6515. if (!$pic_prompt) Utils::throwError('20003:提示词不能为空');
  6516. // 获取 product 字段:1.角色 2.场景 3.道具,默认为1
  6517. $product = getProp($data, 'product');
  6518. if (!in_array($product, [1, 2, 3])) {
  6519. // Utils::throwError('20003:产品类型只能是 1(角色)、2(场景) 或 3(道具)');
  6520. }
  6521. // 获取父文件夹ID和层级
  6522. $parent_id = getProp($data, 'parent_id', 0);
  6523. $parent_level = 0;
  6524. if ($parent_id > 0) {
  6525. $parent = DB::table('mp_products')
  6526. ->where('id', $parent_id)
  6527. ->where('cpid', $cpid)
  6528. ->where('user_id', $store_uid)
  6529. ->where('type', 2)
  6530. ->where('is_deleted', 0)
  6531. ->first();
  6532. if (!$parent) {
  6533. Utils::throwError('20003:父文件夹不存在');
  6534. }
  6535. $parent_level = $parent->level;
  6536. }
  6537. // 创建资产并保存剧本资产关联关系(同一事务)
  6538. DB::beginTransaction();
  6539. try {
  6540. $id = DB::table('mp_products')->insertGetId([
  6541. 'user_id' => $store_uid,
  6542. 'cpid' => $cpid,
  6543. 'type' => 1, // 1=角色图片
  6544. 'parent_id' => $parent_id,
  6545. 'level' => $parent_level + 1,
  6546. 'product_name' => $product_name,
  6547. 'url' => $url,
  6548. 'three_view_image_url' => $three_view_image_url,
  6549. 'timbre_url' => $timbre_url,
  6550. 'pic_prompt' => $pic_prompt,
  6551. 'product' => $product,
  6552. 'versions' => json_encode($versions, 256),
  6553. 'sort_order' => time(), // 使用时间戳作为排序权重
  6554. 'created_at' => date('Y-m-d H:i:s'),
  6555. 'updated_at' => date('Y-m-d H:i:s')
  6556. ]);
  6557. if (!$id) Utils::throwError('20003:创建失败');
  6558. // 保存剧本资产关联关系
  6559. if ($script_id) {
  6560. $this->saveProductScriptMapping($id, $script_id, $episode_numbers);
  6561. }
  6562. DB::commit();
  6563. } catch (\Exception $e) {
  6564. DB::rollback();
  6565. throw $e;
  6566. }
  6567. return [
  6568. 'id' => $id,
  6569. 'type' => 1,
  6570. 'parent_id' => $parent_id,
  6571. 'level' => $parent_level + 1,
  6572. 'product_name' => $product_name,
  6573. 'url' => $url,
  6574. 'three_view_image_url' => $three_view_image_url,
  6575. 'timbre_url' => $timbre_url,
  6576. 'pic_prompt' => $pic_prompt,
  6577. 'product' => $product,
  6578. 'versions' => $versions
  6579. ];
  6580. }
  6581. public function editProduct($data) {
  6582. $uid = Site::getUid();
  6583. $cpid = Site::getCpid();
  6584. $role = Site::getRole();
  6585. $id = getProp($data, 'id');
  6586. if (!$id) Utils::throwError('20003:ID不能为空');
  6587. $versions = getProp($data, 'versions');
  6588. $is_public = getProp($data, 'is_public', 0); // 0=个人资产库 1=公共资产库
  6589. // 新增参数:剧本ID和剧集序号(支持数组传参,多个序号也可用英文逗号隔开)
  6590. $script_id = (int)getProp($data, 'script_id', 0);
  6591. $episode_numbers = $this->normalizeEpisodeNumbers(getProp($data, 'episode_number', []));
  6592. if ($script_id && empty($episode_numbers)) {
  6593. Utils::throwError('20003:剧集序号不能为空');
  6594. }
  6595. if (!$script_id && !empty($episode_numbers)) {
  6596. Utils::throwError('20003:请提供剧本ID');
  6597. }
  6598. // 根据is_public参数确定查询的user_id(公共库user_id=0,cpid保持不变)
  6599. $query_uid = $is_public ? 0 : $uid;
  6600. // 如果是公共库操作,需要admin权限
  6601. if ($is_public && $role !== 'admin') {
  6602. Utils::throwError('20003:只有管理员才能操作公共资产库');
  6603. }
  6604. // 检查是否存在且属于当前用户或公共库
  6605. $role = DB::table('mp_products')
  6606. ->where('id', $id)
  6607. ->where('cpid', $cpid)
  6608. ->where('user_id', $query_uid)
  6609. ->where('type', 1)->first();
  6610. if (!$role) Utils::throwError('20003:记录不存在');
  6611. $updateData = [];
  6612. // $needVersionRecord = false; // 是否需要记录版本
  6613. // 名称
  6614. $product_name = trim(getProp($data, 'product_name'));
  6615. if ($product_name) {
  6616. $product_name = preg_replace('/^[\s*\[\]【】[]{}{}\x{3000}]+|[\s*\[\]【】[]{}{}\x{3000}]+$/u', '', $product_name);
  6617. $updateData['product_name'] = $product_name;
  6618. }
  6619. // $exists_id = DB::table('mp_products')->where('cpid', $cpid)->where('type', 1)->where('product_name', $product_name)->where('is_deleted', 0)->value('id');
  6620. // if ($exists_id && $exists_id != $id) Utils::throwError('20003:名称不能重复,请修改');
  6621. // 图片地址
  6622. $allowedExtensions = ['jpg', 'jpeg', 'png', 'gif', 'webp', 'bmp'];
  6623. $url = trim(getProp($data, 'url'));
  6624. if ($url) {
  6625. // 检查是否是正确的图片格式
  6626. $urlPath = parse_url($url, PHP_URL_PATH);
  6627. $extension = strtolower(pathinfo($urlPath, PATHINFO_EXTENSION));
  6628. if (!in_array($extension, $allowedExtensions)) {
  6629. Utils::throwError('20003:图片格式不正确,仅支持 jpg、jpeg、png、gif、webp、bmp 格式');
  6630. }
  6631. // // 如果 url 有变更,记录版本
  6632. // if ($url !== $role->url) {
  6633. // $needVersionRecord = true;
  6634. // }
  6635. $updateData['url'] = $url;
  6636. }
  6637. // 三视图图片地址(选填),格式校验与 url 一致;显式传空表示当前版本没有三视图
  6638. $three_view_image_url = trim(getProp($data, 'three_view_image_url', ''));
  6639. if ($three_view_image_url) {
  6640. $threeViewPath = parse_url($three_view_image_url, PHP_URL_PATH);
  6641. $threeViewExtension = strtolower(pathinfo($threeViewPath, PATHINFO_EXTENSION));
  6642. if (!in_array($threeViewExtension, $allowedExtensions)) {
  6643. Utils::throwError('20003:三视图图片格式不正确,仅支持 jpg、jpeg、png、gif、webp、bmp 格式');
  6644. }
  6645. }
  6646. // 显式传入三视图(含空值)时同步写入,空值表示当前版本没有三视图
  6647. if (array_key_exists('three_view_image_url', $data)) {
  6648. $updateData['three_view_image_url'] = $three_view_image_url;
  6649. }
  6650. // 音色音频地址(选填,显式传空字符串可清除已有音色)
  6651. if (array_key_exists('timbre_url', $data) || array_key_exists('audio_url', $data) || array_key_exists('timbre', $data)) {
  6652. $timbre_url = $this->getProductTimbreUrl($data);
  6653. if ($timbre_url) {
  6654. $this->validateProductAudioUrl($timbre_url);
  6655. }
  6656. $updateData['timbre_url'] = $timbre_url;
  6657. }
  6658. // 提示词
  6659. $pic_prompt = trim(getProp($data, 'pic_prompt'));
  6660. if ($pic_prompt) {
  6661. // // 如果 pic_prompt 有变更,记录版本
  6662. // if ($pic_prompt !== $role->pic_prompt) {
  6663. // $needVersionRecord = true;
  6664. // }
  6665. $updateData['pic_prompt'] = $pic_prompt;
  6666. }else {
  6667. Utils::throwError('20003:请输入提示词');
  6668. }
  6669. if (empty($updateData) && !$script_id) {
  6670. Utils::throwError('20003:没有需要更新的数据');
  6671. }
  6672. // // 如果需要记录版本,将数据添加到 versions 数组
  6673. // if ($needVersionRecord) {
  6674. // // 获取现有的 versions 数据
  6675. // $versions = json_decode($role->versions, true) ?: [];
  6676. // $isFirstVersion = empty($versions); // 判断是否是第一次记录版本
  6677. // // 如果是第一次记录版本,先添加旧版本(变更前)
  6678. // if ($isFirstVersion) {
  6679. // $oldVersion = [
  6680. // 'url' => $role->url,
  6681. // 'description' => $role->pic_prompt,
  6682. // ];
  6683. // // 旧版本添加到数组末尾
  6684. // $versions[] = $oldVersion;
  6685. // }
  6686. // // 构建新版本(变更后)
  6687. // $newVersion = [
  6688. // 'url' => isset($updateData['url']) ? $updateData['url'] : $role->url,
  6689. // 'description' => isset($updateData['pic_prompt']) ? $updateData['pic_prompt'] : $role->pic_prompt,
  6690. // ];
  6691. // // 检查新版本是否已存在于历史版本中
  6692. // $existingIndex = -1;
  6693. // foreach ($versions as $index => $version) {
  6694. // if ($version['url'] === $newVersion['url'] && $version['description'] === $newVersion['description']) {
  6695. // $existingIndex = $index;
  6696. // break;
  6697. // }
  6698. // }
  6699. // if ($existingIndex !== -1) {
  6700. // // 如果已存在,移除旧的位置
  6701. // array_splice($versions, $existingIndex, 1);
  6702. // }
  6703. // // 新版本添加到数组开头(最新的在前)
  6704. // array_unshift($versions, $newVersion);
  6705. // // // 限制版本数量(可选,例如只保留最近10个版本)
  6706. // // if (count($versions) > 10) {
  6707. // // $versions = array_slice($versions, 0, 10);
  6708. // // }
  6709. // $updateData['versions'] = json_encode($versions, 256);
  6710. // }
  6711. if ($versions) {
  6712. $updateData['versions'] = json_encode($versions, 256);
  6713. }
  6714. if (!empty($updateData)) {
  6715. $updateData['updated_at'] = date('Y-m-d H:i:s');
  6716. }
  6717. // 更新资产并保存剧本资产关联关系(同一事务)
  6718. DB::beginTransaction();
  6719. try {
  6720. $updated = true;
  6721. if (!empty($updateData)) {
  6722. $updated = DB::table('mp_products')
  6723. ->where('cpid', $cpid)
  6724. ->where('id', $id)
  6725. ->update($updateData);
  6726. }
  6727. // 保存剧本资产关联关系
  6728. if ($script_id) {
  6729. $this->saveProductScriptMapping($id, $script_id, $episode_numbers);
  6730. }
  6731. DB::commit();
  6732. } catch (\Exception $e) {
  6733. DB::rollback();
  6734. throw $e;
  6735. }
  6736. return $updated;
  6737. }
  6738. /**
  6739. * 获取资产音色音频地址
  6740. * 兼容 timbre_url/audio_url/timbre 三种传参,timbre 支持字符串或 {"url":"..."} 结构
  6741. *
  6742. * @param array $data
  6743. * @return string
  6744. */
  6745. private function getProductTimbreUrl($data) {
  6746. foreach (['timbre_url', 'audio_url', 'timbre'] as $key) {
  6747. if (!array_key_exists($key, $data)) {
  6748. continue;
  6749. }
  6750. $value = $data[$key];
  6751. if (is_array($value)) {
  6752. $value = getProp($value, 'url', $value[0] ?? '');
  6753. }
  6754. if (!is_string($value)) {
  6755. continue;
  6756. }
  6757. return trim($value);
  6758. }
  6759. return '';
  6760. }
  6761. /**
  6762. * 校验资产音色音频地址格式
  6763. *
  6764. * @param string $url 音频地址
  6765. * @return void
  6766. */
  6767. private function validateProductAudioUrl($url) {
  6768. $allowedExtensions = ['mp3', 'wav', 'm4a', 'aac', 'ogg', 'oga', 'flac', 'amr', 'wma', 'weba'];
  6769. $urlPath = parse_url($url, PHP_URL_PATH);
  6770. $extension = strtolower(pathinfo($urlPath, PATHINFO_EXTENSION));
  6771. if (!in_array($extension, $allowedExtensions)) {
  6772. Utils::throwError('20003:音色音频格式不正确,仅支持 mp3、wav、m4a、aac、ogg、flac、amr、wma 格式');
  6773. }
  6774. }
  6775. /**
  6776. * 保存单一资产与剧本剧集的关联关系
  6777. *
  6778. * @param int $product_id 资产ID
  6779. * @param int $script_id 剧本ID
  6780. * @param array $episode_numbers 剧集序号数组(序号从1开始)
  6781. * @return int 新增关联数量
  6782. */
  6783. private function saveProductScriptMapping($product_id, $script_id, $episode_numbers) {
  6784. $uid = Site::getUid();
  6785. // 验证剧本是否存在
  6786. $script = DB::table('mp_scripts')
  6787. ->where('id', $script_id)
  6788. ->where('is_deleted', 0)
  6789. ->first();
  6790. if (!$script) {
  6791. Utils::throwError('20003:剧本不存在');
  6792. }
  6793. // 验证剧本归属:只能关联自己的剧本
  6794. if ((int)$script->user_id !== (int)$uid) {
  6795. Utils::throwError('20003:只能添加到自己的剧本');
  6796. }
  6797. // 使用 splitContent 拆分剧本内容获取总集数
  6798. $totalEpisodes = $this->getScriptTotalEpisodeCount($script);
  6799. // 解析剧集序号(数组)
  6800. $episodes = [];
  6801. foreach ($episode_numbers as $item) {
  6802. if (is_array($item)) {
  6803. continue;
  6804. }
  6805. $item = trim((string)$item);
  6806. if ($item === '' || !is_numeric($item)) {
  6807. Utils::throwError('20003:剧集序号格式不正确,仅支持数字数组或英文逗号分隔的数字');
  6808. }
  6809. $episodes[] = (int)$item;
  6810. }
  6811. // 去重并校验序号范围(序号从1开始)
  6812. $episodes = array_values(array_unique($episodes));
  6813. if (empty($episodes)) {
  6814. Utils::throwError('20003:剧集序号不能为空');
  6815. }
  6816. foreach ($episodes as $episode) {
  6817. if ($episode < 1 || $episode > $totalEpisodes) {
  6818. Utils::throwError('20003:剧集序号 ' . $episode . ' 超出范围,剧本共 ' . $totalEpisodes . ' 集(序号从1开始)');
  6819. }
  6820. }
  6821. $now = now();
  6822. // 过滤已存在的关联,避免重复
  6823. $existingEpisodes = DB::table('mp_script_product_mappings')
  6824. ->where('script_id', $script_id)
  6825. ->where('product_id', $product_id)
  6826. ->whereIn('episode_number', $episodes)
  6827. ->pluck('episode_number')
  6828. ->all();
  6829. $mappingRecords = [];
  6830. foreach ($episodes as $episode) {
  6831. if (in_array($episode, $existingEpisodes)) {
  6832. continue;
  6833. }
  6834. $mappingRecords[] = [
  6835. 'script_id' => $script_id,
  6836. 'product_id' => $product_id,
  6837. 'episode_number' => $episode,
  6838. 'created_at' => $now,
  6839. 'updated_at' => $now,
  6840. ];
  6841. }
  6842. $insertedCount = 0;
  6843. if (!empty($mappingRecords)) {
  6844. $insertedCount = DB::table('mp_script_product_mappings')->insert($mappingRecords) ? count($mappingRecords) : 0;
  6845. }
  6846. return $insertedCount;
  6847. }
  6848. /**
  6849. * 规范化剧集序号参数,统一为数组
  6850. * 兼容传入数组(如 [1, 3, 5])、逗号分隔字符串(如 "1,3,5")以及字符串数组(如 ["1,3", 5])
  6851. *
  6852. * @param mixed $episode_number 剧集序号参数
  6853. * @return array
  6854. */
  6855. private function normalizeEpisodeNumbers($episode_number) {
  6856. if (!is_array($episode_number)) {
  6857. $episode_number = explode(',', (string)$episode_number);
  6858. }
  6859. $items = [];
  6860. foreach ($episode_number as $item) {
  6861. if (is_array($item)) {
  6862. continue;
  6863. }
  6864. foreach (explode(',', (string)$item) as $part) {
  6865. $part = trim($part);
  6866. if ($part !== '') {
  6867. $items[] = $part;
  6868. }
  6869. }
  6870. }
  6871. return $items;
  6872. }
  6873. /**
  6874. * 获取剧本总集数(通过 splitContent 拆分剧本内容)
  6875. *
  6876. * @param object $script 剧本记录
  6877. * @return int 总集数
  6878. */
  6879. private function getScriptTotalEpisodeCount($script) {
  6880. if (empty($script->content)) {
  6881. Utils::throwError('20003:剧本内容为空,无法确定剧集数量');
  6882. }
  6883. $totalEpisodes = count(splitContent($script->content));
  6884. if ($totalEpisodes < 1) {
  6885. Utils::throwError('20003:剧本内容无法拆分出剧集');
  6886. }
  6887. return $totalEpisodes;
  6888. }
  6889. /**
  6890. * 获取剧本总集数
  6891. *
  6892. * @param array $data 包含 script_id(剧本ID)
  6893. * @return array
  6894. */
  6895. public function getScriptTotalEpisodes($data) {
  6896. $script_id = (int)getProp($data, 'script_id', 0);
  6897. if (!$script_id) {
  6898. Utils::throwError('20003:请提供剧本ID');
  6899. }
  6900. // 验证剧本是否存在
  6901. $script = DB::table('mp_scripts')
  6902. ->where('id', $script_id)
  6903. ->where('is_deleted', 0)
  6904. ->first();
  6905. if (!$script) {
  6906. Utils::throwError('20003:剧本不存在');
  6907. }
  6908. return [
  6909. 'script_id' => $script_id,
  6910. 'script_name' => $script->script_name ?? 'script_' . $script_id,
  6911. 'episode_num' => $this->getScriptTotalEpisodeCount($script),
  6912. ];
  6913. }
  6914. /**
  6915. * 获取角色版本历史
  6916. * @param array $data 包含 id(角色ID)
  6917. * @return array 返回版本历史列表
  6918. */
  6919. public function getProductVersions($data) {
  6920. $cpid = Site::getCpid();
  6921. $id = getProp($data, 'id');
  6922. if (!$id) Utils::throwError('20003:角色ID不能为空');
  6923. $role = DB::table('mp_products')
  6924. ->where('id', $id)
  6925. ->where('cpid', $cpid)
  6926. ->where('type', 1)
  6927. ->first();
  6928. if (!$role) Utils::throwError('20003:角色不存在');
  6929. // 获取版本历史
  6930. $versions = json_decode($role->versions, true) ?: [];
  6931. // 添加当前版本作为最新版本
  6932. $currentVersion = [
  6933. 'version' => 0, // 0 表示当前版本
  6934. 'url' => $role->url,
  6935. 'pic_prompt' => $role->pic_prompt,
  6936. 'updated_at' => $role->updated_at,
  6937. 'is_current' => true
  6938. ];
  6939. array_unshift($versions, $currentVersion);
  6940. return $versions;
  6941. }
  6942. /**
  6943. * 恢复到指定版本
  6944. * @param array $data 包含 id(角色ID)、version(版本号)
  6945. * @return bool
  6946. */
  6947. public function restoreProductVersion($data) {
  6948. $uid = Site::getUid();
  6949. $cpid = Site::getCpid();
  6950. $id = getProp($data, 'id');
  6951. $version = getProp($data, 'version');
  6952. if (!$id) Utils::throwError('20003:角色ID不能为空');
  6953. if (!$version) Utils::throwError('20003:版本号不能为空');
  6954. $role = DB::table('mp_products')
  6955. ->where('id', $id)
  6956. ->where('cpid', $cpid)
  6957. ->where('type', 1)
  6958. ->first();
  6959. if (!$role) Utils::throwError('20003:角色不存在');
  6960. // 获取版本历史
  6961. $versions = json_decode($role->versions, true) ?: [];
  6962. // 查找指定版本
  6963. $targetVersion = null;
  6964. foreach ($versions as $v) {
  6965. if ($v['version'] == $version) {
  6966. $targetVersion = $v;
  6967. break;
  6968. }
  6969. }
  6970. if (!$targetVersion) Utils::throwError('20003:版本不存在');
  6971. // 先将当前版本保存到历史
  6972. $newVersion = [
  6973. 'version' => count($versions) + 1,
  6974. 'url' => $role->url,
  6975. 'pic_prompt' => $role->pic_prompt,
  6976. 'updated_at' => date('Y-m-d H:i:s'),
  6977. 'updated_by' => $uid
  6978. ];
  6979. array_unshift($versions, $newVersion);
  6980. // 限制版本数量
  6981. if (count($versions) > 10) {
  6982. $versions = array_slice($versions, 0, 10);
  6983. }
  6984. // 恢复到指定版本
  6985. return DB::table('mp_products')
  6986. ->where('id', $id)
  6987. ->where('cpid', $cpid)
  6988. ->update([
  6989. 'url' => $targetVersion['url'],
  6990. 'pic_prompt' => $targetVersion['pic_prompt'],
  6991. 'versions' => json_encode($versions, JSON_UNESCAPED_UNICODE),
  6992. 'updated_at' => date('Y-m-d H:i:s')
  6993. ]);
  6994. }
  6995. public function deleteProduct($data) {
  6996. $uid = Site::getUid();
  6997. $cpid = Site::getCpid();
  6998. $role = Site::getRole();
  6999. $id = getProp($data, 'id');
  7000. if (!$id) Utils::throwError('20003:ID不能为空');
  7001. $ids = explode(',', $id);
  7002. $is_public = getProp($data, 'is_public', 0); // 0=个人资产库 1=公共资产库
  7003. // 根据is_public参数确定查询的user_id(公共库user_id=0,cpid保持不变)
  7004. $query_uid = $is_public ? 0 : $uid;
  7005. // 如果是公共库操作,需要admin权限
  7006. if ($is_public && $role !== 'admin') {
  7007. Utils::throwError('20003:只有管理员才能操作公共资产库');
  7008. }
  7009. // 检查是否存在且属于当前用户或公共库
  7010. $role = DB::table('mp_products')
  7011. ->whereIn('id', $ids)
  7012. ->where('cpid', $cpid)
  7013. ->where('user_id', $query_uid)
  7014. ->get();
  7015. if (!$role) Utils::throwError('20003:记录不存在');
  7016. return DB::table('mp_products')
  7017. ->where('cpid', $cpid)
  7018. ->where('user_id', $query_uid)
  7019. ->whereIn('id', $ids)
  7020. ->update([
  7021. 'is_deleted' => 1,
  7022. 'updated_at' => date('Y-m-d H:i:s')
  7023. ]);
  7024. }
  7025. public function generateThreeView($data) {
  7026. $uid = Site::getUid();
  7027. $cpid = Site::getCpid();
  7028. $role = Site::getRole();
  7029. $id = getProp($data, 'id');
  7030. if (!$id) Utils::throwError('20003:ID不能为空');
  7031. $is_public = getProp($data, 'is_public', 0); // 0=个人资产库 1=公共资产库
  7032. // 根据is_public参数确定查询的user_id(公共库user_id=0,cpid保持不变)
  7033. $query_uid = $is_public ? 0 : $uid;
  7034. // 如果是公共库操作,需要admin权限
  7035. if ($is_public && $role !== 'admin') {
  7036. Utils::throwError('20003:只有管理员才能操作公共资产库');
  7037. }
  7038. // 检查是否存在且属于当前用户或公共库
  7039. $product = DB::table('mp_products')
  7040. ->where('id', $id)
  7041. ->where('cpid', $cpid)
  7042. ->where('user_id', $query_uid)
  7043. ->where('type', 1)->first();
  7044. if (!$product) Utils::throwError('20003:资产不存在');
  7045. $prompt = trim(getProp($data, 'prompt', '基于参考图生成主体的标准正面、侧面、后面三视图,主体完整。在最左侧添加主体正视图的特写,特写大小为标准一寸照,人物不要带表情。右侧是全身的三视图,其中正面、侧面的三视图给人脸打白色码、不显示五官。主体清晰完整。背景修改成纯白色,整体保持与参考图一致的美术风格和色彩搭配。画面无说明文字。'));
  7046. $ref_img_url = trim(getProp($data, 'ref_img_url'));
  7047. if (!$ref_img_url) {
  7048. // 如果没有传入参考图,使用角色表中的图片
  7049. $ref_img_url = $product->url ?? '';
  7050. if (!$ref_img_url) {
  7051. Utils::throwError('20003:参考图不能为空');
  7052. }
  7053. }
  7054. $pic_prompt = getProp($product, 'pic_prompt');
  7055. if ($pic_prompt) {
  7056. $prompt .= '\n参考图原始提示词: '.$pic_prompt;
  7057. }
  7058. // 检查参考图是否是正确的图片格式
  7059. $allowedExtensions = ['jpg', 'jpeg', 'png', 'gif', 'webp', 'bmp'];
  7060. $urlPath = parse_url($ref_img_url, PHP_URL_PATH);
  7061. $extension = strtolower(pathinfo($urlPath, PATHINFO_EXTENSION));
  7062. if (!in_array($extension, $allowedExtensions)) {
  7063. Utils::throwError('20003:参考图格式不正确,仅支持 jpg、jpeg、png、gif、webp、bmp 格式');
  7064. }
  7065. // 处理图片模型
  7066. $model = getProp($data, 'model');
  7067. if (!$model) {
  7068. // 使用默认模型
  7069. $model = 'gpt-image-2';
  7070. }
  7071. // 验证模型是否在可用模型表中
  7072. if (!DB::table('mp_image_models')->where('model', $model)->where('is_enabled', 1)->exists()) {
  7073. Utils::throwError('20003:该模型已不可用,请更换!');
  7074. }
  7075. $ratio = getProp($data, 'ratio', '16:9');
  7076. $resolution = getProp($data, 'resolution', '2k');
  7077. // 分辨率档位与尺寸映射统一从 BaseConst 获取
  7078. $sizeMap = BaseConst::IMAGE_RESOLUTION_SIZE_MAP;
  7079. // 参数验证
  7080. $resolution = strtolower($resolution);
  7081. if (!isset($sizeMap[$resolution])) {
  7082. Utils::throwError('20003:分辨率参数错误,仅支持 2k、3k、4k');
  7083. }
  7084. if (!isset($sizeMap[$resolution][$ratio])) {
  7085. Utils::throwError('20003:宽高比参数错误,该分辨率下不支持 ' . $ratio . ' 比例');
  7086. }
  7087. // 根据 ratio 和 resolution 确定宽高
  7088. $width = $sizeMap[$resolution][$ratio]['width'];
  7089. $height = $sizeMap[$resolution][$ratio]['height'];
  7090. try {
  7091. // 创建图片生成任务
  7092. $params = [
  7093. 'prompt' => $prompt,
  7094. 'model' => $model,
  7095. 'ref_img_urls' => [$ref_img_url],
  7096. 'width' => $width,
  7097. 'height' => $height
  7098. ];
  7099. $task = $this->aiImageGenerationService->createImageGenerationTask($params);
  7100. $task_id = $task->id;
  7101. if (!$task_id) {
  7102. Utils::throwError('20003:创建图片生成任务失败');
  7103. }
  7104. // 轮询获取结果
  7105. // 只查询数据库,不调用API,不更新任务表
  7106. $start_time = time();
  7107. $timeout = 1800;
  7108. $img_url = '';
  7109. while (time() - $start_time < $timeout) {
  7110. sleep(5);
  7111. // 只查询数据库中的任务状态,不调用API,不更新任务表
  7112. $task = DB::table('mp_generate_pic_tasks')
  7113. ->where('id', $task_id)
  7114. ->first();
  7115. if (!$task) {
  7116. Utils::throwError('20003:任务不存在');
  7117. }
  7118. if ($task->status === 'success' && $task->result_url) {
  7119. $result_urls = is_string($task->result_url)
  7120. ? json_decode($task->result_url, true)
  7121. : $task->result_url;
  7122. $img_url = is_array($result_urls) ? $result_urls[0] : $task->result_url;
  7123. break;
  7124. } elseif ($task->status === 'failed') {
  7125. Utils::throwError('20003:三视图生成失败,' . ($task->error_message ?? '未知错误'));
  7126. }
  7127. // 其他状态继续轮询
  7128. }
  7129. if (empty($img_url)) {
  7130. Utils::throwError('20003:三视图生成超时,请稍后重试');
  7131. }
  7132. // 更新 mp_products 表(不是任务表)
  7133. DB::table('mp_products')
  7134. ->where('id', $id)
  7135. ->where('cpid', $cpid)
  7136. ->update([
  7137. 'three_view_image_url' => $img_url,
  7138. 'updated_at' => date('Y-m-d H:i:s')
  7139. ]);
  7140. return ['three_view_image_url' => $img_url];
  7141. } catch (\Exception $e) {
  7142. dLog('anime')->error('生成三视图失败', [
  7143. 'error' => $e->getMessage()
  7144. ]);
  7145. logDB('anime', 'error', '生成三视图失败', ['error' => $e->getMessage()]);
  7146. Utils::throwError('20003:' . $e->getMessage());
  7147. }
  7148. }
  7149. /**
  7150. * 推送(复制)资产或文件夹到目标位置
  7151. * @param array $data 包含 product_id(要推送的资产或文件夹ID)、target_parent_id(目标父文件夹ID,0表示根目录)
  7152. * @return array 返回推送结果
  7153. */
  7154. public function pushProductOrFolder($data) {
  7155. $uid = Site::getUid();
  7156. $cpid = Site::getCpid();
  7157. $role = Site::getRole();
  7158. $product_id = getProp($data, 'product_id');
  7159. $target_parent_id = getProp($data, 'target_parent_id', 0);
  7160. $target_product = getProp($data, 'product'); // 目标 product 类型,用于跨类型推送
  7161. if (!$product_id) {
  7162. Utils::throwError('20003:请选择要推送的项目');
  7163. }
  7164. // 查询源项目(只通过cpid查询,不限制user_id)
  7165. $sourceItem = DB::table('mp_products')
  7166. ->where('id', $product_id)
  7167. ->where('cpid', $cpid)
  7168. ->where('is_deleted', 0)
  7169. ->first();
  7170. if (!$sourceItem) {
  7171. Utils::throwError('20003:要推送的项目不存在');
  7172. }
  7173. // 通过user_id判断源是公共库还是个人库
  7174. $source_uid = $sourceItem->user_id;
  7175. $source_is_public = ($source_uid == 0) ? 1 : 0;
  7176. // 验证目标文件夹并确定目标是公共库还是个人库
  7177. $target_level = 0;
  7178. $target_uid = $uid; // 默认推送到个人库
  7179. $target_is_public = 0;
  7180. $final_product_type = $sourceItem->product; // 默认使用源的 product 类型
  7181. if ($target_parent_id > 0) {
  7182. // 查询目标文件夹(只通过cpid查询,不限制user_id)
  7183. $targetParent = DB::table('mp_products')
  7184. ->where('id', $target_parent_id)
  7185. ->where('cpid', $cpid)
  7186. ->where('type', 2)
  7187. ->where('is_deleted', 0)
  7188. ->first();
  7189. if (!$targetParent) {
  7190. Utils::throwError('20003:目标文件夹不存在');
  7191. }
  7192. // 通过user_id判断目标是公共库还是个人库
  7193. $target_level = $targetParent->level;
  7194. $target_uid = $targetParent->user_id;
  7195. $target_is_public = ($target_uid == 0) ? 1 : 0;
  7196. // 使用目标文件夹的 product 类型
  7197. $final_product_type = $targetParent->product;
  7198. }
  7199. // 如果 target_parent_id = 0(推送到根目录),需要通过参数判断推送到个人库还是公共库
  7200. else {
  7201. $push_to_public = getProp($data, 'push_to_public');
  7202. if ($push_to_public === '') {
  7203. Utils::throwError('20003:请选择是否推送到公共库');
  7204. }
  7205. if ($push_to_public) {
  7206. $target_uid = 0;
  7207. $target_is_public = 1;
  7208. }
  7209. // 推送到根目录时,必须指定 product 类型
  7210. if ($target_product === null || $target_product === '') {
  7211. Utils::throwError('20003:推送到根目录时必须指定目标类型(product)');
  7212. }
  7213. $final_product_type = $target_product;
  7214. }
  7215. // 如果目标是公共库,需要admin权限
  7216. if ($target_is_public && $role !== 'admin') {
  7217. Utils::throwError('20003:只有管理员才能推送到公共资产库');
  7218. }
  7219. // 权限验证:验证是否符合允许的推送规则
  7220. $this->validatePushPermission($source_uid, $target_uid, $uid);
  7221. try {
  7222. DB::beginTransaction();
  7223. // 如果是资产,直接复制(支持跨类型推送,更新 product 字段)
  7224. if ($sourceItem->type == 1) {
  7225. $newId = $this->copyProduct($sourceItem, $target_parent_id, $target_level + 1, $cpid, $target_uid, $final_product_type);
  7226. DB::commit();
  7227. return [
  7228. 'product_id' => $newId,
  7229. ];
  7230. }
  7231. // 如果是文件夹,递归复制(支持跨类型推送)
  7232. $newFolderId = $this->copyFolderRecursive($sourceItem, $target_parent_id, $target_level + 1, $cpid, $target_uid, $source_uid, $final_product_type);
  7233. DB::commit();
  7234. return [
  7235. 'product_id' => $newFolderId,
  7236. ];
  7237. } catch (\Exception $e) {
  7238. DB::rollBack();
  7239. dLog('anime')->error('推送失败', [
  7240. 'error' => $e->getMessage(),
  7241. 'product_id' => $product_id
  7242. ]);
  7243. Utils::throwError('20003:' . $e->getMessage());
  7244. }
  7245. }
  7246. /**
  7247. * 验证推送权限
  7248. * 允许的推送规则:
  7249. * 1. 自己推送给自己的个人库(个人库 → 个人库,同一用户)
  7250. * 2. 公共库推送给自己的个人库(公共库 → 个人库)
  7251. * 3. 公共库推送给公共库(公共库 → 公共库)
  7252. *
  7253. * @param int $source_uid 源的user_id
  7254. * @param int $target_uid 目标的user_id
  7255. * @param int $current_uid 当前用户ID
  7256. * @throws \Exception
  7257. */
  7258. private function validatePushPermission($source_uid, $target_uid, $current_uid) {
  7259. // 规则1:自己推送给自己的个人库(个人库 → 个人库,同一用户)
  7260. if ($source_uid == $current_uid && $target_uid == $current_uid) {
  7261. return; // 允许
  7262. }
  7263. // 规则2:公共库推送给自己的个人库(公共库 → 个人库)
  7264. if ($source_uid == 0 && $target_uid == $current_uid) {
  7265. return; // 允许
  7266. }
  7267. // 规则3:公共库推送给公共库(公共库 → 公共库)
  7268. if ($source_uid == 0 && $target_uid == 0) {
  7269. return; // 允许
  7270. }
  7271. // 其他情况都不允许
  7272. if ($source_uid != 0 && $source_uid != $current_uid) {
  7273. // 源是别人的个人库
  7274. Utils::throwError('20003:无权限访问该资产');
  7275. } elseif ($source_uid == $current_uid && $target_uid == 0) {
  7276. // 个人库推送给公共库(不允许)
  7277. Utils::throwError('20003:不允许将个人资产推送到公共库');
  7278. } elseif ($source_uid != 0 && $target_uid != 0 && $source_uid != $target_uid) {
  7279. // 不同用户的个人库之间推送(不允许)
  7280. Utils::throwError('20003:不允许推送到其他用户的个人库');
  7281. } else {
  7282. // 其他未知情况
  7283. Utils::throwError('20003:不允许的推送操作');
  7284. }
  7285. }
  7286. /**
  7287. * 复制单个资产
  7288. * @param object $sourceProduct 源资产对象
  7289. * @param int $targetParentId 目标父文件夹ID
  7290. * @param int $targetLevel 目标层级
  7291. * @param int $cpid 公司ID
  7292. * @param int $targetUid 目标用户ID
  7293. * @return int 返回新资产ID
  7294. */
  7295. private function copyProduct($sourceProduct, $targetParentId, $targetLevel, $cpid, $targetUid, $productType = null) {
  7296. // 如果指定了 productType,使用指定的;否则使用源的 product 类型
  7297. $finalProductType = ($productType !== null) ? $productType : $sourceProduct->product;
  7298. $newProductData = [
  7299. 'user_id' => $targetUid,
  7300. 'cpid' => $cpid,
  7301. 'type' => 1,
  7302. 'parent_id' => $targetParentId,
  7303. 'level' => $targetLevel,
  7304. 'product_name' => $sourceProduct->product_name,
  7305. 'url' => $sourceProduct->url,
  7306. 'pic_prompt' => $sourceProduct->pic_prompt ?? '',
  7307. 'three_view_image_url' => $sourceProduct->three_view_image_url ?? '',
  7308. 'timbre_url' => $sourceProduct->timbre_url ?? '',
  7309. 'product' => $finalProductType,
  7310. 'versions' => $sourceProduct->versions ?? '',
  7311. 'sort_order' => time(),
  7312. 'is_deleted' => 0,
  7313. 'created_at' => date('Y-m-d H:i:s'),
  7314. 'updated_at' => date('Y-m-d H:i:s')
  7315. ];
  7316. return DB::table('mp_products')->insertGetId($newProductData);
  7317. }
  7318. /**
  7319. * 递归复制文件夹及其子项
  7320. * @param object $sourceFolder 源文件夹对象
  7321. * @param int $targetParentId 目标父文件夹ID
  7322. * @param int $targetLevel 目标层级
  7323. * @param int $cpid 公司ID
  7324. * @param int $targetUid 目标用户ID
  7325. * @param int $sourceUid 源用户ID
  7326. * @return int 返回新文件夹ID
  7327. */
  7328. private function copyFolderRecursive($sourceFolder, $targetParentId, $targetLevel, $cpid, $targetUid, $sourceUid, $productType = null) {
  7329. // 如果指定了 productType,使用指定的;否则使用源的 product 类型
  7330. $finalProductType = ($productType !== null) ? $productType : $sourceFolder->product;
  7331. // 创建新文件夹
  7332. $newFolderData = [
  7333. 'user_id' => $targetUid,
  7334. 'cpid' => $cpid,
  7335. 'type' => 2,
  7336. 'parent_id' => $targetParentId,
  7337. 'level' => $targetLevel,
  7338. 'product_name' => $sourceFolder->product_name,
  7339. 'product' => $finalProductType,
  7340. 'sort_order' => time(),
  7341. 'is_deleted' => 0,
  7342. 'created_at' => date('Y-m-d H:i:s'),
  7343. 'updated_at' => date('Y-m-d H:i:s')
  7344. ];
  7345. $newFolderId = DB::table('mp_products')->insertGetId($newFolderData);
  7346. // 获取源文件夹下的所有子项
  7347. $children = DB::table('mp_products')
  7348. ->where('parent_id', $sourceFolder->id)
  7349. ->where('cpid', $cpid)
  7350. ->where('user_id', $sourceUid)
  7351. ->where('is_deleted', 0)
  7352. ->orderByRaw('type DESC, sort_order DESC, created_at DESC')
  7353. ->get();
  7354. // 递归复制子项(子项继承目标文件夹的 product 类型)
  7355. foreach ($children as $child) {
  7356. if ($child->type == 1) {
  7357. // 资产
  7358. $this->copyProduct($child, $newFolderId, $targetLevel + 1, $cpid, $targetUid, $finalProductType);
  7359. } else {
  7360. // 文件夹
  7361. $this->copyFolderRecursive($child, $newFolderId, $targetLevel + 1, $cpid, $targetUid, $sourceUid, $finalProductType);
  7362. }
  7363. }
  7364. return $newFolderId;
  7365. }
  7366. /**
  7367. * 转让剧本归属(剧本及其关联资产)
  7368. *
  7369. * 仅调整 mp_scripts.user_id 与 mp_products.user_id,其他表保持不变。
  7370. * 权限:仅 admin / superadmin 可操作;目标用户必须是同组(cpid 相同)且角色为 user(组员)的用户,禁止跨组转让。
  7371. * 多个剧本逐个独立事务处理,单个剧本失败不影响其他剧本;
  7372. * 单个剧本内的剧本记录与关联资产必须全部更新成功,否则整体回滚。
  7373. *
  7374. * @param array $data 请求参数:script_ids(数组或英文逗号分隔,兼容单个 script_id)、target_user_id
  7375. * @return array
  7376. */
  7377. public function transferScriptOwner($data) {
  7378. $operatorRole = Site::getRole();
  7379. $operatorCpid = Site::getCpid();
  7380. // 1.权限校验:仅管理员和超管可操作
  7381. if (!in_array($operatorRole, ['admin', 'superadmin'], true)) {
  7382. Utils::throwError(ErrorConst::NOT_ACCESS);
  7383. }
  7384. // 2.目标用户校验:必须存在且角色为 user(组员)
  7385. $targetUserId = (int)getProp($data, 'target_user_id', 0);
  7386. if ($targetUserId < 1) {
  7387. Utils::throwError('1002:请选择转让的目标用户');
  7388. }
  7389. $targetUser = DB::table('mp_manage_users')
  7390. ->where('id', $targetUserId)
  7391. ->where('is_deleted', 0)
  7392. ->first();
  7393. if (!$targetUser) {
  7394. Utils::throwError('20003:目标用户不存在');
  7395. }
  7396. if ((string)getProp($targetUser, 'role') !== 'user') {
  7397. Utils::throwError('20003:只能转让给角色为组员(user)的用户');
  7398. }
  7399. $targetCpid = (int)getProp($targetUser, 'cpid');
  7400. // 3.规范化剧本ID列表(兼容数组、逗号分隔字符串、script_id 单值)
  7401. $rawScriptIds = getProp($data, 'script_ids');
  7402. if (empty($rawScriptIds)) {
  7403. $rawScriptIds = getProp($data, 'script_id');
  7404. }
  7405. $scriptIds = $this->normalizeIdList($rawScriptIds);
  7406. if (empty($scriptIds)) {
  7407. Utils::throwError('20003:请提供剧本ID');
  7408. }
  7409. // 预取剧本名称,便于失败结果中回显
  7410. $scriptNameMap = DB::table('mp_scripts')
  7411. ->whereIn('id', $scriptIds)
  7412. ->pluck('script_name', 'id')
  7413. ->all();
  7414. $successList = [];
  7415. $failedList = [];
  7416. // 4.逐个剧本独立事务处理,单个失败不影响其他剧本
  7417. foreach ($scriptIds as $scriptId) {
  7418. DB::beginTransaction();
  7419. try {
  7420. $successList[] = $this->transferSingleScriptOwner(
  7421. $scriptId,
  7422. $targetUserId,
  7423. $targetCpid,
  7424. $operatorRole,
  7425. $operatorCpid,
  7426. Site::getUid()
  7427. );
  7428. DB::commit();
  7429. } catch (\Throwable $e) {
  7430. DB::rollBack();
  7431. $failedList[] = [
  7432. 'script_id' => (int)$scriptId,
  7433. 'script_name' => (string)($scriptNameMap[$scriptId] ?? ''),
  7434. 'reason' => $e->getMessage() !== '' ? $e->getMessage() : '转让失败',
  7435. ];
  7436. dLog('anime')->error('剧本归属转让失败', [
  7437. 'script_id' => $scriptId,
  7438. 'target_user_id' => $targetUserId,
  7439. 'operator_uid' => Site::getUid(),
  7440. 'error' => $e->getMessage(),
  7441. ]);
  7442. }
  7443. }
  7444. return [
  7445. 'target_user_id' => $targetUserId,
  7446. 'success_count' => count($successList),
  7447. 'failed_count' => count($failedList),
  7448. 'success_list' => $successList,
  7449. 'failed_list' => $failedList,
  7450. ];
  7451. }
  7452. /**
  7453. * 单个剧本的归属转让(需在事务中调用)
  7454. *
  7455. * @param int $scriptId 剧本ID
  7456. * @param int $targetUserId 目标用户ID
  7457. * @param int $targetCpid 目标用户所属公司ID
  7458. * @param string $operatorRole 操作人角色
  7459. * @param int $operatorCpid 操作人所属公司ID
  7460. * @param int $operatorUid 操作人用户ID
  7461. * @return array
  7462. */
  7463. private function transferSingleScriptOwner($scriptId, $targetUserId, $targetCpid, $operatorRole, $operatorCpid, $operatorUid) {
  7464. $script = DB::table('mp_scripts')
  7465. ->where('id', $scriptId)
  7466. ->where('is_deleted', 0)
  7467. ->first();
  7468. if (!$script) {
  7469. Utils::throwError('20003:剧本不存在');
  7470. }
  7471. $scriptCpid = (int)getProp($script, 'cpid');
  7472. $fromUserId = (int)getProp($script, 'user_id');
  7473. // 管理员仅可操作本组剧本
  7474. if ($operatorRole !== 'superadmin' && $scriptCpid !== $operatorCpid) {
  7475. Utils::throwError(ErrorConst::NOT_ACCESS);
  7476. }
  7477. // 管理员仅可转让自己创建的剧本(超管不做此验证)
  7478. if ($operatorRole !== 'superadmin' && $fromUserId !== (int)$operatorUid) {
  7479. Utils::throwError('20003:管理员仅能转让自己创建的剧本和资产');
  7480. }
  7481. // 禁止跨组转让:目标用户必须与剧本同组
  7482. if ($targetCpid !== $scriptCpid) {
  7483. Utils::throwError('20003:不能跨组转让,目标用户与剧本不在同一组');
  7484. }
  7485. // 关联资产ID(同一资产可能关联多个剧集序号,需去重)
  7486. $productIds = $this->normalizeIdList(
  7487. DB::table('mp_script_product_mappings')
  7488. ->where('script_id', $scriptId)
  7489. ->pluck('product_id')
  7490. ->all()
  7491. );
  7492. $folderIds = [];
  7493. if (!empty($productIds)) {
  7494. $products = DB::table('mp_products')
  7495. ->whereIn('id', $productIds)
  7496. ->select('id', 'cpid', 'parent_id', 'user_id')
  7497. ->get();
  7498. // 关联资产必须全部存在,否则视为数据异常,不提交
  7499. if ($products->count() !== count($productIds)) {
  7500. Utils::throwError('20003:剧本存在已丢失的关联资产,无法完成转让');
  7501. }
  7502. foreach ($products as $product) {
  7503. // 关联资产必须与剧本同组,避免误转让跨组资产
  7504. if ((int)getProp($product, 'cpid') !== $scriptCpid) {
  7505. Utils::throwError('20003:剧本存在跨组关联资产,无法完成转让');
  7506. }
  7507. $parentId = (int)getProp($product, 'parent_id', 0);
  7508. if ($parentId > 0 && !in_array($parentId, $folderIds, true)) {
  7509. $folderIds[] = $parentId;
  7510. }
  7511. }
  7512. // 仅转让归属于原剧本所有者的资产
  7513. $folderIds = DB::table('mp_products')
  7514. ->whereIn('id', $folderIds)
  7515. ->where('type', 2)
  7516. ->where('cpid', $scriptCpid)
  7517. ->where('user_id', $fromUserId)
  7518. ->pluck('id')
  7519. ->map('intval')
  7520. ->all();
  7521. // 管理员仅可转让自己创建的资产及其所属文件夹(超管不做此验证)
  7522. if ($operatorRole !== 'superadmin') {
  7523. foreach ($products as $product) {
  7524. if ((int)getProp($product, 'user_id') !== (int)$operatorUid) {
  7525. Utils::throwError('20003:管理员仅能转让自己创建的剧本和资产');
  7526. }
  7527. }
  7528. foreach ($products as $product) {
  7529. $parentId = (int)getProp($product, 'parent_id', 0);
  7530. if ($parentId > 0 && !in_array($parentId, $folderIds, true)) {
  7531. Utils::throwError('20003:管理员仅能转让自己创建的剧本和资产');
  7532. }
  7533. }
  7534. }
  7535. }
  7536. $now = now();
  7537. // 5.更新剧本归属
  7538. DB::table('mp_scripts')
  7539. ->where('id', $scriptId)
  7540. ->update([
  7541. 'user_id' => $targetUserId,
  7542. 'updated_at' => $now,
  7543. ]);
  7544. // 6.更新关联资产归属
  7545. if (!empty($productIds)) {
  7546. DB::table('mp_products')
  7547. ->whereIn('id', $productIds)
  7548. ->update([
  7549. 'user_id' => $targetUserId,
  7550. 'updated_at' => $now,
  7551. ]);
  7552. }
  7553. // 7.更新资产所属的类型根文件夹归属(文件夹属于 mp_products,随资产一并转让)
  7554. if (!empty($folderIds)) {
  7555. DB::table('mp_products')
  7556. ->whereIn('id', $folderIds)
  7557. ->update([
  7558. 'user_id' => $targetUserId,
  7559. 'updated_at' => $now,
  7560. ]);
  7561. }
  7562. // 8.校验剧本与资产是否全部更新成功,任一未成功则回滚
  7563. $scriptOwner = (int)DB::table('mp_scripts')->where('id', $scriptId)->value('user_id');
  7564. if ($scriptOwner !== $targetUserId) {
  7565. Utils::throwError('20003:剧本归属更新失败');
  7566. }
  7567. if (!empty($productIds)) {
  7568. $updatedProductCount = DB::table('mp_products')
  7569. ->whereIn('id', $productIds)
  7570. ->where('user_id', $targetUserId)
  7571. ->count();
  7572. if ($updatedProductCount !== count($productIds)) {
  7573. Utils::throwError('20003:部分剧本资产转让失败,已回滚');
  7574. }
  7575. }
  7576. if (!empty($folderIds)) {
  7577. $updatedFolderCount = DB::table('mp_products')
  7578. ->whereIn('id', $folderIds)
  7579. ->where('user_id', $targetUserId)
  7580. ->count();
  7581. if ($updatedFolderCount !== count($folderIds)) {
  7582. Utils::throwError('20003:部分资产文件夹转让失败,已回滚');
  7583. }
  7584. }
  7585. return [
  7586. 'script_id' => (int)$scriptId,
  7587. 'script_name' => (string)getProp($script, 'script_name', ''),
  7588. 'from_user_id' => $fromUserId,
  7589. 'to_user_id' => $targetUserId,
  7590. 'product_count' => count($productIds),
  7591. 'folder_count' => count($folderIds),
  7592. ];
  7593. }
  7594. /**
  7595. * 规范化ID列表,兼容数组、逗号分隔字符串以及字符串数组
  7596. *
  7597. * @param mixed $ids 待处理的ID集合
  7598. * @return array 去重后的正整数ID数组
  7599. */
  7600. private function normalizeIdList($ids) {
  7601. if (!is_array($ids)) {
  7602. $ids = explode(',', (string)$ids);
  7603. }
  7604. $result = [];
  7605. foreach ($ids as $item) {
  7606. if (is_array($item)) {
  7607. continue;
  7608. }
  7609. foreach (explode(',', (string)$item) as $part) {
  7610. $part = trim($part);
  7611. if ($part !== '' && is_numeric($part) && (int)$part > 0) {
  7612. $result[] = (int)$part;
  7613. }
  7614. }
  7615. }
  7616. return array_values(array_unique($result));
  7617. }
  7618. /**
  7619. * 通过 Excel 批量导入剧本资产(独立实现,不依赖 saveScriptProducts)
  7620. *
  7621. * 流程:
  7622. * 1. 校验剧本存在且属于当前用户
  7623. * 2. 解析 Excel 并校验强制列与数据完整性(资产类型/资产名称/使用范围/参考提示词)
  7624. * 3. 名称去重(与 Excel 内及该剧本已有关联资产比对)
  7625. * 4. 事务内创建类型文件夹、资产与剧本映射
  7626. * 5. 为没有图片的资产创建图片生成任务,生成中返回 SSE 轮询
  7627. *
  7628. * @param array $data 请求参数
  7629. * @param \Illuminate\Http\UploadedFile $file 上传的 Excel 文件
  7630. * @return array|\Generator
  7631. */
  7632. public function importScriptProductsByExcel($data, $file) {
  7633. $uid = Site::getUid();
  7634. $cpid = Site::getCpid();
  7635. $script_id = (int)getProp($data, 'script_id', 0);
  7636. if (!$script_id) {
  7637. Utils::throwError('20003:请提供剧本ID');
  7638. }
  7639. // 验证剧本是否存在,且只能导入自己创建的剧本
  7640. $script = DB::table('mp_scripts')
  7641. ->where('id', $script_id)
  7642. ->where('is_deleted', 0)
  7643. ->where('user_id', $uid)
  7644. ->first();
  7645. if (!$script) {
  7646. Utils::throwError('20003:剧本不存在或无权限操作');
  7647. }
  7648. $script_name = $script->script_name ?? 'script_' . $script_id;
  7649. // 校验上传文件
  7650. if (!$file) {
  7651. Utils::throwError('20003:请上传Excel文件');
  7652. }
  7653. $extension = strtolower($file->getClientOriginalExtension());
  7654. if (!in_array($extension, ['xlsx', 'xls'])) {
  7655. Utils::throwError('20003:文件格式错误,仅支持 xlsx、xls 格式');
  7656. }
  7657. if ($file->getSize() > 10 * 1024 * 1024) {
  7658. Utils::throwError('20003:文件大小不能超过10M');
  7659. }
  7660. // 解析 Excel(第一行为表头)
  7661. $rows = $this->readImportExcelRows($file);
  7662. if (empty($rows)) {
  7663. Utils::throwError('20003:Excel内容为空');
  7664. }
  7665. $headers = array_shift($rows);
  7666. // 定位强制列
  7667. $typeColumnIndex = $this->findImportExcelColumnIndex($headers, ['资产类型'], ['资产类型', '类型']);
  7668. $nameColumnIndex = $this->findImportExcelColumnIndex($headers, ['资产名称'], ['资产名称', '名称']);
  7669. $rangeColumnIndex = $this->findImportExcelColumnIndex($headers, ['使用范围'], ['使用范围', '范围']);
  7670. $promptColumnIndex = $this->findImportExcelColumnIndex($headers, ['参考提示词', '提示词'], ['提示词']);
  7671. $missingColumns = [];
  7672. if ($typeColumnIndex < 0) {
  7673. $missingColumns[] = '资产类型';
  7674. }
  7675. if ($nameColumnIndex < 0) {
  7676. $missingColumns[] = '资产名称';
  7677. }
  7678. if ($rangeColumnIndex < 0) {
  7679. $missingColumns[] = '使用范围';
  7680. }
  7681. if ($promptColumnIndex < 0) {
  7682. $missingColumns[] = '参考提示词';
  7683. }
  7684. if (!empty($missingColumns)) {
  7685. Utils::throwError('20003:Excel缺少必填列:' . implode('、', $missingColumns));
  7686. }
  7687. // 先整体校验 Excel 数据,所有异常行一次性返回
  7688. $validation = $this->validateImportExcelRows(
  7689. $rows,
  7690. $typeColumnIndex,
  7691. $nameColumnIndex,
  7692. $rangeColumnIndex,
  7693. $promptColumnIndex
  7694. );
  7695. $errors = $validation['errors'];
  7696. $checkedRows = $validation['checked_rows'];
  7697. if (empty($checkedRows)) {
  7698. $errors[] = 'Excel中没有有效的数据行';
  7699. }
  7700. if (!empty($errors)) {
  7701. Utils::throwError('20003:Excel数据校验失败:' . implode(';', $errors));
  7702. }
  7703. // 名称去重:Excel 内部 + 该剧本已关联资产(按 createProduct 的名称判断逻辑)
  7704. $existingNames = $this->getScriptProductNames($script_id, $cpid);
  7705. $dedupResult = $this->deduplicateImportRows($checkedRows, $existingNames);
  7706. $validRows = $dedupResult['valid_rows'];
  7707. $skipped = $dedupResult['skipped'];
  7708. // 图片生成参数(与 saveScriptProducts 保持一致的校验规则)
  7709. $model = getProp($data, 'model');
  7710. if (!$model) {
  7711. $model = 'gpt-image-2';
  7712. }
  7713. if (!DB::table('mp_image_models')->where('model', $model)->where('is_enabled', 1)->exists()) {
  7714. Utils::throwError('20003:该模型已不可用,请更换!');
  7715. }
  7716. $ratio = getProp($data, 'ratio', '9:16');
  7717. $resolution = strtolower(getProp($data, 'resolution', '2k'));
  7718. $sizeMap = BaseConst::IMAGE_RESOLUTION_SIZE_MAP;
  7719. if (!isset($sizeMap[$resolution])) {
  7720. Utils::throwError('20003:分辨率参数错误,仅支持 2k、3k、4k');
  7721. }
  7722. if (!isset($sizeMap[$resolution][$ratio])) {
  7723. Utils::throwError('20003:宽高比参数错误,该分辨率下不支持 ' . $ratio . ' 比例');
  7724. }
  7725. $width = $sizeMap[$resolution][$ratio]['width'];
  7726. $height = $sizeMap[$resolution][$ratio]['height'];
  7727. $autoRaw = getProp($data, 'auto_generate_images', true);
  7728. $auto_generate_images = !in_array($autoRaw, [false, 0, '0', 'false', 'False'], true);
  7729. // 创建/复用任务中心记录(md5 验重,避免重复任务)
  7730. $taskCenterId = $this->createScriptProductTaskCenter(
  7731. $uid,
  7732. $cpid,
  7733. $script_id,
  7734. $validRows,
  7735. $model,
  7736. $ratio,
  7737. $resolution,
  7738. $auto_generate_images
  7739. );
  7740. // 全部为重复项:参照 saveScriptProducts,检查已存在资产的图片状态,缺图的补建任务
  7741. if (empty($validRows)) {
  7742. $existingTaskInfo = $this->prepareExistingScriptProductTasks(
  7743. $script_id,
  7744. $model,
  7745. $width,
  7746. $height,
  7747. $auto_generate_images
  7748. );
  7749. $productTaskMap = $existingTaskInfo['product_task_map'];
  7750. $typeFolderIds = $existingTaskInfo['type_folder_ids'];
  7751. if (!empty($productTaskMap)) {
  7752. $message = 'Excel中的资产均已存在,正在为缺少图片的资产生成图片';
  7753. } elseif (!$existingTaskInfo['has_all_tasks']) {
  7754. $message = 'Excel中的资产均已存在,部分资产没有参考提示词,无法生成图片';
  7755. } else {
  7756. $message = 'Excel中的资产均已存在,且图片已全部生成完成';
  7757. }
  7758. $resultData = [
  7759. 'success' => true,
  7760. 'message' => $message,
  7761. 'script_id' => $script_id,
  7762. 'script_name' => $script_name,
  7763. 'imported_count' => 0,
  7764. 'existing_products' => $existingTaskInfo['product_count'],
  7765. 'skipped_count' => count($skipped),
  7766. 'skipped' => $skipped,
  7767. 'created_products' => [],
  7768. 'type_folder_ids' => $typeFolderIds,
  7769. 'pending_tasks_count' => count($productTaskMap),
  7770. 'image_tasks_created' => $existingTaskInfo['created_count'],
  7771. 'task_center_id' => $taskCenterId,
  7772. ];
  7773. // 有需要轮询的任务(已有任务或本次补建):走 SSE 轮询
  7774. if (!empty($productTaskMap)) {
  7775. return $this->pollProductImageTasks(
  7776. $script_id,
  7777. $script_name,
  7778. $productTaskMap,
  7779. $typeFolderIds,
  7780. $taskCenterId,
  7781. ['import_result' => $resultData],
  7782. ['import_result' => $resultData]
  7783. );
  7784. }
  7785. // 没有需要轮询的任务:直接通过 complete 事件返回导入结果
  7786. return $this->streamImportComplete($script_id, $script_name, $resultData, $typeFolderIds, $taskCenterId);
  7787. }
  7788. // 事务内创建资产、类型文件夹与剧本映射
  7789. $typeFolderIds = [];
  7790. $createdProducts = [];
  7791. $mappingRecords = [];
  7792. $now = now();
  7793. DB::beginTransaction();
  7794. try {
  7795. foreach ($validRows as $row) {
  7796. $type = $row['type'];
  7797. if (!isset($typeFolderIds[$type])) {
  7798. // 与 createProduct 一致:先查找该剧本已存在的类型文件夹,没有则创建
  7799. $folder = DB::table('mp_products')
  7800. ->where('cpid', $cpid)
  7801. ->where('type', 2)
  7802. ->where('product', $type)
  7803. ->where('product_name', $script_name)
  7804. ->where('parent_id', 0)
  7805. ->where('is_deleted', 0)
  7806. ->first();
  7807. if ($folder) {
  7808. $typeFolderIds[$type] = $folder->id;
  7809. } else {
  7810. $typeFolderIds[$type] = DB::table('mp_products')->insertGetId([
  7811. 'user_id' => $uid,
  7812. 'cpid' => $cpid,
  7813. 'type' => 2, // 文件夹
  7814. 'product' => $type, // 1=角色 2=场景 3=道具
  7815. 'parent_id' => 0,
  7816. 'level' => 1,
  7817. 'product_name' => $script_name,
  7818. 'sort_order' => time() + $type,
  7819. 'is_deleted' => 0,
  7820. 'created_at' => $now,
  7821. 'updated_at' => $now,
  7822. ]);
  7823. }
  7824. }
  7825. $folder_id = $typeFolderIds[$type];
  7826. $product_id = DB::table('mp_products')->insertGetId([
  7827. 'user_id' => $uid,
  7828. 'cpid' => $cpid,
  7829. 'type' => 1, // 资产
  7830. 'product' => $type,
  7831. 'parent_id' => $folder_id,
  7832. 'level' => 2,
  7833. 'product_name' => $row['product_name'],
  7834. 'pic_prompt' => $row['pic_prompt'],
  7835. 'sort_order' => time(),
  7836. 'is_deleted' => 0,
  7837. 'created_at' => $now,
  7838. 'updated_at' => $now,
  7839. ]);
  7840. $createdProducts[] = [
  7841. 'id' => $product_id,
  7842. 'type' => $type,
  7843. 'product_name' => $row['product_name'],
  7844. 'pic_prompt' => $row['pic_prompt'],
  7845. ];
  7846. // 为每个使用范围(集数)创建映射记录
  7847. foreach ($row['episode_numbers'] as $episodeNumber) {
  7848. $mappingRecords[] = [
  7849. 'script_id' => $script_id,
  7850. 'product_id' => $product_id,
  7851. 'episode_number' => $episodeNumber,
  7852. 'created_at' => $now,
  7853. 'updated_at' => $now,
  7854. ];
  7855. }
  7856. }
  7857. // 批量插入映射数据(使用 insertOrIgnore 避免重复插入)
  7858. DB::table('mp_script_product_mappings')->insertOrIgnore($mappingRecords);
  7859. // 剧本已有资产,同步更新is_products标记
  7860. DB::table('mp_scripts')->where('id', $script_id)->update([
  7861. 'is_products' => 1,
  7862. 'updated_at' => $now,
  7863. ]);
  7864. DB::commit();
  7865. } catch (\Exception $e) {
  7866. DB::rollback();
  7867. if ($taskCenterId) {
  7868. $this->taskCenterService->updateTask($taskCenterId, [
  7869. 'status' => MpTaskCenter::STATUS_FAILED,
  7870. 'error_message' => $e->getMessage(),
  7871. ]);
  7872. }
  7873. dLog('anime')->error('Excel导入剧本资产失败: ' . $e->getMessage(), [
  7874. 'script_id' => $script_id,
  7875. 'error' => $e->getMessage(),
  7876. 'trace' => $e->getTraceAsString(),
  7877. ]);
  7878. Utils::throwError('20003:Excel导入剧本资产失败:' . $e->getMessage());
  7879. }
  7880. // 参照 saveScriptProducts:为新建资产以及已存在但缺图的资产统一补建图片生成任务
  7881. $existingTaskInfo = $this->prepareExistingScriptProductTasks(
  7882. $script_id,
  7883. $model,
  7884. $width,
  7885. $height,
  7886. $auto_generate_images
  7887. );
  7888. $productTaskMap = $existingTaskInfo['product_task_map'];
  7889. $resultData = [
  7890. 'success' => true,
  7891. 'message' => '导入完成',
  7892. 'script_id' => $script_id,
  7893. 'script_name' => $script_name,
  7894. 'imported_count' => count($createdProducts),
  7895. 'skipped_count' => count($skipped),
  7896. 'skipped' => $skipped,
  7897. 'created_products' => array_map(function ($item) {
  7898. return [
  7899. 'id' => $item['id'],
  7900. 'type' => $item['type'],
  7901. 'product_name' => $item['product_name'],
  7902. ];
  7903. }, $createdProducts),
  7904. 'type_folder_ids' => $typeFolderIds,
  7905. 'pending_tasks_count' => count($productTaskMap),
  7906. 'image_tasks_created' => $existingTaskInfo['created_count'],
  7907. 'task_center_id' => $taskCenterId,
  7908. ];
  7909. // 有待生成的图片任务:返回 SSE 轮询结果(导入统计在 init 与 complete 事件中)
  7910. if (!empty($productTaskMap)) {
  7911. return $this->pollProductImageTasks(
  7912. $script_id,
  7913. $script_name,
  7914. $productTaskMap,
  7915. $typeFolderIds,
  7916. $taskCenterId,
  7917. ['import_result' => $resultData],
  7918. ['import_result' => $resultData]
  7919. );
  7920. }
  7921. // 没有需要轮询的任务:直接通过 complete 事件返回导入结果
  7922. return $this->streamImportComplete($script_id, $script_name, $resultData, $typeFolderIds, $taskCenterId);
  7923. }
  7924. /**
  7925. * 校验 Excel 数据行(先校验完毕,再进行后续逻辑)
  7926. *
  7927. * @param array $rows
  7928. * @param int $typeColumnIndex
  7929. * @param int $nameColumnIndex
  7930. * @param int $rangeColumnIndex
  7931. * @param int $promptColumnIndex
  7932. * @return array ['errors' => [], 'checked_rows' => []]
  7933. */
  7934. private function validateImportExcelRows(array $rows, $typeColumnIndex, $nameColumnIndex, $rangeColumnIndex, $promptColumnIndex) {
  7935. $errors = [];
  7936. $checkedRows = [];
  7937. foreach ($rows as $rowIndex => $row) {
  7938. // 数据从第2行开始(表头占第1行)
  7939. $excelRowNo = $rowIndex + 2;
  7940. if (!is_array($row) || $this->isImportExcelRowEmpty($row)) {
  7941. continue;
  7942. }
  7943. $typeRaw = trim((string)($row[$typeColumnIndex] ?? ''));
  7944. $nameRaw = trim((string)($row[$nameColumnIndex] ?? ''));
  7945. $rangeRaw = trim((string)($row[$rangeColumnIndex] ?? ''));
  7946. $promptRaw = trim((string)($row[$promptColumnIndex] ?? ''));
  7947. $missingFields = [];
  7948. if ($typeRaw === '') {
  7949. $missingFields[] = '资产类型';
  7950. }
  7951. if ($nameRaw === '') {
  7952. $missingFields[] = '资产名称';
  7953. }
  7954. if ($rangeRaw === '') {
  7955. $missingFields[] = '使用范围';
  7956. }
  7957. if ($promptRaw === '') {
  7958. $missingFields[] = '参考提示词';
  7959. }
  7960. if (!empty($missingFields)) {
  7961. $errors[] = "第{$excelRowNo}行:" . implode('、', $missingFields) . '不能为空';
  7962. continue;
  7963. }
  7964. // 资产类型校验
  7965. $productType = $this->resolveImportProductType($typeRaw);
  7966. if (!$productType) {
  7967. $errors[] = "第{$excelRowNo}行:资产类型「{$typeRaw}」不正确,仅支持 角色/场景/道具";
  7968. continue;
  7969. }
  7970. // 资产名称去除两边特殊符号
  7971. $productName = $this->normalizeImportProductName($nameRaw);
  7972. if ($productName === '') {
  7973. $errors[] = "第{$excelRowNo}行:资产名称「{$nameRaw}」去除特殊符号后为空";
  7974. continue;
  7975. }
  7976. if (mb_strlen($productName, 'UTF-8') > 64) {
  7977. $errors[] = "第{$excelRowNo}行:资产名称「{$productName}」超过64个字符";
  7978. continue;
  7979. }
  7980. // 解析使用范围(逗号分隔的集数)
  7981. $episodeNumbers = $this->parseImportEpisodeNumbers($rangeRaw);
  7982. if (empty($episodeNumbers)) {
  7983. $errors[] = "第{$excelRowNo}行:使用范围「{$rangeRaw}」格式错误,仅支持数字或逗号分隔的数字";
  7984. continue;
  7985. }
  7986. $checkedRows[] = [
  7987. 'row' => $excelRowNo,
  7988. 'type' => $productType,
  7989. 'product_name' => $productName,
  7990. 'episode_numbers' => $episodeNumbers,
  7991. 'pic_prompt' => $promptRaw,
  7992. ];
  7993. }
  7994. return [
  7995. 'errors' => $errors,
  7996. 'checked_rows' => $checkedRows,
  7997. ];
  7998. }
  7999. /**
  8000. * Excel 资产名称去重:Excel 内部 + 剧本已有关联资产
  8001. *
  8002. * @param array $checkedRows
  8003. * @param array $existingNames 剧本已有关联资产名称集合(name => true)
  8004. * @return array ['valid_rows' => [], 'skipped' => []]
  8005. */
  8006. private function deduplicateImportRows(array $checkedRows, array $existingNames) {
  8007. $seenNames = [];
  8008. $validRows = [];
  8009. $skipped = [];
  8010. foreach ($checkedRows as $row) {
  8011. $nameKey = $row['product_name'];
  8012. $typeText = $this->getImportProductTypeText($row['type']);
  8013. if (isset($seenNames[$nameKey])) {
  8014. $skipped[] = [
  8015. 'row' => $row['row'],
  8016. 'type' => $typeText,
  8017. 'product_name' => $row['product_name'],
  8018. 'reason' => 'Excel中资产名称重复',
  8019. ];
  8020. continue;
  8021. }
  8022. if (isset($existingNames[$nameKey])) {
  8023. $skipped[] = [
  8024. 'row' => $row['row'],
  8025. 'type' => $typeText,
  8026. 'product_name' => $row['product_name'],
  8027. 'reason' => '剧本中已存在同名资产',
  8028. ];
  8029. continue;
  8030. }
  8031. $seenNames[$nameKey] = true;
  8032. $validRows[] = $row;
  8033. }
  8034. return [
  8035. 'valid_rows' => $validRows,
  8036. 'skipped' => $skipped,
  8037. ];
  8038. }
  8039. /**
  8040. * 读取 Excel 文件为二维数组(第一行为表头)
  8041. *
  8042. * @param \Illuminate\Http\UploadedFile $file
  8043. * @return array
  8044. */
  8045. private function readImportExcelRows($file) {
  8046. try {
  8047. $reader = IOFactory::createReaderForFile($file->getRealPath());
  8048. $reader->setReadDataOnly(true);
  8049. $spreadsheet = $reader->load($file->getRealPath());
  8050. $sheet = $spreadsheet->getSheet(0);
  8051. $rows = $sheet->toArray(null, true, true, false);
  8052. $spreadsheet->disconnectWorksheets();
  8053. unset($spreadsheet);
  8054. return $rows;
  8055. } catch (\Exception $e) {
  8056. dLog('anime')->error('Excel文件解析失败', [
  8057. 'error' => $e->getMessage(),
  8058. ]);
  8059. Utils::throwError('20003:Excel文件解析失败,请确认文件格式正确');
  8060. }
  8061. }
  8062. /**
  8063. * 查找 Excel 表头列索引(先精确匹配,再模糊匹配)
  8064. *
  8065. * @param array $headers
  8066. * @param array $exactKeywords
  8067. * @param array $fuzzyKeywords
  8068. * @return int
  8069. */
  8070. private function findImportExcelColumnIndex(array $headers, array $exactKeywords, array $fuzzyKeywords) {
  8071. foreach ($headers as $index => $header) {
  8072. $header = trim((string)$header);
  8073. if ($header === '') {
  8074. continue;
  8075. }
  8076. foreach ($exactKeywords as $keyword) {
  8077. if ($header === $keyword) {
  8078. return $index;
  8079. }
  8080. }
  8081. }
  8082. foreach ($headers as $index => $header) {
  8083. $header = trim((string)$header);
  8084. if ($header === '') {
  8085. continue;
  8086. }
  8087. foreach ($fuzzyKeywords as $keyword) {
  8088. if (mb_strpos($header, $keyword) !== false) {
  8089. return $index;
  8090. }
  8091. }
  8092. }
  8093. return -1;
  8094. }
  8095. /**
  8096. * 判断 Excel 行是否为空行
  8097. *
  8098. * @param array $row
  8099. * @return bool
  8100. */
  8101. private function isImportExcelRowEmpty(array $row) {
  8102. foreach ($row as $cell) {
  8103. if (trim((string)$cell) !== '') {
  8104. return false;
  8105. }
  8106. }
  8107. return true;
  8108. }
  8109. /**
  8110. * 资产名称去除两边特殊符号(与 createProduct 保持一致)
  8111. *
  8112. * @param string $name
  8113. * @return string
  8114. */
  8115. private function normalizeImportProductName($name) {
  8116. $name = trim((string)$name);
  8117. $name = preg_replace('/^[\s*\[\]【】[]{}{}\x{3000}]+|[\s*\[\]【】[]{}{}\x{3000}]+$/u', '', $name);
  8118. if (!$name || preg_match('/^[-—_]+$/u', $name)) {
  8119. return '';
  8120. }
  8121. return $name;
  8122. }
  8123. /**
  8124. * 解析 Excel 中的资产类型
  8125. *
  8126. * @param string $value
  8127. * @return int|null 1=角色 2=场景 3=道具
  8128. */
  8129. private function resolveImportProductType($value) {
  8130. $value = trim((string)$value);
  8131. $map = [
  8132. '角色' => 1,
  8133. '主体' => 1,
  8134. '人物' => 1,
  8135. '1' => 1,
  8136. '场景' => 2,
  8137. '2' => 2,
  8138. '道具' => 3,
  8139. '3' => 3,
  8140. ];
  8141. return isset($map[$value]) ? $map[$value] : null;
  8142. }
  8143. /**
  8144. * 资产类型文案
  8145. *
  8146. * @param int $type
  8147. * @return string
  8148. */
  8149. private function getImportProductTypeText($type) {
  8150. $map = [1 => '角色', 2 => '场景', 3 => '道具'];
  8151. return isset($map[$type]) ? $map[$type] : (string)$type;
  8152. }
  8153. /**
  8154. * 解析使用范围(逗号分隔的集数)
  8155. *
  8156. * @param string $value
  8157. * @return array
  8158. */
  8159. private function parseImportEpisodeNumbers($value) {
  8160. $parts = preg_split('/[,,、\s]+/u', trim((string)$value));
  8161. $episodeNumbers = [];
  8162. foreach ($parts as $part) {
  8163. if ($part === '') {
  8164. continue;
  8165. }
  8166. if (!is_numeric($part)) {
  8167. return [];
  8168. }
  8169. $episodeNumbers[] = (int)$part;
  8170. }
  8171. $episodeNumbers = array_values(array_unique($episodeNumbers));
  8172. sort($episodeNumbers);
  8173. return $episodeNumbers;
  8174. }
  8175. /**
  8176. * 获取剧本已关联资产名称集合(按 createProduct 的名称判断逻辑)
  8177. *
  8178. * @param int $script_id
  8179. * @param int $cpid
  8180. * @return array
  8181. */
  8182. private function getScriptProductNames($script_id, $cpid) {
  8183. $products = DB::table('mp_script_product_mappings as m')
  8184. ->join('mp_products as p', 'm.product_id', '=', 'p.id')
  8185. ->where('m.script_id', $script_id)
  8186. ->where('p.cpid', $cpid)
  8187. ->where('p.type', 1)
  8188. ->where('p.is_deleted', 0)
  8189. ->get(['p.product_name']);
  8190. $names = [];
  8191. foreach ($products as $product) {
  8192. $name = $this->normalizeImportProductName($product->product_name);
  8193. if ($name !== '') {
  8194. $names[$name] = true;
  8195. }
  8196. }
  8197. return $names;
  8198. }
  8199. /**
  8200. * 获取剧本已关联的资产名称(仅按剧本判重,不区分资产类型)
  8201. *
  8202. * @param int $script_id
  8203. * @return array ['资产名称' => true]
  8204. */
  8205. private function getScriptAssetNames($script_id) {
  8206. $products = DB::table('mp_script_product_mappings as m')
  8207. ->join('mp_products as p', 'm.product_id', '=', 'p.id')
  8208. ->where('m.script_id', $script_id)
  8209. ->where('p.type', 1)
  8210. ->where('p.is_deleted', 0)
  8211. ->get(['p.product_name']);
  8212. $names = [];
  8213. foreach ($products as $product) {
  8214. $name = $this->normalizeImportProductName($product->product_name);
  8215. if ($name !== '') {
  8216. $names[$name] = true;
  8217. }
  8218. }
  8219. return $names;
  8220. }
  8221. /**
  8222. * 校验并提取本次入参中的新增资产行
  8223. *
  8224. * 规则:
  8225. * - 资产名称为空(或仅剩占位符):跳过
  8226. * - 同一份入参内重名(跨类型):保留最后一条
  8227. * - 与剧本已关联资产同名(跨类型判重,仅限当前剧本):不算新增
  8228. * - 新增行的参考提示词为空:直接报错,不进行任何后续处理
  8229. *
  8230. * @param int $script_id
  8231. * @param mixed $products 入参(数组或 JSON 字符串)
  8232. * @return array [['type' => int, 'product_name' => string, 'pic_prompt' => string, 'episode_numbers' => []]]
  8233. */
  8234. private function extractNewScriptProductRows($script_id, $products) {
  8235. // 兼容 JSON 字符串;无法解析时按"没有新增行"处理,由后续创建逻辑给出原有报错
  8236. if (is_string($products)) {
  8237. $decoded = json_decode($products, true);
  8238. $products = (json_last_error() === JSON_ERROR_NONE) ? $decoded : [];
  8239. }
  8240. if (!is_array($products) || empty($products)) {
  8241. return [];
  8242. }
  8243. $rowMap = [];
  8244. foreach ($products as $productGroup) {
  8245. $type = getProp($productGroup, 'type');
  8246. $content = getProp($productGroup, 'content', []);
  8247. if (!in_array($type, [1, 2, 3]) || empty($content) || count($content) < 2) {
  8248. continue;
  8249. }
  8250. // 获取表头(第一行)并查找关键列的位置
  8251. $headers = $content[0];
  8252. $nameColumnIndex = -1;
  8253. $sequenceColumnIndex = -1;
  8254. $promptColumnIndex = -1;
  8255. $fallbackPromptColumnIndex = -1;
  8256. foreach ($headers as $index => $header) {
  8257. if (strpos($header, '资产名称') !== false || strpos($header, '名称') !== false) {
  8258. $nameColumnIndex = $index;
  8259. }
  8260. if (strpos($header, '使用范围') !== false || strpos($header, '范围') !== false) {
  8261. $sequenceColumnIndex = $index;
  8262. }
  8263. if (strpos($header, '参考') !== false && strpos($header, '提示词') !== false) {
  8264. $promptColumnIndex = $index;
  8265. } elseif (strpos($header, '提示词') !== false && $fallbackPromptColumnIndex === -1) {
  8266. // 与 Excel 导入保持一致:优先"参考提示词",否则兼容"提示词"列
  8267. $fallbackPromptColumnIndex = $index;
  8268. }
  8269. }
  8270. if ($promptColumnIndex === -1) {
  8271. $promptColumnIndex = $fallbackPromptColumnIndex;
  8272. }
  8273. if ($nameColumnIndex === -1) {
  8274. continue;
  8275. }
  8276. for ($i = 1; $i < count($content); $i++) {
  8277. $row = $content[$i];
  8278. if (empty($row) || !isset($row[$nameColumnIndex])) {
  8279. continue;
  8280. }
  8281. // 处理product_name两边的符号;名称为空或仅剩占位符号则跳过
  8282. $product_name = $this->normalizeImportProductName($row[$nameColumnIndex]);
  8283. if ($product_name === '') {
  8284. continue;
  8285. }
  8286. $pic_prompt = '';
  8287. if ($promptColumnIndex >= 0 && isset($row[$promptColumnIndex])) {
  8288. $pic_prompt = trim((string)$row[$promptColumnIndex]);
  8289. }
  8290. // 解析使用范围(逗号分隔的序号),为空时由创建逻辑写入默认映射(序号0)
  8291. $sequences = [];
  8292. $sequence_str = ($sequenceColumnIndex >= 0 && isset($row[$sequenceColumnIndex]))
  8293. ? trim((string)$row[$sequenceColumnIndex])
  8294. : '';
  8295. if ($sequence_str !== '') {
  8296. foreach (array_map('trim', explode(',', $sequence_str)) as $part) {
  8297. if (is_numeric($part)) {
  8298. $sequences[] = (int)$part;
  8299. }
  8300. }
  8301. }
  8302. // 跨类型判重,同一份入参内重名保留最后一条
  8303. $rowMap[$product_name] = [
  8304. 'type' => (int)$type,
  8305. 'product_name' => $product_name,
  8306. 'pic_prompt' => $pic_prompt,
  8307. 'episode_numbers' => $sequences,
  8308. ];
  8309. }
  8310. }
  8311. // 与剧本已关联资产判重(仅限当前剧本,跨类型)
  8312. $existingNames = $this->getScriptAssetNames($script_id);
  8313. $newRows = [];
  8314. $emptyPromptNames = [];
  8315. foreach ($rowMap as $name => $row) {
  8316. if (isset($existingNames[$name])) {
  8317. continue;
  8318. }
  8319. if ($row['pic_prompt'] === '') {
  8320. $emptyPromptNames[] = $name;
  8321. continue;
  8322. }
  8323. $newRows[] = $row;
  8324. }
  8325. // 新增行的参考提示词为空:直接报错,不进行任何后续处理
  8326. if (!empty($emptyPromptNames)) {
  8327. Utils::throwError('20003:以下新增资产的参考提示词不能为空:' . implode('、', $emptyPromptNames));
  8328. }
  8329. return $newRows;
  8330. }
  8331. /**
  8332. * 已有关联资产的图片任务处理(参照 saveScriptProducts 的处理方式)
  8333. *
  8334. * - 已有图片任务的资产:收集任务ID,交给轮询
  8335. * - 已有图片且生成成功的资产:跳过
  8336. * - 没有图片的资产:允许自动生成时补建图片任务(需要提示词)
  8337. *
  8338. * @param int $script_id
  8339. * @param string $model
  8340. * @param int $width
  8341. * @param int $height
  8342. * @param bool $auto_generate_images
  8343. * @return array ['product_task_map' => [], 'type_folder_ids' => [], 'has_all_tasks' => bool, 'product_count' => int, 'created_count' => int]
  8344. */
  8345. private function prepareExistingScriptProductTasks($script_id, $model, $width, $height, $auto_generate_images) {
  8346. $productTaskMap = [];
  8347. $typeFolderIds = [];
  8348. $hasAllTasks = true;
  8349. $createdCount = 0;
  8350. $existingMappings = DB::table('mp_script_product_mappings')
  8351. ->where('script_id', $script_id)
  8352. ->get();
  8353. $productIds = $existingMappings->pluck('product_id')->unique()->toArray();
  8354. $productsWithTasks = DB::table('mp_products')
  8355. ->whereIn('id', $productIds)
  8356. ->where('is_deleted', 0)
  8357. ->get();
  8358. foreach ($productsWithTasks as $product) {
  8359. // 收集类型文件夹ID
  8360. if ($product->parent_id > 0 && !in_array($product->parent_id, $typeFolderIds)) {
  8361. $parentFolder = DB::table('mp_products')
  8362. ->where('id', $product->parent_id)
  8363. ->where('type', 2)
  8364. ->first();
  8365. if ($parentFolder) {
  8366. $typeFolderIds[$parentFolder->product] = $parentFolder->id;
  8367. }
  8368. }
  8369. // 检查是否有图片生成任务
  8370. if (!empty($product->pic_task_id)) {
  8371. $productTaskMap[$product->id] = $product->pic_task_id;
  8372. } elseif ($product->url && $product->pic_task_status == '生成成功') {
  8373. continue;
  8374. } else {
  8375. // 有资产没有图片
  8376. $hasAllTasks = false;
  8377. }
  8378. }
  8379. // 为没有图片的资产补建图片生成任务
  8380. if (!$hasAllTasks && $auto_generate_images && $productsWithTasks->isNotEmpty()) {
  8381. DB::beginTransaction();
  8382. try {
  8383. foreach ($productsWithTasks as $product) {
  8384. // 跳过已有任务的资产
  8385. if (!empty($product->pic_task_id)) {
  8386. continue;
  8387. }
  8388. // 跳过没有提示词的资产
  8389. if (empty($product->pic_prompt)) {
  8390. dLog('anime')->warning('资产没有提示词,跳过图片生成', [
  8391. 'product_id' => $product->id,
  8392. 'product_name' => $product->product_name,
  8393. ]);
  8394. continue;
  8395. }
  8396. try {
  8397. $task = $this->aiImageGenerationService->createImageGenerationTask([
  8398. 'prompt' => $product->pic_prompt,
  8399. 'model' => $model,
  8400. 'ref_img_urls' => [],
  8401. 'width' => $width,
  8402. 'height' => $height,
  8403. // 计费锚点(剧本),用于积分明细归属统计
  8404. 'script_id' => $script_id,
  8405. ]);
  8406. $task_id = $task->id;
  8407. if ($task_id) {
  8408. $productTaskMap[$product->id] = $task_id;
  8409. $createdCount++;
  8410. DB::table('mp_products')
  8411. ->where('id', $product->id)
  8412. ->update([
  8413. 'pic_task_id' => $task_id,
  8414. 'pic_task_status' => '生成中',
  8415. 'updated_at' => now(),
  8416. ]);
  8417. dLog('anime')->info('为已存在资产创建图片生成任务', [
  8418. 'product_id' => $product->id,
  8419. 'task_id' => $task_id,
  8420. ]);
  8421. }
  8422. } catch (\Exception $e) {
  8423. dLog('anime')->error('创建资产图片生成任务失败', [
  8424. 'product_id' => $product->id,
  8425. 'error' => $e->getMessage(),
  8426. ]);
  8427. DB::table('mp_products')
  8428. ->where('id', $product->id)
  8429. ->update([
  8430. 'pic_task_status' => '生成失败',
  8431. 'updated_at' => now(),
  8432. ]);
  8433. }
  8434. }
  8435. DB::commit();
  8436. } catch (\Exception $e) {
  8437. DB::rollback();
  8438. dLog('anime')->error('为已存在资产创建图片任务失败', [
  8439. 'script_id' => $script_id,
  8440. 'error' => $e->getMessage(),
  8441. ]);
  8442. Utils::throwError('20003:创建图片任务失败:' . $e->getMessage());
  8443. }
  8444. }
  8445. return [
  8446. 'product_task_map' => $productTaskMap,
  8447. 'type_folder_ids' => $typeFolderIds,
  8448. 'has_all_tasks' => $hasAllTasks,
  8449. 'product_count' => count($productIds),
  8450. 'created_count' => $createdCount,
  8451. ];
  8452. }
  8453. /**
  8454. * 保存剧本资产关联关系
  8455. * @param array $data 请求参数
  8456. * @return bool
  8457. */
  8458. public function saveScriptProducts($data) {
  8459. $uid = Site::getUid();
  8460. $cpid = Site::getCpid();
  8461. $script_id = getProp($data, 'script_id');
  8462. $products = getProp($data, 'products', []);
  8463. $auto_generate_images = getProp($data, 'auto_generate_images', true); // 是否自动生成图片,默认true
  8464. if (!$script_id) {
  8465. Utils::throwError('20003:请提供剧本ID');
  8466. }
  8467. // 验证剧本是否存在
  8468. $script = DB::table('mp_scripts')
  8469. ->where('id', $script_id)
  8470. ->where('is_deleted', 0)
  8471. ->first();
  8472. if (!$script) {
  8473. Utils::throwError('20003:剧本不存在');
  8474. }
  8475. // 处理图片模型
  8476. $model = getProp($data, 'model');
  8477. if (!$model) {
  8478. // 使用默认模型
  8479. $model = 'gpt-image-2';
  8480. }
  8481. // 验证模型是否在可用模型表中
  8482. if (!DB::table('mp_image_models')->where('model', $model)->where('is_enabled', 1)->exists()) {
  8483. Utils::throwError('20003:该模型已不可用,请更换!');
  8484. }
  8485. $ratio = getProp($data, 'ratio', '9:16');
  8486. $resolution = getProp($data, 'resolution', '2k');
  8487. // 分辨率档位与尺寸映射统一从 BaseConst 获取
  8488. $sizeMap = BaseConst::IMAGE_RESOLUTION_SIZE_MAP;
  8489. // 参数验证
  8490. $resolution = strtolower($resolution);
  8491. if (!isset($sizeMap[$resolution])) {
  8492. Utils::throwError('20003:分辨率参数错误,仅支持 2k、3k、4k');
  8493. }
  8494. if (!isset($sizeMap[$resolution][$ratio])) {
  8495. Utils::throwError('20003:宽高比参数错误,该分辨率下不支持 ' . $ratio . ' 比例');
  8496. }
  8497. // 根据 ratio 和 resolution 确定宽高
  8498. $width = $sizeMap[$resolution][$ratio]['width'];
  8499. $height = $sizeMap[$resolution][$ratio]['height'];
  8500. $script_name = $script->script_name ?? 'script_' . $script_id;
  8501. // 先校验并提取本次入参中的新增资产行:
  8502. // 新增行的参考提示词为空时直接报错,不写任何数据、不创建任务中心记录
  8503. $newRows = $this->extractNewScriptProductRows($script_id, $products);
  8504. // 根据入参创建/复用任务中心记录(params md5 验重,避免重复任务)
  8505. $taskCenterId = $this->createScriptProductTaskCenter(
  8506. $uid,
  8507. $cpid,
  8508. $script_id,
  8509. $products,
  8510. $model,
  8511. $ratio,
  8512. $resolution,
  8513. $auto_generate_images
  8514. );
  8515. // 检查是否已经有该剧本的资产数据
  8516. $existingMappings = DB::table('mp_script_product_mappings')
  8517. ->where('script_id', $script_id)
  8518. ->get();
  8519. // 已有资产且本次没有新增行时,走原有的"已存在"处理;否则走下方创建逻辑
  8520. if ($existingMappings->isNotEmpty() && empty($newRows)) {
  8521. // 已存在资产映射,检查是否所有资产都有图片生成任务
  8522. $productIds = $existingMappings->pluck('product_id')->unique()->toArray();
  8523. // 查询这些资产的图片生成任务状态
  8524. $productsWithTasks = DB::table('mp_products')
  8525. ->whereIn('id', $productIds)
  8526. ->where('is_deleted', 0)
  8527. ->get();
  8528. $productTaskMap = [];
  8529. $typeFolderIds = [];
  8530. $hasAllTasks = true;
  8531. foreach ($productsWithTasks as $product) {
  8532. // 收集类型文件夹ID
  8533. if ($product->parent_id > 0 && !in_array($product->parent_id, $typeFolderIds)) {
  8534. $parentFolder = DB::table('mp_products')
  8535. ->where('id', $product->parent_id)
  8536. ->where('type', 2)
  8537. ->first();
  8538. if ($parentFolder) {
  8539. $typeFolderIds[$parentFolder->product] = $parentFolder->id;
  8540. }
  8541. }
  8542. // 检查是否有图片生成任务
  8543. if (!empty($product->pic_task_id)) {
  8544. $productTaskMap[$product->id] = $product->pic_task_id;
  8545. } else if($product->url && $product->pic_task_status == '生成成功') {
  8546. continue;
  8547. } else {
  8548. // 有资产没有图片任务
  8549. $hasAllTasks = false;
  8550. }
  8551. }
  8552. // 如果所有资产都有任务ID,直接轮询返回结果
  8553. if ($hasAllTasks && !empty($productTaskMap)) {
  8554. dLog('anime')->info('剧本资产已存在且都有图片任务,直接轮询结果', [
  8555. 'script_id' => $script_id,
  8556. 'script_name' => $script_name,
  8557. 'product_count' => count($productTaskMap)
  8558. ]);
  8559. // 直接返回 SSE 流轮询结果
  8560. return $this->pollProductImageTasks($script_id, $script_name, $productTaskMap, $typeFolderIds, $taskCenterId);
  8561. }
  8562. // 如果部分资产没有任务ID,只为这些资产创建任务
  8563. if (!$hasAllTasks && $auto_generate_images) {
  8564. dLog('anime')->info('剧本资产已存在,但部分资产没有图片任务,为缺失的资产创建任务', [
  8565. 'script_id' => $script_id,
  8566. 'script_name' => $script_name
  8567. ]);
  8568. // 开启事务
  8569. DB::beginTransaction();
  8570. try {
  8571. foreach ($productsWithTasks as $product) {
  8572. // 跳过已有任务的资产
  8573. if (!empty($product->pic_task_id)) {
  8574. continue;
  8575. }
  8576. // 跳过没有提示词的资产
  8577. if (empty($product->pic_prompt)) {
  8578. dLog('anime')->warning('资产没有提示词,跳过图片生成', [
  8579. 'product_id' => $product->id,
  8580. 'product_name' => $product->product_name
  8581. ]);
  8582. continue;
  8583. }
  8584. try {
  8585. // 创建图片生成任务
  8586. $params = [
  8587. 'prompt' => $product->pic_prompt,
  8588. 'model' => $model,
  8589. 'ref_img_urls' => [],
  8590. 'width' => $width,
  8591. 'height' => $height,
  8592. // 计费锚点(剧本),用于积分明细归属统计
  8593. 'script_id' => $script_id,
  8594. ];
  8595. $task = $this->aiImageGenerationService->createImageGenerationTask($params);
  8596. $task_id = $task->id;
  8597. if ($task_id) {
  8598. $productTaskMap[$product->id] = $task_id;
  8599. // 在事务中更新资产表的任务ID和状态
  8600. DB::table('mp_products')
  8601. ->where('id', $product->id)
  8602. ->update([
  8603. 'pic_task_id' => $task_id,
  8604. 'pic_task_status' => '生成中',
  8605. 'updated_at' => now()
  8606. ]);
  8607. dLog('anime')->info('为已存在资产创建图片生成任务', [
  8608. 'product_id' => $product->id,
  8609. 'task_id' => $task_id
  8610. ]);
  8611. }
  8612. } catch (\Exception $e) {
  8613. dLog('anime')->error('创建资产图片生成任务失败', [
  8614. 'product_id' => $product->id,
  8615. 'error' => $e->getMessage()
  8616. ]);
  8617. // 标记为失败(仍在事务中)
  8618. DB::table('mp_products')
  8619. ->where('id', $product->id)
  8620. ->update([
  8621. 'pic_task_status' => '生成失败',
  8622. 'updated_at' => now()
  8623. ]);
  8624. }
  8625. }
  8626. // 提交事务
  8627. DB::commit();
  8628. // 如果有新创建的任务,返回 SSE 流
  8629. if (!empty($productTaskMap)) {
  8630. return $this->pollProductImageTasks($script_id, $script_name, $productTaskMap, $typeFolderIds, $taskCenterId);
  8631. }
  8632. } catch (\Exception $e) {
  8633. // 回滚事务
  8634. DB::rollback();
  8635. dLog('anime')->error('为已存在资产创建图片任务失败', [
  8636. 'script_id' => $script_id,
  8637. 'error' => $e->getMessage()
  8638. ]);
  8639. Utils::throwError('20003:创建图片任务失败:' . $e->getMessage());
  8640. }
  8641. }
  8642. // 如果不需要生成图片,返回已存在的信息
  8643. $resultData = [
  8644. 'success' => true,
  8645. 'message' => '剧本资产已存在',
  8646. 'script_id' => $script_id,
  8647. 'script_name' => $script_name,
  8648. 'type_folder_ids' => $typeFolderIds,
  8649. 'existing_products' => count($productIds),
  8650. 'tasks_count' => count($productTaskMap),
  8651. 'task_center_id' => $taskCenterId
  8652. ];
  8653. // 接口已正常完成,更新任务中心状态和结果
  8654. if ($taskCenterId) {
  8655. $this->taskCenterService->updateTask($taskCenterId, [
  8656. 'status' => MpTaskCenter::STATUS_SUCCESS,
  8657. 'result' => json_encode($resultData, JSON_UNESCAPED_UNICODE),
  8658. 'error_message' => null
  8659. ]);
  8660. }
  8661. return $resultData;
  8662. }
  8663. // 走到这里说明有新行需要创建(或剧本还没有任何资产),保留原有的入参校验报错
  8664. if (empty($newRows)) {
  8665. $decodedProducts = $products;
  8666. if (is_string($decodedProducts)) {
  8667. $decodedProducts = json_decode($decodedProducts, true);
  8668. if (json_last_error() !== JSON_ERROR_NONE) {
  8669. Utils::throwError('20003:产品数据格式错误');
  8670. }
  8671. }
  8672. if (!is_array($decodedProducts) || empty($decodedProducts)) {
  8673. Utils::throwError('20003:产品数据不能为空');
  8674. }
  8675. Utils::throwError('20003:没有有效的产品数据');
  8676. }
  8677. // 仅保留本次新增的资产行,复用下方原有的创建逻辑
  8678. $products = [];
  8679. foreach ($newRows as $newRow) {
  8680. if (!isset($products[$newRow['type']])) {
  8681. $products[$newRow['type']] = [
  8682. 'type' => $newRow['type'],
  8683. 'content' => [['资产名称', '使用范围', '参考提示词']],
  8684. ];
  8685. }
  8686. $products[$newRow['type']]['content'][] = [
  8687. $newRow['product_name'],
  8688. implode(',', $newRow['episode_numbers']),
  8689. $newRow['pic_prompt'],
  8690. ];
  8691. }
  8692. $products = array_values($products);
  8693. // 以下是原有的创建逻辑...
  8694. // 开启事务
  8695. DB::beginTransaction();
  8696. try {
  8697. $now = now();
  8698. $mappingRecords = [];
  8699. $createdProductIds = []; // 记录所有创建的资产ID
  8700. // 获取剧本名称
  8701. $script_name = $script->script_name ?? 'script_' . $script_id;
  8702. // 存储每个类型的根文件夹ID
  8703. $typeFolderIds = [];
  8704. // 遍历每个产品类型(type: 1=角色, 2=场景, 3=道具)
  8705. foreach ($products as $productGroup) {
  8706. $type = getProp($productGroup, 'type');
  8707. $title = getProp($productGroup, 'title', '');
  8708. $content = getProp($productGroup, 'content', []);
  8709. if (!in_array($type, [1, 2, 3]) || empty($content) || count($content) < 2) {
  8710. continue;
  8711. }
  8712. // 为当前类型获取根文件夹:该剧本已存在则复用,避免重复创建根文件夹
  8713. if (!isset($typeFolderIds[$type])) {
  8714. $folder = DB::table('mp_products')
  8715. ->where('cpid', $cpid)
  8716. ->where('type', 2)
  8717. ->where('product', $type)
  8718. ->where('product_name', $script_name)
  8719. ->where('parent_id', 0)
  8720. ->where('is_deleted', 0)
  8721. ->first();
  8722. if ($folder) {
  8723. $typeFolderIds[$type] = $folder->id;
  8724. } else {
  8725. $typeFolderIds[$type] = DB::table('mp_products')->insertGetId([
  8726. 'user_id' => $uid,
  8727. 'cpid' => $cpid,
  8728. 'type' => 2, // 1.资产 2文件夹
  8729. 'product' => $type, // 1.主体 2.场景 3.道具
  8730. 'parent_id' => 0, // 根文件夹,parent_id=0
  8731. 'level' => 1, // 第一层级
  8732. 'product_name' => $script_name,
  8733. 'sort_order' => time() + $type,
  8734. 'is_deleted' => 0,
  8735. 'created_at' => $now,
  8736. 'updated_at' => $now
  8737. ]);
  8738. }
  8739. }
  8740. $folder_id = $typeFolderIds[$type];
  8741. // 获取表头(第一行)并查找关键列的位置
  8742. $headers = $content[0];
  8743. $nameColumnIndex = -1; // 资产名称列索引
  8744. $sequenceColumnIndex = -1; // 使用范围列索引
  8745. $promptColumnIndex = -1; // 参考提示词列索引
  8746. foreach ($headers as $index => $header) {
  8747. // 查找"资产名称"列
  8748. if (strpos($header, '资产名称') !== false || strpos($header, '名称') !== false) {
  8749. $nameColumnIndex = $index;
  8750. }
  8751. // 查找"使用范围"列
  8752. if (strpos($header, '使用范围') !== false || strpos($header, '范围') !== false) {
  8753. $sequenceColumnIndex = $index;
  8754. }
  8755. // 查找"参考提示词"列(可能是"干净参考图提示词"、"参考提示词"等)
  8756. if (strpos($header, '参考') !== false && strpos($header, '提示词') !== false) {
  8757. $promptColumnIndex = $index;
  8758. }
  8759. }
  8760. // 验证必要的列是否都找到了
  8761. if ($nameColumnIndex === -1) {
  8762. dLog('anime')->warning('未找到资产名称列', ['type' => $type, 'headers' => $headers]);
  8763. continue;
  8764. }
  8765. if ($sequenceColumnIndex === -1) {
  8766. dLog('anime')->warning('未找到使用范围列', ['type' => $type, 'headers' => $headers]);
  8767. continue;
  8768. }
  8769. // 跳过表头,解析每一行数据
  8770. for ($i = 1; $i < count($content); $i++) {
  8771. $row = $content[$i];
  8772. // 确保行数据有效
  8773. if (empty($row) || count($row) <= max($nameColumnIndex, $sequenceColumnIndex)) {
  8774. continue;
  8775. }
  8776. // 根据动态查找的列索引提取数据
  8777. $product_name = isset($row[$nameColumnIndex]) ? trim((string)$row[$nameColumnIndex]) : '';
  8778. $sequence_str = isset($row[$sequenceColumnIndex]) ? trim($row[$sequenceColumnIndex]) : '';
  8779. $pic_prompt = '';
  8780. // 提取参考提示词(如果找到了该列)
  8781. if ($promptColumnIndex >= 0 && isset($row[$promptColumnIndex])) {
  8782. $pic_prompt = trim($row[$promptColumnIndex]);
  8783. }
  8784. // 解析使用范围(逗号分隔的序号)
  8785. $sequences = [];
  8786. if (!empty($sequence_str)) {
  8787. $sequenceParts = array_map('trim', explode(',', $sequence_str));
  8788. foreach ($sequenceParts as $part) {
  8789. if (is_numeric($part)) {
  8790. $sequences[] = (int)$part;
  8791. }
  8792. }
  8793. }
  8794. if (empty($product_name)) {
  8795. continue;
  8796. }
  8797. // 处理product_name两边的符号
  8798. $product_name = preg_replace('/^[\s*\[\]【】[]{}{}\x{3000}]+|[\s*\[\]【】[]{}{}\x{3000}]+$/u', '', $product_name);
  8799. // 如果名称不存在或仅剩占位符号,则跳过
  8800. if (!$product_name || preg_match('/^[-—_]+$/u', $product_name)) {
  8801. dLog('anime')->warning('资产名称无效,跳过保存', [
  8802. 'script_id' => $script_id,
  8803. 'type' => $type,
  8804. 'product_name' => $product_name
  8805. ]);
  8806. continue;
  8807. }
  8808. // 直接插入新资产到 mp_products 表(parent_id 指向对应类型的根文件夹)
  8809. $product_id = DB::table('mp_products')->insertGetId([
  8810. 'product_name' => $product_name,
  8811. 'type' => 1, // 1=资产 2.文件夹
  8812. 'product' => $type, // 1=角色, 2=场景, 3=道具
  8813. 'parent_id' => $folder_id, // 父文件夹是该类型的根文件夹
  8814. 'level' => 2, // 第二层级
  8815. 'pic_prompt' => $pic_prompt,
  8816. 'user_id' => $uid,
  8817. 'cpid' => $cpid,
  8818. 'sort_order' => time(),
  8819. 'is_deleted' => 0,
  8820. 'created_at' => $now,
  8821. 'updated_at' => $now,
  8822. ]);
  8823. // 记录创建的资产ID
  8824. $createdProductIds[] = $product_id;
  8825. // 为每个序号创建映射记录
  8826. if (!empty($sequences)) {
  8827. foreach ($sequences as $sequence) {
  8828. $mappingRecords[] = [
  8829. 'script_id' => $script_id,
  8830. 'product_id' => $product_id,
  8831. 'episode_number' => $sequence,
  8832. 'created_at' => $now,
  8833. 'updated_at' => $now,
  8834. ];
  8835. }
  8836. } else {
  8837. // 如果没有指定序号,创建一个默认映射(序号为0)
  8838. $mappingRecords[] = [
  8839. 'script_id' => $script_id,
  8840. 'product_id' => $product_id,
  8841. 'episode_number' => 0,
  8842. 'created_at' => $now,
  8843. 'updated_at' => $now,
  8844. ];
  8845. }
  8846. }
  8847. }
  8848. if (empty($mappingRecords)) {
  8849. Utils::throwError('20003:没有有效的产品数据');
  8850. }
  8851. // 批量插入映射数据(使用 insertOrIgnore 避免重复插入)
  8852. $insertedCount = DB::table('mp_script_product_mappings')->insertOrIgnore($mappingRecords);
  8853. // 剧本已有资产,同步更新is_products标记
  8854. DB::table('mp_scripts')->where('id', $script_id)->update([
  8855. 'is_products' => 1,
  8856. 'updated_at' => $now
  8857. ]);
  8858. // 如果需要自动生成图片,在事务中创建图片生成任务
  8859. $productTaskMap = [];
  8860. if ($auto_generate_images && !empty($createdProductIds)) {
  8861. // 查询所有创建的资产
  8862. $productsToGenerate = DB::table('mp_products')
  8863. ->whereIn('id', $createdProductIds)
  8864. ->where('is_deleted', 0)
  8865. ->get();
  8866. foreach ($productsToGenerate as $product) {
  8867. if (empty($product->pic_prompt)) {
  8868. dLog('anime')->warning('资产没有提示词,跳过图片生成', [
  8869. 'product_id' => $product->id,
  8870. 'product_name' => $product->product_name
  8871. ]);
  8872. continue;
  8873. }
  8874. try {
  8875. // 创建图片生成任务
  8876. $params = [
  8877. 'prompt' => $product->pic_prompt,
  8878. 'model' => $model,
  8879. 'ref_img_urls' => [],
  8880. 'width' => $width,
  8881. 'height' => $height,
  8882. // 计费锚点(剧本),用于积分明细归属统计
  8883. 'script_id' => $script_id,
  8884. ];
  8885. $task = $this->aiImageGenerationService->createImageGenerationTask($params);
  8886. $task_id = $task->id;
  8887. if ($task_id) {
  8888. $productTaskMap[$product->id] = $task_id;
  8889. // 在事务中更新资产表的任务ID和状态
  8890. DB::table('mp_products')
  8891. ->where('id', $product->id)
  8892. ->update([
  8893. 'pic_task_id' => $task_id,
  8894. 'pic_task_status' => '生成中',
  8895. 'updated_at' => now()
  8896. ]);
  8897. dLog('anime')->info('创建资产图片生成任务', [
  8898. 'product_id' => $product->id,
  8899. 'task_id' => $task_id
  8900. ]);
  8901. }
  8902. } catch (\Exception $e) {
  8903. dLog('anime')->error('创建资产图片生成任务失败', [
  8904. 'product_id' => $product->id,
  8905. 'error' => $e->getMessage()
  8906. ]);
  8907. // 标记为失败(仍在事务中)
  8908. DB::table('mp_products')
  8909. ->where('id', $product->id)
  8910. ->update([
  8911. 'pic_task_status' => '生成失败',
  8912. 'updated_at' => now()
  8913. ]);
  8914. }
  8915. }
  8916. }
  8917. // 提交事务
  8918. DB::commit();
  8919. // 本次新增资产创建的图片任务
  8920. $createdTaskMap = $productTaskMap;
  8921. } catch (\Exception $e) {
  8922. // 回滚事务
  8923. DB::rollback();
  8924. // 更新任务中心状态为失败
  8925. if (!empty($taskCenterId)) {
  8926. $this->taskCenterService->updateTask($taskCenterId, [
  8927. 'status' => MpTaskCenter::STATUS_FAILED,
  8928. 'error_message' => $e->getMessage()
  8929. ]);
  8930. }
  8931. // 记录错误日志
  8932. dLog('anime')->error('保存剧本资产失败: ' . $e->getMessage(), [
  8933. 'script_id' => $script_id,
  8934. 'error' => $e->getMessage(),
  8935. 'trace' => $e->getTraceAsString()
  8936. ]);
  8937. // 统一使用 Utils::throwError 抛出错误
  8938. Utils::throwError('20003:保存剧本资产失败:' . $e->getMessage());
  8939. }
  8940. // 落库成功后统一处理图片任务:
  8941. // 1) 本次新增资产的图片任务已在上方事务中创建
  8942. // 2) 剧本内已存在但缺图的资产在此补建,并与新增资产的任务一并收集为待轮询任务
  8943. $existingTaskInfo = $this->prepareExistingScriptProductTasks(
  8944. $script_id,
  8945. $model,
  8946. $width,
  8947. $height,
  8948. $auto_generate_images
  8949. );
  8950. $productTaskMap = $existingTaskInfo['product_task_map'];
  8951. // 创建阶段解析到的类型根文件夹优先
  8952. $typeFolderIds = $typeFolderIds + $existingTaskInfo['type_folder_ids'];
  8953. // 保存结果(SSE 的 init / complete 事件会携带该结构)
  8954. $resultData = [
  8955. 'success' => true,
  8956. 'message' => '保存完成',
  8957. 'script_id' => $script_id,
  8958. 'script_name' => $script_name,
  8959. 'type_folder_ids' => $typeFolderIds,
  8960. 'inserted_count' => $insertedCount,
  8961. 'total_records' => count($mappingRecords),
  8962. 'created_products' => count($createdProductIds),
  8963. 'pending_tasks_count' => count($productTaskMap),
  8964. 'image_tasks_created' => count($createdTaskMap) + $existingTaskInfo['created_count'],
  8965. 'task_center_id' => $taskCenterId,
  8966. ];
  8967. // 有待完成的图片任务:返回 SSE 轮询流(事务外轮询)
  8968. if ($auto_generate_images && !empty($productTaskMap)) {
  8969. return $this->pollProductImageTasks(
  8970. $script_id,
  8971. $script_name,
  8972. $productTaskMap,
  8973. $typeFolderIds,
  8974. $taskCenterId,
  8975. ['import_result' => $resultData],
  8976. ['import_result' => $resultData]
  8977. );
  8978. }
  8979. // 没有需要轮询的任务:通过 SSE complete 事件返回保存结果
  8980. return $this->streamImportComplete($script_id, $script_name, $resultData, $typeFolderIds, $taskCenterId);
  8981. }
  8982. /**
  8983. * 根据入参创建或复用任务中心记录
  8984. *
  8985. * 以规范化入参计算 md5 并保存到任务中心 params 字段中用于验重:
  8986. * 同一用户/企业下,相同入参且任务未结束(pending/processing)时复用已有任务,
  8987. * 避免生成重复任务。
  8988. *
  8989. * @param int|string $uid
  8990. * @param int|string $cpid
  8991. * @param int|string $script_id
  8992. * @param mixed $products
  8993. * @param string $model
  8994. * @param string $ratio
  8995. * @param string $resolution
  8996. * @param mixed $auto_generate_images
  8997. * @return int 任务中心ID
  8998. */
  8999. private function createScriptProductTaskCenter($uid, $cpid, $script_id, $products, $model, $ratio, $resolution, $auto_generate_images) {
  9000. // 规范化 products(兼容 JSON 字符串和数组),保证 md5 稳定
  9001. if (is_string($products)) {
  9002. $decoded = json_decode($products, true);
  9003. if (json_last_error() === JSON_ERROR_NONE) {
  9004. $products = $decoded;
  9005. }
  9006. }
  9007. $params = [
  9008. 'script_id' => (int)$script_id,
  9009. 'products' => $products,
  9010. 'model' => $model,
  9011. 'ratio' => $ratio,
  9012. 'resolution' => $resolution,
  9013. 'auto_generate_images' => (bool)$auto_generate_images,
  9014. ];
  9015. $paramsMd5 = md5(json_encode($params, JSON_UNESCAPED_UNICODE | JSON_UNESCAPED_SLASHES));
  9016. // 验重:相同 md5 且任务未结束(pending/processing)时复用已有任务中心记录
  9017. $existing = DB::table('mp_task_center')
  9018. ->where('uid', (int)$uid)
  9019. ->where('cpid', (int)$cpid)
  9020. ->where('task_type', MpTaskCenter::TYPE_SAVE_SCRIPT_PRODUCTS)
  9021. ->whereIn('status', [MpTaskCenter::STATUS_PENDING, MpTaskCenter::STATUS_PROCESSING])
  9022. ->where('params_md5', $paramsMd5)
  9023. ->orderBy('id', 'desc')
  9024. ->first();
  9025. if ($existing) {
  9026. dLog('anime')->info('复用已有任务中心记录,避免重复任务', [
  9027. 'script_id' => $script_id,
  9028. 'task_center_id' => $existing->id,
  9029. 'params_md5' => $paramsMd5,
  9030. ]);
  9031. return (int)$existing->id;
  9032. }
  9033. // 唯一索引 (uid, cpid, task_type, params_md5) 兜底并发重复,冲突时静默忽略
  9034. $now = date('Y-m-d H:i:s');
  9035. DB::table('mp_task_center')->insertOrIgnore([
  9036. 'uid' => (int)$uid,
  9037. 'cpid' => (int)$cpid,
  9038. 'task_type' => MpTaskCenter::TYPE_SAVE_SCRIPT_PRODUCTS,
  9039. 'title' => '剧本资产图片生成',
  9040. 'ref_task_id' => 0,
  9041. 'status' => MpTaskCenter::STATUS_PROCESSING,
  9042. 'result' => null,
  9043. 'error_message' => null,
  9044. 'prompt' => null,
  9045. 'params' => json_encode($params + ['params_md5' => $paramsMd5], JSON_UNESCAPED_UNICODE | JSON_UNESCAPED_SLASHES),
  9046. 'params_md5' => $paramsMd5,
  9047. 'created_at' => $now,
  9048. 'updated_at' => $now,
  9049. ]);
  9050. // 获取任务中心ID(insertOrIgnore 冲突时复用并发插入的已有记录)
  9051. $taskId = (int)DB::table('mp_task_center')
  9052. ->where('uid', (int)$uid)
  9053. ->where('cpid', (int)$cpid)
  9054. ->where('task_type', MpTaskCenter::TYPE_SAVE_SCRIPT_PRODUCTS)
  9055. ->where('params_md5', $paramsMd5)
  9056. ->orderBy('id', 'desc')
  9057. ->value('id');
  9058. dLog('anime')->info('创建任务中心记录', [
  9059. 'script_id' => $script_id,
  9060. 'task_center_id' => $taskId,
  9061. 'params_md5' => $paramsMd5,
  9062. ]);
  9063. return $taskId;
  9064. }
  9065. /**
  9066. * 任务结束时更新任务中心记录的状态和结果
  9067. *
  9068. * result 字段保存与 saveScriptProducts 接口返回给客户端一致的结果数据
  9069. * (普通数组返回为完整返回数组,SSE 轮询为 complete/timeout 事件载荷)。
  9070. *
  9071. * @param int|null $taskCenterId
  9072. * @param array $resultData 接口返回结果数组
  9073. * @param bool $timeout 是否超时未完成
  9074. */
  9075. private function finishScriptProductTask($taskCenterId, array $resultData, $timeout = false) {
  9076. if (!$taskCenterId) {
  9077. return;
  9078. }
  9079. $stats = $resultData['stats'] ?? [];
  9080. $successCount = (int)array_sum(array_column((array)$stats, 'success'));
  9081. $completedCount = (int)array_sum(array_column((array)$stats, 'completed'));
  9082. $failedCount = $completedCount - $successCount;
  9083. // 与接口返回给客户端的结果保持一致
  9084. $result = json_encode($resultData, JSON_UNESCAPED_UNICODE);
  9085. if ($timeout) {
  9086. $this->taskCenterService->updateTask((int)$taskCenterId, [
  9087. 'status' => MpTaskCenter::STATUS_FAILED,
  9088. 'result' => $result,
  9089. 'error_message' => '部分任务超时,请稍后查看结果',
  9090. ]);
  9091. return;
  9092. }
  9093. $this->taskCenterService->updateTask((int)$taskCenterId, [
  9094. 'status' => $failedCount > 0 ? MpTaskCenter::STATUS_FAILED : MpTaskCenter::STATUS_SUCCESS,
  9095. 'result' => $result,
  9096. 'error_message' => $failedCount > 0 ? ('有 ' . $failedCount . ' 个资产生成失败') : null,
  9097. ]);
  9098. }
  9099. /**
  9100. * 批量为剧本资产生成图片
  9101. *
  9102. * @param array $data 请求参数
  9103. * @return \Generator 返回 SSE 流
  9104. */
  9105. public function batchGenerateProductImages($data) {
  9106. $script_id = getProp($data, 'script_id');
  9107. $type_folder_ids = getProp($data, 'type_folder_ids', []); // {1: 角色文件夹ID, 2: 场景文件夹ID, 3: 道具文件夹ID}
  9108. if (!$script_id) {
  9109. Utils::throwError('20003:请提供剧本ID');
  9110. }
  9111. // 验证剧本是否存在
  9112. $script = DB::table('mp_scripts')
  9113. ->where('id', $script_id)
  9114. ->where('is_deleted', 0)
  9115. ->first();
  9116. if (!$script) {
  9117. Utils::throwError('20003:剧本不存在');
  9118. }
  9119. $script_name = $script->script_name ?? 'script_' . $script_id;
  9120. // 获取需要生成图片的所有资产
  9121. $products = DB::table('mp_products')
  9122. ->whereIn('parent_id', array_values($type_folder_ids))
  9123. ->where('is_deleted', 0)
  9124. ->whereIn('type', [1, 2, 3]) // 只处理资产,不处理文件夹
  9125. ->get();
  9126. if ($products->isEmpty()) {
  9127. Utils::throwError('20003:没有找到需要生成图片的资产');
  9128. }
  9129. // 默认参数
  9130. $model = 'gpt-image-2';
  9131. $width = 1600;
  9132. $height = 2848;
  9133. // 开始为每个资产创建图片生成任务
  9134. $taskIds = [];
  9135. $productTaskMap = []; // 资产ID到任务ID的映射
  9136. foreach ($products as $product) {
  9137. if (empty($product->pic_prompt)) {
  9138. dLog('anime')->warning('资产没有提示词,跳过', ['product_id' => $product->id, 'product_name' => $product->product_name]);
  9139. continue;
  9140. }
  9141. try {
  9142. // 创建图片生成任务
  9143. $params = [
  9144. 'prompt' => $product->pic_prompt,
  9145. 'model' => $model,
  9146. 'ref_img_urls' => [],
  9147. 'width' => $width,
  9148. 'height' => $height,
  9149. // 计费锚点(剧本),用于积分明细归属统计
  9150. 'script_id' => $script_id,
  9151. ];
  9152. $task = $this->aiImageGenerationService->createImageGenerationTask($params);
  9153. $task_id = $task->id;
  9154. if ($task_id) {
  9155. $taskIds[] = $task_id;
  9156. $productTaskMap[$product->id] = $task_id;
  9157. // 更新资产表的任务ID和状态
  9158. DB::table('mp_products')
  9159. ->where('id', $product->id)
  9160. ->update([
  9161. 'pic_task_id' => $task_id,
  9162. 'pic_task_status' => '生成中',
  9163. 'updated_at' => now()
  9164. ]);
  9165. dLog('anime')->info('创建资产图片生成任务', ['product_id' => $product->id, 'task_id' => $task_id]);
  9166. }
  9167. } catch (\Exception $e) {
  9168. dLog('anime')->error('创建资产图片生成任务失败', [
  9169. 'product_id' => $product->id,
  9170. 'error' => $e->getMessage()
  9171. ]);
  9172. // 标记为失败
  9173. DB::table('mp_products')
  9174. ->where('id', $product->id)
  9175. ->update([
  9176. 'pic_task_status' => '生成失败',
  9177. 'updated_at' => now()
  9178. ]);
  9179. }
  9180. }
  9181. if (empty($taskIds)) {
  9182. Utils::throwError('20003:没有成功创建任何图片生成任务');
  9183. }
  9184. // 返回 SSE 流
  9185. return $this->pollProductImageTasks($script_id, $script_name, $productTaskMap, $type_folder_ids);
  9186. }
  9187. /**
  9188. * 无需轮询时的 SSE 返回:直接通过 complete 事件返回导入结果
  9189. *
  9190. * @param int $script_id
  9191. * @param string $script_name
  9192. * @param array $resultData 导入结果(原普通 JSON 的 data 内容)
  9193. * @param array $type_folder_ids
  9194. * @param int|null $taskCenterId
  9195. * @return \Generator
  9196. */
  9197. private function streamImportComplete($script_id, $script_name, array $resultData, $type_folder_ids, $taskCenterId = null) {
  9198. if ($taskCenterId) {
  9199. $initResponse = [
  9200. 'type' => 'init',
  9201. 'script_id' => $script_id,
  9202. 'script_name' => $script_name,
  9203. 'timestamp' => date('Y-m-d H:i:s'),
  9204. 'task_center_id' => (int)$taskCenterId,
  9205. 'import_result' => $resultData,
  9206. ];
  9207. yield "data: " . json_encode($initResponse, JSON_UNESCAPED_UNICODE) . "\n\n";
  9208. }
  9209. $stats = $this->collectScriptProductStats($script_id);
  9210. $response = [
  9211. 'type' => 'complete',
  9212. 'script_id' => $script_id,
  9213. 'script_name' => $script_name,
  9214. 'stats' => $stats,
  9215. 'timestamp' => date('Y-m-d H:i:s'),
  9216. 'import_result' => $resultData,
  9217. ];
  9218. if ($taskCenterId) {
  9219. $response['task_center_id'] = (int)$taskCenterId;
  9220. }
  9221. yield "data: " . json_encode($response, JSON_UNESCAPED_UNICODE) . "\n\n";
  9222. // 更新任务中心状态和结果
  9223. $this->finishScriptProductTask($taskCenterId, $response);
  9224. }
  9225. /**
  9226. * 统计剧本资产的图片生成状态(仅按 mp_products 当前状态统计,不驱动任务)
  9227. *
  9228. * @param int $script_id
  9229. * @return array
  9230. */
  9231. private function collectScriptProductStats($script_id) {
  9232. $stats = [
  9233. 'character' => ['total' => 0, 'success' => 0, 'completed' => 0],
  9234. 'scene' => ['total' => 0, 'success' => 0, 'completed' => 0],
  9235. 'prop' => ['total' => 0, 'success' => 0, 'completed' => 0],
  9236. ];
  9237. $typeNames = [1 => 'roles', 2 => 'scenes', 3 => 'props'];
  9238. $productIds = DB::table('mp_script_product_mappings')
  9239. ->where('script_id', $script_id)
  9240. ->pluck('product_id')
  9241. ->unique()
  9242. ->toArray();
  9243. if (empty($productIds)) {
  9244. return [];
  9245. }
  9246. $products = DB::table('mp_products')
  9247. ->whereIn('id', $productIds)
  9248. ->where('is_deleted', 0)
  9249. ->get();
  9250. foreach ($products as $product) {
  9251. $typeName = $typeNames[$product->product] ?? 'unknown';
  9252. if (!isset($stats[$typeName])) {
  9253. $stats[$typeName] = ['total' => 0, 'success' => 0, 'completed' => 0];
  9254. }
  9255. $stats[$typeName]['total']++;
  9256. if ($product->pic_task_status === '生成成功') {
  9257. $stats[$typeName]['success']++;
  9258. $stats[$typeName]['completed']++;
  9259. } elseif ($product->pic_task_status === '生成失败') {
  9260. $stats[$typeName]['completed']++;
  9261. }
  9262. }
  9263. foreach ($stats as $typeName => $stat) {
  9264. if ($stat['total'] === 0) {
  9265. unset($stats[$typeName]);
  9266. }
  9267. }
  9268. return $stats;
  9269. }
  9270. /**
  9271. * 轮询资产图片生成任务状态(SSE流式返回)
  9272. * 只通过查询数据库获取任务状态,不主动调用API
  9273. *
  9274. * @param int $script_id 剧本ID
  9275. * @param string $script_name 剧本名称
  9276. * @param array $productTaskMap 资产ID到任务ID的映射
  9277. * @param array $type_folder_ids 类型文件夹ID映射
  9278. * @param int|null $taskCenterId 任务中心ID
  9279. * @param array $initExtra 追加到 init 事件中的额外数据
  9280. * @param array $completeExtra 追加到 complete、timeout 事件中的额外数据
  9281. * @return \Generator
  9282. */
  9283. private function pollProductImageTasks($script_id, $script_name, $productTaskMap, $type_folder_ids, $taskCenterId = null, array $initExtra = [], array $completeExtra = []) {
  9284. $startTime = time();
  9285. $timeout = 1800; // 30分钟超时
  9286. $pollInterval = 10; // 10秒轮询一次
  9287. $lastStatus = []; // 记录上次的状态,用于判断是否有变化
  9288. // 流一开始即返回 init 事件(saveScriptProducts 场景下携带任务中心ID)
  9289. if ($taskCenterId) {
  9290. $initResponse = array_merge([
  9291. 'type' => 'init',
  9292. 'script_id' => $script_id,
  9293. 'script_name' => $script_name,
  9294. 'timestamp' => date('Y-m-d H:i:s'),
  9295. 'task_center_id' => (int)$taskCenterId,
  9296. ], $initExtra);
  9297. yield "data: " . json_encode($initResponse, JSON_UNESCAPED_UNICODE) . "\n\n";
  9298. }
  9299. // 定义类型名称映射
  9300. $typeNames = [
  9301. 1 => 'roles', // 角色
  9302. 2 => 'scenes', // 场景
  9303. 3 => 'props' // 道具
  9304. ];
  9305. while (time() - $startTime < $timeout) {
  9306. sleep($pollInterval);
  9307. // 从 mp_script_product_mappings 表获取该剧本的所有资产ID
  9308. $mappings = DB::table('mp_script_product_mappings')
  9309. ->where('script_id', $script_id)
  9310. ->pluck('product_id')
  9311. ->unique()
  9312. ->toArray();
  9313. if (empty($mappings)) {
  9314. dLog('anime')->warning('该剧本没有关联的资产', [
  9315. 'script_id' => $script_id,
  9316. 'script_name' => $script_name
  9317. ]);
  9318. break;
  9319. }
  9320. // 查询所有资产的当前状态
  9321. $products = DB::table('mp_products')
  9322. ->whereIn('id', $mappings)
  9323. ->where('is_deleted', 0)
  9324. ->get();
  9325. // 统计各类型的状态(使用类型名称作为键名)
  9326. $stats = [
  9327. 'character' => ['total' => 0, 'success' => 0, 'completed' => 0], // 角色
  9328. 'scene' => ['total' => 0, 'success' => 0, 'completed' => 0], // 场景
  9329. 'prop' => ['total' => 0, 'success' => 0, 'completed' => 0], // 道具
  9330. ];
  9331. $allCompleted = true;
  9332. $hasStatusChange = false;
  9333. foreach ($products as $product) {
  9334. $type = $product->product;
  9335. $typeName = $typeNames[$type] ?? 'unknown'; // 使用 unknown 作为未知类型
  9336. // 如果类型名称不在 stats 中,初始化
  9337. if (!isset($stats[$typeName])) {
  9338. $stats[$typeName] = ['total' => 0, 'success' => 0, 'completed' => 0];
  9339. }
  9340. $stats[$typeName]['total']++;
  9341. $task_id = $product->pic_task_id;
  9342. $currentStatus = $product->pic_task_status;
  9343. // 检查状态是否有变化
  9344. if (!isset($lastStatus[$product->id]) || $lastStatus[$product->id] !== $currentStatus) {
  9345. $hasStatusChange = true;
  9346. $lastStatus[$product->id] = $currentStatus;
  9347. }
  9348. // 如果是生成中,查询任务表状态
  9349. if ($currentStatus === '生成中' && $task_id) {
  9350. // 只查询数据库,不调用API
  9351. $task = DB::table('mp_generate_pic_tasks')
  9352. ->where('id', $task_id)
  9353. ->first();
  9354. if ($task) {
  9355. // 检查任务状态
  9356. if ($task->status === 'success' && $task->result_url) {
  9357. // 解析图片URL
  9358. $result_urls = $task->result_url;
  9359. if (is_string($result_urls)) {
  9360. $result_urls = json_decode($result_urls, true);
  9361. }
  9362. $img_url = is_array($result_urls) ? $result_urls[0] : $task->result_url;
  9363. // 更新资产表状态
  9364. DB::table('mp_products')
  9365. ->where('id', $product->id)
  9366. ->update([
  9367. 'pic_task_status' => '生成成功',
  9368. 'url' => $img_url,
  9369. 'updated_at' => now()
  9370. ]);
  9371. $stats[$typeName]['success']++;
  9372. $stats[$typeName]['completed']++;
  9373. $hasStatusChange = true;
  9374. dLog('anime')->info('资产图片生成成功', [
  9375. 'product_id' => $product->id,
  9376. 'task_id' => $task_id,
  9377. 'img_url' => $img_url
  9378. ]);
  9379. } elseif ($task->status === 'failed') {
  9380. // 更新资产表状态
  9381. DB::table('mp_products')
  9382. ->where('id', $product->id)
  9383. ->update([
  9384. 'pic_task_status' => '生成失败',
  9385. 'updated_at' => now()
  9386. ]);
  9387. $stats[$typeName]['completed']++;
  9388. $hasStatusChange = true;
  9389. dLog('anime')->warning('资产图片生成失败', [
  9390. 'product_id' => $product->id,
  9391. 'task_id' => $task_id,
  9392. 'error' => $task->error_message ?? '未知错误'
  9393. ]);
  9394. } else {
  9395. // 任务还在处理中
  9396. $allCompleted = false;
  9397. }
  9398. } else {
  9399. // 任务不存在,标记为失败
  9400. DB::table('mp_products')
  9401. ->where('id', $product->id)
  9402. ->update([
  9403. 'pic_task_status' => '生成失败',
  9404. 'updated_at' => now()
  9405. ]);
  9406. $stats[$typeName]['completed']++;
  9407. $hasStatusChange = true;
  9408. dLog('anime')->error('图片生成任务不存在', [
  9409. 'product_id' => $product->id,
  9410. 'task_id' => $task_id
  9411. ]);
  9412. }
  9413. } elseif ($currentStatus === '生成成功') {
  9414. $stats[$typeName]['success']++;
  9415. $stats[$typeName]['completed']++;
  9416. } elseif ($currentStatus === '生成失败') {
  9417. $stats[$typeName]['completed']++;
  9418. } else {
  9419. // 其他状态也认为未完成
  9420. $allCompleted = false;
  9421. }
  9422. }
  9423. // 移除没有数据的类型(total=0)
  9424. foreach ($stats as $typeName => $stat) {
  9425. if ($stat['total'] === 0) {
  9426. unset($stats[$typeName]);
  9427. }
  9428. }
  9429. // 如果有状态变化,发送 SSE 更新
  9430. if ($hasStatusChange) {
  9431. $eventType = $allCompleted ? 'complete' : 'update';
  9432. $response = [
  9433. 'type' => $eventType,
  9434. 'script_id' => $script_id,
  9435. 'script_name' => $script_name,
  9436. 'stats' => $stats,
  9437. 'timestamp' => date('Y-m-d H:i:s')
  9438. ];
  9439. if ($taskCenterId) {
  9440. $response['task_center_id'] = $taskCenterId;
  9441. }
  9442. if ($eventType === 'complete') {
  9443. $response = array_merge($response, $completeExtra);
  9444. }
  9445. yield "data: " . json_encode($response, JSON_UNESCAPED_UNICODE) . "\n\n";
  9446. dLog('anime')->info('SSE更新', [
  9447. 'event_type' => $eventType,
  9448. 'script_id' => $script_id,
  9449. 'script_name' => $script_name,
  9450. 'stats' => $stats
  9451. ]);
  9452. if ($allCompleted) {
  9453. dLog('anime')->info('所有资产图片生成任务已完成', [
  9454. 'script_id' => $script_id,
  9455. 'script_name' => $script_name,
  9456. 'stats' => $stats
  9457. ]);
  9458. // 全部任务完成,更新任务中心状态和结果
  9459. $this->finishScriptProductTask($taskCenterId, $response);
  9460. break;
  9461. }
  9462. }
  9463. }
  9464. // 超时处理
  9465. if (time() - $startTime >= $timeout && !$allCompleted) {
  9466. $response = [
  9467. 'type' => 'timeout',
  9468. 'message' => '部分任务超时,请稍后查看结果',
  9469. 'script_id' => $script_id,
  9470. 'script_name' => $script_name,
  9471. 'timestamp' => date('Y-m-d H:i:s')
  9472. ];
  9473. if ($taskCenterId) {
  9474. $response['task_center_id'] = $taskCenterId;
  9475. }
  9476. $response = array_merge($response, $completeExtra);
  9477. yield "data: " . json_encode($response, JSON_UNESCAPED_UNICODE) . "\n\n";
  9478. dLog('anime')->warning('资产图片生成任务超时', [
  9479. 'script_id' => $script_id,
  9480. 'script_name' => $script_name,
  9481. 'timeout' => $timeout
  9482. ]);
  9483. // 超时未完成,更新任务中心状态和结果
  9484. $this->finishScriptProductTask($taskCenterId, $response, true);
  9485. }
  9486. }
  9487. /**
  9488. * 定时任务:检查产品图片生成任务状态并更新产品记录
  9489. * 扫描 mp_products 中 pic_task_id 非空且 pic_task_status 为生成中的记录,
  9490. * 通过 pic_task_id 查询 mp_generate_pic_tasks 获取生成结果,按结果更新状态
  9491. *
  9492. * @return array ['total' => 总数, 'success' => 成功数, 'failed' => 失败数, 'pending' => 待处理数]
  9493. */
  9494. public function checkProductPicTasks() {
  9495. // 查询所有生成中的产品图片任务
  9496. $products = DB::table('mp_products')
  9497. ->whereNotNull('pic_task_id')
  9498. ->where('pic_task_status', '生成中')
  9499. ->where('is_deleted', 0)
  9500. ->get();
  9501. $stats = [
  9502. 'total' => $products->count(),
  9503. 'success' => 0,
  9504. 'failed' => 0,
  9505. 'pending' => 0,
  9506. ];
  9507. foreach ($products as $product) {
  9508. try {
  9509. $task_id = $product->pic_task_id;
  9510. // 通过 pic_task_id 查询图片生成任务结果
  9511. $task = DB::table('mp_generate_pic_tasks')
  9512. ->where('id', $task_id)
  9513. ->first();
  9514. if ($task) {
  9515. if ($task->status === 'success' && $task->result_url) {
  9516. // 解析图片URL
  9517. $result_urls = $task->result_url;
  9518. if (is_string($result_urls)) {
  9519. $result_urls = json_decode($result_urls, true);
  9520. }
  9521. $img_url = is_array($result_urls) ? ($result_urls[0] ?? $task->result_url) : $task->result_url;
  9522. // 更新资产表状态
  9523. DB::table('mp_products')
  9524. ->where('id', $product->id)
  9525. ->update([
  9526. 'pic_task_status' => '生成成功',
  9527. 'url' => $img_url,
  9528. 'updated_at' => now()
  9529. ]);
  9530. $stats['success']++;
  9531. dLog('anime')->info('资产图片生成成功', [
  9532. 'product_id' => $product->id,
  9533. 'task_id' => $task_id,
  9534. 'img_url' => $img_url
  9535. ]);
  9536. } elseif ($task->status === 'failed') {
  9537. // 更新资产表状态
  9538. DB::table('mp_products')
  9539. ->where('id', $product->id)
  9540. ->update([
  9541. 'pic_task_status' => '生成失败',
  9542. 'updated_at' => now()
  9543. ]);
  9544. $stats['failed']++;
  9545. dLog('anime')->warning('资产图片生成失败', [
  9546. 'product_id' => $product->id,
  9547. 'task_id' => $task_id,
  9548. 'error' => $task->error_message ?? '未知错误'
  9549. ]);
  9550. } else {
  9551. // 任务还在处理中
  9552. $stats['pending']++;
  9553. }
  9554. } else {
  9555. // 任务不存在,标记为失败
  9556. DB::table('mp_products')
  9557. ->where('id', $product->id)
  9558. ->update([
  9559. 'pic_task_status' => '生成失败',
  9560. 'updated_at' => now()
  9561. ]);
  9562. $stats['failed']++;
  9563. dLog('anime')->error('图片生成任务不存在', [
  9564. 'product_id' => $product->id,
  9565. 'task_id' => $task_id
  9566. ]);
  9567. }
  9568. } catch (\Exception $e) {
  9569. dLog('anime')->error('检查产品图片生成任务异常', [
  9570. 'product_id' => $product->id,
  9571. 'task_id' => $product->pic_task_id ?? null,
  9572. 'error' => $e->getMessage()
  9573. ]);
  9574. }
  9575. }
  9576. return $stats;
  9577. }
  9578. /**
  9579. * 定时任务:检查任务中心中 saveScriptProducts 类型的任务是否已完成
  9580. *
  9581. * 当保存剧本资产的 SSE 连接中断等原因导致任务中心记录未及时更新时,
  9582. * 通过关联资产的图片生成状态兜底判断任务是否全部完成;
  9583. * 全部完成后更新任务中心的状态和结果(result 与 saveScriptProducts 接口返回保持一致)。
  9584. *
  9585. * @return int 更新的任务中心记录数
  9586. */
  9587. public function checkSaveScriptProductTaskCenters() {
  9588. $updated = 0;
  9589. // 只扫描尚未结束的 saveScriptProducts 任务
  9590. $tasks = DB::table('mp_task_center')
  9591. ->where('task_type', MpTaskCenter::TYPE_SAVE_SCRIPT_PRODUCTS)
  9592. ->whereIn('status', [MpTaskCenter::STATUS_PENDING, MpTaskCenter::STATUS_PROCESSING])
  9593. ->orderBy('id', 'desc')
  9594. ->limit(500)
  9595. ->get();
  9596. // 与 pollProductImageTasks 保持一致的类型名称映射
  9597. $typeNames = [
  9598. 1 => 'roles', // 角色
  9599. 2 => 'scenes', // 场景
  9600. 3 => 'props', // 道具
  9601. ];
  9602. foreach ($tasks as $task) {
  9603. try {
  9604. $taskParams = json_decode((string)$task->params, true);
  9605. $script_id = is_array($taskParams) ? (int)($taskParams['script_id'] ?? 0) : 0;
  9606. if (!$script_id) {
  9607. dLog('command')->warning('saveScriptProducts任务缺少script_id,跳过', [
  9608. 'task_center_id' => $task->id,
  9609. ]);
  9610. continue;
  9611. }
  9612. // 获取该剧本关联的全部资产ID
  9613. $productIds = DB::table('mp_script_product_mappings')
  9614. ->where('script_id', $script_id)
  9615. ->pluck('product_id')
  9616. ->unique()
  9617. ->toArray();
  9618. if (empty($productIds)) {
  9619. // 剧本没有关联资产,不视为完成,等待下一次检查
  9620. continue;
  9621. }
  9622. $products = DB::table('mp_products')
  9623. ->whereIn('id', $productIds)
  9624. ->where('is_deleted', 0)
  9625. ->get();
  9626. $stats = [];
  9627. $allCompleted = true;
  9628. foreach ($products as $product) {
  9629. $typeName = $typeNames[$product->product] ?? 'unknown';
  9630. if (!isset($stats[$typeName])) {
  9631. $stats[$typeName] = ['total' => 0, 'success' => 0, 'completed' => 0];
  9632. }
  9633. $stats[$typeName]['total']++;
  9634. if ($product->pic_task_status === '生成成功') {
  9635. $stats[$typeName]['success']++;
  9636. $stats[$typeName]['completed']++;
  9637. } elseif ($product->pic_task_status === '生成失败') {
  9638. $stats[$typeName]['completed']++;
  9639. } else {
  9640. // 仍有资产在生成中或未生成,任务未完成
  9641. $allCompleted = false;
  9642. }
  9643. }
  9644. if (!$allCompleted) {
  9645. continue;
  9646. }
  9647. // 全部完成,更新任务中心状态和结果(与接口返回结果保持一致)
  9648. $script = DB::table('mp_scripts')
  9649. ->where('id', $script_id)
  9650. ->where('is_deleted', 0)
  9651. ->first();
  9652. $script_name = $script->script_name ?? 'script_' . $script_id;
  9653. $this->finishScriptProductTask($task->id, [
  9654. 'type' => 'complete',
  9655. 'script_id' => $script_id,
  9656. 'script_name' => $script_name,
  9657. 'stats' => $stats,
  9658. 'timestamp' => date('Y-m-d H:i:s'),
  9659. 'task_center_id' => (int)$task->id,
  9660. ]);
  9661. $updated++;
  9662. dLog('command')->info('saveScriptProducts任务已完成,更新任务中心', [
  9663. 'task_center_id' => $task->id,
  9664. 'script_id' => $script_id,
  9665. 'stats' => $stats,
  9666. ]);
  9667. } catch (\Exception $e) {
  9668. dLog('command')->error('检查saveScriptProducts任务中心状态异常', [
  9669. 'task_center_id' => $task->id,
  9670. 'error' => $e->getMessage(),
  9671. ]);
  9672. }
  9673. }
  9674. return $updated;
  9675. }
  9676. /**
  9677. * 获取剧本关联的资产列表
  9678. * @param array $data 请求参数
  9679. * @return array
  9680. */
  9681. public function getScriptProducts($data) {
  9682. $uid = Site::getUid();
  9683. $cpid = Site::getCpid();
  9684. $script_id = getProp($data, 'script_id');
  9685. $episode_number = getProp($data, 'episode_number');
  9686. if (!$script_id) {
  9687. Utils::throwError('20003:请提供剧本ID');
  9688. }
  9689. // 验证剧本是否存在
  9690. $script = DB::table('mp_scripts')
  9691. ->where('id', $script_id)
  9692. ->where('is_deleted', 0)
  9693. ->first();
  9694. if (!$script) {
  9695. Utils::throwError('20003:剧本不存在');
  9696. }
  9697. // 联表查询资产信息
  9698. $query = DB::table('mp_script_product_mappings as mapping')
  9699. ->join('mp_products as product', 'mapping.product_id', '=', 'product.id')
  9700. ->where('mapping.script_id', $script_id)
  9701. ->where('product.cpid', $cpid)
  9702. ->where('product.is_deleted', 0);
  9703. // 如果提供了 episode_number,则过滤指定集数
  9704. if ($episode_number !== null && $episode_number !== '') {
  9705. $query->where('mapping.episode_number', $episode_number);
  9706. }
  9707. $mappings = $query->select(
  9708. 'mapping.script_id',
  9709. 'mapping.product_id',
  9710. 'mapping.episode_number',
  9711. 'product.product_name',
  9712. 'product.type',
  9713. 'product.product',
  9714. 'product.pic_prompt',
  9715. 'product.url',
  9716. 'product.pic_task_id',
  9717. 'product.pic_task_status',
  9718. 'product.three_view_image_url',
  9719. 'product.timbre_url',
  9720. 'mapping.created_at'
  9721. )
  9722. ->orderBy('mapping.product_id', 'asc')
  9723. ->orderBy('mapping.episode_number', 'asc')
  9724. ->get();
  9725. // 按 product_id 分组,合并 episode_number
  9726. $productMap = [];
  9727. foreach ($mappings as $item) {
  9728. $product_id = $item->product_id;
  9729. if (!isset($productMap[$product_id])) {
  9730. $productMap[$product_id] = [
  9731. 'product_id' => $product_id,
  9732. 'product_name' => $item->product_name,
  9733. 'type' => (int)$item->type,
  9734. 'product' => (int)$item->product,
  9735. 'pic_prompt' => $item->pic_prompt,
  9736. 'url' => $item->url,
  9737. 'timbre_url' => $item->timbre_url,
  9738. 'pic_task_id' => $item->pic_task_id,
  9739. 'pic_task_status' => $item->pic_task_status,
  9740. 'episode_numbers' => [],
  9741. 'created_at' => $item->created_at,
  9742. ];
  9743. }
  9744. // 添加 episode_number(去重)
  9745. if (!in_array($item->episode_number, $productMap[$product_id]['episode_numbers'])) {
  9746. $productMap[$product_id]['episode_numbers'][] = $item->episode_number;
  9747. }
  9748. }
  9749. // 按类型分组
  9750. $roles = []; // type=1 角色/主体
  9751. $scenes = []; // type=2 场景
  9752. $props = []; // type=3 道具
  9753. foreach ($productMap as $product) {
  9754. // 将 episode_numbers 数组转换为逗号分隔的字符串
  9755. $episodeNumbersStr = implode(',', $product['episode_numbers']);
  9756. // 构造返回数据
  9757. $productData = [
  9758. 'product_id' => $product['product_id'],
  9759. 'product_name' => $product['product_name'],
  9760. 'product' => $product['product'],
  9761. 'pic_prompt' => $product['pic_prompt'],
  9762. 'url' => $product['url'],
  9763. 'timbre_url' => $product['timbre_url'] ?? '',
  9764. 'pic_task_id' => $product['pic_task_id'],
  9765. 'pic_task_status' => $product['pic_task_status'],
  9766. 'episode_numbers' => $episodeNumbersStr,
  9767. 'created_at' => $product['created_at'],
  9768. ];
  9769. // 根据 type 分类(注意:type 字段表示资产类型,不是文件夹)
  9770. // 根据 product 字段分类(1=角色, 2=场景, 3=道具)
  9771. switch ($product['product']) {
  9772. case 1:
  9773. $roles[] = $productData;
  9774. break;
  9775. case 2:
  9776. $scenes[] = $productData;
  9777. break;
  9778. case 3:
  9779. $props[] = $productData;
  9780. break;
  9781. }
  9782. }
  9783. return [
  9784. 'script_id' => $script_id,
  9785. 'script_name' => $script->script_name ?? '',
  9786. 'roles' => $roles, // 主体
  9787. 'scenes' => $scenes, // 场景
  9788. 'props' => $props, // 道具
  9789. ];
  9790. }
  9791. /**
  9792. * 处理act_content中的{}标记,替换为product_name(图+序号)格式,并收集参考图片
  9793. * @param string $actContent 原始内容
  9794. * @param array $products 产品数组(包含product_name和url)
  9795. * @return array ['content' => 处理后的内容, 'reference_images' => 参考图片数组]
  9796. */
  9797. /**
  9798. * 根据片段内容与资产构建提示词、参考图、参考音频
  9799. *
  9800. * @param string $actContent 片段内容
  9801. * @param array $products 资产数组(角色/场景/道具)
  9802. * @param bool $supportAudioReference 模型是否支持参考音频;支持时角色音色优先使用 timbre_url
  9803. * @return array
  9804. */
  9805. public function processActContentWithProducts($actContent, $products, $supportAudioReference = false, $allowedAudioProducts = null, $allowedImageProducts = null) {
  9806. if (empty($actContent) || empty($products)) {
  9807. return [
  9808. 'content' => $actContent,
  9809. 'reference_images' => [],
  9810. 'reference_images_all' => [],
  9811. 'reference_audios' => [],
  9812. 'audio_voice_fallbacks' => []
  9813. ];
  9814. }
  9815. // 构建产品名称到产品信息的映射
  9816. $product_dict = [];
  9817. foreach ($products as $product) {
  9818. $product_name = getProp($product, 'product_name');
  9819. if ($product_name) {
  9820. $product_dict[$product_name] = [
  9821. // 优先使用三视图图片作为素材/参考图,否则使用原图 url
  9822. 'url' => getProp($product, 'three_view_image_url') ?: getProp($product, 'url'),
  9823. 'voice_prompt' => getProp($product, 'voice_prompt'),
  9824. // 角色音色参考音频(选填),有值时优先于 voice_prompt
  9825. 'timbre_url' => trim((string)getProp($product, 'timbre_url', '')),
  9826. 'product' => (int)getProp($product, 'product', 1)
  9827. ];
  9828. }
  9829. }
  9830. // 第一步:查找内容中所有 {产品名称} 格式的标记(按出现顺序,去重)
  9831. preg_match_all('/\{([^}]+)\}/u', $actContent, $matches);
  9832. $reference_images = [];
  9833. $reference_images_all = []; // 正文中出现且有图的资产图(不受模型上限影响,用于任务记录)
  9834. $product_index_map = []; // 产品名称 => 图片序号的映射
  9835. $reference_audios = [];
  9836. $product_audio_index_map = []; // 产品名称 => 音频序号的映射(与图片序号互相独立)
  9837. $audio_voice_fallbacks = []; // 产品名称 => voice_prompt(参考音频素材不可用时兜底使用)
  9838. $voice_prompts = []; // 存储需要添加到开头的voice_prompt信息
  9839. $narrator_voice_prompt = ''; // 单独存储旁白的voice_prompt
  9840. $current_index = 1;
  9841. $current_audio_index = 1;
  9842. if (!empty($matches[1])) {
  9843. // 按照在内容中第一次出现的顺序,为每个产品分配序号
  9844. $seen_products = []; // 用于去重
  9845. foreach ($matches[1] as $product_name) {
  9846. // 跳过已处理的产品
  9847. if (isset($seen_products[$product_name])) {
  9848. continue;
  9849. }
  9850. $seen_products[$product_name] = true;
  9851. // 检查产品是否在字典中
  9852. if (isset($product_dict[$product_name])) {
  9853. $url = $product_dict[$product_name]['url'];
  9854. $voice_prompt = $product_dict[$product_name]['voice_prompt'];
  9855. $timbre_url = $product_dict[$product_name]['timbre_url'];
  9856. // 判断该角色的参考音频是否可用(模型支持 + 配置了音色 + 未超出模型段数/时长限制)
  9857. $audio_allowed = $supportAudioReference && !empty($timbre_url);
  9858. if ($audio_allowed && is_array($allowedAudioProducts)) {
  9859. $audio_allowed = isset($allowedAudioProducts[$product_name])
  9860. && $allowedAudioProducts[$product_name] === $timbre_url;
  9861. }
  9862. // 分配音频序号(与图片序号互相独立;相同音频URL复用同一序号,保证角色与音频一一对应)
  9863. if ($audio_allowed) {
  9864. if (!in_array($timbre_url, $reference_audios)) {
  9865. $reference_audios[] = $timbre_url;
  9866. $product_audio_index_map[$product_name] = $current_audio_index;
  9867. $current_audio_index++;
  9868. } else {
  9869. $existing_audio_index = array_search($timbre_url, $reference_audios) + 1;
  9870. $product_audio_index_map[$product_name] = $existing_audio_index;
  9871. }
  9872. // 记录该角色的音色提示词:参考音频素材不可用时用它兜底(无提示词时记录空串,用于清理残留说明行)
  9873. $audio_voice_fallbacks[$product_name] = $voice_prompt ?? '';
  9874. }
  9875. // 处理voice_prompt:有可用参考音频的角色优先使用音频,不再输出音色提示词(旁白是公共的在后面单独处理)
  9876. if (!$audio_allowed && !empty($voice_prompt) && $product_name !== '旁白') {
  9877. $voice_prompts[] = $product_name . ':' . $voice_prompt . "\n";
  9878. }
  9879. // 只有URL非空且未被模型参考图上限截断,才分配序号并加入参考图片
  9880. if (!empty($url)) {
  9881. // 任务记录用:正文中出现且有图的资产图全部记录(不受模型上限影响)
  9882. if (!in_array($url, $reference_images_all)) {
  9883. $reference_images_all[] = $url;
  9884. }
  9885. $image_allowed = true;
  9886. if (is_array($allowedImageProducts)) {
  9887. $image_allowed = isset($allowedImageProducts[$product_name])
  9888. && $allowedImageProducts[$product_name] === $url;
  9889. }
  9890. if (!$image_allowed) {
  9891. // 超出模型参考图上限的资产不分配序号,提示词中不会出现<图片N>
  9892. $product_index_map[$product_name] = 0;
  9893. } elseif (!in_array($url, $reference_images)) {
  9894. $reference_images[] = $url;
  9895. $product_index_map[$product_name] = $current_index;
  9896. $current_index++;
  9897. } else {
  9898. // URL重复,找到已有的序号
  9899. $existing_index = array_search($url, $reference_images) + 1;
  9900. $product_index_map[$product_name] = $existing_index;
  9901. }
  9902. } else {
  9903. // URL为空,不分配序号(后续直接去掉{})
  9904. $product_index_map[$product_name] = 0;
  9905. }
  9906. } else {
  9907. // 产品不在字典中,不分配序号
  9908. $product_index_map[$product_name] = 0;
  9909. }
  9910. }
  9911. }
  9912. // 第二步:替换内容中的 {产品名称}
  9913. $processedContent = $actContent;
  9914. foreach ($product_index_map as $product_name => $index) {
  9915. $escaped_name = preg_quote($product_name, '/');
  9916. if ($index > 0) {
  9917. // 有图片,替换为:产品名称<图片X>
  9918. $replacement = $product_name . '<图片' . $index . '>';
  9919. } else {
  9920. // 无图片,只保留产品名称
  9921. $replacement = $product_name;
  9922. }
  9923. // 有参考音频的角色追加音频标记(如 角色A<图片1><音频1>),保证角色与音频一一对应
  9924. $audio_index = $product_audio_index_map[$product_name] ?? 0;
  9925. if ($audio_index > 0) {
  9926. $replacement .= '<音频' . $audio_index . '>';
  9927. }
  9928. // 替换所有 {产品名称} 为处理后的格式
  9929. $processedContent = preg_replace('/\{' . $escaped_name . '\}/u', $replacement, $processedContent);
  9930. }
  9931. // 第三步:单独处理旁白的voice_prompt(旁白是公共的,不依赖product_dict)
  9932. foreach ($products as $product) {
  9933. $product_name = getProp($product, 'product_name');
  9934. $voice_prompt = getProp($product, 'voice_prompt');
  9935. if ($product_name === '旁白' && !empty($voice_prompt) && empty($product_audio_index_map['旁白'])) {
  9936. $narrator_voice_prompt = $product_name . ':' . $voice_prompt . "\n";
  9937. break; // 找到旁白后退出循环
  9938. }
  9939. }
  9940. // 第四步:将参考音频音色信息和voice_prompt信息添加到内容最前面
  9941. $voice_prompt_prefix = '';
  9942. // 有参考音频的角色:按官方推荐句式"参考<音频N>中的音色"声明对应关系,
  9943. // 素材上传失败时与正文标记一起被清理/重排,保证角色与音频始终对应
  9944. foreach ($product_audio_index_map as $product_name => $audio_index) {
  9945. $voice_prompt_prefix .= '参考<音频' . $audio_index . '>中的音色,为' . $product_name . '配音' . "\n";
  9946. }
  9947. if (!empty($voice_prompts)) {
  9948. $voice_prompt_prefix .= implode('', $voice_prompts);
  9949. }
  9950. // 旁白的voice_prompt放在最后
  9951. if (!empty($narrator_voice_prompt)) {
  9952. $voice_prompt_prefix .= $narrator_voice_prompt;
  9953. }
  9954. // 如果有voice_prompt信息,添加到内容开头
  9955. if (!empty($voice_prompt_prefix)) {
  9956. $processedContent = "人物音色:\n" . $voice_prompt_prefix . "\n" . $processedContent;
  9957. }
  9958. return [
  9959. 'content' => $processedContent,
  9960. 'reference_images' => $reference_images,
  9961. 'reference_images_all' => $reference_images_all,
  9962. 'reference_audios' => $reference_audios,
  9963. 'audio_voice_fallbacks' => $audio_voice_fallbacks
  9964. ];
  9965. }
  9966. /**
  9967. * 用剧本资产关联(mappings)的数据补齐资产数组
  9968. * 批量转视频时资产取值的优先级:剧本资产关联(mappings) > extra_products > 剧集单独设置
  9969. * 资产库对应字段为空时不覆盖,避免把分集里的有效数据清空
  9970. *
  9971. * @param array $products 资产数组
  9972. * @param int $script_id 剧本ID
  9973. * @param bool $overwrite 资产库有值时是否覆盖数组中的已有值(true 表示 mappings 优先级最高)
  9974. * @return array
  9975. */
  9976. public function fillProductsFromMapping($products, $script_id, $overwrite = false) {
  9977. if (empty($products) || !$script_id) {
  9978. return $products;
  9979. }
  9980. $mappingItems = DB::table('mp_script_product_mappings as mapping')
  9981. ->join('mp_products as product', 'mapping.product_id', '=', 'product.id')
  9982. ->where('mapping.script_id', $script_id)
  9983. ->where('product.is_deleted', 0)
  9984. ->select(
  9985. 'mapping.product_id',
  9986. 'product.product_name',
  9987. 'product.product',
  9988. 'product.pic_prompt',
  9989. 'product.url',
  9990. 'product.three_view_image_url',
  9991. 'product.timbre_url'
  9992. )
  9993. ->get();
  9994. if ($mappingItems->isEmpty()) {
  9995. return $products;
  9996. }
  9997. $mappingMap = [];
  9998. foreach ($mappingItems as $item) {
  9999. $normalized_name = $this->normalizeProductName($item->product_name);
  10000. if ($normalized_name === '' || isset($mappingMap[$normalized_name])) {
  10001. continue;
  10002. }
  10003. // 资产库字段有值才纳入覆盖范围(三视图、音色等为选填,可能为空)
  10004. $mappingProduct = [];
  10005. if (!empty($item->product_id)) {
  10006. $mappingProduct['product_id'] = (int)$item->product_id;
  10007. }
  10008. if (!empty($item->product)) {
  10009. $mappingProduct['product'] = (int)$item->product;
  10010. }
  10011. if (!empty($item->pic_prompt)) {
  10012. $mappingProduct['pic_prompt'] = $item->pic_prompt;
  10013. }
  10014. if (!empty($item->url)) {
  10015. $mappingProduct['url'] = $item->url;
  10016. }
  10017. if (!empty($item->three_view_image_url)) {
  10018. $mappingProduct['three_view_image_url'] = $item->three_view_image_url;
  10019. }
  10020. if (!empty($item->timbre_url)) {
  10021. $mappingProduct['timbre_url'] = $item->timbre_url;
  10022. }
  10023. if (!empty($mappingProduct)) {
  10024. $mappingMap[$normalized_name] = $mappingProduct;
  10025. }
  10026. }
  10027. if (empty($mappingMap)) {
  10028. return $products;
  10029. }
  10030. foreach ($products as &$product) {
  10031. $normalized_name = $this->normalizeProductName(getProp($product, 'product_name'));
  10032. if ($normalized_name === '' || empty($mappingMap[$normalized_name])) {
  10033. continue;
  10034. }
  10035. foreach ($mappingMap[$normalized_name] as $key => $value) {
  10036. // 不覆盖模式:只补齐数组中缺失的字段
  10037. if (!$overwrite && !empty(getProp($product, $key))) {
  10038. continue;
  10039. }
  10040. $product[$key] = $value;
  10041. }
  10042. }
  10043. unset($product);
  10044. return $products;
  10045. }
  10046. /**
  10047. * 资产名称归一化(去掉首尾空白、方括号、花括号等符号)
  10048. *
  10049. * @param string $name
  10050. * @return string
  10051. */
  10052. private function normalizeProductName($name) {
  10053. return trim(preg_replace(
  10054. '/^[\s*\[\]【】[]{}{}\x{3000}]+|[\s*\[\]【】[]{}{}\x{3000}]+$/u',
  10055. '',
  10056. trim((string)$name)
  10057. ));
  10058. }
  10059. /**
  10060. * 是否启用参考音频(角色音色)
  10061. * 优先取调用方传入的 enable_reference_audio,未传时读取环境变量 ENABLE_REFERENCE_AUDIO,默认开启
  10062. *
  10063. * @param array $data 调用方入参
  10064. * @return bool
  10065. */
  10066. public function isReferenceAudioEnabled($data) {
  10067. // 环境变量兜底:兼容 true/false/1/0/on/off/yes/no 等写法,无法识别时按默认开启
  10068. $envValue = env('ENABLE_REFERENCE_AUDIO', true);
  10069. $envDefault = is_bool($envValue)
  10070. ? $envValue
  10071. : filter_var($envValue, FILTER_VALIDATE_BOOLEAN, FILTER_NULL_ON_FAILURE);
  10072. if ($envDefault === null) {
  10073. $envDefault = true;
  10074. }
  10075. $value = getProp($data, 'enable_reference_audio', null);
  10076. if ($value === null || $value === '') {
  10077. return $envDefault;
  10078. }
  10079. $bool = filter_var($value, FILTER_VALIDATE_BOOLEAN, FILTER_NULL_ON_FAILURE);
  10080. return $bool === null ? $envDefault : $bool;
  10081. }
  10082. /**
  10083. * 判断视频模型是否支持角色参考音频(音色)
  10084. * 目前支持:智帧统一API、Seedance 2.0 系列(国内百度/海外百度/快快AI)
  10085. *
  10086. * @param string $model
  10087. * @return bool
  10088. */
  10089. public function isActReferenceAudioSupported($model) {
  10090. if (!$model) {
  10091. return false;
  10092. }
  10093. return strpos($model, 'zhizhen') !== false || $this->isSeedance20SeriesModel($model);
  10094. }
  10095. /**
  10096. * 获取模型对参考图片的数量上限
  10097. * Seedance 2.0(含 2.0 mini/fast)与智帧:9 张;Seedance 2.5:30 张
  10098. *
  10099. * @param string $model
  10100. * @return int 0 表示该模型不走参考图逻辑(不做限制)
  10101. */
  10102. public function getActReferenceImageLimit($model) {
  10103. if (!$this->isActReferenceAudioSupported($model)) {
  10104. return 0;
  10105. }
  10106. if (strpos($model, '2.5') !== false || strpos($model, '2-5') !== false) {
  10107. return 30;
  10108. }
  10109. return 9;
  10110. }
  10111. /**
  10112. * 生成提示词之前解析可用的资产参考图
  10113. * 按正文中{资产名}首次出现的顺序取有图片的资产(相同图片URL复用同一编号);
  10114. * 超过模型上限的资产不分配图片编号,提示词中也不会出现<图片N>引用
  10115. * 调用方显式传入的 reference_images 不占用这里的额度,由调用方按剩余额度补充
  10116. *
  10117. * @param string $actContent 片段内容
  10118. * @param array $products 资产数组
  10119. * @param string $model 视频模型
  10120. * @return array ['allowed' => [产品名 => 图片URL], 'excluded' => [产品名 => 原因], 'limit' => 上限]
  10121. */
  10122. public function resolveActReferenceImages($actContent, $products, $model) {
  10123. $result = ['allowed' => [], 'excluded' => [], 'limit' => 0];
  10124. $limit = $this->getActReferenceImageLimit($model);
  10125. if ($limit <= 0 || empty($actContent) || empty($products)) {
  10126. return $result;
  10127. }
  10128. $result['limit'] = $limit;
  10129. // 产品名 => 图片(优先三视图,其次原图)
  10130. $imageMap = [];
  10131. foreach ($products as $product) {
  10132. $name = getProp($product, 'product_name');
  10133. if (!$name) {
  10134. continue;
  10135. }
  10136. $url = trim((string)(getProp($product, 'three_view_image_url') ?: getProp($product, 'url')));
  10137. if ($url !== '') {
  10138. $imageMap[$name] = $url;
  10139. }
  10140. }
  10141. if (empty($imageMap)) {
  10142. return $result;
  10143. }
  10144. preg_match_all('/\{([^}]+)\}/u', $actContent, $matches);
  10145. $orderedNames = [];
  10146. foreach (($matches[1] ?? []) as $name) {
  10147. if (!isset($orderedNames[$name])) {
  10148. $orderedNames[$name] = true;
  10149. }
  10150. }
  10151. $usedUrls = [];
  10152. foreach (array_keys($orderedNames) as $name) {
  10153. $url = $imageMap[$name] ?? '';
  10154. if ($url === '') {
  10155. continue;
  10156. }
  10157. // 相同图片复用同一编号,不重复计数
  10158. if (isset($usedUrls[$url])) {
  10159. $result['allowed'][$name] = $url;
  10160. continue;
  10161. }
  10162. if (count($usedUrls) >= $limit) {
  10163. $result['excluded'][$name] = '超过参考图数量上限(' . $limit . '张)';
  10164. continue;
  10165. }
  10166. $usedUrls[$url] = true;
  10167. $result['allowed'][$name] = $url;
  10168. }
  10169. if (!empty($result['excluded'])) {
  10170. dLog('anime')->info('资产参考图超出模型限制,已截断', [
  10171. 'model' => $model,
  10172. 'limit' => $limit,
  10173. 'allowed' => array_keys($result['allowed']),
  10174. 'excluded' => $result['excluded'],
  10175. ]);
  10176. }
  10177. return $result;
  10178. }
  10179. /**
  10180. * 获取模型对参考音频的限制
  10181. * Seedance 2.0(含 2.0 lite / 2.0 fast):最多3段,单个[2,15]s,总时长不超过15s
  10182. * Seedance 2.5:最多10段,单个[2,30]s,总时长不超过30s
  10183. *
  10184. * @param string $model
  10185. * @return array|null 非参考音频模型返回 null
  10186. */
  10187. public function getActAudioLimits($model) {
  10188. if (!$this->isActReferenceAudioSupported($model)) {
  10189. return null;
  10190. }
  10191. if (strpos($model, '2.5') !== false || strpos($model, '2-5') !== false) {
  10192. return ['max_count' => 10, 'max_single' => 30, 'max_total' => 30];
  10193. }
  10194. return ['max_count' => 3, 'max_single' => 15, 'max_total' => 15];
  10195. }
  10196. /**
  10197. * 生成提示词之前解析可用的参考音频
  10198. * 按正文中{资产名}首次出现的顺序,逐个校验单个音频时长、段数与总时长,超出限制的部分直接截断;
  10199. * 被截断(或单个时长超限)的角色不会出现在提示词的<音频N>引用中,会自动回退使用音色提示词
  10200. *
  10201. * @param string $actContent 片段内容
  10202. * @param array $products 资产数组
  10203. * @param string $model 视频模型
  10204. * @return array ['allowed' => [产品名 => 音频URL], 'excluded' => [产品名 => 原因], 'total_duration' => 秒]
  10205. */
  10206. public function resolveActReferenceAudios($actContent, $products, $model) {
  10207. $result = ['allowed' => [], 'excluded' => [], 'total_duration' => 0];
  10208. $limits = $this->getActAudioLimits($model);
  10209. if (!$limits || empty($actContent) || empty($products)) {
  10210. return $result;
  10211. }
  10212. // 产品名 => 音色音频
  10213. $timbreMap = [];
  10214. foreach ($products as $product) {
  10215. $name = getProp($product, 'product_name');
  10216. if (!$name) {
  10217. continue;
  10218. }
  10219. $timbre = trim((string)getProp($product, 'timbre_url', ''));
  10220. if ($timbre !== '') {
  10221. $timbreMap[$name] = $timbre;
  10222. }
  10223. }
  10224. if (empty($timbreMap)) {
  10225. return $result;
  10226. }
  10227. // 按正文中{资产名}首次出现的顺序确定音频编号顺序(与提示词生成保持一致)
  10228. preg_match_all('/\{([^}]+)\}/u', $actContent, $matches);
  10229. $orderedNames = [];
  10230. foreach (($matches[1] ?? []) as $name) {
  10231. if (!isset($orderedNames[$name])) {
  10232. $orderedNames[$name] = true;
  10233. }
  10234. }
  10235. // 收集候选音频(同一音频可能被多个角色复用,只保留首次出现的URL用于筛选)
  10236. $orderedUrls = [];
  10237. foreach (array_keys($orderedNames) as $name) {
  10238. $timbre = $timbreMap[$name] ?? '';
  10239. if ($timbre !== '' && !in_array($timbre, $orderedUrls, true)) {
  10240. $orderedUrls[] = $timbre;
  10241. }
  10242. }
  10243. if (empty($orderedUrls)) {
  10244. return $result;
  10245. }
  10246. // 复用统一的筛选逻辑:单个音频时长 → 段数 → 总时长(与通用接口 generateVideo 共用)
  10247. $filtered = $this->filterActReferenceAudiosWithDetail($orderedUrls, $limits);
  10248. $result['total_duration'] = $filtered['total_duration'];
  10249. // 按角色在正文中的出现顺序回填结果,保证键顺序与提示词编号顺序一致
  10250. foreach (array_keys($orderedNames) as $name) {
  10251. $timbre = $timbreMap[$name] ?? '';
  10252. if ($timbre === '') {
  10253. continue;
  10254. }
  10255. if (isset($filtered['durations'][$timbre])) {
  10256. $result['allowed'][$name] = $timbre;
  10257. } elseif (isset($filtered['rejected'][$timbre])) {
  10258. $result['excluded'][$name] = $filtered['rejected'][$timbre];
  10259. }
  10260. }
  10261. if (!empty($result['excluded'])) {
  10262. dLog('anime')->info('参考音频超出模型限制,已截断', [
  10263. 'model' => $model,
  10264. 'limits' => $limits,
  10265. 'allowed' => array_keys($result['allowed']),
  10266. 'excluded' => $result['excluded'],
  10267. 'total_duration' => $result['total_duration'],
  10268. ]);
  10269. }
  10270. return $result;
  10271. }
  10272. /**
  10273. * 按模型限制逐条筛选参考音频(片段转视频与通用文生视频共用的判断逻辑)
  10274. * 顺序:单个音频时长 → 段数上限 → 总时长上限;相同URL复用同一段素材,不重复计数
  10275. *
  10276. * @param array $referenceAudios 参考音频URL数组
  10277. * @param array $limits 限制,如 ['max_count'=>3,'max_single'=>15,'max_total'=>15]
  10278. * @return array ['allowed' => [url...], 'durations' => [url=>秒], 'rejected' => [url=>原因], 'total_duration' => 秒]
  10279. */
  10280. public function filterActReferenceAudiosWithDetail(array $referenceAudios, array $limits) {
  10281. $allowed = [];
  10282. $durations = [];
  10283. $rejected = [];
  10284. $totalDuration = 0;
  10285. foreach ($referenceAudios as $url) {
  10286. if (!is_string($url) || trim($url) === '' || isset($durations[$url]) || isset($rejected[$url])) {
  10287. continue;
  10288. }
  10289. $duration = $this->getRemoteAudioDurationSeconds($url);
  10290. if ($duration > 0 && $duration > $limits['max_single']) {
  10291. $rejected[$url] = '单个音频时长超限(' . $duration . 's > ' . $limits['max_single'] . 's)';
  10292. continue;
  10293. }
  10294. if (count($allowed) >= $limits['max_count']) {
  10295. $rejected[$url] = '超过参考音频段数上限(' . $limits['max_count'] . '段)';
  10296. continue;
  10297. }
  10298. if ($duration > 0 && ($totalDuration + $duration) > $limits['max_total']) {
  10299. $rejected[$url] = '超过参考音频总时长上限(' . $limits['max_total'] . 's)';
  10300. continue;
  10301. }
  10302. $allowed[] = $url;
  10303. $durations[$url] = max(0, $duration);
  10304. $totalDuration += max(0, $duration);
  10305. }
  10306. return [
  10307. 'allowed' => $allowed,
  10308. 'durations' => $durations,
  10309. 'rejected' => $rejected,
  10310. 'total_duration' => round($totalDuration, 2),
  10311. ];
  10312. }
  10313. /**
  10314. * 按模型限制过滤参考音频(通用接口用,仅返回通过的URL数组)
  10315. *
  10316. * @param array $referenceAudios 参考音频URL数组
  10317. * @param array $limits 限制
  10318. * @return array 过滤后的音频URL数组
  10319. */
  10320. public function filterActReferenceAudios(array $referenceAudios, array $limits) {
  10321. $filtered = $this->filterActReferenceAudiosWithDetail($referenceAudios, $limits);
  10322. if (!empty($filtered['rejected'])) {
  10323. dLog('anime')->info('参考音频超出模型限制,已截断', [
  10324. 'limits' => $limits,
  10325. 'allowed' => $filtered['allowed'],
  10326. 'rejected' => $filtered['rejected'],
  10327. 'total_duration' => $filtered['total_duration'],
  10328. ]);
  10329. }
  10330. return $filtered['allowed'];
  10331. }
  10332. /**
  10333. * 探测远程音频时长(wav 精确解析;mp3 按首帧码率估算)
  10334. *
  10335. * @param string $url 音频URL
  10336. * @return float 秒;无法探测时返回 0
  10337. */
  10338. public function getRemoteAudioDurationSeconds($url) {
  10339. try {
  10340. // 使用 Guzzle(不依赖 allow_url_fopen,LNMP 环境下同样可用)
  10341. $client = new \GuzzleHttp\Client(['verify' => false, 'timeout' => 20, 'connect_timeout' => 10]);
  10342. $response = $client->get($url, [
  10343. 'headers' => ['Range' => 'bytes=0-1048575'],
  10344. 'http_errors' => false,
  10345. ]);
  10346. $data = (string)$response->getBody();
  10347. if (strlen($data) < 64) {
  10348. return 0;
  10349. }
  10350. // 文件总大小:206 时取 Content-Range 的分母,否则用 Content-Length
  10351. $totalSize = 0;
  10352. $contentRange = $response->getHeaderLine('Content-Range');
  10353. if ($contentRange !== '' && preg_match('#/(\d+)#', $contentRange, $m)) {
  10354. $totalSize = (int)$m[1];
  10355. } else {
  10356. $contentLength = $response->getHeaderLine('Content-Length');
  10357. if ($contentLength !== '') {
  10358. $totalSize = (int)$contentLength;
  10359. }
  10360. }
  10361. // WAV:解析 fmt/data chunk 精确计算
  10362. if (substr($data, 0, 4) === 'RIFF' && substr($data, 8, 4) === 'WAVE') {
  10363. $offset = 12;
  10364. $byteRate = 0;
  10365. $dataSize = 0;
  10366. while ($offset + 8 <= strlen($data)) {
  10367. $chunkId = substr($data, $offset, 4);
  10368. $chunkSize = unpack('V', substr($data, $offset + 4, 4))[1];
  10369. if ($chunkId === 'fmt ' && $offset + 8 + 12 <= strlen($data)) {
  10370. $byteRate = unpack('V', substr($data, $offset + 16, 4))[1];
  10371. } elseif ($chunkId === 'data') {
  10372. $dataSize = $chunkSize;
  10373. break;
  10374. }
  10375. $offset += 8 + $chunkSize + ($chunkSize % 2);
  10376. }
  10377. if ($byteRate > 0 && $dataSize > 0) {
  10378. return round($dataSize / $byteRate, 2);
  10379. }
  10380. return 0;
  10381. }
  10382. // MP3:优先 Xing/Info 帧数,其次逐帧统计,最后按码率估算
  10383. $scanStart = 0;
  10384. if (strlen($data) >= 10 && substr($data, 0, 3) === 'ID3') {
  10385. // 跳过 ID3v2 标签,避免命中标签数据中的伪同步字
  10386. $tagSize = ((ord($data[6]) & 0x7F) << 21) | ((ord($data[7]) & 0x7F) << 14)
  10387. | ((ord($data[8]) & 0x7F) << 7) | (ord($data[9]) & 0x7F);
  10388. $scanStart = 10 + $tagSize;
  10389. }
  10390. $mpeg1Layer3 = [0, 32, 40, 48, 56, 64, 80, 96, 112, 128, 160, 192, 224, 256, 320];
  10391. $mpeg2Layer3 = [0, 8, 16, 24, 32, 40, 48, 56, 64, 80, 96, 112, 128, 144, 160];
  10392. $sampleRatesV1 = [44100, 48000, 32000, 0];
  10393. $sampleRatesV2 = [22050, 24000, 16000, 0];
  10394. $parseFrame = function ($buffer, $offset) use ($mpeg1Layer3, $mpeg2Layer3, $sampleRatesV1, $sampleRatesV2) {
  10395. if ($offset < 0 || $offset + 4 > strlen($buffer)) {
  10396. return null;
  10397. }
  10398. if (ord($buffer[$offset]) !== 0xFF) {
  10399. return null;
  10400. }
  10401. $b1 = ord($buffer[$offset + 1]);
  10402. if (($b1 & 0xE0) !== 0xE0) {
  10403. return null;
  10404. }
  10405. $b2 = ord($buffer[$offset + 2]);
  10406. $b3 = ord($buffer[$offset + 3]);
  10407. $versionBits = ($b1 >> 3) & 0x03; // 3=MPEG1, 2=MPEG2, 0=MPEG2.5
  10408. $layerBits = ($b1 >> 1) & 0x03; // 1=Layer3
  10409. $bitrateIndex = ($b2 >> 4) & 0x0F;
  10410. $sampleIndex = ($b2 >> 2) & 0x03;
  10411. $channelMode = ($b3 >> 6) & 0x03; // 3=单声道
  10412. if ($versionBits === 1 || $layerBits !== 1 || $bitrateIndex === 0 || $bitrateIndex === 15 || $sampleIndex === 3) {
  10413. return null;
  10414. }
  10415. $bitrate = $versionBits === 3 ? $mpeg1Layer3[$bitrateIndex] : $mpeg2Layer3[$bitrateIndex];
  10416. $rate = $versionBits === 3 ? $sampleRatesV1[$sampleIndex] : $sampleRatesV2[$sampleIndex];
  10417. if ($bitrate <= 0 || $rate <= 0) {
  10418. return null;
  10419. }
  10420. $samplesPerFrame = $versionBits === 3 ? 1152 : 576;
  10421. $frameLen = (int)(($samplesPerFrame / 8 * $bitrate * 1000) / $rate);
  10422. if ($frameLen <= 4) {
  10423. return null;
  10424. }
  10425. return [
  10426. 'version' => $versionBits,
  10427. 'bitrate' => $bitrate,
  10428. 'rate' => $rate,
  10429. 'samples' => $samplesPerFrame,
  10430. 'length' => $frameLen,
  10431. 'channel_mode' => $channelMode,
  10432. ];
  10433. };
  10434. // 定位首个有效帧,并校验下一帧也合法(避免命中伪同步字)
  10435. $firstFrame = null;
  10436. $frameOffset = -1;
  10437. for ($i = $scanStart; $i + 4 <= strlen($data); $i++) {
  10438. $frame = $parseFrame($data, $i);
  10439. if (!$frame) {
  10440. continue;
  10441. }
  10442. $nextOffset = $i + $frame['length'];
  10443. if ($nextOffset + 4 <= strlen($data) && !$parseFrame($data, $nextOffset)) {
  10444. continue;
  10445. }
  10446. $firstFrame = $frame;
  10447. $frameOffset = $i;
  10448. break;
  10449. }
  10450. if (!$firstFrame) {
  10451. return 0;
  10452. }
  10453. // 1) Xing/Info 头包含总帧数,可直接精确计算
  10454. $sideInfoSize = $firstFrame['version'] === 3
  10455. ? ($firstFrame['channel_mode'] === 3 ? 17 : 32)
  10456. : ($firstFrame['channel_mode'] === 3 ? 9 : 17);
  10457. $xingOffset = $frameOffset + 4 + $sideInfoSize;
  10458. $xingTag = substr($data, $xingOffset, 4);
  10459. if (($xingTag === 'Xing' || $xingTag === 'Info') && strlen($data) >= $xingOffset + 12) {
  10460. $flags = unpack('N', substr($data, $xingOffset + 4, 4))[1];
  10461. if ($flags & 0x01) {
  10462. $frameCount = unpack('N', substr($data, $xingOffset + 8, 4))[1];
  10463. if ($frameCount > 0) {
  10464. return round($frameCount * $firstFrame['samples'] / $firstFrame['rate'], 2);
  10465. }
  10466. }
  10467. }
  10468. // 2) 文件不大时下载完整内容逐帧统计(精确)
  10469. $fullData = $data;
  10470. if ($totalSize > 0 && strlen($data) < $totalSize && $totalSize <= 10485760) {
  10471. $fullData = (string)$client->get($url, ['http_errors' => false])->getBody();
  10472. }
  10473. if ($totalSize > 0 && strlen($fullData) >= $totalSize) {
  10474. $samples = 0;
  10475. $i = $frameOffset;
  10476. $bufferLength = strlen($fullData);
  10477. while ($i + 4 <= $bufferLength) {
  10478. $frame = $parseFrame($fullData, $i);
  10479. if (!$frame) {
  10480. $i++;
  10481. continue;
  10482. }
  10483. $samples += $frame['samples'];
  10484. $i += $frame['length'];
  10485. }
  10486. if ($samples > 0) {
  10487. return round($samples / $firstFrame['rate'], 2);
  10488. }
  10489. }
  10490. // 3) 回退:按首帧码率估算(仅用于无法读取完整文件的极端情况)
  10491. return round(($totalSize * 8) / ($firstFrame['bitrate'] * 1000), 2);
  10492. } catch (\Throwable $e) {
  10493. dLog('anime')->warning('参考音频时长探测失败', ['url' => $url, 'error' => $e->getMessage()]);
  10494. return 0;
  10495. }
  10496. }
  10497. /**
  10498. * 将角色音色参考音频按模型分支上传为素材
  10499. * 上传失败时对应素材的<音频N>标记会从 $prompt 中清理(引用传递),与参考图处理保持一致
  10500. *
  10501. * @param array $referenceAudios 参考音频URL数组(顺序与<音频N>标记一一对应)
  10502. * @param string $model 视频模型
  10503. * @param string $prompt 完整提示词(引用传递)
  10504. * @return array 素材数组(asset://格式),非支持模型返回空数组
  10505. */
  10506. public function processActReferenceAudiosToAssets(array $referenceAudios, $model, &$prompt) {
  10507. if (empty($referenceAudios)) {
  10508. return [];
  10509. }
  10510. if (strpos($model, 'zhizhen') !== false) {
  10511. return $this->aiImageGenerationService->processReferenceAudiosToAssets($referenceAudios, $prompt);
  10512. }
  10513. if ($this->isSeedance20SeriesModel($model)) {
  10514. if ($this->isKuaikuaiSeedanceModel($model)) {
  10515. return $this->aiVideoGenerationService->processReferenceAudiosToKuaikuaiAssets($referenceAudios, $prompt);
  10516. }
  10517. if ($this->isOverseasBaiduSeedanceModel($model)) {
  10518. return $this->aiVideoGenerationService->processReferenceAudiosToBaiduDreaminaAssets($referenceAudios, $prompt);
  10519. }
  10520. return $this->aiVideoGenerationService->processReferenceAudiosToSeedance20Assets($referenceAudios, $prompt);
  10521. }
  10522. return [];
  10523. }
  10524. /**
  10525. * 参考音频素材上传失败时,用该角色原本的音色提示词兜底
  10526. * 说明行中的<音频N>标记被清理即代表该角色的音频素材不可用
  10527. *
  10528. * @param string $prompt 完整提示词
  10529. * @param array $audioVoiceFallbacks 角色名 => voice_prompt(仅包含配置了参考音频的角色)
  10530. * @return string
  10531. */
  10532. public function applyAudioVoiceFallbacks($prompt, array $audioVoiceFallbacks) {
  10533. if (empty($prompt) || empty($audioVoiceFallbacks)) {
  10534. return $prompt;
  10535. }
  10536. foreach ($audioVoiceFallbacks as $product_name => $voice_prompt) {
  10537. $voice_prompt = trim((string)$voice_prompt);
  10538. if ($product_name === '') {
  10539. continue;
  10540. }
  10541. $escaped_name = preg_quote($product_name, '/');
  10542. // 说明行中仍有<音频N>标记,说明该角色的音频素材可用,无需兜底
  10543. if (preg_match('/^参考<音频\d+>中的音色,为' . $escaped_name . '配音[^\n]*$/mu', $prompt)) {
  10544. continue;
  10545. }
  10546. $linePattern = '/^参考<音频\d+>中的音色,为' . $escaped_name . '配音[^\n]*$/mu';
  10547. if (!preg_match($linePattern, $prompt)) {
  10548. continue;
  10549. }
  10550. if ($voice_prompt === '') {
  10551. // 该角色没有音色提示词,素材不可用时直接移除残留的说明行
  10552. $prompt = preg_replace('/^参考<音频\d+>中的音色,为' . $escaped_name . '配音[^\n]*\n?/mu', '', $prompt, 1);
  10553. } else {
  10554. // 素材不可用:把说明行替换为该角色原本的音色提示词
  10555. $prompt = preg_replace_callback($linePattern, function () use ($product_name, $voice_prompt) {
  10556. return $product_name . ':' . $voice_prompt;
  10557. }, $prompt, 1);
  10558. }
  10559. dLog('anime')->info('参考音频素材不可用,使用音色提示词兜底', [
  10560. 'product_name' => $product_name,
  10561. 'has_voice_prompt' => $voice_prompt === '' ? 0 : 1,
  10562. ]);
  10563. }
  10564. return $prompt;
  10565. }
  10566. /**
  10567. * 整段配音音频素材不可用时,移除对应的提示语句,避免出现残句
  10568. *
  10569. * @param string $prompt 完整提示词
  10570. * @return string
  10571. */
  10572. public function removeUnavailableSegmentAudioPrompt($prompt) {
  10573. if (empty($prompt) || strpos($prompt, '作为视频配音') === false) {
  10574. return $prompt;
  10575. }
  10576. return preg_replace_callback('/^全程使用[^\n]*?作为视频配音。\n?/mu', function ($matches) {
  10577. return strpos($matches[0], '<音频') === false ? '' : $matches[0];
  10578. }, $prompt);
  10579. }
  10580. /**
  10581. * 生成整段配音音频的提示词引用,并返回合并后的参考音频数组
  10582. * 角色音色音频排在前面(音频1..N,与提示词中的<音频N>一一对应),整段配音音频排在其后
  10583. *
  10584. * @param string $prompt 当前提示词
  10585. * @param array $referenceAudios 角色音色参考音频URL数组
  10586. * @param string $segmentAudioUrl 整段配音音频URL(为空表示无整段配音)
  10587. * @return array ['prompt' => 新提示词, 'has_audio_mark' => 是否使用<音频N>标记, 'reference_audios' => 合并后的音频数组]
  10588. */
  10589. public function buildSegmentAudioReference($prompt, array $referenceAudios, $segmentAudioUrl) {
  10590. $result = [
  10591. 'prompt' => $prompt,
  10592. 'has_audio_mark' => false,
  10593. 'reference_audios' => $referenceAudios,
  10594. ];
  10595. if (empty($segmentAudioUrl)) {
  10596. return $result;
  10597. }
  10598. // 有角色音色时整段配音排在角色音色之后,使用<音频N>标记交由素材上传统一做失败清理与序号重排;
  10599. // 没有角色音色时保持原有文案
  10600. $audioReference = $referenceAudios
  10601. ? "使用<音频" . (count($referenceAudios) + 1) . ">"
  10602. : "使用音频1";
  10603. $hasAudioMark = strpos($audioReference, '<音频') !== false;
  10604. // 有角色音色时整段配音独占一行,便于失败时按行清理
  10605. $result['prompt'] = $hasAudioMark
  10606. ? "全程" . $audioReference . "作为视频配音。\n" . $prompt
  10607. : "全程" . $audioReference . "作为视频配音。" . $prompt;
  10608. $result['has_audio_mark'] = $hasAudioMark;
  10609. $result['reference_audios'] = array_merge($referenceAudios, [$segmentAudioUrl]);
  10610. return $result;
  10611. }
  10612. /**
  10613. * 任务记录用:把参考音频追加到 ref_image_url 中
  10614. * 参考图与参考音色音频一起保存,便于后续核对任务实际使用的素材
  10615. * 合并后统一去重并过滤空值,保证同一素材只出现一次
  10616. *
  10617. * @param string $refImageUrlJson 当前 ref_image_url(JSON数组字符串)
  10618. * @param array $referenceAudios 参考音频URL数组
  10619. * @return string
  10620. */
  10621. public function mergeReferenceAudiosIntoRefImageUrl($refImageUrlJson, array $referenceAudios) {
  10622. $refImageUrls = json_decode((string)$refImageUrlJson, true) ?: [];
  10623. if (!is_array($refImageUrls)) {
  10624. $refImageUrls = [];
  10625. }
  10626. // 参考图在前、参考音频在后,合并后去重并过滤空值
  10627. $merged = array_values(array_unique(array_filter(array_merge($refImageUrls, $referenceAudios))));
  10628. return json_encode($merged, 256);
  10629. }
  10630. public function saveActVideoGenerateParams($data) {
  10631. $episode_id = getProp($data, 'episode_id');
  10632. $model = getProp($data, 'video_model');
  10633. $valid_models = DB::table('mp_video_models')->where('ace_mode', 1)->select('model')->pluck('model')->toArray();
  10634. if (!in_array($model, $valid_models)) {
  10635. Utils::throwError('20003:该模型不可用');
  10636. }
  10637. // 验证模型是否在可用模型表中
  10638. if (!DB::table('mp_video_models')->where('model', $model)->where('is_enabled', 1)->exists()) {
  10639. Utils::throwError('20003:该模型已不可用,请更换!');
  10640. }
  10641. $video_resolution = getProp($data, 'video_resolution', '720p');
  10642. $ratio = getProp($data, 'ratio');
  10643. if (!$ratio) $ratio = '9:16';
  10644. $episode = DB::table('mp_anime_episodes')->where('id', $episode_id)->first(['anime_id']);
  10645. if (!$episode) {
  10646. Utils::throwError('20003:分集不存在');
  10647. }
  10648. dLog('anime')->info('保存分集视频参数', $data);
  10649. try {
  10650. DB::beginTransaction();
  10651. $result = DB::table('mp_anime_episodes')->where('id', $episode_id)->update([
  10652. 'video_model' => $model,
  10653. 'video_resolution' => $video_resolution,
  10654. 'ratio' => $ratio,
  10655. 'updated_at' => date('Y-m-d H:i:s')
  10656. ]);
  10657. if ($result === false) {
  10658. Utils::throwError('20003:分集视频参数保存失败');
  10659. }
  10660. // 同步更新mp_animes表
  10661. $anime_result = DB::table('mp_animes')->where('id', $episode->anime_id)->update([
  10662. 'video_model' => $model,
  10663. 'video_resolution' => $video_resolution,
  10664. 'video_ratio' => $ratio,
  10665. 'updated_at' => date('Y-m-d H:i:s')
  10666. ]);
  10667. if ($anime_result === false) {
  10668. Utils::throwError('20003:动漫视频参数保存失败');
  10669. }
  10670. } catch (\Exception $e) {
  10671. DB::rollBack();
  10672. Utils::throwError('20003:'.$e->getMessage());
  10673. }
  10674. DB::commit();
  10675. return $result;
  10676. }
  10677. public function confirmActs($data) {
  10678. $episode_id = getProp($data, 'episode_id');
  10679. $episode = DB::table('mp_anime_episodes')->where('id', $episode_id)->first();
  10680. if (!$episode) {
  10681. Utils::throwError('20003:分集不存在');
  10682. }
  10683. $roles = json_decode(getProp($episode, 'roles'), true) ?: [];
  10684. $scenes = json_decode(getProp($episode, 'scenes'), true) ?: [];
  10685. $props = json_decode(getProp($episode, 'props'), true) ?: [];
  10686. // 确认前校验并等待角色、场景、道具图片全部生成(参照 episodePicsInfo 更新与监控逻辑),未全部生成不得继续后续逻辑
  10687. $this->waitForEpisodeAssetsImagesReady($episode_id, $roles, $scenes, $props);
  10688. // 获取所有片段数据
  10689. $acts = DB::table('mp_episode_segments')->where('episode_id', $episode_id)->orderBy('act_number')->get();
  10690. // 先构建完整的 products(角色、场景、道具、extra_products,并用资产库映射覆盖),
  10691. // 再处理每个片段的 act_content,避免 extra_products 等资产名未被格式化为 {资产名}
  10692. // 合并角色、场景、道具和extra_products作为products,统一字段名为product_name
  10693. // extra_products优先级更高,会覆盖同名的roles、scenes和props
  10694. $products = [];
  10695. // 先处理角色数组
  10696. foreach ($roles as $role) {
  10697. $product = $role;
  10698. // 将role字段重命名为product_name
  10699. if (isset($product['role'])) {
  10700. $product['product_name'] = $product['role'];
  10701. unset($product['role']);
  10702. $product['product'] = 1; // 标记类型为角色
  10703. $products[$product['product_name']] = $product; // 使用product_name作为key便于后续覆盖
  10704. }
  10705. }
  10706. // 处理场景数组
  10707. foreach ($scenes as $scene) {
  10708. $product = $scene;
  10709. // 将scene字段重命名为product_name
  10710. if (isset($product['scene'])) {
  10711. $product['product_name'] = $product['scene'];
  10712. unset($product['scene']);
  10713. $product['product'] = 2; // 标记类型为场景
  10714. $products[$product['product_name']] = $product; // 使用product_name作为key便于后续覆盖
  10715. }
  10716. }
  10717. // 处理道具数组(逻辑与场景一致)
  10718. foreach ($props as $prop) {
  10719. $product = $prop;
  10720. // 将prop字段重命名为product_name
  10721. if (isset($product['prop'])) {
  10722. $product['product_name'] = $product['prop'];
  10723. unset($product['prop']);
  10724. $product['product'] = 3; // 标记类型为道具
  10725. $products[$product['product_name']] = $product; // 使用product_name作为key便于后续覆盖
  10726. }
  10727. }
  10728. // extra_products优先级更高,直接覆盖同名的roles和scenes
  10729. $extra_products = json_decode(getProp($episode, 'extra_products', '[]'), true) ?: [];
  10730. foreach ($extra_products as $extra_product) {
  10731. $product_name = getProp($extra_product, 'product_name');
  10732. if ($product_name) {
  10733. $products[$product_name] = $extra_product; // 覆盖同名数据
  10734. }
  10735. }
  10736. // mp_script_product_mappings 信息优先级更高:
  10737. // 获取当前剧集所属动漫剧本下、与本集资产同名的资产库最新数据(url/三视图/提示词等),
  10738. // 覆盖分集 JSON 中保存的同名旧快照;分集内独有的 description、voice_prompt 等字段保留
  10739. $anime = DB::table('mp_animes')->where('id', getProp($episode, 'anime_id'))->first();
  10740. $script_id = $anime ? (int)getProp($anime, 'script_id', 0) : 0;
  10741. if ($script_id && !empty($products)) {
  10742. $currentProductNames = array_keys($products);
  10743. $normalizeName = function($name) {
  10744. return trim(preg_replace(
  10745. '/^[\s*\[\]【】[]{}{}\x{3000}]+|[\s*\[\]【】[]{}{}\x{3000}]+$/u',
  10746. '',
  10747. trim((string)$name)
  10748. ));
  10749. };
  10750. $mappingItems = DB::table('mp_script_product_mappings as mapping')
  10751. ->join('mp_products as product', 'mapping.product_id', '=', 'product.id')
  10752. ->where('mapping.script_id', $script_id)
  10753. ->where('product.is_deleted', 0)
  10754. ->whereIn('product.product_name', $currentProductNames)
  10755. ->select(
  10756. 'mapping.product_id',
  10757. 'product.product_name',
  10758. 'product.product',
  10759. 'product.pic_prompt',
  10760. 'product.url',
  10761. 'product.three_view_image_url',
  10762. 'product.timbre_url',
  10763. )
  10764. ->get();
  10765. $mappingByName = [];
  10766. foreach ($mappingItems as $mappingItem) {
  10767. $normalizedName = $normalizeName($mappingItem->product_name);
  10768. if (!$normalizedName) continue;
  10769. $mappingProduct = [
  10770. 'product_id' => (int)$mappingItem->product_id,
  10771. 'product_name' => $mappingItem->product_name,
  10772. 'product' => (int)$mappingItem->product,
  10773. 'pic_prompt' => $mappingItem->pic_prompt ?? '',
  10774. 'url' => $mappingItem->url ?? '',
  10775. 'three_view_image_url' => $mappingItem->three_view_image_url ?? '',
  10776. ];
  10777. // 音色音频:资产库有值时才覆盖分集自带的值,避免空值把已有音色清掉
  10778. if (!empty($mappingItem->timbre_url)) {
  10779. $mappingProduct['timbre_url'] = $mappingItem->timbre_url;
  10780. }
  10781. $mappingByName[$normalizedName] = $mappingProduct;
  10782. }
  10783. foreach ($products as $key => &$product) {
  10784. $normalizedKey = $normalizeName($key);
  10785. if ($normalizedKey && isset($mappingByName[$normalizedKey])) {
  10786. $product = array_merge($product, $mappingByName[$normalizedKey]);
  10787. }
  10788. }
  10789. unset($product);
  10790. }
  10791. // 兼容返回 three_view_image_url / timbre_url 字段(旧数据可能没有该键,统一补空值)
  10792. foreach ($products as &$product) {
  10793. if (!isset($product['three_view_image_url'])) {
  10794. $product['three_view_image_url'] = '';
  10795. }
  10796. if (!isset($product['timbre_url'])) {
  10797. $product['timbre_url'] = '';
  10798. }
  10799. }
  10800. unset($product);
  10801. // 重新索引数组(去除key)
  10802. $products = array_values($products);
  10803. // 基于构建完成的 products 收集所有资产名称(含 extra_products 中的资产)
  10804. $product_names = [];
  10805. foreach ($products as $product) {
  10806. $product_name = getProp($product, 'product_name');
  10807. if ($product_name && $product_name !== '旁白') {
  10808. $product_names[] = $product_name;
  10809. }
  10810. }
  10811. // 去重并按长度降序排序(避免短名称先匹配到长名称的一部分)
  10812. $product_names = array_unique($product_names);
  10813. usort($product_names, function($a, $b) {
  10814. return mb_strlen($b) - mb_strlen($a);
  10815. });
  10816. try {
  10817. DB::beginTransaction();
  10818. // 处理每个片段
  10819. foreach ($acts as $act) {
  10820. $act_content = getProp($act, 'act_content');
  10821. if (!$act_content) continue;
  10822. $processed_content = $act_content;
  10823. // 统一替换所有资产名称为 {资产名} 格式
  10824. // 使用占位符避免嵌套替换问题
  10825. $placeholder_map = [];
  10826. $placeholder_index = 0;
  10827. foreach ($product_names as $product_name) {
  10828. // 转义特殊字符
  10829. $escaped_product = preg_quote($product_name, '/');
  10830. // 检查是否匹配且未被 {} 包裹
  10831. $processed_content = preg_replace_callback(
  10832. '/(?<![{])(' . $escaped_product . ')(?![}])/u',
  10833. function($matches) use (&$placeholder_map, &$placeholder_index) {
  10834. // 使用唯一占位符
  10835. $placeholder = '<<<PLACEHOLDER_' . $placeholder_index . '>>>';
  10836. $placeholder_map[$placeholder] = '{' . $matches[1] . '}';
  10837. $placeholder_index++;
  10838. return $placeholder;
  10839. },
  10840. $processed_content
  10841. );
  10842. }
  10843. // 将所有占位符替换回实际内容
  10844. foreach ($placeholder_map as $placeholder => $replacement) {
  10845. $processed_content = str_replace($placeholder, $replacement, $processed_content);
  10846. }
  10847. // 处理【镜头X】或【分镜X】重新编号为从1开始的连续整数【镜头X】
  10848. $shot_counter = 0;
  10849. $processed_content = preg_replace_callback(
  10850. '/【(?:镜头|分镜)(\d+)】/u',
  10851. function($matches) use (&$shot_counter) {
  10852. $shot_counter++;
  10853. return '【镜头' . $shot_counter . '】';
  10854. },
  10855. $processed_content
  10856. );
  10857. // 按动漫画风给 act_show_content 的「画面:[…]」插入画风提示词
  10858. // 总开关 config('anime.act_show_art_style_enabled') 默认关闭,只处理 act_show_content
  10859. $processed_content = ActShowContent::insertArtStylePrompt($processed_content, getProp($episode, 'anime_id'));
  10860. // 更新数据库
  10861. $boolen = DB::table('mp_episode_segments')
  10862. ->where('id', $act->id)
  10863. ->update([
  10864. 'act_show_content' => $processed_content,
  10865. 'updated_at' => date('Y-m-d H:i:s')
  10866. ]);
  10867. if (!$boolen) {
  10868. Utils::throwError('20003:片段处理失败');
  10869. }
  10870. }
  10871. }catch (\Exception $e) {
  10872. DB::rollBack();
  10873. Utils::throwError('20003:'.$e->getMessage());
  10874. }
  10875. $boolen1 = DB::table('mp_anime_episodes')->where('id', $episode_id)->update([
  10876. 'is_generated' => 1,
  10877. 'updated_at' => date('Y-m-d H:i:s')
  10878. ]);
  10879. if (!$boolen1) {
  10880. DB::rollBack();
  10881. Utils::throwError('20003:分集处理失败!');
  10882. }
  10883. DB::commit();
  10884. // 重新查询更新后的片段数据
  10885. $acts = DB::table('mp_episode_segments')->where('episode_id', $episode_id)->orderBy('act_number')->get();
  10886. // 构建返回的acts数组
  10887. $return_acts = [];
  10888. foreach ($acts as $act) {
  10889. $return_acts[] = [
  10890. 'act_id' => getProp($act, 'id'),
  10891. 'act_number' => getProp($act, 'act_number'),
  10892. 'act_duration' => getProp($act, 'video_duration') ? getProp($act, 'video_duration') : getProp($act, 'act_duration'),
  10893. 'act_show_content' => getProp($act, 'act_show_content'),
  10894. 'video_url' => getProp($act, 'video_url'),
  10895. 'video_duration' => getProp($act, 'video_duration'),
  10896. 'video_time_point_start' => getProp($act, 'video_time_point_start'),
  10897. 'video_time_point_end' => getProp($act, 'video_time_point_end'),
  10898. ];
  10899. }
  10900. return [
  10901. 'anime_id' => getProp($episode, 'anime_id'),
  10902. 'episode_id' => $episode_id,
  10903. 'title' => getProp($episode, 'title'),
  10904. 'episode_number' => getProp($episode, 'episode_number'),
  10905. 'is_generated' => getProp($episode, 'is_generated'),
  10906. 'video_params' => [
  10907. 'video_model' => getProp($episode, 'video_model'),
  10908. 'video_resolution' => getProp($episode, 'video_resolution'),
  10909. 'ratio' => getProp($episode, 'ratio'),
  10910. ],
  10911. 'products' => $products,
  10912. 'acts' => $return_acts
  10913. ];
  10914. }
  10915. /**
  10916. * 参照 episodePicsInfo 的更新与监控逻辑:
  10917. * 每5秒查询一次角色/场景/道具的图片任务状态,任务成功后将图片URL回填到对应资产并写回分集表。
  10918. * 所有需要图片的资产均已生成(url 非空)才返回;最多等待1分钟,仍有图片未生成则直接报错。
  10919. */
  10920. private function waitForEpisodeAssetsImagesReady($episode_id, &$roles, &$scenes, &$props) {
  10921. $pollInterval = 5; // 每5秒查询一次
  10922. $maxWaitSeconds = 60; // 最多持续1分钟
  10923. $startTime = time();
  10924. while (true) {
  10925. // 从数据库读取最新数据,兼容后台 Anime:checkImgUrl 等任务对角色/场景/道具图片URL的更新
  10926. $episode = DB::table('mp_anime_episodes')->where('id', $episode_id)->first();
  10927. if (!$episode) {
  10928. Utils::throwError('20003:分集不存在');
  10929. }
  10930. $roles = json_decode(getProp($episode, 'roles'), true) ?: [];
  10931. $scenes = json_decode(getProp($episode, 'scenes'), true) ?: [];
  10932. $props = json_decode(getProp($episode, 'props'), true) ?: [];
  10933. $updated = false;
  10934. $waitingAssets = []; // 任务仍在处理中,可等待后续轮询
  10935. $missingAssets = []; // 无任务或任务已失败/不存在,无法通过等待自动恢复
  10936. $this->refreshEpisodeAssetsImageTasks($roles, 'role', '旁白', $waitingAssets, $missingAssets, $updated);
  10937. $this->refreshEpisodeAssetsImageTasks($scenes, 'scene', '', $waitingAssets, $missingAssets, $updated);
  10938. $this->refreshEpisodeAssetsImageTasks($props, 'prop', '', $waitingAssets, $missingAssets, $updated);
  10939. // 有图片任务结果更新时写回分集表
  10940. if ($updated) {
  10941. DB::table('mp_anime_episodes')->where('id', $episode_id)->update([
  10942. 'roles' => json_encode($roles, JSON_UNESCAPED_UNICODE),
  10943. 'scenes' => json_encode($scenes, JSON_UNESCAPED_UNICODE),
  10944. 'props' => json_encode($props, JSON_UNESCAPED_UNICODE),
  10945. 'updated_at' => date('Y-m-d H:i:s')
  10946. ]);
  10947. }
  10948. // 所有需要图片的资产都已生成,允许继续 confirmActs 后续逻辑
  10949. if (empty($waitingAssets) && empty($missingAssets)) {
  10950. return;
  10951. }
  10952. // 其他任务都已处理完毕,仍有角色、场景或道具图片未生成,统一报错阻止后续逻辑
  10953. if (empty($waitingAssets)) {
  10954. Utils::throwError('20003:还有主体、场景或道具图片未生成,请等待图片生成后重试');
  10955. }
  10956. // 超过1分钟仍未生成完毕,阻止 confirmActs 后续逻辑
  10957. if (time() - $startTime >= $maxWaitSeconds) {
  10958. Utils::throwError('20003:还有主体、场景或道具图片未生成,请等待图片生成后重试');
  10959. }
  10960. sleep($pollInterval);
  10961. }
  10962. }
  10963. /**
  10964. * 参照 episodePicsInfo:遍历单个资产列表,对有图片任务但还没有图片URL的资产查询图片任务结果并回填。
  10965. * 无任务、任务不存在或生成失败的资产记录为缺失项,不在此处直接报错;
  10966. * 仍在处理中的任务记录为等待项,由外层统一等待所有任务完成后,再对缺失资产统一报错。
  10967. */
  10968. private function refreshEpisodeAssetsImageTasks(&$assets, $nameKey, $skipName, &$waitingAssets, &$missingAssets, &$updated) {
  10969. foreach ($assets as &$asset) {
  10970. $assetName = getProp($asset, $nameKey);
  10971. if ($assetName === '' || ($skipName !== '' && $assetName === $skipName)) {
  10972. continue;
  10973. }
  10974. // 已有图片URL的资产视为已生成
  10975. if (getProp($asset, 'url')) {
  10976. continue;
  10977. }
  10978. $task_id = getProp($asset, 'task_id');
  10979. // 没有图片任务且没有图片URL:记录为缺失项,继续遍历其他资产,待其他任务都完成后再统一报错
  10980. if (!$task_id) {
  10981. $missingAssets[] = $assetName;
  10982. continue;
  10983. }
  10984. $task = DB::table('mp_generate_pic_tasks')
  10985. ->where('id', $task_id)
  10986. ->select('status', 'result_url')
  10987. ->first();
  10988. // 任务不存在:同样记录为缺失项,不在此处直接报错
  10989. if (!$task) {
  10990. $missingAssets[] = $assetName;
  10991. continue;
  10992. }
  10993. if ($task->status === 'success') {
  10994. $result_url = getProp($task, 'result_url');
  10995. if ($result_url) {
  10996. $result_urls = is_json($result_url) ? json_decode($result_url, true) : [$result_url];
  10997. if (is_array($result_urls) && !empty($result_urls[0])) {
  10998. $asset['url'] = $result_urls[0];
  10999. $asset['task_status'] = 'success';
  11000. $updated = true;
  11001. continue;
  11002. }
  11003. }
  11004. // 任务成功但没有可用的结果URL,仍视为未生成,继续等待后续轮询结果
  11005. $waitingAssets[] = $assetName;
  11006. } elseif ($task->status === 'failed') {
  11007. // 生成失败:记录为缺失项,待其他任务处理完后统一报错
  11008. $missingAssets[] = $assetName;
  11009. } else {
  11010. // 任务仍在生成中,等待下一次轮询
  11011. $waitingAssets[] = $assetName;
  11012. }
  11013. }
  11014. unset($asset);
  11015. }
  11016. /**
  11017. * 导出动漫剧本为PDF(参照示例PDF版式)
  11018. * @param int $animeId 动漫ID
  11019. * @param int $episodeCount 导出集数,默认8,传-1表示全部
  11020. * @param string|null $savePath 指定保存路径(为空则直接下载输出)
  11021. * @return string|null
  11022. */
  11023. public function exportAnimeScriptAsPdf($animeId, $episodeCount = 8, $savePath = null) {
  11024. // 图片下载与转换可能占用较多内存
  11025. ini_set('memory_limit', '512M');
  11026. $anime = DB::table('mp_animes')->where('id', $animeId)->where('is_deleted', 0)->first();
  11027. if (!$anime) Utils::throwError('20003:该动漫不存在!');
  11028. $anime = (array)$anime;
  11029. // 剧本名去掉末尾"_数字"标识后缀,只保留剧名本身
  11030. $anime['anime_name'] = trim((string)preg_replace('/_\d+$/u', '', getProp($anime, 'anime_name', '')));
  11031. // 获取分集(默认展示版本,按集数升序)
  11032. $episodeQuery = DB::table('mp_anime_episodes')
  11033. ->where('anime_id', $animeId)
  11034. ->where('is_default', 1)
  11035. ->orderBy('episode_number')
  11036. ->orderBy('id');
  11037. if ($episodeCount > 0) {
  11038. $episodeQuery->limit($episodeCount);
  11039. }
  11040. $episodes = $episodeQuery->get()->map(function ($value) {
  11041. return (array)$value;
  11042. })->toArray();
  11043. if (!$episodes) Utils::throwError('20003:该动漫暂无分集数据');
  11044. // 聚合主体/场景/道具列表(前N集内容,按名称去重)
  11045. $roles = $this->mergeEpisodeItems($episodes, 'role');
  11046. $scenes = $this->mergeEpisodeItems($episodes, 'scene');
  11047. $props = $this->mergeEpisodeItems($episodes, 'prop');
  11048. // 组装分集剧本数据
  11049. $episodeScripts = [];
  11050. foreach ($episodes as $episode) {
  11051. $segments = DB::table('mp_episode_segments')
  11052. ->where('anime_id', $animeId)
  11053. ->where('episode_id', $episode['id'])
  11054. ->get();
  11055. // 按act_number分组,同一片段多版本时取最新一条(id最大)
  11056. $acts = [];
  11057. foreach ($segments as $segment) {
  11058. $segment = (array)$segment;
  11059. $actNumber = (int)getProp($segment, 'act_number', 0);
  11060. if ($actNumber <= 0) continue;
  11061. if (!isset($acts[$actNumber]) || (int)$segment['id'] > (int)$acts[$actNumber]['id']) {
  11062. $acts[$actNumber] = [
  11063. 'id' => (int)$segment['id'],
  11064. 'act_number' => $actNumber,
  11065. 'duration' => getProp($segment, 'act_duration', ''),
  11066. 'content' => getProp($segment, 'act_content', ''),
  11067. ];
  11068. }
  11069. }
  11070. ksort($acts);
  11071. // 分镜序号按出现先后重新编号(整集范围内保持连续,兼容【镜头N】/【分镜N】两种格式)
  11072. $segmentCounter = 0;
  11073. foreach ($acts as &$act) {
  11074. $act['content'] = $this->renumberSegmentBlocks($act['content'], $segmentCounter);
  11075. }
  11076. unset($act);
  11077. // 旁白音色:优先取分集roles中"旁白"的voice_prompt,否则从片段内容解析
  11078. $narratorVoice = '';
  11079. $episodeRoles = json_decode(getProp($episode, 'roles', ''), true) ?: [];
  11080. foreach ($episodeRoles as $role) {
  11081. if (getProp($role, 'role') === '旁白') {
  11082. $narratorVoice = trim((string)getProp($role, 'voice_prompt', ''));
  11083. break;
  11084. }
  11085. }
  11086. if ($narratorVoice === '') {
  11087. foreach ($acts as $act) {
  11088. if (preg_match('/旁白音色[::]\s*([^\n]+)/u', $act['content'], $match)) {
  11089. $narratorVoice = trim($match[1]);
  11090. break;
  11091. }
  11092. }
  11093. }
  11094. $episodeScripts[] = [
  11095. 'episode_number' => getProp($episode, 'episode_number'),
  11096. 'title' => getProp($episode, 'title', ''),
  11097. 'act_count' => count($acts),
  11098. 'narrator_voice' => $narratorVoice,
  11099. 'acts' => array_values($acts),
  11100. ];
  11101. }
  11102. // 并发下载列表图片(主体/场景/道具),url => 临时文件
  11103. $imageCache = $this->downloadImagesConcurrently(array_merge($roles, $scenes, $props));
  11104. // 构建PDF
  11105. $pdf = $this->buildAnimeScriptPdf($anime, $roles, $scenes, $props, $episodeScripts, $imageCache);
  11106. // 图片已嵌入PDF,清理临时文件
  11107. foreach ($imageCache as $imgFile) {
  11108. @unlink($imgFile);
  11109. }
  11110. $filename = $anime['anime_name'] . '_' . date('YmdHis');
  11111. if ($savePath) {
  11112. $pdf->Output($savePath, 'F');
  11113. return $savePath;
  11114. }
  11115. // 直接下载输出
  11116. header('Content-Type: application/pdf');
  11117. header("Content-Disposition: attachment; filename*=UTF-8''" . rawurlencode($filename . '.pdf'));
  11118. $pdf->Output($filename . '.pdf', 'D');
  11119. exit();
  11120. }
  11121. /**
  11122. * 聚合分集的主体/场景/道具列表,按名称去重(保留首次出现)
  11123. * @param array $episodes 分集数据
  11124. * @param string $nameKey role|scene|prop
  11125. * @return array
  11126. */
  11127. private function mergeEpisodeItems(array $episodes, $nameKey) {
  11128. $fieldMap = [
  11129. 'role' => 'roles',
  11130. 'scene' => 'scenes',
  11131. 'prop' => 'props',
  11132. ];
  11133. $field = isset($fieldMap[$nameKey]) ? $fieldMap[$nameKey] : $nameKey;
  11134. $items = [];
  11135. foreach ($episodes as $episode) {
  11136. $list = json_decode(getProp($episode, $field, ''), true) ?: [];
  11137. foreach ($list as $item) {
  11138. if (!is_array($item)) continue;
  11139. $name = trim((string)getProp($item, $nameKey, ''));
  11140. if ($name === '') continue;
  11141. // 旁白不进入主体列表(仅作为旁白音色来源)
  11142. if ($nameKey === 'role' && $name === '旁白') continue;
  11143. if (!isset($items[$name])) {
  11144. $items[$name] = $item;
  11145. }
  11146. }
  11147. }
  11148. return array_values($items);
  11149. }
  11150. /**
  11151. * 构建动漫剧本PDF
  11152. * @param array $anime 动漫信息
  11153. * @param array $roles 主体列表
  11154. * @param array $scenes 场景列表
  11155. * @param array $props 道具列表
  11156. * @param array $episodeScripts 分集剧本数据
  11157. * @param array $imageCache 图片缓存(url => 临时文件路径)
  11158. * @return \TCPDF
  11159. */
  11160. private function buildAnimeScriptPdf($anime, $roles, $scenes, $props, $episodeScripts, $imageCache = []) {
  11161. $pdf = new \TCPDF('P', 'mm', 'A4', true, 'UTF-8', false);
  11162. $pdf->SetCreator('动漫剧本导出系统');
  11163. $pdf->SetAuthor('系统');
  11164. $pdf->SetTitle(getProp($anime, 'anime_name', '动漫剧本'));
  11165. $pdf->SetSubject('动漫剧本导出');
  11166. $pdf->SetMargins(15, 15, 15);
  11167. $pdf->SetAutoPageBreak(true, 15);
  11168. // 剧本名
  11169. $pdf->AddPage();
  11170. $pdf->SetFont('simsun', 'B', 20);
  11171. $pdf->Cell(0, 15, getProp($anime, 'anime_name', ''), 0, 1, 'C');
  11172. $pdf->Ln(5);
  11173. // 故事梗概
  11174. $intro = trim((string)getProp($anime, 'intro', ''));
  11175. if ($intro !== '') {
  11176. $this->pdfSectionTitle($pdf, '故事梗概');
  11177. $this->pdfBody($pdf, $intro);
  11178. }
  11179. // 美术风格
  11180. $artStyle = trim((string)getProp($anime, 'art_style', ''));
  11181. if ($artStyle !== '') {
  11182. $this->pdfSectionTitle($pdf, '美术风格');
  11183. $this->pdfBody($pdf, $artStyle);
  11184. }
  11185. // 主体列表(文字+图片)
  11186. $this->pdfSectionTitle($pdf, '主体列表');
  11187. foreach ($roles as $index => $role) {
  11188. $this->pdfBody($pdf, ($index + 1) . '. ' . getProp($role, 'role', '') . ':' . getProp($role, 'description', ''));
  11189. }
  11190. $this->pdfItemImages($pdf, $roles, 'role', $imageCache);
  11191. // 场景列表(文字+图片)
  11192. $this->pdfSectionTitle($pdf, '场景列表');
  11193. foreach ($scenes as $index => $scene) {
  11194. $this->pdfBody($pdf, ($index + 1) . '. ' . getProp($scene, 'scene', '') . ':' . getProp($scene, 'description', ''));
  11195. }
  11196. $this->pdfItemImages($pdf, $scenes, 'scene', $imageCache);
  11197. // 道具列表(文字+图片)
  11198. $this->pdfSectionTitle($pdf, '道具列表');
  11199. foreach ($props as $index => $prop) {
  11200. $this->pdfBody($pdf, ($index + 1) . '. ' . getProp($prop, 'prop', '') . ':' . getProp($prop, 'description', ''));
  11201. }
  11202. $this->pdfItemImages($pdf, $props, 'prop', $imageCache);
  11203. // 分镜剧本
  11204. $this->pdfSectionTitle($pdf, '分镜剧本');
  11205. foreach ($episodeScripts as $episodeScript) {
  11206. $episodeTitle = '第' . getProp($episodeScript, 'episode_number') . '集';
  11207. $episodeTitleRaw = trim((string)getProp($episodeScript, 'title', ''));
  11208. if ($episodeTitleRaw !== '') {
  11209. // title 字段可能已带"第N集"前缀,避免重复
  11210. if (preg_match('/^第\d+集[::\s]/u', $episodeTitleRaw)) {
  11211. $episodeTitle = $episodeTitleRaw;
  11212. } else {
  11213. $episodeTitle .= ':' . $episodeTitleRaw;
  11214. }
  11215. }
  11216. $this->pdfSubTitle($pdf, $episodeTitle, 13);
  11217. $this->pdfBody($pdf, '片段数量:' . getProp($episodeScript, 'act_count', 0));
  11218. if (getProp($episodeScript, 'narrator_voice') !== '') {
  11219. $this->pdfBody($pdf, '旁白音色:' . getProp($episodeScript, 'narrator_voice'));
  11220. }
  11221. foreach (getProp($episodeScript, 'acts', []) as $act) {
  11222. $actTitle = '片段' . getProp($act, 'act_number');
  11223. if (getProp($act, 'duration') !== '' && getProp($act, 'duration') !== null) {
  11224. $actTitle .= ' 时长 ' . getProp($act, 'duration') . 's';
  11225. }
  11226. $this->pdfSubTitle($pdf, $actTitle, 12);
  11227. if (getProp($act, 'content') !== '') {
  11228. $this->pdfBody($pdf, getProp($act, 'content'));
  11229. }
  11230. }
  11231. }
  11232. return $pdf;
  11233. }
  11234. /**
  11235. * PDF章节标题(带分隔线)
  11236. */
  11237. private function pdfSectionTitle($pdf, $title) {
  11238. if ($pdf->GetY() > 230) {
  11239. $pdf->AddPage();
  11240. }
  11241. $pdf->SetFont('simsun', 'B', 15);
  11242. $pdf->Cell(0, 10, $title, 0, 1, 'L');
  11243. $y = $pdf->GetY();
  11244. $pdf->SetLineWidth(0.4);
  11245. $pdf->Line(15, $y, 195, $y);
  11246. $pdf->Ln(4);
  11247. }
  11248. /**
  11249. * PDF子标题(集数/片段标题)
  11250. */
  11251. private function pdfSubTitle($pdf, $title, $size = 13) {
  11252. if ($pdf->GetY() > 240) {
  11253. $pdf->AddPage();
  11254. }
  11255. $pdf->SetFont('simsun', 'B', $size);
  11256. $pdf->Cell(0, 8, $title, 0, 1, 'L');
  11257. $pdf->Ln(1);
  11258. }
  11259. /**
  11260. * PDF正文段落
  11261. */
  11262. private function pdfBody($pdf, $text) {
  11263. $pdf->SetFont('simsun', '', 11);
  11264. $pdf->MultiCell(0, 6, $text, 0, 'L');
  11265. $pdf->Ln(2);
  11266. }
  11267. /**
  11268. * 输出列表项图片(每张图单独一页,图下标注名称)
  11269. * @param \TCPDF $pdf
  11270. * @param array $items 列表项
  11271. * @param string $nameKey role|scene|prop
  11272. * @param array $imageCache 图片缓存(url => 临时文件路径)
  11273. */
  11274. private function pdfItemImages($pdf, array $items, $nameKey, array $imageCache) {
  11275. foreach ($items as $item) {
  11276. $url = trim((string)getProp($item, 'url', ''));
  11277. $name = trim((string)getProp($item, $nameKey, ''));
  11278. if ($url === '' || !isset($imageCache[$url])) continue;
  11279. $imgPath = $imageCache[$url];
  11280. $size = @getimagesize($imgPath);
  11281. if (!$size || $size[0] <= 0 || $size[1] <= 0) {
  11282. continue;
  11283. }
  11284. $pdf->AddPage();
  11285. // 图片按比例缩放,居中偏上,为底部名称标注预留空间
  11286. $maxW = 160;
  11287. $maxH = 170;
  11288. $ratio = min($maxW / $size[0], $maxH / $size[1], 1);
  11289. $drawW = $size[0] * $ratio;
  11290. $drawH = $size[1] * $ratio;
  11291. $x = (210 - $drawW) / 2;
  11292. $y = max(15, (297 - $drawH) / 2 - 10);
  11293. $pdf->Image($imgPath, $x, $y, $drawW, $drawH, '', '', '', false, 300, '', false, false, 0, false, false, false);
  11294. // 图下标注名称
  11295. $pdf->SetFont('simsun', 'B', 13);
  11296. $pdf->SetY(297 - 28);
  11297. $pdf->Cell(0, 8, $name, 0, 1, 'C');
  11298. }
  11299. }
  11300. /**
  11301. * 并发下载远程图片到临时文件,并统一缩放转为JPEG
  11302. * @param array $items 包含url字段的列表项
  11303. * @return array url => 临时文件路径
  11304. */
  11305. private function downloadImagesConcurrently(array $items) {
  11306. // 收集唯一的图片URL
  11307. $urls = [];
  11308. foreach ($items as $item) {
  11309. $url = trim((string)getProp($item, 'url', ''));
  11310. if ($url !== '') $urls[$url] = true;
  11311. }
  11312. if (!$urls) return [];
  11313. $urls = array_keys($urls);
  11314. $tmpDir = sys_get_temp_dir();
  11315. $rawFiles = [];
  11316. foreach ($urls as $url) {
  11317. $rawFile = $tmpDir . '/anime_pdf_raw_' . md5($url) . '.img';
  11318. $rawFiles[$url] = $rawFile;
  11319. }
  11320. $client = new Client(['timeout' => 180, 'verify' => false]);
  11321. // 低并发下载,sink写入文件避免大图占用内存
  11322. $generator = (function () use ($urls, $client, $rawFiles) {
  11323. foreach ($urls as $url) {
  11324. yield $url => $client->getAsync($url, ['sink' => $rawFiles[$url]]);
  11325. }
  11326. })();
  11327. $errors = [];
  11328. $each = new \GuzzleHttp\Promise\EachPromise($generator, [
  11329. 'concurrency' => 4,
  11330. 'rejected' => function ($reason, $url) use (&$errors) {
  11331. $errors[$url] = $reason ? $reason->getMessage() : 'unknown';
  11332. },
  11333. ]);
  11334. $each->promise()->wait();
  11335. // 失败的图片串行重试一次(独占带宽,提高成功率)
  11336. foreach ($urls as $url) {
  11337. if (!isset($errors[$url])) continue;
  11338. try {
  11339. $client->get($url, ['sink' => $rawFiles[$url], 'timeout' => 300]);
  11340. unset($errors[$url]);
  11341. } catch (\Throwable $e) {
  11342. // 重试仍失败
  11343. }
  11344. }
  11345. $cache = [];
  11346. foreach ($urls as $url) {
  11347. $rawFile = $rawFiles[$url];
  11348. if (isset($errors[$url])) {
  11349. dLog('anime')->error('导出PDF图片下载失败', [
  11350. 'url' => $url,
  11351. 'error' => $errors[$url],
  11352. ]);
  11353. @unlink($rawFile);
  11354. continue;
  11355. }
  11356. $converted = $this->convertImageFile($rawFile, $url);
  11357. if ($converted !== null) {
  11358. $cache[$url] = $converted;
  11359. } else {
  11360. @unlink($rawFile);
  11361. }
  11362. }
  11363. return $cache;
  11364. }
  11365. /**
  11366. * 将已下载的图片文件缩放并转为JPEG
  11367. * @param string $rawFile 原始图片临时文件
  11368. * @param string $url 图片地址(用于命名)
  11369. * @return string|null 转换后的文件路径,转换失败返回null
  11370. */
  11371. private function convertImageFile($rawFile, $url) {
  11372. $content = @file_get_contents($rawFile);
  11373. if ($content === false || $content === '') return null;
  11374. if (!function_exists('imagecreatefromstring')) return null;
  11375. $image = @imagecreatefromstring($content);
  11376. if ($image === false) return null;
  11377. $jpeg = $this->compressImageForPdf($image, $rawFile, $url);
  11378. imagedestroy($image);
  11379. if ($jpeg !== null) {
  11380. @unlink($rawFile);
  11381. }
  11382. return $jpeg;
  11383. }
  11384. /**
  11385. * 图片压缩:白底合成后转JPEG,分级缩小尺寸与降低质量,保证每张不超过2MB
  11386. * @param resource $srcImage GD图片资源
  11387. * @param string $rawFile 原始图片临时文件
  11388. * @param string $url 图片地址(用于命名)
  11389. * @return string|null 压缩后的JPEG文件路径
  11390. */
  11391. private function compressImageForPdf($srcImage, $rawFile, $url) {
  11392. $maxBytes = 2 * 1024 * 1024; // 2MB
  11393. $sizes = [2048, 1600, 1280, 1024, 800];
  11394. $qualities = [85, 70, 55, 40];
  11395. $jpeg = dirname($rawFile) . '/anime_pdf_img_' . md5($url) . '.jpg';
  11396. foreach ($sizes as $size) {
  11397. $resized = $this->copyAndResize($srcImage, $size);
  11398. $flat = $this->flattenToWhite($resized);
  11399. imagedestroy($resized);
  11400. foreach ($qualities as $quality) {
  11401. ob_start();
  11402. $saved = imagejpeg($flat, null, $quality);
  11403. $data = ob_get_clean();
  11404. if ($saved && $data !== false && $data !== '' && strlen($data) <= $maxBytes) {
  11405. file_put_contents($jpeg, $data);
  11406. imagedestroy($flat);
  11407. dLog('anime')->info('导出PDF图片压缩完成', [
  11408. 'url' => $url,
  11409. 'size' => filesize($jpeg),
  11410. 'edge' => $size,
  11411. 'quality' => $quality,
  11412. ]);
  11413. return $jpeg;
  11414. }
  11415. }
  11416. imagedestroy($flat);
  11417. }
  11418. // 兜底:最小尺寸、最低质量强制输出
  11419. $resized = $this->copyAndResize($srcImage, 800);
  11420. $flat = $this->flattenToWhite($resized);
  11421. imagedestroy($resized);
  11422. $saved = imagejpeg($flat, $jpeg, 30);
  11423. imagedestroy($flat);
  11424. if (!$saved) return null;
  11425. dLog('anime')->info('导出PDF图片压缩完成(兜底)', [
  11426. 'url' => $url,
  11427. 'size' => filesize($jpeg),
  11428. ]);
  11429. return $jpeg;
  11430. }
  11431. /**
  11432. * 等比缩放图片副本(不销毁原图)
  11433. * @param resource $srcImage GD图片资源
  11434. * @param int $maxEdge 最大边长
  11435. * @return resource
  11436. */
  11437. private function copyAndResize($srcImage, $maxEdge) {
  11438. $width = imagesx($srcImage);
  11439. $height = imagesy($srcImage);
  11440. $max = max($width, $height);
  11441. if ($max <= $maxEdge) {
  11442. $copy = imagecreatetruecolor($width, $height);
  11443. imagecopy($copy, $srcImage, 0, 0, 0, 0, $width, $height);
  11444. return $copy;
  11445. }
  11446. $ratio = $maxEdge / $max;
  11447. $newWidth = max(1, (int)round($width * $ratio));
  11448. $newHeight = max(1, (int)round($height * $ratio));
  11449. $resized = imagecreatetruecolor($newWidth, $newHeight);
  11450. imagealphablending($resized, false);
  11451. imagesavealpha($resized, true);
  11452. imagecopyresampled($resized, $srcImage, 0, 0, 0, 0, $newWidth, $newHeight, $width, $height);
  11453. return $resized;
  11454. }
  11455. /**
  11456. * 将GD图片合成到白色背景上(处理透明通道,输出RGB)
  11457. * @param resource $image GD图片资源
  11458. * @return resource
  11459. */
  11460. private function flattenToWhite($image) {
  11461. $width = imagesx($image);
  11462. $height = imagesy($image);
  11463. $flat = imagecreatetruecolor($width, $height);
  11464. $white = imagecolorallocate($flat, 255, 255, 255);
  11465. imagefill($flat, 0, 0, $white);
  11466. imagecopy($flat, $image, 0, 0, 0, 0, $width, $height);
  11467. return $flat;
  11468. }
  11469. /**
  11470. * 将片段内容中的分镜序号按出现先后重新编号(保证整集连续)
  11471. * @param string $content 片段内容
  11472. * @param int $counter 当前已编号数量(引用传递,整集累计)
  11473. * @return string
  11474. */
  11475. private function renumberSegmentBlocks($content, &$counter) {
  11476. return preg_replace_callback('/^【(分镜|镜头)\d+】/mu', function ($match) use (&$counter) {
  11477. $counter++;
  11478. return '【' . $match[1] . $counter . '】';
  11479. }, $content);
  11480. }
  11481. }