AnimeService.php 435 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695705715725735745755765775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206216226236246256266276286296306316326336346356366376386396406416426436446456466476486496506516526536546556566576586596606616626636646656666676686696706716726736746756766776786796806816826836846856866876886896906916926936946956966976986997007017027037047057067077087097107117127137147157167177187197207217227237247257267277287297307317327337347357367377387397407417427437447457467477487497507517527537547557567577587597607617627637647657667677687697707717727737747757767777787797807817827837847857867877887897907917927937947957967977987998008018028038048058068078088098108118128138148158168178188198208218228238248258268278288298308318328338348358368378388398408418428438448458468478488498508518528538548558568578588598608618628638648658668678688698708718728738748758768778788798808818828838848858868878888898908918928938948958968978988999009019029039049059069079089099109119129139149159169179189199209219229239249259269279289299309319329339349359369379389399409419429439449459469479489499509519529539549559569579589599609619629639649659669679689699709719729739749759769779789799809819829839849859869879889899909919929939949959969979989991000100110021003100410051006100710081009101010111012101310141015101610171018101910201021102210231024102510261027102810291030103110321033103410351036103710381039104010411042104310441045104610471048104910501051105210531054105510561057105810591060106110621063106410651066106710681069107010711072107310741075107610771078107910801081108210831084108510861087108810891090109110921093109410951096109710981099110011011102110311041105110611071108110911101111111211131114111511161117111811191120112111221123112411251126112711281129113011311132113311341135113611371138113911401141114211431144114511461147114811491150115111521153115411551156115711581159116011611162116311641165116611671168116911701171117211731174117511761177117811791180118111821183118411851186118711881189119011911192119311941195119611971198119912001201120212031204120512061207120812091210121112121213121412151216121712181219122012211222122312241225122612271228122912301231123212331234123512361237123812391240124112421243124412451246124712481249125012511252125312541255125612571258125912601261126212631264126512661267126812691270127112721273127412751276127712781279128012811282128312841285128612871288128912901291129212931294129512961297129812991300130113021303130413051306130713081309131013111312131313141315131613171318131913201321132213231324132513261327132813291330133113321333133413351336133713381339134013411342134313441345134613471348134913501351135213531354135513561357135813591360136113621363136413651366136713681369137013711372137313741375137613771378137913801381138213831384138513861387138813891390139113921393139413951396139713981399140014011402140314041405140614071408140914101411141214131414141514161417141814191420142114221423142414251426142714281429143014311432143314341435143614371438143914401441144214431444144514461447144814491450145114521453145414551456145714581459146014611462146314641465146614671468146914701471147214731474147514761477147814791480148114821483148414851486148714881489149014911492149314941495149614971498149915001501150215031504150515061507150815091510151115121513151415151516151715181519152015211522152315241525152615271528152915301531153215331534153515361537153815391540154115421543154415451546154715481549155015511552155315541555155615571558155915601561156215631564156515661567156815691570157115721573157415751576157715781579158015811582158315841585158615871588158915901591159215931594159515961597159815991600160116021603160416051606160716081609161016111612161316141615161616171618161916201621162216231624162516261627162816291630163116321633163416351636163716381639164016411642164316441645164616471648164916501651165216531654165516561657165816591660166116621663166416651666166716681669167016711672167316741675167616771678167916801681168216831684168516861687168816891690169116921693169416951696169716981699170017011702170317041705170617071708170917101711171217131714171517161717171817191720172117221723172417251726172717281729173017311732173317341735173617371738173917401741174217431744174517461747174817491750175117521753175417551756175717581759176017611762176317641765176617671768176917701771177217731774177517761777177817791780178117821783178417851786178717881789179017911792179317941795179617971798179918001801180218031804180518061807180818091810181118121813181418151816181718181819182018211822182318241825182618271828182918301831183218331834183518361837183818391840184118421843184418451846184718481849185018511852185318541855185618571858185918601861186218631864186518661867186818691870187118721873187418751876187718781879188018811882188318841885188618871888188918901891189218931894189518961897189818991900190119021903190419051906190719081909191019111912191319141915191619171918191919201921192219231924192519261927192819291930193119321933193419351936193719381939194019411942194319441945194619471948194919501951195219531954195519561957195819591960196119621963196419651966196719681969197019711972197319741975197619771978197919801981198219831984198519861987198819891990199119921993199419951996199719981999200020012002200320042005200620072008200920102011201220132014201520162017201820192020202120222023202420252026202720282029203020312032203320342035203620372038203920402041204220432044204520462047204820492050205120522053205420552056205720582059206020612062206320642065206620672068206920702071207220732074207520762077207820792080208120822083208420852086208720882089209020912092209320942095209620972098209921002101210221032104210521062107210821092110211121122113211421152116211721182119212021212122212321242125212621272128212921302131213221332134213521362137213821392140214121422143214421452146214721482149215021512152215321542155215621572158215921602161216221632164216521662167216821692170217121722173217421752176217721782179218021812182218321842185218621872188218921902191219221932194219521962197219821992200220122022203220422052206220722082209221022112212221322142215221622172218221922202221222222232224222522262227222822292230223122322233223422352236223722382239224022412242224322442245224622472248224922502251225222532254225522562257225822592260226122622263226422652266226722682269227022712272227322742275227622772278227922802281228222832284228522862287228822892290229122922293229422952296229722982299230023012302230323042305230623072308230923102311231223132314231523162317231823192320232123222323232423252326232723282329233023312332233323342335233623372338233923402341234223432344234523462347234823492350235123522353235423552356235723582359236023612362236323642365236623672368236923702371237223732374237523762377237823792380238123822383238423852386238723882389239023912392239323942395239623972398239924002401240224032404240524062407240824092410241124122413241424152416241724182419242024212422242324242425242624272428242924302431243224332434243524362437243824392440244124422443244424452446244724482449245024512452245324542455245624572458245924602461246224632464246524662467246824692470247124722473247424752476247724782479248024812482248324842485248624872488248924902491249224932494249524962497249824992500250125022503250425052506250725082509251025112512251325142515251625172518251925202521252225232524252525262527252825292530253125322533253425352536253725382539254025412542254325442545254625472548254925502551255225532554255525562557255825592560256125622563256425652566256725682569257025712572257325742575257625772578257925802581258225832584258525862587258825892590259125922593259425952596259725982599260026012602260326042605260626072608260926102611261226132614261526162617261826192620262126222623262426252626262726282629263026312632263326342635263626372638263926402641264226432644264526462647264826492650265126522653265426552656265726582659266026612662266326642665266626672668266926702671267226732674267526762677267826792680268126822683268426852686268726882689269026912692269326942695269626972698269927002701270227032704270527062707270827092710271127122713271427152716271727182719272027212722272327242725272627272728272927302731273227332734273527362737273827392740274127422743274427452746274727482749275027512752275327542755275627572758275927602761276227632764276527662767276827692770277127722773277427752776277727782779278027812782278327842785278627872788278927902791279227932794279527962797279827992800280128022803280428052806280728082809281028112812281328142815281628172818281928202821282228232824282528262827282828292830283128322833283428352836283728382839284028412842284328442845284628472848284928502851285228532854285528562857285828592860286128622863286428652866286728682869287028712872287328742875287628772878287928802881288228832884288528862887288828892890289128922893289428952896289728982899290029012902290329042905290629072908290929102911291229132914291529162917291829192920292129222923292429252926292729282929293029312932293329342935293629372938293929402941294229432944294529462947294829492950295129522953295429552956295729582959296029612962296329642965296629672968296929702971297229732974297529762977297829792980298129822983298429852986298729882989299029912992299329942995299629972998299930003001300230033004300530063007300830093010301130123013301430153016301730183019302030213022302330243025302630273028302930303031303230333034303530363037303830393040304130423043304430453046304730483049305030513052305330543055305630573058305930603061306230633064306530663067306830693070307130723073307430753076307730783079308030813082308330843085308630873088308930903091309230933094309530963097309830993100310131023103310431053106310731083109311031113112311331143115311631173118311931203121312231233124312531263127312831293130313131323133313431353136313731383139314031413142314331443145314631473148314931503151315231533154315531563157315831593160316131623163316431653166316731683169317031713172317331743175317631773178317931803181318231833184318531863187318831893190319131923193319431953196319731983199320032013202320332043205320632073208320932103211321232133214321532163217321832193220322132223223322432253226322732283229323032313232323332343235323632373238323932403241324232433244324532463247324832493250325132523253325432553256325732583259326032613262326332643265326632673268326932703271327232733274327532763277327832793280328132823283328432853286328732883289329032913292329332943295329632973298329933003301330233033304330533063307330833093310331133123313331433153316331733183319332033213322332333243325332633273328332933303331333233333334333533363337333833393340334133423343334433453346334733483349335033513352335333543355335633573358335933603361336233633364336533663367336833693370337133723373337433753376337733783379338033813382338333843385338633873388338933903391339233933394339533963397339833993400340134023403340434053406340734083409341034113412341334143415341634173418341934203421342234233424342534263427342834293430343134323433343434353436343734383439344034413442344334443445344634473448344934503451345234533454345534563457345834593460346134623463346434653466346734683469347034713472347334743475347634773478347934803481348234833484348534863487348834893490349134923493349434953496349734983499350035013502350335043505350635073508350935103511351235133514351535163517351835193520352135223523352435253526352735283529353035313532353335343535353635373538353935403541354235433544354535463547354835493550355135523553355435553556355735583559356035613562356335643565356635673568356935703571357235733574357535763577357835793580358135823583358435853586358735883589359035913592359335943595359635973598359936003601360236033604360536063607360836093610361136123613361436153616361736183619362036213622362336243625362636273628362936303631363236333634363536363637363836393640364136423643364436453646364736483649365036513652365336543655365636573658365936603661366236633664366536663667366836693670367136723673367436753676367736783679368036813682368336843685368636873688368936903691369236933694369536963697369836993700370137023703370437053706370737083709371037113712371337143715371637173718371937203721372237233724372537263727372837293730373137323733373437353736373737383739374037413742374337443745374637473748374937503751375237533754375537563757375837593760376137623763376437653766376737683769377037713772377337743775377637773778377937803781378237833784378537863787378837893790379137923793379437953796379737983799380038013802380338043805380638073808380938103811381238133814381538163817381838193820382138223823382438253826382738283829383038313832383338343835383638373838383938403841384238433844384538463847384838493850385138523853385438553856385738583859386038613862386338643865386638673868386938703871387238733874387538763877387838793880388138823883388438853886388738883889389038913892389338943895389638973898389939003901390239033904390539063907390839093910391139123913391439153916391739183919392039213922392339243925392639273928392939303931393239333934393539363937393839393940394139423943394439453946394739483949395039513952395339543955395639573958395939603961396239633964396539663967396839693970397139723973397439753976397739783979398039813982398339843985398639873988398939903991399239933994399539963997399839994000400140024003400440054006400740084009401040114012401340144015401640174018401940204021402240234024402540264027402840294030403140324033403440354036403740384039404040414042404340444045404640474048404940504051405240534054405540564057405840594060406140624063406440654066406740684069407040714072407340744075407640774078407940804081408240834084408540864087408840894090409140924093409440954096409740984099410041014102410341044105410641074108410941104111411241134114411541164117411841194120412141224123412441254126412741284129413041314132413341344135413641374138413941404141414241434144414541464147414841494150415141524153415441554156415741584159416041614162416341644165416641674168416941704171417241734174417541764177417841794180418141824183418441854186418741884189419041914192419341944195419641974198419942004201420242034204420542064207420842094210421142124213421442154216421742184219422042214222422342244225422642274228422942304231423242334234423542364237423842394240424142424243424442454246424742484249425042514252425342544255425642574258425942604261426242634264426542664267426842694270427142724273427442754276427742784279428042814282428342844285428642874288428942904291429242934294429542964297429842994300430143024303430443054306430743084309431043114312431343144315431643174318431943204321432243234324432543264327432843294330433143324333433443354336433743384339434043414342434343444345434643474348434943504351435243534354435543564357435843594360436143624363436443654366436743684369437043714372437343744375437643774378437943804381438243834384438543864387438843894390439143924393439443954396439743984399440044014402440344044405440644074408440944104411441244134414441544164417441844194420442144224423442444254426442744284429443044314432443344344435443644374438443944404441444244434444444544464447444844494450445144524453445444554456445744584459446044614462446344644465446644674468446944704471447244734474447544764477447844794480448144824483448444854486448744884489449044914492449344944495449644974498449945004501450245034504450545064507450845094510451145124513451445154516451745184519452045214522452345244525452645274528452945304531453245334534453545364537453845394540454145424543454445454546454745484549455045514552455345544555455645574558455945604561456245634564456545664567456845694570457145724573457445754576457745784579458045814582458345844585458645874588458945904591459245934594459545964597459845994600460146024603460446054606460746084609461046114612461346144615461646174618461946204621462246234624462546264627462846294630463146324633463446354636463746384639464046414642464346444645464646474648464946504651465246534654465546564657465846594660466146624663466446654666466746684669467046714672467346744675467646774678467946804681468246834684468546864687468846894690469146924693469446954696469746984699470047014702470347044705470647074708470947104711471247134714471547164717471847194720472147224723472447254726472747284729473047314732473347344735473647374738473947404741474247434744474547464747474847494750475147524753475447554756475747584759476047614762476347644765476647674768476947704771477247734774477547764777477847794780478147824783478447854786478747884789479047914792479347944795479647974798479948004801480248034804480548064807480848094810481148124813481448154816481748184819482048214822482348244825482648274828482948304831483248334834483548364837483848394840484148424843484448454846484748484849485048514852485348544855485648574858485948604861486248634864486548664867486848694870487148724873487448754876487748784879488048814882488348844885488648874888488948904891489248934894489548964897489848994900490149024903490449054906490749084909491049114912491349144915491649174918491949204921492249234924492549264927492849294930493149324933493449354936493749384939494049414942494349444945494649474948494949504951495249534954495549564957495849594960496149624963496449654966496749684969497049714972497349744975497649774978497949804981498249834984498549864987498849894990499149924993499449954996499749984999500050015002500350045005500650075008500950105011501250135014501550165017501850195020502150225023502450255026502750285029503050315032503350345035503650375038503950405041504250435044504550465047504850495050505150525053505450555056505750585059506050615062506350645065506650675068506950705071507250735074507550765077507850795080508150825083508450855086508750885089509050915092509350945095509650975098509951005101510251035104510551065107510851095110511151125113511451155116511751185119512051215122512351245125512651275128512951305131513251335134513551365137513851395140514151425143514451455146514751485149515051515152515351545155515651575158515951605161516251635164516551665167516851695170517151725173517451755176517751785179518051815182518351845185518651875188518951905191519251935194519551965197519851995200520152025203520452055206520752085209521052115212521352145215521652175218521952205221522252235224522552265227522852295230523152325233523452355236523752385239524052415242524352445245524652475248524952505251525252535254525552565257525852595260526152625263526452655266526752685269527052715272527352745275527652775278527952805281528252835284528552865287528852895290529152925293529452955296529752985299530053015302530353045305530653075308530953105311531253135314531553165317531853195320532153225323532453255326532753285329533053315332533353345335533653375338533953405341534253435344534553465347534853495350535153525353535453555356535753585359536053615362536353645365536653675368536953705371537253735374537553765377537853795380538153825383538453855386538753885389539053915392539353945395539653975398539954005401540254035404540554065407540854095410541154125413541454155416541754185419542054215422542354245425542654275428542954305431543254335434543554365437543854395440544154425443544454455446544754485449545054515452545354545455545654575458545954605461546254635464546554665467546854695470547154725473547454755476547754785479548054815482548354845485548654875488548954905491549254935494549554965497549854995500550155025503550455055506550755085509551055115512551355145515551655175518551955205521552255235524552555265527552855295530553155325533553455355536553755385539554055415542554355445545554655475548554955505551555255535554555555565557555855595560556155625563556455655566556755685569557055715572557355745575557655775578557955805581558255835584558555865587558855895590559155925593559455955596559755985599560056015602560356045605560656075608560956105611561256135614561556165617561856195620562156225623562456255626562756285629563056315632563356345635563656375638563956405641564256435644564556465647564856495650565156525653565456555656565756585659566056615662566356645665566656675668566956705671567256735674567556765677567856795680568156825683568456855686568756885689569056915692569356945695569656975698569957005701570257035704570557065707570857095710571157125713571457155716571757185719572057215722572357245725572657275728572957305731573257335734573557365737573857395740574157425743574457455746574757485749575057515752575357545755575657575758575957605761576257635764576557665767576857695770577157725773577457755776577757785779578057815782578357845785578657875788578957905791579257935794579557965797579857995800580158025803580458055806580758085809581058115812581358145815581658175818581958205821582258235824582558265827582858295830583158325833583458355836583758385839584058415842584358445845584658475848584958505851585258535854585558565857585858595860586158625863586458655866586758685869587058715872587358745875587658775878587958805881588258835884588558865887588858895890589158925893589458955896589758985899590059015902590359045905590659075908590959105911591259135914591559165917591859195920592159225923592459255926592759285929593059315932593359345935593659375938593959405941594259435944594559465947594859495950595159525953595459555956595759585959596059615962596359645965596659675968596959705971597259735974597559765977597859795980598159825983598459855986598759885989599059915992599359945995599659975998599960006001600260036004600560066007600860096010601160126013601460156016601760186019602060216022602360246025602660276028602960306031603260336034603560366037603860396040604160426043604460456046604760486049605060516052605360546055605660576058605960606061606260636064606560666067606860696070607160726073607460756076607760786079608060816082608360846085608660876088608960906091609260936094609560966097609860996100610161026103610461056106610761086109611061116112611361146115611661176118611961206121612261236124612561266127612861296130613161326133613461356136613761386139614061416142614361446145614661476148614961506151615261536154615561566157615861596160616161626163616461656166616761686169617061716172617361746175617661776178617961806181618261836184618561866187618861896190619161926193619461956196619761986199620062016202620362046205620662076208620962106211621262136214621562166217621862196220622162226223622462256226622762286229623062316232623362346235623662376238623962406241624262436244624562466247624862496250625162526253625462556256625762586259626062616262626362646265626662676268626962706271627262736274627562766277627862796280628162826283628462856286628762886289629062916292629362946295629662976298629963006301630263036304630563066307630863096310631163126313631463156316631763186319632063216322632363246325632663276328632963306331633263336334633563366337633863396340634163426343634463456346634763486349635063516352635363546355635663576358635963606361636263636364636563666367636863696370637163726373637463756376637763786379638063816382638363846385638663876388638963906391639263936394639563966397639863996400640164026403640464056406640764086409641064116412641364146415641664176418641964206421642264236424642564266427642864296430643164326433643464356436643764386439644064416442644364446445644664476448644964506451645264536454645564566457645864596460646164626463646464656466646764686469647064716472647364746475647664776478647964806481648264836484648564866487648864896490649164926493649464956496649764986499650065016502650365046505650665076508650965106511651265136514651565166517651865196520652165226523652465256526652765286529653065316532653365346535653665376538653965406541654265436544654565466547654865496550655165526553655465556556655765586559656065616562656365646565656665676568656965706571657265736574657565766577657865796580658165826583658465856586658765886589659065916592659365946595659665976598659966006601660266036604660566066607660866096610661166126613661466156616661766186619662066216622662366246625662666276628662966306631663266336634663566366637663866396640664166426643664466456646664766486649665066516652665366546655665666576658665966606661666266636664666566666667666866696670667166726673667466756676667766786679668066816682668366846685668666876688668966906691669266936694669566966697669866996700670167026703670467056706670767086709671067116712671367146715671667176718671967206721672267236724672567266727672867296730673167326733673467356736673767386739674067416742674367446745674667476748674967506751675267536754675567566757675867596760676167626763676467656766676767686769677067716772677367746775677667776778677967806781678267836784678567866787678867896790679167926793679467956796679767986799680068016802680368046805680668076808680968106811681268136814681568166817681868196820682168226823682468256826682768286829683068316832683368346835683668376838683968406841684268436844684568466847684868496850685168526853685468556856685768586859686068616862686368646865686668676868686968706871687268736874687568766877687868796880688168826883688468856886688768886889689068916892689368946895689668976898689969006901690269036904690569066907690869096910691169126913691469156916691769186919692069216922692369246925692669276928692969306931693269336934693569366937693869396940694169426943694469456946694769486949695069516952695369546955695669576958695969606961696269636964696569666967696869696970697169726973697469756976697769786979698069816982698369846985698669876988698969906991699269936994699569966997699869997000700170027003700470057006700770087009701070117012701370147015701670177018701970207021702270237024702570267027702870297030703170327033703470357036703770387039704070417042704370447045704670477048704970507051705270537054705570567057705870597060706170627063706470657066706770687069707070717072707370747075707670777078707970807081708270837084708570867087708870897090709170927093709470957096709770987099710071017102710371047105710671077108710971107111711271137114711571167117711871197120712171227123712471257126712771287129713071317132713371347135713671377138713971407141714271437144714571467147714871497150715171527153715471557156715771587159716071617162716371647165716671677168716971707171717271737174717571767177717871797180718171827183718471857186718771887189719071917192719371947195719671977198719972007201720272037204720572067207720872097210721172127213721472157216721772187219722072217222722372247225722672277228722972307231723272337234723572367237723872397240724172427243724472457246724772487249725072517252725372547255725672577258725972607261726272637264726572667267726872697270727172727273727472757276727772787279728072817282728372847285728672877288728972907291729272937294729572967297729872997300730173027303730473057306730773087309731073117312731373147315731673177318731973207321732273237324732573267327732873297330733173327333733473357336733773387339734073417342734373447345734673477348734973507351735273537354735573567357735873597360736173627363736473657366736773687369737073717372737373747375737673777378737973807381738273837384738573867387738873897390739173927393739473957396739773987399740074017402740374047405740674077408740974107411741274137414741574167417741874197420742174227423742474257426742774287429743074317432743374347435743674377438743974407441744274437444744574467447744874497450745174527453745474557456745774587459746074617462746374647465746674677468746974707471747274737474747574767477747874797480748174827483748474857486748774887489749074917492749374947495749674977498749975007501750275037504750575067507750875097510751175127513751475157516751775187519752075217522752375247525752675277528752975307531753275337534753575367537753875397540754175427543754475457546754775487549755075517552755375547555755675577558755975607561756275637564756575667567756875697570757175727573757475757576757775787579758075817582758375847585758675877588758975907591759275937594759575967597759875997600760176027603760476057606760776087609761076117612761376147615761676177618761976207621762276237624762576267627762876297630763176327633763476357636763776387639764076417642764376447645764676477648764976507651765276537654765576567657765876597660766176627663766476657666766776687669767076717672767376747675767676777678767976807681768276837684768576867687768876897690769176927693769476957696769776987699770077017702770377047705770677077708770977107711771277137714771577167717771877197720772177227723772477257726772777287729773077317732773377347735773677377738773977407741774277437744774577467747774877497750775177527753775477557756775777587759776077617762776377647765776677677768776977707771777277737774777577767777777877797780778177827783778477857786778777887789779077917792779377947795779677977798779978007801780278037804780578067807780878097810781178127813781478157816781778187819782078217822782378247825782678277828782978307831783278337834783578367837783878397840784178427843784478457846784778487849785078517852785378547855785678577858785978607861786278637864786578667867786878697870787178727873787478757876787778787879788078817882788378847885788678877888788978907891789278937894789578967897789878997900790179027903790479057906790779087909791079117912791379147915791679177918791979207921792279237924792579267927792879297930793179327933793479357936793779387939794079417942794379447945794679477948794979507951795279537954795579567957795879597960796179627963796479657966796779687969797079717972797379747975797679777978797979807981798279837984798579867987798879897990799179927993799479957996799779987999800080018002800380048005800680078008800980108011801280138014801580168017801880198020802180228023802480258026802780288029803080318032803380348035803680378038803980408041804280438044804580468047804880498050805180528053805480558056805780588059806080618062806380648065806680678068806980708071807280738074807580768077807880798080808180828083808480858086808780888089809080918092809380948095809680978098809981008101810281038104810581068107810881098110811181128113811481158116811781188119812081218122812381248125812681278128812981308131813281338134813581368137813881398140814181428143814481458146814781488149815081518152815381548155815681578158815981608161816281638164816581668167816881698170817181728173817481758176817781788179818081818182818381848185818681878188818981908191819281938194819581968197819881998200820182028203820482058206820782088209821082118212821382148215821682178218821982208221822282238224822582268227822882298230823182328233823482358236823782388239824082418242824382448245824682478248824982508251825282538254825582568257825882598260826182628263826482658266826782688269827082718272827382748275827682778278827982808281828282838284828582868287828882898290829182928293829482958296829782988299830083018302830383048305830683078308830983108311831283138314831583168317831883198320832183228323832483258326832783288329833083318332833383348335833683378338833983408341834283438344834583468347834883498350835183528353835483558356835783588359836083618362836383648365836683678368836983708371837283738374837583768377837883798380838183828383838483858386838783888389839083918392839383948395839683978398839984008401840284038404840584068407840884098410841184128413841484158416841784188419842084218422842384248425842684278428842984308431843284338434843584368437843884398440844184428443844484458446844784488449845084518452845384548455845684578458845984608461846284638464846584668467846884698470847184728473847484758476847784788479848084818482848384848485848684878488848984908491849284938494849584968497849884998500850185028503850485058506850785088509851085118512851385148515851685178518851985208521852285238524852585268527852885298530853185328533853485358536853785388539854085418542854385448545854685478548854985508551855285538554855585568557855885598560856185628563856485658566856785688569857085718572857385748575857685778578857985808581858285838584858585868587858885898590859185928593859485958596859785988599860086018602860386048605860686078608860986108611861286138614861586168617861886198620862186228623862486258626862786288629863086318632863386348635863686378638863986408641864286438644864586468647864886498650865186528653865486558656865786588659866086618662866386648665866686678668866986708671867286738674867586768677867886798680868186828683868486858686868786888689869086918692869386948695869686978698869987008701870287038704870587068707870887098710871187128713871487158716871787188719872087218722872387248725872687278728872987308731873287338734873587368737873887398740874187428743874487458746874787488749875087518752875387548755875687578758875987608761876287638764876587668767876887698770877187728773877487758776877787788779878087818782878387848785878687878788878987908791879287938794879587968797879887998800880188028803880488058806880788088809881088118812881388148815881688178818881988208821882288238824882588268827882888298830883188328833883488358836883788388839884088418842884388448845884688478848884988508851885288538854885588568857885888598860886188628863886488658866886788688869887088718872887388748875887688778878887988808881888288838884888588868887888888898890889188928893889488958896889788988899890089018902890389048905890689078908890989108911891289138914891589168917891889198920892189228923892489258926892789288929893089318932893389348935893689378938893989408941894289438944894589468947894889498950895189528953895489558956895789588959896089618962896389648965896689678968896989708971897289738974897589768977897889798980898189828983898489858986898789888989899089918992899389948995899689978998899990009001900290039004900590069007900890099010901190129013901490159016901790189019902090219022902390249025902690279028902990309031903290339034903590369037903890399040904190429043904490459046904790489049905090519052905390549055905690579058905990609061906290639064906590669067906890699070907190729073907490759076907790789079908090819082908390849085908690879088908990909091909290939094909590969097909890999100910191029103910491059106910791089109911091119112911391149115911691179118911991209121912291239124912591269127912891299130913191329133913491359136913791389139914091419142914391449145914691479148914991509151915291539154915591569157915891599160916191629163916491659166916791689169917091719172917391749175917691779178917991809181918291839184918591869187918891899190919191929193919491959196919791989199920092019202920392049205920692079208920992109211921292139214921592169217921892199220922192229223922492259226922792289229923092319232923392349235923692379238923992409241924292439244924592469247924892499250925192529253925492559256925792589259926092619262926392649265926692679268926992709271927292739274927592769277927892799280928192829283928492859286928792889289929092919292929392949295929692979298929993009301930293039304930593069307930893099310931193129313931493159316931793189319932093219322932393249325932693279328932993309331933293339334933593369337933893399340934193429343934493459346934793489349935093519352935393549355935693579358935993609361936293639364936593669367936893699370937193729373937493759376937793789379938093819382938393849385938693879388938993909391939293939394939593969397939893999400940194029403940494059406940794089409941094119412941394149415941694179418941994209421942294239424942594269427942894299430943194329433943494359436943794389439944094419442944394449445944694479448944994509451945294539454945594569457945894599460946194629463946494659466946794689469947094719472947394749475947694779478947994809481948294839484948594869487948894899490949194929493949494959496949794989499950095019502950395049505950695079508950995109511951295139514951595169517951895199520952195229523952495259526952795289529953095319532953395349535953695379538953995409541954295439544954595469547954895499550955195529553955495559556955795589559956095619562956395649565956695679568956995709571957295739574957595769577957895799580958195829583958495859586958795889589959095919592959395949595959695979598959996009601960296039604960596069607960896099610961196129613961496159616961796189619962096219622962396249625962696279628962996309631963296339634963596369637963896399640964196429643964496459646964796489649965096519652965396549655965696579658965996609661966296639664966596669667966896699670967196729673967496759676967796789679968096819682968396849685968696879688968996909691969296939694969596969697969896999700970197029703970497059706970797089709971097119712971397149715971697179718971997209721972297239724972597269727972897299730973197329733973497359736973797389739974097419742974397449745974697479748974997509751975297539754975597569757975897599760976197629763976497659766976797689769977097719772977397749775977697779778977997809781978297839784978597869787978897899790979197929793979497959796979797989799980098019802980398049805980698079808980998109811981298139814981598169817981898199820982198229823982498259826982798289829983098319832983398349835983698379838983998409841984298439844984598469847984898499850985198529853985498559856985798589859986098619862986398649865986698679868986998709871987298739874987598769877987898799880988198829883988498859886988798889889989098919892989398949895989698979898989999009901990299039904990599069907990899099910991199129913991499159916991799189919992099219922992399249925992699279928992999309931993299339934993599369937993899399940994199429943994499459946994799489949995099519952995399549955995699579958995999609961996299639964996599669967996899699970997199729973997499759976997799789979998099819982998399849985998699879988998999909991999299939994999599969997999899991000010001100021000310004100051000610007100081000910010100111001210013100141001510016100171001810019100201002110022100231002410025100261002710028100291003010031100321003310034100351003610037100381003910040100411004210043100441004510046100471004810049100501005110052100531005410055100561005710058100591006010061100621006310064100651006610067100681006910070100711007210073100741007510076100771007810079100801008110082100831008410085100861008710088100891009010091100921009310094100951009610097100981009910100101011010210103101041010510106101071010810109101101011110112101131011410115101161011710118101191012010121101221012310124101251012610127101281012910130101311013210133101341013510136101371013810139101401014110142101431014410145101461014710148
  1. <?php
  2. namespace App\Services\Anime;
  3. use App\Consts\BaseConst;
  4. use App\Consts\ErrorConst;
  5. use App\Facade\Site;
  6. use App\Libs\Utils;
  7. use App\Models\MpGeneratePicTask;
  8. use App\Services\AIGeneration\AIImageGenerationService;
  9. use App\Services\AIGeneration\AIVideoGenerationService;
  10. use App\Services\DeepSeek\DeepSeekService;
  11. use App\Services\PointsService;
  12. use App\Services\TaskCenterService;
  13. use Dflydev\DotAccessData\Util;
  14. use GuzzleHttp\Client;
  15. use Illuminate\Support\Facades\DB;
  16. use Illuminate\Support\Facades\Log;
  17. use Illuminate\Support\Facades\Redis;
  18. use OSS\Core\OssException;
  19. use OSS\OssClient;
  20. class AnimeService
  21. {
  22. protected $aiImageGenerationService;
  23. protected $aiVideoGenerationService;
  24. protected $DeepSeekService;
  25. protected $pointsService;
  26. protected $taskCenterService;
  27. private $url;
  28. private $api_key;
  29. private $headers;
  30. public function __construct(
  31. AIImageGenerationService $aiImageGenerationService,
  32. AIVideoGenerationService $aiVideoGenerationService,
  33. DeepSeekService $DeepSeekService,
  34. PointsService $pointsService,
  35. TaskCenterService $taskCenterService
  36. ) {
  37. $this->aiImageGenerationService = $aiImageGenerationService;
  38. $this->aiVideoGenerationService = $aiVideoGenerationService;
  39. $this->DeepSeekService = $DeepSeekService;
  40. $this->pointsService = $pointsService;
  41. $this->taskCenterService = $taskCenterService;
  42. $this->url = 'https://api.deepseek.com/chat/completions';
  43. $this->api_key = env('DEEPSEEK_API_KEY');
  44. $this->headers = [
  45. 'Authorization' => 'Bearer '.$this->api_key,
  46. 'Content-Type' => 'application/json; charset=UTF-8'
  47. ];
  48. }
  49. /**
  50. * 构建统一的分镜数据结构(episodeInfo格式)
  51. * @param array $segments 分镜数据数组
  52. * @return array 返回包含acts和total_duration的数组
  53. */
  54. public function buildEpisodeSegmentsStructure($segments) {
  55. $acts = [];
  56. $totalDuration = 0; // 初始化总时长
  57. foreach($segments as $segment) {
  58. // 计算分镜时长,优先级:video_duration > audio_duration > 默认5秒
  59. $videoDuration = getProp($segment, 'video_duration');
  60. $audioDuration = getProp($segment, 'audio_duration');
  61. if (!empty($videoDuration) && is_numeric($videoDuration)) {
  62. $totalDuration += floatval($videoDuration);
  63. } elseif (!empty($audioDuration) && is_numeric($audioDuration)) {
  64. $totalDuration += floatval($audioDuration);
  65. } else {
  66. $totalDuration += 5; // 默认5秒
  67. }
  68. $segment_content = getProp($segment, 'segment_content');
  69. // 判断是否有尾帧描述,如果有则去掉这部分内容
  70. if (strpos($segment_content, '尾帧') !== false) {
  71. // 使用正则表达式匹配"尾帧"及其后面的内容并移除(s修饰符让.匹配换行符)
  72. $segment_content = preg_replace('/尾帧.*$/s', '', $segment_content);
  73. }
  74. // 构建分镜信息
  75. $segmentInfo = [
  76. 'segment_id' => getProp($segment, 'segment_id'),
  77. 'segment_number' => getProp($segment, 'segment_number'),
  78. 'segment_content' => $segment_content,
  79. 'description' => getProp($segment, 'description'),
  80. 'composition' => getProp($segment, 'composition'),
  81. 'camera_movement' => getProp($segment, 'camera_movement'),
  82. 'voice_actor' => getProp($segment, 'voice_actor'),
  83. 'dialogue' => getProp($segment, 'dialogue'),
  84. 'frame_type' => getProp($segment, 'frame_type'),
  85. 'scene' => getProp($segment, 'scene'),
  86. 'characters' => getProp($segment, 'characters'),
  87. 'tail_frame' => getProp($segment, 'tail_frame'),
  88. 'emotion' => getProp($segment, 'emotion'),
  89. 'emotion_type' => getProp($segment, 'emotion_type'),
  90. 'gender' => getProp($segment, 'gender'),
  91. 'speed_ratio' => getProp($segment, 'speed_ratio'),
  92. 'loudness_ratio' => getProp($segment, 'loudness_ratio'),
  93. 'emotion_scale' => getProp($segment, 'emotion_scale'),
  94. 'pitch' => getProp($segment, 'pitch'),
  95. 'voice_name' => getProp($segment, 'voice_name'),
  96. 'voice_type' => getProp($segment, 'voice_type'),
  97. 'voice_audio_url' => getProp($segment, 'voice_audio_url'),
  98. 'img_url' => getProp($segment, 'img_url'),
  99. 'audio_url' => getProp($segment, 'audio_url'),
  100. 'audio_duration' => getProp($segment, 'audio_duration', 0),
  101. 'video_url' => getProp($segment, 'video_url'),
  102. 'video_duration' => getProp($segment, 'video_duration', 0),
  103. 'video_time_point_start' => getProp($segment, 'video_time_point_start', 0),
  104. 'video_time_point_end' => getProp($segment, 'video_time_point_end', getProp($segment, 'video_duration', 0)),
  105. 'last_frame_url' => getProp($segment, 'last_frame_url'),
  106. 'current_type' => getProp($segment, 'current_type'),
  107. ];
  108. $actNumber = getProp($segment, 'act_number');
  109. if (isset($acts[$actNumber])) {
  110. $acts[$actNumber]['segments'][] = $segmentInfo;
  111. } else {
  112. $acts[$actNumber] = [
  113. 'act_number' => $actNumber,
  114. 'act_title' => getProp($segment, 'act_title'),
  115. 'act_duration' => getProp($segment, 'act_duration'),
  116. 'segments' => [$segmentInfo]
  117. ];
  118. }
  119. }
  120. return [
  121. 'acts' => array_values($acts),
  122. 'total_duration' => intval(round($totalDuration))
  123. ];
  124. }
  125. /**
  126. * 构建统一的分段数据结构(episodeInfoForAce格式)
  127. * @param array $segments 分段数据数组
  128. * @return array 返回包含acts和total_duration的数组
  129. */
  130. public function buildEpisodeActsStructureForAce($segments) {
  131. $acts = [];
  132. $totalDuration = 0; // 初始化总时长
  133. foreach($segments as $segment) {
  134. // 计算分镜时长,优先级:video_duration > act_duration > 默认5秒
  135. $videoDuration = getProp($segment, 'video_duration');
  136. $actDuration = getProp($segment, 'act_duration');
  137. if (!empty($videoDuration) && is_numeric($videoDuration)) {
  138. $totalDuration += floatval($videoDuration);
  139. } elseif (!empty($actDuration) && is_numeric($actDuration)) {
  140. $totalDuration += floatval($actDuration);
  141. } else {
  142. $totalDuration += 5; // 默认5秒
  143. }
  144. // 构建分镜信息
  145. $segmentInfo = [
  146. 'act_id' => getProp($segment, 'id'),
  147. 'act_number' => getProp($segment, 'act_number'),
  148. 'act_title' => getProp($segment, 'act_title'),
  149. 'act_duration' => getProp($segment, 'act_duration'),
  150. 'act_content' => getProp($segment, 'act_content'),
  151. 'video_url' => getProp($segment, 'video_url'),
  152. 'video_duration' => getProp($segment, 'video_duration', 0),
  153. 'video_time_point_start' => getProp($segment, 'video_time_point_start', 0),
  154. 'video_time_point_end' => getProp($segment, 'video_time_point_end', getProp($segment, 'video_duration', 0)),
  155. 'last_frame_url' => getProp($segment, 'last_frame_url'),
  156. 'current_type' => getProp($segment, 'current_type'),
  157. ];
  158. $acts[] = $segmentInfo;
  159. }
  160. return [
  161. 'acts' => array_values($acts),
  162. 'total_duration' => intval(round($totalDuration))
  163. ];
  164. }
  165. /**
  166. * 验证画面比例是否有效
  167. * @param string $ratio 画面比例
  168. * @return bool
  169. */
  170. public function validateRatio($ratio) {
  171. return isset(BaseConst::IMAGE_RATIOS[$ratio]);
  172. }
  173. /**
  174. * 获取画面比例对应的宽高
  175. * @param string $ratio 画面比例
  176. * @return array ['width' => int, 'height' => int]
  177. * @throws \Exception
  178. */
  179. private function getRatioDimensions($ratio) {
  180. if ($ratio && !$this->validateRatio($ratio)) {
  181. $validRatios = implode('、', array_keys(BaseConst::IMAGE_RATIOS));
  182. Utils::throwError("1002:画面比例选择不正确,只支持{$validRatios}");
  183. }
  184. return isset(BaseConst::IMAGE_RATIOS[$ratio]) ? BaseConst::IMAGE_RATIOS[$ratio] : ['width' => 1600, 'height' => 2848];
  185. }
  186. public function createAnime($data) {
  187. $uid = Site::getUid();
  188. $cpid = Site::getCpid();
  189. $input_art_style = getProp($data, 'art_style');
  190. $file = getProp($data, 'file');
  191. $content = getProp($data, 'content', '');
  192. $bid = getProp($data, 'bid', 0);
  193. $script_id = getProp($data, 'script_id', 0);
  194. $ace_mode = getProp($data, 'ace_mode', 0);
  195. $extra_products = getProp($data, 'products', []);
  196. if (is_string($extra_products)) $extra_products = json_decode($extra_products, true);
  197. if (!is_array($extra_products)) {
  198. Utils::throwError('20003:传入的资产格式不正确');
  199. }
  200. // 替换美术风格
  201. $mappedArtStyle = $this->DeepSeekService->getArtStylePromptByInput($input_art_style);
  202. // 提取文件内容
  203. if ($file) {
  204. $content = $this->DeepSeekService->extractFileContent($file);
  205. if (!$content) {
  206. Utils::throwError('20003:无法提取文件内容,请检查文件格式');
  207. }
  208. } elseif ($script_id) {
  209. $content = $this->DeepSeekService->getContentByScriptId($script_id);
  210. if (!$content) {
  211. Utils::throwError('20003:无法获取剧本内容,请检查剧本');
  212. }
  213. } elseif ($bid) {
  214. $content = $this->DeepSeekService->getContentByBid($bid);
  215. if (!$content) {
  216. Utils::throwError('20003:无法获取书籍内容,请检查书籍');
  217. }
  218. } elseif ($content) {
  219. $content = filterContent($content);
  220. }else {
  221. $content = '';
  222. }
  223. $anime_data = [
  224. 'user_id' => $uid,
  225. 'cpid' => $cpid,
  226. 'anime_name' => '新剧本策划',
  227. 'is_multi' => getProp($data, 'is_multi', 1),
  228. 'content' => $content,
  229. 'art_style_type' => $input_art_style,
  230. 'ace_mode' => $ace_mode,
  231. 'script_id' => $script_id,
  232. 'extra_products' => json_encode($extra_products, 256),
  233. 'created_at' => date('Y-m-d H:i:s'),
  234. 'updated_at' => date('Y-m-d H:i:s'),
  235. ];
  236. // 处理文本模型
  237. $model = getProp($data, 'model');
  238. if (!$model) {
  239. // 用户没有输入,使用默认值
  240. $model = 'deepseek-v4-pro';
  241. }
  242. // 验证模型是否在可用模型表中
  243. if (!DB::table('mp_text_models')->where('model', $model)->where('is_enabled', 1)->exists()) {
  244. $model = 'deepseek-v4-pro';
  245. }
  246. $anime_data['model'] = $model;
  247. if ($mappedArtStyle) $anime_data['art_style'] = $mappedArtStyle;
  248. return DB::table('mp_animes')->insertGetId($anime_data);
  249. }
  250. public function chatList($data) {
  251. $uid = Site::getUid();
  252. $anime_name = getProp($data, 'anime_name');
  253. $query = DB::table('mp_animes')->where('is_deleted', 0)->where('user_id', $uid);
  254. if ($anime_name) {
  255. $query->where('anime_name', 'like', "%$anime_name%");
  256. }
  257. return $query->orderBy('id', 'desc')->paginate();
  258. }
  259. public function chatHistory($data) {
  260. $anime_id = getProp($data, 'anime_id');
  261. $sequence = getProp($data, 'sequence', 0);
  262. if (!$anime_id) Utils::throwError('20003:请选择对话!');
  263. $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)
  264. ->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');
  265. return $query->orderBy('ar.id')->get()->map(function ($value) {
  266. $value = (array)$value;
  267. if ($value['role'] == 'assistant') $value['content'] = filterScriptContent($value['content']);
  268. $value['created_at'] = transDate($value['created_at']);
  269. $value['episode_created_at'] = transDate($value['episode_created_at']);
  270. return $value;
  271. })->toArray();
  272. }
  273. public function batchSetRoleImg($data) {
  274. $episode_id = getProp($data, 'episode_id');
  275. if (!$episode_id) Utils::throwError('1002:请选择分集');
  276. $episode = DB::table('mp_anime_episodes')->where('id', $episode_id)->first();
  277. $roles = json_decode(getProp($data, 'roles'), true) ?: [];
  278. $art_style = getProp($episode, 'art_style');
  279. $anime_id = getProp($episode, 'anime_id');
  280. $anime = DB::table('mp_animes')->where('id', $anime_id)->first();
  281. $art_style_type = getProp($anime, 'art_style_type');
  282. $character_prefix = '';
  283. $scene_prefix = '';
  284. if ($art_style_type) {
  285. $art_style_arr = $this->DeepSeekService->getArtStyleShortPromptByInput($art_style_type);
  286. $character_prefix = isset($art_style_arr['character_prefix']) ? $art_style_arr['character_prefix'] : '';
  287. $scene_prefix = isset($art_style_arr['scene_prefix']) ? $art_style_arr['scene_prefix'] : '';
  288. }
  289. foreach ($roles as &$role) {
  290. $role_name = getProp($role, 'role');
  291. if ($role_name == '旁白') continue;
  292. // 优先使用 pic_prompt,如果没有则使用 description
  293. $pic_prompt = getProp($role, 'pic_prompt');
  294. $description = !empty($pic_prompt) ? trim((string)$pic_prompt) : getProp($role, 'description');
  295. // if ($art_style) $description = "美术风格:\n{$art_style}\n主体描述:{$description}\n图片要求:图片侧重点是人物,不要出现场景或背景,并且只能生成一个人物";
  296. $description = "{$character_prefix}。\n主体描述:{$description}\n超高清,高细节,主体突出,构图合理,画面干净,无场景或背景,单人物,无文字,无水印,无字幕,电影级光影,视觉焦点明确";
  297. // 参考图地址
  298. $ref_img_url = getProp($role, 'url');
  299. if ($ref_img_url) continue; // 已有图片则跳过
  300. // 此处调用AIImageGenerationService的生成图片任务接口: createImageGenerationTask(注意使用默认参数,prompt使用角色描述),并返回任务id
  301. try {
  302. $params = [
  303. 'prompt' => $description,
  304. 'ref_img_urls' => !empty($ref_img_url) ? [$ref_img_url] : []
  305. ];
  306. $task = $this->aiImageGenerationService->createImageGenerationTask($params);
  307. $task_id = $task->id;
  308. if (!$task_id) {
  309. Utils::throwError("20003:角色({$role_name})生成图片失败");
  310. }
  311. $role['task_id'] = $task_id;
  312. $role['task_status'] = 'processing';
  313. } catch (\Exception $e) {
  314. logDB('anime', 'error', "角色({$role_name})生成图片失败", ['error' => $e->getMessage()]);
  315. Utils::throwError("20003:" . $e->getMessage());
  316. }
  317. }
  318. // 保存角色信息
  319. $boolen = DB::table('mp_anime_episodes')->where('id', $episode_id)->update([
  320. 'roles' => json_encode($roles, 256),
  321. 'generate_status' => '执行中',
  322. 'generate_at' => date('Y-m-d H:i:s'),
  323. 'updated_at' => date('Y-m-d H:i:s')
  324. ]);
  325. if (!$boolen) {
  326. Utils::throwError('20003:保存角色信息失败');
  327. }
  328. return $boolen;
  329. }
  330. public function batchSetSceneImg($data) {
  331. $episode_id = getProp($data, 'episode_id');
  332. if (!$episode_id) Utils::throwError('1002:请选择分集');
  333. $episode = DB::table('mp_anime_episodes')->where('id', $episode_id)->first();
  334. $scenes = json_decode(getProp($episode, 'scenes'), true);
  335. $art_style = getProp($episode, 'art_style');
  336. $target_scene = getProp($data, 'target_scene');
  337. $anime_id = getProp($episode, 'anime_id');
  338. $anime = DB::table('mp_animes')->where('id', $anime_id)->first();
  339. $art_style_type = getProp($anime, 'art_style_type');
  340. $character_prefix = '';
  341. $scene_prefix = '';
  342. if ($art_style_type) {
  343. $art_style_arr = $this->DeepSeekService->getArtStyleShortPromptByInput($art_style_type);
  344. $character_prefix = isset($art_style_arr['character_prefix']) ? $art_style_arr['character_prefix'] : '';
  345. $scene_prefix = isset($art_style_arr['scene_prefix']) ? $art_style_arr['scene_prefix'] : '';
  346. }
  347. foreach ($scenes as &$scene) {
  348. $scene_name = getProp($scene, 'scene');
  349. if ($scene_name != $target_scene) continue;
  350. // 优先使用 pic_prompt,如果没有则使用 description
  351. $pic_prompt = getProp($scene, 'pic_prompt');
  352. $description = !empty($pic_prompt) ? trim((string)$pic_prompt) : getProp($scene, 'description');
  353. // if ($art_style) $description = "美术风格:\n{$art_style}\n\n场景描述:{$description}\n图片要求: 图片侧重点是场景,生成的是场景环境图片,不要出现人物(此为第一优先要求)";
  354. $description = "{$scene_prefix}。\n场景描述:{$description}\n无人物,超高清,高细节,主体突出,构图合理,画面干净,无文字,无水印,无字幕,电影级光影,视觉焦点明确";
  355. // 参考图地址
  356. $ref_img_url = getProp($scene, 'url');
  357. if ($ref_img_url) continue; // 已有图片则跳过
  358. // 此处调用AIImageGenerationService的生成图片任务接口: createImageGenerationTask(注意使用默认参数,prompt使用角色描述),并返回任务id
  359. try {
  360. $params = [
  361. 'prompt' => $description,
  362. 'ref_img_urls' => !empty($ref_img_url) ? [$ref_img_url] : []
  363. ];
  364. $task = $this->aiImageGenerationService->createImageGenerationTask($params);
  365. $task_id = $task->id;
  366. if (!$task_id) {
  367. Utils::throwError("20003:场景({$scene_name})生成图片失败");
  368. }
  369. $scene['task_id'] = $task_id;
  370. $scene['task_status'] = 'processing';
  371. } catch (\Exception $e) {
  372. logDB('anime', 'error', "场景({$scene_name})生成图片失败", ['error' => $e->getMessage()]);
  373. Utils::throwError("20003:" . $e->getMessage());
  374. }
  375. }
  376. // 保存场景信息
  377. $boolen = DB::table('mp_anime_episodes')->where('id', $episode_id)->update([
  378. 'scenes' => json_encode($scenes, 256),
  379. 'generate_status' => '执行中',
  380. 'generate_at' => date('Y-m-d H:i:s'),
  381. 'updated_at' => date('Y-m-d H:i:s')
  382. ]);
  383. if (!$boolen) {
  384. Utils::throwError('20003:保存角色信息失败');
  385. }
  386. return $boolen;
  387. }
  388. public function editAnime($data) {
  389. $anime_id = getProp($data, 'anime_id');
  390. $anime_name = trim(getProp($data, 'anime_name'));
  391. // 确认对话名称唯一性
  392. if ($id = DB::table('mp_animes')->where('anime_name', $anime_name)->value('id')) {
  393. if ($id != $anime_id) $anime_name = $anime_name . '_' . date('YmdHis');
  394. }
  395. if (!$anime_id || !$anime_name) {
  396. Utils::throwError('20003:参数异常');
  397. }
  398. return DB::table('mp_animes')->where('id', $anime_id)->update([
  399. 'anime_name' => $anime_name,
  400. 'updated_at' => date('Y-m-d H:i:s')
  401. ]);
  402. // $script_arr =getProp($data, 'script', []);
  403. // if (!$script_arr) Utils::throwError('20003:剧本内容不能为空');
  404. // $start_episode_sequence = getProp($data, 'start_episode_sequence', 1);
  405. // $anime_id = getProp($data, 'anime_id');
  406. // try {
  407. // DB::beginTransaction();
  408. // $table_data = [
  409. // 'intro' => isset($script_arr['intro']) ? $script_arr['intro'] : '',
  410. // 'highlights' => isset($script_arr['highlights']) ? $script_arr['highlights'] : '',
  411. // 'role_relationship' => isset($script_arr['role_relationship']) ? $script_arr['role_relationship'] : '',
  412. // 'core_contradiction' => isset($script_arr['core_contradiction']) ? $script_arr['core_contradiction'] : '',
  413. // 'roles' => isset($script_arr['roles']) ? json_encode($script_arr['roles'], 256) : '',
  414. // 'art_style' => isset($script_arr['art_style']) ? $script_arr['art_style'] : '',
  415. // 'scenes' => isset($script_arr['scenes']) ? json_encode($script_arr['scenes'], 256) : '',
  416. // 'status' => 3,
  417. // 'start_episode_sequence' => $start_episode_sequence,
  418. // 'end_episode_sequence' => $start_episode_sequence + count($script_arr['episodes']) - 1,
  419. // 'episode_num' => count($script_arr['episodes']),
  420. // 'updated_at' => date('Y-m-d H:i:s')
  421. // ];
  422. // // 保存剧本内容
  423. // if (!empty($anime_id)) {
  424. // $boolen = DB::table('mp_animes')->where('id', $anime_id)->update($table_data);
  425. // if (!$boolen) {
  426. // dLog('anime')->info('对话保存失败', $table_data);
  427. // Utils::throwError('20003:对话保存失败');
  428. // }
  429. // }else {
  430. // $table['created_at'] = $table_data['updated_at'];
  431. // $anime_id = DB::table('mp_animes')->insertGetId($table_data);
  432. // if (!$anime_id) {
  433. // dLog('anime')->info('对话保存失败', $table_data);
  434. // Utils::throwError('20003:对话保存失败');
  435. // }
  436. // }
  437. // // 保存分集内容
  438. // // 删除历史分集内容
  439. // $boolen1 = DB::table('mp_anime_episodes')->where('anime_id', $anime_id)->delete();
  440. // $episodes = [];
  441. // $sequence = 1;
  442. // foreach ($script_arr['episodes'] as $episode) {
  443. // $segment_number = 1;
  444. // foreach($episode['segments'] as $segment) {
  445. // $episodes[] = [
  446. // 'anime_id' => $anime_id,
  447. // 'episode_number' => $episode['episode_number'],
  448. // 'title' => $episode['title'],
  449. // // 'content' => $episode['content'],
  450. // 'content' => '',
  451. // 'segment_number' => $segment_number,
  452. // 'segment_content' => $segment['segment_content'],
  453. // 'sequence' => $sequence,
  454. // 'created_at' => date('Y-m-d H:i:s'),
  455. // 'updated_at' => date('Y-m-d H:i:s')
  456. // ];
  457. // $sequence++;
  458. // $segment_number++;
  459. // }
  460. // }
  461. // $boolen2 = DB::table('mp_anime_episodes')->insert($episodes);
  462. // if (!$boolen2) {
  463. // dLog('deepseek')->info('分集内容保存失败', $episodes);
  464. // logDB('deepseek', 'error', '分集内容保存失败', ['episodes_count' => count($episodes)]);
  465. // Utils::throwError('20003:分集内容保存失败');
  466. // }
  467. // } catch (\Exception $e) {
  468. // DB::rollBack();
  469. // Utils::throwError('20003:'.$e->getMessage());
  470. // }
  471. // DB::commit();
  472. // return true;
  473. }
  474. public function delAnime($data) {
  475. $anime_id = getProp($data, 'anime_id');
  476. if (!$anime_id) {
  477. Utils::throwError('20003:请选择剧本');
  478. }
  479. return DB::table('mp_animes')->where('id', $anime_id)->update([
  480. 'is_deleted' => 1,
  481. 'updated_at' => date('Y-m-d H:i:s')
  482. ]);
  483. }
  484. public function animeDetail($data) {
  485. $uid = Site::getUid();
  486. $anime_id = getProp($data, 'anime_id');
  487. $anime = DB::table('mp_animes')->where('id', $anime_id)->where('is_deleted', 0)->where('user_id', $uid)
  488. ->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();
  489. if (!$anime) Utils::throwError('20003:权限不足');
  490. $anime = (array)$anime;
  491. $anime['roles'] = json_decode($anime['roles']);
  492. $anime['scenes'] = json_decode($anime['scenes']);
  493. // 获取分集信息
  494. $episodes = DB::table('mp_anime_episodes')->where('anime_id', $anime_id)->where('is_default', 1)
  495. ->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"))
  496. ->orderBy('episode_number')->get()->map(function ($value) {
  497. return (array)$value;
  498. })->toArray();
  499. $anime['episodes'] = $episodes;
  500. return $anime;
  501. }
  502. public function episodeInfo($data) {
  503. $uid = Site::getUid();
  504. $anime_id = getProp($data, 'anime_id');
  505. $episode_id = getProp($data, 'episode_id');
  506. if (!$anime_id || !$episode_id) {
  507. Utils::throwError('1002:请选择剧集');
  508. }
  509. // 验证用户权限
  510. $anime = DB::table('mp_animes')->where('id', $anime_id)->where('user_id', $uid)->where('is_deleted', 0)->first();
  511. if (!$anime) Utils::throwError('20003:权限不足');
  512. $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();
  513. if (!$episode) Utils::throwError('20003:该剧集不存在!');
  514. $episode = (array)$episode;
  515. $episode['roles'] = json_decode($episode['roles'], true);
  516. // foreach($episode['roles'] as &$item) {
  517. // if (isset($item['pic_prompt']) && mb_substr($item['pic_prompt'], 0, 11) != '写实。全景,正面拍摄。') $item['pic_prompt'] = '写实。全景,正面拍摄。'.$item['pic_prompt'];
  518. // }
  519. $episode['scenes'] = json_decode($episode['scenes'], true);
  520. // foreach($episode['scenes'] as &$item) {
  521. // if (isset($item['pic_prompt']) && mb_substr($item['pic_prompt'], 0, 3) != '写实。') $item['pic_prompt'] = '写实。'.$item['pic_prompt'];
  522. // }
  523. // 获取分镜信息
  524. $segments = DB::table('mp_episode_segments')->where('anime_id', $anime_id)->where('episode_id', getProp($episode, 'episode_id'))->orderBy('segment_number')
  525. ->select('*')->get()->map(function ($value) {
  526. return (array)$value;
  527. })->toArray();
  528. // 使用公共方法构建分镜结构
  529. $segmentsStructure = $this->buildEpisodeSegmentsStructure($segments);
  530. $episode['acts'] = $segmentsStructure['acts'];
  531. $episode['total_duration'] = $segmentsStructure['total_duration'];
  532. return $episode;
  533. }
  534. public function episodeInfoForAce($data) {
  535. $anime_id = getProp($data, 'anime_id');
  536. $episode_id = getProp($data, 'episode_id');
  537. if (!$anime_id || !$episode_id) {
  538. Utils::throwError('1002:请选择剧集');
  539. }
  540. $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();
  541. if (!$episode) Utils::throwError('20003:该剧集不存在!');
  542. $episode = (array)$episode;
  543. $episode['roles'] = json_decode($episode['roles'], true);
  544. // foreach($episode['roles'] as &$item) {
  545. // if (isset($item['pic_prompt']) && mb_substr($item['pic_prompt'], 0, 11) != '写实。全景,正面拍摄。') $item['pic_prompt'] = '写实。全景,正面拍摄。'.$item['pic_prompt'];
  546. // }
  547. $episode['scenes'] = json_decode($episode['scenes'], true);
  548. // foreach($episode['scenes'] as &$item) {
  549. // if (isset($item['pic_prompt']) && mb_substr($item['pic_prompt'], 0, 3) != '写实。') $item['pic_prompt'] = '写实。'.$item['pic_prompt'];
  550. // }
  551. $episode['props'] = $episode['props'] ? json_decode($episode['props'], true) : [];
  552. // 获取分镜信息
  553. $segments = DB::table('mp_episode_segments')->where('anime_id', $anime_id)->where('episode_id', getProp($episode, 'episode_id'))->orderBy('act_number')
  554. ->select('*')->get()->map(function ($value) {
  555. return (array)$value;
  556. })->toArray();
  557. $segmentsStructure = $this->buildEpisodeActsStructureForAce($segments);
  558. $episode['acts'] = $segmentsStructure['acts'];
  559. $episode['total_duration'] = $segmentsStructure['total_duration'];
  560. // 获取mp_animes表中的视频参数
  561. $anime = DB::table('mp_animes')->where('id', $anime_id)->first(['video_model', 'video_resolution', 'video_ratio']);
  562. $episode['video_params'] = [
  563. 'video_model' => getProp($anime, 'video_model'),
  564. 'video_resolution' => getProp($anime, 'video_resolution'),
  565. 'ratio' => getProp($anime, 'video_ratio'),
  566. ];
  567. return $episode;
  568. }
  569. public function segmentInfo($data) {
  570. $uid = Site::getUid();
  571. $segment_id = getProp($data, 'segment_id');
  572. if (!$segment_id) {
  573. Utils::throwError('1002:请选择分镜');
  574. }
  575. // 获取分镜信息
  576. $segment = DB::table('mp_episode_segments')->where('segment_id', $segment_id)->first();
  577. // 验证用户权限
  578. if ($segment) {
  579. $anime = DB::table('mp_animes')->where('id', getProp($segment, 'anime_id'))->where('user_id', $uid)->where('is_deleted', 0)->first();
  580. if (!$anime) Utils::throwError('20003:权限不足');
  581. }
  582. $result = [
  583. 'segment_id' => getProp($segment, 'segment_id'),
  584. 'segment_number' => getProp($segment, 'segment_number'),
  585. 'segment_content' => getProp($segment, 'segment_content'),
  586. 'description' => getProp($segment, 'description'),
  587. 'composition' => getProp($segment, 'composition'),
  588. 'camera_movement' => getProp($segment, 'camera_movement'),
  589. 'voice_actor' => getProp($segment, 'voice_actor'),
  590. 'dialogue' => getProp($segment, 'dialogue'),
  591. 'frame_type' => getProp($segment, 'frame_type'),
  592. 'scene' => getProp($segment, 'scene'),
  593. 'characters' => getProp($segment, 'characters'),
  594. 'tail_frame' => getProp($segment, 'tail_frame'),
  595. 'emotion' => getProp($segment, 'emotion'),
  596. 'emotion_type' => getProp($segment, 'emotion_type'),
  597. 'gender' => getProp($segment, 'gender'),
  598. 'speed_ratio' => getProp($segment, 'speed_ratio'),
  599. 'loudness_ratio' => getProp($segment, 'loudness_ratio'),
  600. 'emotion_scale' => getProp($segment, 'emotion_scale'),
  601. 'pitch' => getProp($segment, 'pitch'),
  602. 'voice_name' => getProp($segment, 'voice_name'),
  603. 'voice_type' => getProp($segment, 'voice_type'),
  604. 'voice_audio_url' => getProp($segment, 'voice_audio_url'),
  605. 'img_url' => getProp($segment, 'img_url'),
  606. 'video_url' => getProp($segment, 'video_url'),
  607. 'last_frame_url' => getProp($segment, 'last_frame_url'),
  608. ];
  609. return $result;
  610. }
  611. public function copyEpisodeVersion($data) {
  612. $episode_id = getProp($data, 'episode_id');
  613. $uid = Site::getUid();
  614. $cpid = Site::getCpid();
  615. $episode = DB::table('mp_anime_episodes')->where('id', $episode_id)->first();
  616. if (!$episode) Utils::throwError('20003:该剧集不存在');
  617. $episode = (array)$episode;
  618. $anime_id = $episode['anime_id'];
  619. $episode_number = $episode['episode_number'];
  620. $count = DB::table('mp_anime_episodes')->where('anime_id', $anime_id)->where('episode_number', $episode_number)->count('id');
  621. $sequence = $count + 1;
  622. unset($episode['id']);
  623. $now = date('Y-m-d H:i:s');
  624. $episode['created_at'] = $now;
  625. $episode['updated_at'] = $now;
  626. $episode['is_default'] = 1;
  627. // 获取版本中含有"(副本"字样的个数
  628. $copy_count = DB::table('mp_anime_episodes')->where('anime_id', $anime_id)->where('episode_number', $episode_number)->where('title', 'like', '%(副本%')->count('id');
  629. $episode['title'] = $copy_count > 0 ? $episode['title']."(副本{$copy_count})" : $episode['title']."(副本)"; // 生成带(副本)字样的标题
  630. $episode['sequence'] = $sequence;
  631. $episode['is_generated'] = 0;
  632. $episode['cpid'] = $cpid;
  633. // 获取ace_mode
  634. $ace_mode = DB::table('mp_animes')->where('id', $anime_id)->value('ace_mode');
  635. try {
  636. DB::beginTransaction();
  637. DB::table('mp_anime_episodes')->where('anime_id', $anime_id)->where('episode_number', $episode_number)->update(['is_default' => 0, 'updated_at'=>$now]);
  638. // 新增副本
  639. $new_episode_id = DB::table('mp_anime_episodes')->insertGetId($episode);
  640. if (!$new_episode_id) {
  641. Utils::throwError('20003:创建副本失败!');
  642. }
  643. // 获取分镜数据并准备插入
  644. $segments_for_insert = DB::table('mp_episode_segments')
  645. ->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')
  646. ->where('episode_id', $episode_id)->orderBy('segment_number')->get()->map(function($item) use ($new_episode_id,$ace_mode) {
  647. $item = (array)$item;
  648. $item['episode_id'] = $new_episode_id;
  649. if ((int)$ace_mode !== 1) $item['segment_id'] = date('YmdHis').mt_rand(1000,9999).str_pad($item['segment_number'], 3, "0", STR_PAD_LEFT);
  650. $item['created_at'] = $item['updated_at'] = date('Y-m-d H:i:s');
  651. return $item;
  652. })->toArray();
  653. // 写入分镜数据
  654. $boolen2 = DB::table('mp_episode_segments')->insert($segments_for_insert);
  655. if (!$boolen2) {
  656. Utils::throwError('20003:写入分镜数据失败!');
  657. }
  658. // 写入对话历史
  659. $records = [
  660. [
  661. 'uid' => $uid,
  662. 'anime_id' => $anime_id,
  663. 'role' => 'user',
  664. 'content' => '创建副本',
  665. 'sequence' => $episode_number,
  666. 'episode_id' => $new_episode_id,
  667. 'created_at' => $now,
  668. 'updated_at' => $now
  669. ],
  670. [
  671. 'uid' => $uid,
  672. 'anime_id' => $anime_id,
  673. 'role' => 'assistant',
  674. 'content' => '好的,已为您创建副本',
  675. 'sequence' => $episode_number,
  676. 'episode_id' => $new_episode_id,
  677. 'created_at' => $now,
  678. 'updated_at' => $now
  679. ]
  680. ];
  681. $boolen3 = DB::table('mp_anime_records')->insert($records);
  682. if (!$boolen3) {
  683. Utils::throwError('20003:对话记录保存失败');
  684. }
  685. }catch (\Exception $e) {
  686. DB::rollBack();
  687. Utils::throwError('20003:'.$e->getMessage());
  688. }
  689. DB::commit();
  690. // 构建与 episodeInfo 方法一致的返回数据结构
  691. $result = [
  692. 'episode_id' => $new_episode_id,
  693. 'anime_id' => $anime_id,
  694. 'episode_number' => $episode_number,
  695. 'title' => $episode['title'],
  696. 'intro' => $episode['intro'],
  697. 'art_style' => $episode['art_style'],
  698. 'roles' => json_decode($episode['roles'], true),
  699. 'scenes' => json_decode($episode['scenes'], true),
  700. 'is_generated' => (int)$episode['is_generated']
  701. ];
  702. if ((int)$ace_mode === 1) {
  703. // 获取分镜信息
  704. $segments = DB::table('mp_episode_segments')->where('anime_id', $anime_id)->where('episode_id', $new_episode_id)->orderBy('act_number')
  705. ->select('*')->get()->map(function ($value) {
  706. return (array)$value;
  707. })->toArray();
  708. $segmentsStructure = $this->buildEpisodeActsStructureForAce($segments);
  709. }else {
  710. // 复用已有的分镜数据,按 act 分组(避免重复查询数据库)
  711. $segmentsStructure = $this->buildEpisodeSegmentsStructure($segments_for_insert);
  712. }
  713. $result['acts'] = $segmentsStructure['acts'];
  714. $result['total_duration'] = $segmentsStructure['total_duration'];
  715. return $result;
  716. }
  717. public function episodeVersions($data) {
  718. $anime_id = getProp($data, 'anime_id');
  719. $episode_id = getProp($data, 'episode_id');
  720. if (!$anime_id || !$episode_id) {
  721. Utils::throwError('1002:请选择剧集');
  722. }
  723. $episode_number = DB::table('mp_anime_episodes')->where('anime_id', $anime_id)->where('id', $episode_id)->value('episode_number');
  724. $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) {
  725. return (array)$value;
  726. })->toArray();
  727. if (!$episodes) Utils::throwError('20003:该剧集不存在!');
  728. foreach($episodes as &$episode) {
  729. $episode['version'] = 'V'.$episode['sequence'];
  730. $episode['roles'] = json_decode($episode['roles'], true);
  731. $episode['scenes'] = json_decode($episode['scenes'], true);
  732. // 获取分镜信息
  733. $segments = DB::table('mp_episode_segments')->where('anime_id', $anime_id)->where('episode_id', getProp($episode, 'episode_id'))->orderBy('segment_number')
  734. ->select('*')->get()->map(function ($value) {
  735. return (array)$value;
  736. })->toArray();
  737. // 使用公共方法构建分镜结构
  738. $segmentsStructure = $this->buildEpisodeSegmentsStructure($segments);
  739. $episode['acts'] = $segmentsStructure['acts'];
  740. $episode['total_duration'] = $segmentsStructure['total_duration'];
  741. }
  742. return $episodes;
  743. }
  744. public function bindEpisodeVersion($data) {
  745. $episode_id = getProp($data, 'episode_id');
  746. $episode = DB::table('mp_anime_episodes')->where('id', $episode_id)->first();
  747. if (!$episode) Utils::throwError('20003:该剧集不存在');
  748. $episode = (array)$episode;
  749. if ((int)$episode['is_default'] === 1) return true;
  750. try {
  751. DB::beginTransaction();
  752. // 移除is_default标志
  753. $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')]);
  754. if (!$boolen) {
  755. Utils::throwError('20003:更新失败!');
  756. }
  757. // 绑定副本
  758. $boolen2 = DB::table('mp_anime_episodes')->where('id', $episode_id)->update(['is_default' => 1, 'updated_at'=>date('Y-m-d H:i:s')]);
  759. if (!$boolen2) {
  760. Utils::throwError('20003:绑定失败!');
  761. }
  762. }catch (\Exception $e) {
  763. DB::rollBack();
  764. Utils::throwError('20003:'.$e->getMessage());
  765. }
  766. DB::commit();
  767. return true;
  768. }
  769. public function chatChangeImg($data) {
  770. $segment_id = getProp($data, 'segment_id');
  771. $type = getProp($data, 'type', 1); // 类型: 1.对话改图 2.图片生成
  772. $prompt = getProp($data, 'prompt');
  773. if (!$prompt || !$segment_id) {
  774. Utils::throwError('1002:请输入提示词,并且选择分镜');
  775. }
  776. $segment = DB::table("mp_episode_segments")->where('segment_id', $segment_id)->first();
  777. if (!$segment) Utils::throwError('20003:该分镜不存在!');
  778. if ((int)$type === 1) $ref_img_url = getProp($segment, 'img_url');
  779. else $ref_img_url = '';
  780. // $ref_img_url = '';
  781. if (empty($prompt)) {
  782. if (empty($ref_img_url)) {
  783. $prompt = getProp($segment, 'segment_content');
  784. }else {
  785. $prompt = '请根据图片生成';
  786. }
  787. }
  788. $anime_id = getProp($segment, 'anime_id');
  789. $episode_id = getProp($segment, 'episode_id');
  790. $episode_number = getProp($segment, 'episode_number');
  791. $episode = DB::table('mp_anime_episodes')->where('id', $episode_id)->first();
  792. $ratio = getProp($data, 'ratio');
  793. if (!$ratio) {
  794. $ratio = getProp($episode, 'ratio');
  795. if (!$ratio) $ratio = '9:16';
  796. }
  797. $art_style = getProp($episode, 'art_style');
  798. if ($art_style) {
  799. $prompt = "美术风格:{$art_style}\n{$prompt}";
  800. }
  801. $dimensions = $this->getRatioDimensions($ratio);
  802. $width = $dimensions['width'];
  803. $height = $dimensions['height'];
  804. try {
  805. $params = [
  806. 'alias_segment_id' => $segment_id,
  807. 'prompt' => $prompt,
  808. 'ref_img_urls' => !empty($ref_img_url) ? [$ref_img_url] : [],
  809. 'width' => $width,
  810. 'height' => $height
  811. ];
  812. // 优化提示词(不要生成字幕)
  813. $params['prompt'] = "前置要求:图片中不要带有任何对话台词或字幕信息\n".$params['prompt'];
  814. $task = $this->aiImageGenerationService->createImageGenerationTask($params);
  815. $task_id = $task->id;
  816. if (!$task_id) {
  817. Utils::throwError("20003:生成图片失败");
  818. }
  819. // 更新任务ID
  820. $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')]);
  821. if (!$boolen) Utils::throwError('20003:更新任务ID失败');
  822. } catch (\Exception $e) {
  823. Utils::throwError("20003:" . $e->getMessage());
  824. }
  825. // 创建任务之后先暂停10s等待异步任务完成
  826. sleep(10);
  827. $img_url = $this->loopGetPicTaskResult($task_id);
  828. if (!$img_url) Utils::throwError('20003:图片生成中,请稍后刷新');
  829. // 图片生成后新增对话记录
  830. try {
  831. $uid = Site::getUid();
  832. $now = date('Y-m-d H:i:s');
  833. // 使用AI反推图片提示词
  834. $pic_prompt = $this->generateImagePromptFromUrl($img_url);
  835. // 保存对话记录
  836. $records = [
  837. [
  838. 'uid' => $uid,
  839. 'anime_id' => $anime_id,
  840. 'sequence' => $episode_number,
  841. 'role' => 'user',
  842. 'content' => $prompt,
  843. 'segment_id' => $segment_id,
  844. 'pic_task_id' => $task_id,
  845. 'image_url' => '',
  846. 'created_at' => $now,
  847. 'updated_at' => $now
  848. ],
  849. [
  850. 'uid' => $uid,
  851. 'anime_id' => $anime_id,
  852. 'sequence' => $episode_number,
  853. 'role' => 'assistant',
  854. 'content' => $pic_prompt,
  855. 'segment_id' => $segment_id,
  856. 'pic_task_id' => $task_id,
  857. 'image_url' => $img_url,
  858. 'created_at' => $now,
  859. 'updated_at' => $now
  860. ]
  861. ];
  862. DB::table('mp_anime_records')->insert($records);
  863. } catch (\Exception $e) {
  864. // 记录日志但不影响主流程
  865. dLog('anime')->error('保存对话记录失败: ' . $e->getMessage(), [
  866. 'segment_id' => $segment_id,
  867. 'img_url' => $img_url
  868. ]);
  869. logDB('anime', 'error', '保存对话记录失败', [
  870. 'segment_id' => $segment_id,
  871. 'img_url' => $img_url,
  872. 'error' => $e->getMessage()
  873. ]);
  874. }
  875. return $img_url;
  876. }
  877. public function segmentChatHistory($data) {
  878. $segment_id = getProp($data, 'segment_id');
  879. if (!$segment_id) Utils::throwError('20003:请选择分镜!');
  880. $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');
  881. $chat = $query->orderBy('id')->get()->map(function ($value) {
  882. $value = (array)$value;
  883. $value['created_at'] = transDate($value['created_at']);
  884. return $value;
  885. })->toArray();
  886. // 获取历史图片
  887. $url = [];
  888. $pic_history = DB::table('mp_generate_pic_tasks')->where('alias_segment_id', $segment_id)->where('status', 'success')->orderBy('created_at', 'desc')->get();
  889. foreach($pic_history as $task) {
  890. $result_url = getProp($task, 'result_url');
  891. if (is_json($result_url)) {
  892. $url = array_merge($url, json_decode($result_url, true));
  893. }else {
  894. $url[] = $result_url;
  895. }
  896. }
  897. // 获取历史视频
  898. $video_history = DB::table('mp_generate_video_tasks')->where('alias_segment_id', $segment_id)->where('status', 'success')->orderBy('created_at', 'desc')->get();
  899. foreach($video_history as $task) {
  900. $result_url = getProp($task, 'compressed_url');
  901. if (is_json($result_url)) {
  902. $url = array_merge($url, json_decode($result_url, true));
  903. }else {
  904. $url[] = $result_url;
  905. }
  906. }
  907. return compact('chat', 'url');
  908. }
  909. public function changeEpisodeRoles($data) {
  910. $anime_id = getProp($data, 'anime_id');
  911. $episode_id = getProp($data, 'episode_id');
  912. $target_roles = getProp($data, 'roles');
  913. $is_deleted = getProp($data, 'is_deleted', 0);
  914. // 参数验证
  915. if (!$anime_id) Utils::throwError('20003:请提供动漫ID');
  916. if (!$episode_id) Utils::throwError('20003:请提供剧集ID');
  917. if (!$target_roles) Utils::throwError('20003:请提供角色信息');
  918. // 验证剧集是否存在
  919. $episode = DB::table('mp_anime_episodes')
  920. ->where('anime_id', $anime_id)
  921. ->where('id', $episode_id)
  922. ->first();
  923. if (!$episode) Utils::throwError('20003:该剧集不存在');
  924. $roles = json_decode(getProp($episode, 'roles'), true);
  925. // 获取anime信息,检查是否有关联的script_id
  926. $anime = DB::table('mp_animes')->where('id', $anime_id)->first();
  927. if (!$anime) Utils::throwError('20003:动漫不存在');
  928. $script_id = getProp($anime, 'script_id');
  929. $episode_number = getProp($episode, 'episode_number', 1);
  930. $uid = Site::getUid();
  931. $cpid = Site::getCpid();
  932. try {
  933. $target_role_name = getProp($target_roles, 'role');
  934. if (empty($target_role_name)) {
  935. Utils::throwError('20003:角色名称不能为空');
  936. }
  937. // 如果是删除操作
  938. if ($is_deleted == 1) {
  939. // 从角色列表中移除该角色
  940. $roles = array_values(array_filter($roles, function($role) use ($target_role_name) {
  941. return getProp($role, 'role') !== $target_role_name;
  942. }));
  943. // 更新角色列表
  944. $result = DB::table('mp_anime_episodes')
  945. ->where('anime_id', $anime_id)
  946. ->where('id', $episode_id)
  947. ->update([
  948. 'roles' => json_encode($roles, 256),
  949. 'updated_at' => date('Y-m-d H:i:s')
  950. ]);
  951. if ($result === false) {
  952. Utils::throwError('20003:删除角色失败');
  953. }
  954. } else {
  955. // 新增或更新操作
  956. $role_found = false;
  957. $is_new_role = false;
  958. // 查找并更新已存在的角色
  959. foreach($roles as &$role) {
  960. if (getProp($role, 'role') === $target_role_name) {
  961. $role = $target_roles;
  962. $role_found = true;
  963. break;
  964. }
  965. }
  966. // 如果角色不存在,则新增
  967. if (!$role_found) {
  968. $roles[] = $target_roles;
  969. $is_new_role = true;
  970. }
  971. // 更新角色列表
  972. $result = DB::table('mp_anime_episodes')
  973. ->where('anime_id', $anime_id)
  974. ->where('id', $episode_id)
  975. ->update([
  976. 'roles' => json_encode($roles, 256),
  977. 'updated_at' => date('Y-m-d H:i:s')
  978. ]);
  979. if ($result === false) {
  980. Utils::throwError('20003:更新角色列表失败');
  981. }
  982. // 同步更新分镜表中对应主体的音色信息
  983. $voice_name = getProp($target_roles, 'voice_name');
  984. $voice_type = getProp($target_roles, 'voice_type');
  985. $voice_audio_url = getProp($target_roles, 'voice_audio_url');
  986. DB::table('mp_episode_segments')
  987. ->where('anime_id', $anime_id)
  988. ->where('episode_id', $episode_id)
  989. ->where('voice_actor', $target_role_name)
  990. ->update([
  991. 'voice_name' => $voice_name,
  992. 'voice_type' => $voice_type,
  993. 'voice_audio_url' => $voice_audio_url,
  994. 'updated_at' => date('Y-m-d H:i:s')
  995. ]);
  996. // 如果有关联的script_id,则同步到mp_products表
  997. if ($script_id) {
  998. // 查询剧本信息
  999. $script = DB::table('mp_scripts')
  1000. ->where('id', $script_id)
  1001. ->where('is_deleted', 0)
  1002. ->first();
  1003. if ($script) {
  1004. $script_name = $script->script_name ?? 'script_' . $script_id;
  1005. $product_name = getProp($target_roles, 'role');
  1006. $pic_prompt = getProp($target_roles, 'pic_prompt', '');
  1007. $url = getProp($target_roles, 'url', '');
  1008. $product_type = 1; // 1=角色
  1009. // 查找或创建以script_name命名的文件夹
  1010. $folder = DB::table('mp_products')
  1011. ->where('cpid', $cpid)
  1012. ->where('type', 2) // 文件夹类型
  1013. ->where('product', $product_type) // 角色类型
  1014. ->where('product_name', $script_name)
  1015. ->where('parent_id', 0)
  1016. ->where('is_deleted', 0)
  1017. ->first();
  1018. if (!$folder) {
  1019. // 创建文件夹
  1020. $folder_id = DB::table('mp_products')->insertGetId([
  1021. 'user_id' => $uid,
  1022. 'cpid' => $cpid,
  1023. 'type' => 2, // 文件夹
  1024. 'product' => $product_type, // 角色类型
  1025. 'parent_id' => 0,
  1026. 'level' => 1,
  1027. 'product_name' => $script_name,
  1028. 'sort_order' => time(),
  1029. 'is_deleted' => 0,
  1030. 'created_at' => date('Y-m-d H:i:s'),
  1031. 'updated_at' => date('Y-m-d H:i:s')
  1032. ]);
  1033. } else {
  1034. $folder_id = $folder->id;
  1035. }
  1036. // 查找该文件夹下是否已存在同名资产
  1037. $existing_product = DB::table('mp_products')
  1038. ->where('cpid', $cpid)
  1039. ->where('type', 1) // 资产类型
  1040. ->where('product', $product_type)
  1041. ->where('parent_id', $folder_id)
  1042. ->where('product_name', $product_name)
  1043. ->where('is_deleted', 0)
  1044. ->first();
  1045. if ($existing_product) {
  1046. // 更新已存在的资产
  1047. $updateData = [
  1048. 'pic_task_status' => '生成成功',
  1049. ];
  1050. if ($pic_prompt) $updateData['pic_prompt'] = $pic_prompt;
  1051. if ($url) $updateData['url'] = $url;
  1052. // 处理versions字段
  1053. $versions = getProp($target_roles, 'versions', []);
  1054. if ($versions && is_array($versions)) {
  1055. $updateData['versions'] = json_encode($versions, 256);
  1056. }
  1057. $updateData['updated_at'] = date('Y-m-d H:i:s');
  1058. DB::table('mp_products')
  1059. ->where('id', $existing_product->id)
  1060. ->update($updateData);
  1061. $product_id = $existing_product->id;
  1062. } else {
  1063. // 创建新资产
  1064. $versions = getProp($target_roles, 'versions', []);
  1065. $product_id = DB::table('mp_products')->insertGetId([
  1066. 'user_id' => $uid,
  1067. 'cpid' => $cpid,
  1068. 'type' => 1, // 资产
  1069. 'product' => $product_type, // 角色
  1070. 'parent_id' => $folder_id,
  1071. 'level' => 2,
  1072. 'product_name' => $product_name,
  1073. 'url' => $url,
  1074. 'pic_prompt' => $pic_prompt,
  1075. 'versions' => is_array($versions) ? json_encode($versions, 256) : '[]',
  1076. 'sort_order' => time(),
  1077. 'is_deleted' => 0,
  1078. 'pic_task_status' => '生成成功',
  1079. 'created_at' => date('Y-m-d H:i:s'),
  1080. 'updated_at' => date('Y-m-d H:i:s')
  1081. ]);
  1082. }
  1083. // 建立或更新绑定关系
  1084. $existing_mapping = DB::table('mp_script_product_mappings')
  1085. ->where('script_id', $script_id)
  1086. ->where('product_id', $product_id)
  1087. ->where('episode_number', $episode_number)
  1088. ->first();
  1089. if (!$existing_mapping) {
  1090. // 创建绑定关系
  1091. DB::table('mp_script_product_mappings')->insert([
  1092. 'script_id' => $script_id,
  1093. 'product_id' => $product_id,
  1094. 'episode_number' => $episode_number,
  1095. 'created_at' => date('Y-m-d H:i:s'),
  1096. 'updated_at' => date('Y-m-d H:i:s')
  1097. ]);
  1098. }
  1099. }
  1100. }
  1101. }
  1102. } catch (\Exception $e) {
  1103. dLog('anime')->error('更新剧集角色失败', [
  1104. 'anime_id' => $anime_id,
  1105. 'episode_id' => $episode_id,
  1106. 'error' => $e->getMessage()
  1107. ]);
  1108. Utils::throwError('20003:更新角色列表失败 ' . $e->getMessage());
  1109. }
  1110. return true;
  1111. }
  1112. public function changeEpisodeScenes($data) {
  1113. $anime_id = getProp($data, 'anime_id');
  1114. $episode_id = getProp($data, 'episode_id');
  1115. $target_scenes = getProp($data, 'scenes');
  1116. $is_deleted = getProp($data, 'is_deleted', 0);
  1117. // 参数验证
  1118. if (!$anime_id) Utils::throwError('20003:请提供动漫ID');
  1119. if (!$episode_id) Utils::throwError('20003:请提供剧集ID');
  1120. if (!$target_scenes) Utils::throwError('20003:请提供场景信息');
  1121. // 验证剧集是否存在
  1122. $episode = DB::table('mp_anime_episodes')
  1123. ->where('anime_id', $anime_id)
  1124. ->where('id', $episode_id)
  1125. ->first();
  1126. if (!$episode) Utils::throwError('20003:该剧集不存在');
  1127. $scenes = json_decode(getProp($episode, 'scenes'), true);
  1128. // 获取anime信息,检查是否有关联的script_id
  1129. $anime = DB::table('mp_animes')->where('id', $anime_id)->first();
  1130. if (!$anime) Utils::throwError('20003:动漫不存在');
  1131. $script_id = getProp($anime, 'script_id');
  1132. $episode_number = getProp($episode, 'episode_number', 1);
  1133. $uid = Site::getUid();
  1134. $cpid = Site::getCpid();
  1135. try {
  1136. $target_scene_name = getProp($target_scenes, 'scene');
  1137. if (empty($target_scene_name)) {
  1138. Utils::throwError('20003:场景名称不能为空');
  1139. }
  1140. // 如果是删除操作
  1141. if ($is_deleted == 1) {
  1142. // 从场景列表中移除该场景
  1143. $scenes = array_values(array_filter($scenes, function($scene) use ($target_scene_name) {
  1144. return getProp($scene, 'scene') !== $target_scene_name;
  1145. }));
  1146. // 更新场景列表
  1147. $result = DB::table('mp_anime_episodes')
  1148. ->where('anime_id', $anime_id)
  1149. ->where('id', $episode_id)
  1150. ->update([
  1151. 'scenes' => json_encode($scenes, 256),
  1152. 'updated_at' => date('Y-m-d H:i:s')
  1153. ]);
  1154. if ($result === false) {
  1155. Utils::throwError('20003:删除场景失败');
  1156. }
  1157. } else {
  1158. // 新增或更新操作
  1159. $scene_found = false;
  1160. $is_new_scene = false;
  1161. // 查找并更新已存在的场景
  1162. foreach($scenes as &$scene) {
  1163. if (getProp($scene, 'scene') === $target_scene_name) {
  1164. $scene = $target_scenes;
  1165. $scene_found = true;
  1166. break;
  1167. }
  1168. }
  1169. // 如果场景不存在,则新增
  1170. if (!$scene_found) {
  1171. $scenes[] = $target_scenes;
  1172. $is_new_scene = true;
  1173. }
  1174. // 更新场景列表
  1175. $result = DB::table('mp_anime_episodes')
  1176. ->where('anime_id', $anime_id)
  1177. ->where('id', $episode_id)
  1178. ->update([
  1179. 'scenes' => json_encode($scenes, 256),
  1180. 'updated_at' => date('Y-m-d H:i:s')
  1181. ]);
  1182. if ($result === false) {
  1183. Utils::throwError('20003:更新场景列表失败');
  1184. }
  1185. // 如果有关联的script_id,则同步到mp_products表
  1186. if ($script_id) {
  1187. // 查询剧本信息
  1188. $script = DB::table('mp_scripts')
  1189. ->where('id', $script_id)
  1190. ->where('is_deleted', 0)
  1191. ->first();
  1192. if ($script) {
  1193. $script_name = $script->script_name ?? 'script_' . $script_id;
  1194. $product_name = getProp($target_scenes, 'scene');
  1195. $pic_prompt = getProp($target_scenes, 'pic_prompt', '');
  1196. $url = getProp($target_scenes, 'url', '');
  1197. $product_type = 2; // 2=场景
  1198. // 查找或创建以script_name命名的文件夹
  1199. $folder = DB::table('mp_products')
  1200. ->where('cpid', $cpid)
  1201. ->where('type', 2) // 文件夹类型
  1202. ->where('product', $product_type) // 场景类型
  1203. ->where('product_name', $script_name)
  1204. ->where('parent_id', 0)
  1205. ->where('is_deleted', 0)
  1206. ->first();
  1207. if (!$folder) {
  1208. // 创建文件夹
  1209. $folder_id = DB::table('mp_products')->insertGetId([
  1210. 'user_id' => $uid,
  1211. 'cpid' => $cpid,
  1212. 'type' => 2, // 文件夹
  1213. 'product' => $product_type, // 场景类型
  1214. 'parent_id' => 0,
  1215. 'level' => 1,
  1216. 'product_name' => $script_name,
  1217. 'sort_order' => time(),
  1218. 'is_deleted' => 0,
  1219. 'created_at' => date('Y-m-d H:i:s'),
  1220. 'updated_at' => date('Y-m-d H:i:s')
  1221. ]);
  1222. } else {
  1223. $folder_id = $folder->id;
  1224. }
  1225. // 查找该文件夹下是否已存在同名资产
  1226. $existing_product = DB::table('mp_products')
  1227. ->where('cpid', $cpid)
  1228. ->where('type', 1) // 资产类型
  1229. ->where('product', $product_type)
  1230. ->where('parent_id', $folder_id)
  1231. ->where('product_name', $product_name)
  1232. ->where('is_deleted', 0)
  1233. ->first();
  1234. if ($existing_product) {
  1235. // 更新已存在的资产
  1236. $updateData = [
  1237. 'pic_task_status' => '生成成功'
  1238. ];
  1239. if ($pic_prompt) $updateData['pic_prompt'] = $pic_prompt;
  1240. if ($url) $updateData['url'] = $url;
  1241. // 处理versions字段
  1242. $versions = getProp($target_scenes, 'versions', []);
  1243. if ($versions && is_array($versions)) {
  1244. $updateData['versions'] = json_encode($versions, 256);
  1245. }
  1246. $updateData['updated_at'] = date('Y-m-d H:i:s');
  1247. DB::table('mp_products')
  1248. ->where('id', $existing_product->id)
  1249. ->update($updateData);
  1250. $product_id = $existing_product->id;
  1251. } else {
  1252. // 创建新资产
  1253. $versions = getProp($target_scenes, 'versions', []);
  1254. $product_id = DB::table('mp_products')->insertGetId([
  1255. 'user_id' => $uid,
  1256. 'cpid' => $cpid,
  1257. 'type' => 1, // 资产
  1258. 'product' => $product_type, // 场景
  1259. 'parent_id' => $folder_id,
  1260. 'level' => 2,
  1261. 'product_name' => $product_name,
  1262. 'url' => $url,
  1263. 'pic_prompt' => $pic_prompt,
  1264. 'versions' => is_array($versions) ? json_encode($versions, 256) : '[]',
  1265. 'sort_order' => time(),
  1266. 'is_deleted' => 0,
  1267. 'pic_task_status' => '生成成功',
  1268. 'created_at' => date('Y-m-d H:i:s'),
  1269. 'updated_at' => date('Y-m-d H:i:s')
  1270. ]);
  1271. }
  1272. // 建立或更新绑定关系
  1273. $existing_mapping = DB::table('mp_script_product_mappings')
  1274. ->where('script_id', $script_id)
  1275. ->where('product_id', $product_id)
  1276. ->where('episode_number', $episode_number)
  1277. ->first();
  1278. if (!$existing_mapping) {
  1279. // 创建绑定关系
  1280. DB::table('mp_script_product_mappings')->insert([
  1281. 'script_id' => $script_id,
  1282. 'product_id' => $product_id,
  1283. 'episode_number' => $episode_number,
  1284. 'created_at' => date('Y-m-d H:i:s'),
  1285. 'updated_at' => date('Y-m-d H:i:s')
  1286. ]);
  1287. }
  1288. }
  1289. }
  1290. }
  1291. } catch (\Exception $e) {
  1292. dLog('anime')->error('更新剧集场景失败', [
  1293. 'anime_id' => $anime_id,
  1294. 'episode_id' => $episode_id,
  1295. 'error' => $e->getMessage()
  1296. ]);
  1297. Utils::throwError('20003:更新场景列表失败 ' . $e->getMessage());
  1298. }
  1299. return true;
  1300. }
  1301. public function changeEpisodeProps($data) {
  1302. $anime_id = getProp($data, 'anime_id');
  1303. $episode_id = getProp($data, 'episode_id');
  1304. $target_props = getProp($data, 'props');
  1305. $is_deleted = getProp($data, 'is_deleted', 0);
  1306. // 参数验证
  1307. if (!$anime_id) Utils::throwError('20003:请提供动漫ID');
  1308. if (!$episode_id) Utils::throwError('20003:请提供剧集ID');
  1309. if (!$target_props) Utils::throwError('20003:请提供道具信息');
  1310. // 验证剧集是否存在
  1311. $episode = DB::table('mp_anime_episodes')
  1312. ->where('anime_id', $anime_id)
  1313. ->where('id', $episode_id)
  1314. ->first();
  1315. if (!$episode) Utils::throwError('20003:该剧集不存在');
  1316. $props = json_decode(getProp($episode, 'props'), true);
  1317. // 获取anime信息,检查是否有关联的script_id
  1318. $anime = DB::table('mp_animes')->where('id', $anime_id)->first();
  1319. if (!$anime) Utils::throwError('20003:动漫不存在');
  1320. $script_id = getProp($anime, 'script_id');
  1321. $episode_number = getProp($episode, 'episode_number', 1);
  1322. $uid = Site::getUid();
  1323. $cpid = Site::getCpid();
  1324. try {
  1325. $target_prop_name = getProp($target_props, 'prop');
  1326. if (empty($target_prop_name)) {
  1327. Utils::throwError('20003:道具名称不能为空');
  1328. }
  1329. // 如果是删除操作
  1330. if ($is_deleted == 1) {
  1331. // 从道具列表中移除该道具
  1332. $props = array_values(array_filter($props, function($prop) use ($target_prop_name) {
  1333. return getProp($prop, 'prop') !== $target_prop_name;
  1334. }));
  1335. // 更新道具列表
  1336. $result = DB::table('mp_anime_episodes')
  1337. ->where('anime_id', $anime_id)
  1338. ->where('id', $episode_id)
  1339. ->update([
  1340. 'props' => json_encode($props, 256),
  1341. 'updated_at' => date('Y-m-d H:i:s')
  1342. ]);
  1343. if ($result === false) {
  1344. Utils::throwError('20003:删除道具失败');
  1345. }
  1346. } else {
  1347. // 新增或更新操作
  1348. $prop_found = false;
  1349. $is_new_prop = false;
  1350. // 查找并更新已存在的道具
  1351. foreach($props as &$prop) {
  1352. if (getProp($prop, 'prop') === $target_prop_name) {
  1353. $prop = $target_props;
  1354. $prop_found = true;
  1355. break;
  1356. }
  1357. }
  1358. // 如果道具不存在,则新增
  1359. if (!$prop_found) {
  1360. $props[] = $target_props;
  1361. $is_new_prop = true;
  1362. }
  1363. // 更新道具列表
  1364. $result = DB::table('mp_anime_episodes')
  1365. ->where('anime_id', $anime_id)
  1366. ->where('id', $episode_id)
  1367. ->update([
  1368. 'props' => json_encode($props, 256),
  1369. 'updated_at' => date('Y-m-d H:i:s')
  1370. ]);
  1371. if ($result === false) {
  1372. Utils::throwError('20003:更新道具列表失败');
  1373. }
  1374. // 如果有关联的script_id,则同步到mp_products表
  1375. if ($script_id) {
  1376. // 查询剧本信息
  1377. $script = DB::table('mp_scripts')
  1378. ->where('id', $script_id)
  1379. ->where('is_deleted', 0)
  1380. ->first();
  1381. if ($script) {
  1382. $script_name = $script->script_name ?? 'script_' . $script_id;
  1383. $product_name = getProp($target_props, 'prop');
  1384. $pic_prompt = getProp($target_props, 'pic_prompt', '');
  1385. $url = getProp($target_props, 'url', '');
  1386. $product_type = 3; // 3=道具
  1387. // 查找或创建以script_name命名的文件夹
  1388. $folder = DB::table('mp_products')
  1389. ->where('cpid', $cpid)
  1390. ->where('type', 2) // 文件夹类型
  1391. ->where('product', $product_type) // 道具类型
  1392. ->where('product_name', $script_name)
  1393. ->where('parent_id', 0)
  1394. ->where('is_deleted', 0)
  1395. ->first();
  1396. if (!$folder) {
  1397. // 创建文件夹
  1398. $folder_id = DB::table('mp_products')->insertGetId([
  1399. 'user_id' => $uid,
  1400. 'cpid' => $cpid,
  1401. 'type' => 2, // 文件夹
  1402. 'product' => $product_type, // 道具类型
  1403. 'parent_id' => 0,
  1404. 'level' => 1,
  1405. 'product_name' => $script_name,
  1406. 'sort_order' => time(),
  1407. 'is_deleted' => 0,
  1408. 'created_at' => date('Y-m-d H:i:s'),
  1409. 'updated_at' => date('Y-m-d H:i:s')
  1410. ]);
  1411. } else {
  1412. $folder_id = $folder->id;
  1413. }
  1414. // 查找该文件夹下是否已存在同名资产
  1415. $existing_product = DB::table('mp_products')
  1416. ->where('cpid', $cpid)
  1417. ->where('type', 1) // 资产类型
  1418. ->where('product', $product_type)
  1419. ->where('parent_id', $folder_id)
  1420. ->where('product_name', $product_name)
  1421. ->where('is_deleted', 0)
  1422. ->first();
  1423. if ($existing_product) {
  1424. // 更新已存在的资产
  1425. $updateData = [
  1426. 'pic_task_status' => '生成成功'
  1427. ];
  1428. if ($pic_prompt) $updateData['pic_prompt'] = $pic_prompt;
  1429. if ($url) $updateData['url'] = $url;
  1430. // 处理versions字段
  1431. $versions = getProp($target_props, 'versions', []);
  1432. if ($versions && is_array($versions)) {
  1433. $updateData['versions'] = json_encode($versions, 256);
  1434. }
  1435. $updateData['updated_at'] = date('Y-m-d H:i:s');
  1436. DB::table('mp_products')
  1437. ->where('id', $existing_product->id)
  1438. ->update($updateData);
  1439. $product_id = $existing_product->id;
  1440. } else {
  1441. // 创建新资产
  1442. $versions = getProp($target_props, 'versions', []);
  1443. $product_id = DB::table('mp_products')->insertGetId([
  1444. 'user_id' => $uid,
  1445. 'cpid' => $cpid,
  1446. 'type' => 1, // 资产
  1447. 'product' => $product_type, // 道具
  1448. 'parent_id' => $folder_id,
  1449. 'level' => 2,
  1450. 'product_name' => $product_name,
  1451. 'url' => $url,
  1452. 'pic_prompt' => $pic_prompt,
  1453. 'versions' => is_array($versions) ? json_encode($versions, 256) : '[]',
  1454. 'sort_order' => time(),
  1455. 'is_deleted' => 0,
  1456. 'pic_task_status' => '生成成功',
  1457. 'created_at' => date('Y-m-d H:i:s'),
  1458. 'updated_at' => date('Y-m-d H:i:s')
  1459. ]);
  1460. }
  1461. // 建立或更新绑定关系
  1462. $existing_mapping = DB::table('mp_script_product_mappings')
  1463. ->where('script_id', $script_id)
  1464. ->where('product_id', $product_id)
  1465. ->where('episode_number', $episode_number)
  1466. ->first();
  1467. if (!$existing_mapping) {
  1468. // 创建绑定关系
  1469. DB::table('mp_script_product_mappings')->insert([
  1470. 'script_id' => $script_id,
  1471. 'product_id' => $product_id,
  1472. 'episode_number' => $episode_number,
  1473. 'created_at' => date('Y-m-d H:i:s'),
  1474. 'updated_at' => date('Y-m-d H:i:s')
  1475. ]);
  1476. }
  1477. }
  1478. }
  1479. }
  1480. } catch (\Exception $e) {
  1481. dLog('anime')->error('更新剧集道具失败', [
  1482. 'anime_id' => $anime_id,
  1483. 'episode_id' => $episode_id,
  1484. 'error' => $e->getMessage()
  1485. ]);
  1486. Utils::throwError('20003:更新道具列表失败 ' . $e->getMessage());
  1487. }
  1488. return true;
  1489. }
  1490. public function editSegment($data) {
  1491. $segment_id = getProp($data, 'segment_id');
  1492. $segment_content = getProp($data, 'segment_content');
  1493. $image_url = getProp($data, 'image_url');
  1494. $video_url = getProp($data, 'video_url');
  1495. // 参数验证
  1496. if (!$segment_id) Utils::throwError('20003:请提供分镜ID');
  1497. // 验证分镜是否存在
  1498. $segment = DB::table('mp_episode_segments')
  1499. ->where('segment_id', $segment_id)
  1500. ->first();
  1501. if (!$segment) Utils::throwError('20003:该分镜不存在');
  1502. $dubTaskId = 0;
  1503. try {
  1504. DB::beginTransaction();
  1505. // 准备更新数据
  1506. $update_data = [
  1507. 'updated_at' => date('Y-m-d H:i:s')
  1508. ];
  1509. if ($segment_content) {
  1510. // 先将segment_content赋值到update_data
  1511. $update_data['segment_content'] = $segment_content;
  1512. // 使用现有方法分析segment_content,提取各个字段
  1513. $this->handleSegmentContent($update_data);
  1514. // 如果有对话内容,创建视频配音合成任务
  1515. $dialogue = getProp($update_data, 'dialogue');
  1516. if (!empty($dialogue)) {
  1517. $now = date('Y-m-d H:i:s');
  1518. $generate_json = [
  1519. 'text' => $dialogue,
  1520. 'role' => getProp($update_data, 'voice_actor'),
  1521. 'voice_type' => getProp($update_data, 'voice_type'),
  1522. 'voice_name' => getProp($update_data, 'voice_name'),
  1523. 'emotion' => getProp($update_data, 'emotion'),
  1524. 'emotion_type' => getProp($update_data, 'emotion_type'),
  1525. 'gender' => getProp($update_data, 'gender'),
  1526. 'speed_ratio' => getProp($update_data, 'speed_ratio', 0),
  1527. 'loudness_ratio' => getProp($update_data, 'loudness_ratio', 0),
  1528. 'emotion_scale' => getProp($update_data, 'emotion_scale', 0),
  1529. 'pitch' => getProp($update_data, 'pitch', 0),
  1530. ];
  1531. // 插入视频配音合成任务
  1532. $dubTaskId = DB::table('mp_dub_video_tasks')->insertGetId([
  1533. 'alias_segment_id' => $segment_id,
  1534. 'generate_status' => '执行中',
  1535. 'audio_url' => '',
  1536. 'generate_json' => json_encode($generate_json, 256),
  1537. 'created_at' => $now,
  1538. 'updated_at' => $now,
  1539. ]);
  1540. if (!$dubTaskId) {
  1541. Utils::throwError('20003:创建配音任务失败!');
  1542. }
  1543. $update_data['audio_url'] = '';
  1544. } else {
  1545. // dialogue为空时,直接写入默认音频信息
  1546. $update_data['audio_url'] = 'https://zw-audiobook.tos-cn-beijing.volces.com/effects/ellipses_2s.mp3';
  1547. $update_data['audio_duration'] = 2.0;
  1548. $update_data['subtitle_info'] = json_encode(['duration' => 2.0, 'words' => []], 256);
  1549. }
  1550. }
  1551. if ($image_url) {
  1552. $update_data['img_url'] = $image_url;
  1553. // 同时写入一个简单的图片生成任务
  1554. $pic_task = [
  1555. 'alias_segment_id' => $segment_id,
  1556. 'ref_img_url' => json_encode([]),
  1557. 'status' => 'success',
  1558. 'result_url' => json_encode([$image_url], 256),
  1559. 'model' => '',
  1560. 'created_at' => date('Y-m-d H:i:s'),
  1561. 'updated_at' => date('Y-m-d H:i:s'),
  1562. ];
  1563. DB::table('mp_generate_pic_tasks')->insert($pic_task);
  1564. }
  1565. if ($video_url) {
  1566. $update_data['origin_video_url'] = $video_url;
  1567. $compressed_video_url = compressVideo($video_url);
  1568. $update_data['current_type'] = 2;
  1569. $update_data['video_url'] = $compressed_video_url ?: $video_url;
  1570. // 同时写入一个简单的视频生成任务
  1571. $video_task = [
  1572. 'alias_segment_id' => $segment_id,
  1573. 'status' => 'success',
  1574. 'result_url' => $update_data['origin_video_url'],
  1575. 'compressed_url' => $update_data['video_url'],
  1576. 'created_at' => date('Y-m-d H:i:s'),
  1577. 'updated_at' => date('Y-m-d H:i:s'),
  1578. ];
  1579. DB::table('mp_generate_video_tasks')->insert($video_task);
  1580. }
  1581. // 更新分镜信息
  1582. $result = DB::table('mp_episode_segments')
  1583. ->where('segment_id', $segment_id)
  1584. ->update($update_data);
  1585. if ($result === false) {
  1586. Utils::throwError('20003:更新分镜剧本失败');
  1587. }
  1588. DB::commit();
  1589. // 如果有创建音频生成任务则调用API
  1590. if ($dubTaskId) {
  1591. // 请求远程服务器执行生成
  1592. $client = new Client(['timeout' => 300, 'verify' => false]);
  1593. $result = $client->get("http://122.9.129.83:5000/api/anime/genAudio?taskId={$dubTaskId}");
  1594. $response = $result->getBody()->getContents();
  1595. $response_arr = json_decode($response, true);
  1596. if (!isset($response_arr['code']) || (int)$response_arr['code'] !== 0) {
  1597. $error_msg = isset($response_arr['msg']) ? $response_arr['msg'] : '未知错误';
  1598. dLog('anime')->error('火山生成音频失败', ['error' => $error_msg, 'task_id' => $dubTaskId, 'segment_id'=>$segment_id]);
  1599. logDB('anime', 'error', '火山生成音频失败', ['error' => $error_msg, 'task_id' => $dubTaskId, 'segment_id'=>$segment_id]);
  1600. Utils::throwError('20003:火山生成音频失败');
  1601. }
  1602. }
  1603. return true;
  1604. } catch (\Exception $e) {
  1605. DB::rollBack();
  1606. dLog('anime')->error('更新分镜剧本失败', [
  1607. 'segment_id' => $segment_id,
  1608. 'error' => $e->getMessage()
  1609. ]);
  1610. Utils::throwError('20003:更新分镜剧本失败 ' . $e->getMessage());
  1611. }
  1612. }
  1613. public function batchSetSegmentPics($data) {
  1614. $anime_id = getProp($data, 'anime_id');
  1615. $episode_id = getProp($data, 'episode_id');
  1616. $ratio = getProp($data, 'ratio');
  1617. $dimensions = $this->getRatioDimensions($ratio);
  1618. $width = $dimensions['width'];
  1619. $height = $dimensions['height'];
  1620. if (!$anime_id || !$episode_id) {
  1621. Utils::throwError('1002:请选择剧集');
  1622. }
  1623. // 获取剧集信息
  1624. $episode = DB::table('mp_anime_episodes')
  1625. ->where('anime_id', $anime_id)
  1626. ->where('id', $episode_id)
  1627. ->where('is_default', 1)
  1628. ->select('id as episode_id', 'anime_id', 'episode_number', 'roles', 'scenes', 'image_model')
  1629. ->first();
  1630. if (!$episode) {
  1631. Utils::throwError('20003:该剧集不存在');
  1632. }
  1633. $model = getProp($data, 'model');
  1634. if (!$model) {
  1635. $model = getProp($episode, 'image_model');
  1636. if (!$model) {
  1637. // episode表也没有,使用默认值
  1638. $model = 'doubao-seedream-5-0-lite-260128';
  1639. }
  1640. }
  1641. // 验证模型是否在可用模型表中
  1642. if (!DB::table('mp_image_models')->where('model', $model)->where('is_enabled', 1)->exists()) {
  1643. $model = 'doubao-seedream-5-0-lite-260128';
  1644. }
  1645. $roles = json_decode(getProp($episode, 'roles'), true);
  1646. if (!$roles) {
  1647. Utils::throwError('20003:角色信息格式错误');
  1648. }
  1649. // 构建角色名称到参考图的映射
  1650. $role_map = [];
  1651. foreach ($roles as $role) {
  1652. $role_name = getProp($role, 'role');
  1653. $role_url = getProp($role, 'url');
  1654. if (!empty($role_name) && !empty($role_url)) {
  1655. // // 处理角色名称,去除装扮后缀(如:许芸-校服装 -> 许芸)- 修复中文乱码问题(弃用,容易产生重复图片)
  1656. // $base_name = preg_replace('/[--].*$/u', '', $role_name);
  1657. // $role_map[$base_name] = $role_url;
  1658. // 同时保存完整名称的映射
  1659. $role_map[$role_name] = $role_url;
  1660. }
  1661. }
  1662. $scenes = json_decode(getProp($episode, 'roles'), true);
  1663. if (!$scenes) {
  1664. Utils::throwError('20003:场景信息格式错误');
  1665. }
  1666. // 构建角色名称到参考图的映射
  1667. $scene_map = [];
  1668. foreach ($scenes as $scene) {
  1669. $scene_name = getProp($scene, 'scene');
  1670. $scene_url = getProp($scene, 'url');
  1671. if (!empty($scene_name) && !empty($scene_url)) {
  1672. $scene_map[$scene_name] = $scene_url;
  1673. }
  1674. }
  1675. // 获取所有分镜信息
  1676. $segments = DB::table('mp_episode_segments')
  1677. ->where('anime_id', $anime_id)
  1678. ->where('episode_id', $episode_id)
  1679. ->whereNotIn('pic_task_status', ['已完成', '生成中'])
  1680. ->orderBy('segment_number')
  1681. ->get()
  1682. ->toArray();
  1683. if (empty($segments)) {
  1684. Utils::throwError('20003:所有分镜图片已完成或正在生成中');
  1685. }
  1686. // 保存图片比例
  1687. DB::table('mp_anime_episodes')->where('id', $episode_id)->update(['ratio' => $ratio, 'updated_at' => date('Y-m-d H:i:s')]);
  1688. $updated_segments = [];
  1689. $failed_segments = [];
  1690. // 批量为每个分镜生成图片任务
  1691. foreach ($segments as $segment) {
  1692. $segment_id = $segment->segment_id;
  1693. $segment_content = $segment->segment_content;
  1694. if (empty($segment_content)) {
  1695. $failed_segments[] = [
  1696. 'segment_id' => $segment_id,
  1697. 'error' => '分镜内容为空'
  1698. ];
  1699. continue;
  1700. }
  1701. try {
  1702. $dubTaskId = 0;
  1703. // 解析分镜内容,提取画面描述作为主要提示词
  1704. $prompt = $segment_content;
  1705. $ref_img_urls = [];
  1706. // 分镜场景
  1707. $scene = getProp($segment, 'scene');
  1708. $matched_scene = '';
  1709. if (isset($scene_map[$scene])) {
  1710. $img_index = count($ref_img_urls) + 1;
  1711. $prompt = "场景:$scene(图$img_index)\n$prompt";
  1712. $ref_img_urls[] = $scene_map[$scene];
  1713. $matched_scene = $scene;
  1714. }
  1715. // 分镜角色
  1716. $characters = getProp($segment, 'characters');
  1717. $characters = str_replace(['、', ',', ';'], ',', $characters);
  1718. $roles = explode(',', $characters);
  1719. // 从分镜内容中提取涉及的角色
  1720. $segment_characters = $this->extractCharactersFromSegment($segment_content, array_keys($role_map), $roles);
  1721. // 获取匹配角色的参考图
  1722. foreach ($segment_characters as $character) {
  1723. if (isset($role_map[$character])) {
  1724. // 将$prompt中出现的角色替换成角色(图1、2、3,序号是$ref_img_urls的个数加1)
  1725. $img_index = count($ref_img_urls) + 1;
  1726. $prompt = str_replace($character, $character . '(图' . $img_index . ')', $prompt);
  1727. $ref_img_urls[] = $role_map[$character];
  1728. }
  1729. }
  1730. // 如果没有找到匹配的角色参考图,不使用参考图
  1731. if (empty($ref_img_urls)) {
  1732. $ref_img_urls = [];
  1733. }
  1734. // 准备生成任务参数
  1735. $params = [
  1736. 'model' => $model,
  1737. 'alias_segment_id' => $segment_id,
  1738. 'prompt' => $prompt,
  1739. 'ref_img_urls' => $ref_img_urls,
  1740. 'width' => $width,
  1741. 'height' => $height,
  1742. ];
  1743. // 优化提示词(不要生成字幕)
  1744. $params['prompt'] = "前置要求:图片中不要带有任何对话台词或字幕信息\n".$params['prompt'];
  1745. // $task_id = mt_rand(100000, 999999);
  1746. // 调用AI图片生成服务
  1747. $task = $this->aiImageGenerationService->createImageGenerationTask($params);
  1748. $task_id = $task->id;
  1749. if (!$task_id) {
  1750. $failed_segments[] = [
  1751. 'segment_id' => $segment_id,
  1752. 'error' => '创建生成任务失败'
  1753. ];
  1754. continue;
  1755. }
  1756. $update_data = [
  1757. 'pic_task_id' => $task_id,
  1758. 'pic_task_status' => '生成中',
  1759. 'audio_url' => '',
  1760. 'updated_at' => date('Y-m-d H:i:s')
  1761. ];
  1762. // 如果有对话内容,创建视频配音合成任务
  1763. $dialogue = getProp($segment, 'dialogue');
  1764. if (!empty($dialogue)) {
  1765. $now = date('Y-m-d H:i:s');
  1766. $generate_json = [
  1767. 'text' => $dialogue,
  1768. 'role' => getProp($segment, 'voice_actor'),
  1769. 'voice_type' => getProp($segment, 'voice_type'),
  1770. 'voice_name' => getProp($segment, 'voice_name'),
  1771. 'emotion' => getProp($segment, 'emotion'),
  1772. 'emotion_type' => getProp($segment, 'emotion_type'),
  1773. 'gender' => getProp($segment, 'gender'),
  1774. 'speed_ratio' => getProp($segment, 'speed_ratio', 0),
  1775. 'loudness_ratio' => getProp($segment, 'loudness_ratio', 0),
  1776. 'emotion_scale' => getProp($segment, 'emotion_scale', 0),
  1777. 'pitch' => getProp($segment, 'pitch', 0),
  1778. ];
  1779. // 插入视频配音合成任务
  1780. $dubTaskId = DB::table('mp_dub_video_tasks')->insertGetId([
  1781. 'alias_segment_id' => $segment_id,
  1782. 'generate_status' => '执行中',
  1783. 'audio_url' => '',
  1784. 'generate_json' => json_encode($generate_json, 256),
  1785. 'created_at' => $now,
  1786. 'updated_at' => $now,
  1787. ]);
  1788. if (!$dubTaskId) {
  1789. dLog('anime')->error('火山生成音频失败', ['segment_id' => $segment_id, 'generate_json'=>$generate_json]);
  1790. logDB('anime', 'error', '火山生成音频失败', ['segment_id' => $segment_id, 'generate_json'=>$generate_json]);
  1791. // Utils::throwError('20003:创建配音任务失败!');
  1792. }
  1793. } else {
  1794. // dialogue为空时,直接写入默认音频信息到分镜表
  1795. $update_data['audio_url'] = 'https://zw-audiobook.tos-cn-beijing.volces.com/effects/ellipses_2s.mp3';
  1796. $update_data['audio_duration'] = 2.0;
  1797. $update_data['subtitle_info'] = json_encode(['duration' => 2.0, 'words' => []], 256);
  1798. }
  1799. // 更新分镜的任务信息
  1800. $update_result = DB::table('mp_episode_segments')
  1801. ->where('segment_id', $segment_id)
  1802. ->update($update_data);
  1803. // 如果是第一集的首帧图片,则存入待更新数组
  1804. if ($update_result && (int)getProp($segment, 'episode_number') === 1 && (int)getProp($segment, 'segment_number') === 1) {
  1805. Redis::sadd('anime_first_frame_urls', $segment_id);
  1806. }
  1807. if ($update_result) {
  1808. $updated_segments[] = [
  1809. 'segment_id' => $segment_id,
  1810. 'task_id' => $task_id,
  1811. 'status' => '生成中',
  1812. 'matched_scenes' => $matched_scene,
  1813. 'matched_roles' => $segment_characters,
  1814. 'ref_urls_count' => count($ref_img_urls)
  1815. ];
  1816. } else {
  1817. $failed_segments[] = [
  1818. 'segment_id' => $segment_id,
  1819. 'error' => '更新分镜任务状态失败'
  1820. ];
  1821. }
  1822. if ($dubTaskId) {
  1823. sleep(1);
  1824. // 请求远程服务器执行生成
  1825. $client = new Client(['timeout' => 300, 'verify' => false]);
  1826. $result = $client->get("http://122.9.129.83:5000/api/anime/genAudio?taskId={$dubTaskId}");
  1827. $response = $result->getBody()->getContents();
  1828. $response_arr = json_decode($response, true);
  1829. if (!isset($response_arr['code']) || (int)$response_arr['code'] !== 0) {
  1830. $error_msg = isset($response_arr['msg']) ? $response_arr['msg'] : '未知错误';
  1831. dLog('anime')->error('火山生成音频失败', ['error' => $error_msg, 'task_id' => $dubTaskId, 'segment_id' => $segment_id]);
  1832. logDB('anime', 'error', '火山生成音频失败', ['error' => $error_msg, 'task_id' => $dubTaskId, 'segment_id' => $segment_id]);
  1833. }
  1834. }
  1835. } catch (\Exception $e) {
  1836. $failed_segments[] = [
  1837. 'segment_id' => $segment_id,
  1838. 'error' => $e->getMessage()
  1839. ];
  1840. }
  1841. }
  1842. // 更新剧集生成状态
  1843. if (!empty($updated_segments)) {
  1844. DB::table('mp_anime_episodes')
  1845. ->where('id', $episode_id)
  1846. ->update([
  1847. 'is_generated' => 1,
  1848. 'updated_at' => date('Y-m-d H:i:s')
  1849. ]);
  1850. }
  1851. return [
  1852. 'success_count' => count($updated_segments),
  1853. 'failed_count' => count($failed_segments),
  1854. 'success_segments' => $updated_segments,
  1855. 'failed_segments' => $failed_segments,
  1856. 'total_segments' => count($segments)
  1857. ];
  1858. }
  1859. public function reGenerateSegment($data) {
  1860. $segment_id = getProp($data, 'segment_id');
  1861. $segment = DB::table('mp_episode_segments')->where('segment_id', $segment_id)->first();
  1862. $anime_id = getProp($segment, 'anime_id');
  1863. $episode_id = getProp($segment, 'episode_id');
  1864. $episode_number = getProp($segment, 'episode_number');
  1865. $segment_content = getProp($data, 'segment_content');
  1866. $ratio = getProp($data, 'ratio');
  1867. if (!$ratio) {
  1868. $ratio = DB::table('mp_anime_episodes')->where('id', $episode_id)->value('ratio');
  1869. if (!$ratio) $ratio = '9:16';
  1870. }
  1871. $dimensions = $this->getRatioDimensions($ratio);
  1872. $width = $dimensions['width'];
  1873. $height = $dimensions['height'];
  1874. if (!$anime_id || !$episode_id) {
  1875. Utils::throwError('1002:请选择分镜');
  1876. }
  1877. // 使用文生文模型重新解析segment_content
  1878. if (!empty($segment_content)) {
  1879. $segment_content = $this->parseSegmentContentWithAI($segment_content);
  1880. }
  1881. // 获取动漫的角色信息(包含参考图)
  1882. $anime = DB::table('mp_animes')
  1883. ->where('id', $anime_id)
  1884. ->select('roles', 'scenes')
  1885. ->first();
  1886. if (!$anime || !$anime->roles) {
  1887. Utils::throwError('20003:未找到角色信息');
  1888. }
  1889. $roles = json_decode($anime->roles, true);
  1890. if (!$roles) {
  1891. Utils::throwError('20003:角色信息格式错误');
  1892. }
  1893. // 构建角色名称到参考图的映射
  1894. $role_map = [];
  1895. foreach ($roles as $role) {
  1896. $role_name = getProp($role, 'role');
  1897. $role_url = getProp($role, 'url');
  1898. if (!empty($role_name) && !empty($role_url)) {
  1899. $role_map[$role_name] = $role_url;
  1900. }
  1901. }
  1902. $scenes = json_decode($anime->scenes, true);
  1903. if (!$scenes) {
  1904. Utils::throwError('20003:角色信息格式错误');
  1905. }
  1906. // 构建角色名称到参考图的映射
  1907. $scene_map = [];
  1908. foreach ($scenes as $scene) {
  1909. $scene_name = getProp($scene, 'scene');
  1910. $scene_url = getProp($scene, 'url');
  1911. if (!empty($scene_name) && !empty($scene_url)) {
  1912. $scene_map[$scene_name] = $scene_url;
  1913. }
  1914. }
  1915. $segment_id = $segment->segment_id;
  1916. $original_segment_content = $segment->segment_content;
  1917. // 如果传入了新的segment_content,使用新的内容,否则使用原有内容
  1918. $final_segment_content = !empty($segment_content) ? $segment_content : $original_segment_content;
  1919. if (empty($final_segment_content)) {
  1920. Utils::throwError('20003:分镜内容不存在,请填写内容后重试');
  1921. }
  1922. try {
  1923. $dubTaskId = 0;
  1924. // 分镜剧本数组
  1925. $update_data = [
  1926. 'segment_content' => $final_segment_content,
  1927. 'pic_task_status' => '生成中',
  1928. 'updated_at' => date('Y-m-d H:i:s')
  1929. ];
  1930. // 解析分镜内容,提取画面描述作为主要提示词
  1931. $prompt = $final_segment_content;
  1932. $ref_img_urls = [];
  1933. // 分镜场景
  1934. $scene = getProp($data, 'scene');
  1935. if ($scene) {
  1936. $matched_scene = '';
  1937. if (isset($scene_map[$scene])) {
  1938. $img_index = count($ref_img_urls) + 1;
  1939. $prompt = "场景:$scene(图$img_index)\n$prompt";
  1940. $ref_img_urls[] = $scene_map[$scene];
  1941. $matched_scene = $scene;
  1942. }
  1943. $update_data['scene'] = $scene;
  1944. }
  1945. // 分镜角色
  1946. $characters = getProp($data, 'characters');
  1947. if ($characters) {
  1948. $update_data['characters'] = $characters;
  1949. $characters = str_replace(['、', ',', ';'], ',', $characters);
  1950. $characters = explode(',', $characters);
  1951. // 从分镜内容中提取涉及的角色
  1952. $segment_characters = $this->extractCharactersFromSegment($final_segment_content, array_keys($role_map), $characters);
  1953. // 获取匹配角色的参考图
  1954. foreach ($segment_characters as $character) {
  1955. if (isset($role_map[$character])) {
  1956. // 将$prompt中出现的角色替换成角色(图1、2、3,序号是$ref_img_urls的个数加1)
  1957. $img_index = count($ref_img_urls) + 1;
  1958. $prompt = str_replace($character, $character . '(图' . $img_index . ')', $prompt);
  1959. $ref_img_urls[] = $role_map[$character];
  1960. }
  1961. }
  1962. }
  1963. // 如果没有找到匹配的角色参考图,不使用参考图
  1964. if (empty($ref_img_urls)) {
  1965. $ref_img_urls = [];
  1966. }
  1967. // 准备生成任务参数
  1968. $params = [
  1969. 'alias_segment_id' => $segment_id,
  1970. 'prompt' => $prompt,
  1971. 'ref_img_urls' => $ref_img_urls,
  1972. 'width' => $width,
  1973. 'height' => $height,
  1974. ];
  1975. // 优化提示词(不要生成字幕)
  1976. $params['prompt'] = "前置要求:图片中不要带有任何对话台词或字幕信息\n".$params['prompt'];
  1977. // 调用AI图片生成服务
  1978. $task = $this->aiImageGenerationService->createImageGenerationTask($params);
  1979. $task_id = $task->id;
  1980. if (!$task_id) {
  1981. Utils::throwError('20003:创建生成任务失败!');
  1982. }
  1983. $update_data['pic_task_id'] = $task_id;
  1984. // 更新分镜剧本信息
  1985. $this->handleSegmentContent($update_data);
  1986. // 如果有对话内容,创建视频配音合成任务(有更改分镜内容时创建)
  1987. if ($segment_content) {
  1988. $dialogue = getProp($update_data, 'dialogue');
  1989. if (!empty($dialogue)) {
  1990. $now = date('Y-m-d H:i:s');
  1991. $generate_json = [
  1992. 'text' => $dialogue,
  1993. 'role' => getProp($update_data, 'voice_actor'),
  1994. 'voice_type' => getProp($update_data, 'voice_type'),
  1995. 'voice_name' => getProp($update_data, 'voice_name'),
  1996. 'emotion' => getProp($update_data, 'emotion'),
  1997. 'emotion_type' => getProp($update_data, 'emotion_type'),
  1998. 'gender' => getProp($update_data, 'gender'),
  1999. 'speed_ratio' => getProp($update_data, 'speed_ratio', 0),
  2000. 'loudness_ratio' => getProp($update_data, 'loudness_ratio', 0),
  2001. 'emotion_scale' => getProp($update_data, 'emotion_scale', 0),
  2002. 'pitch' => getProp($update_data, 'pitch', 0),
  2003. ];
  2004. // 插入视频配音合成任务
  2005. $dubTaskId = DB::table('mp_dub_video_tasks')->insertGetId([
  2006. 'alias_segment_id' => $segment_id,
  2007. 'generate_status' => '执行中',
  2008. 'audio_url' => '',
  2009. 'generate_json' => json_encode($generate_json, 256),
  2010. 'created_at' => date('Y-m-d H:i:s'),
  2011. 'updated_at' => date('Y-m-d H:i:s'),
  2012. ]);
  2013. if (!$dubTaskId) {
  2014. Utils::throwError('20003:创建配音任务失败!');
  2015. }
  2016. $update_data['audio_url'] = '';
  2017. } else {
  2018. // dialogue为空时,直接写入默认音频信息
  2019. $update_data['audio_url'] = 'https://zw-audiobook.tos-cn-beijing.volces.com/effects/ellipses_2s.mp3';
  2020. $update_data['audio_duration'] = 2.0;
  2021. $update_data['subtitle_info'] = json_encode(['duration' => 2.0, 'words' => []], 256);
  2022. }
  2023. }
  2024. $boolen = DB::table('mp_episode_segments')
  2025. ->where('segment_id', $segment_id)
  2026. ->update($update_data);
  2027. // 如果是第一集的首帧图片,则存入待更新数组
  2028. if ($boolen && (int)getProp($segment, 'episode_number') === 1 && (int)getProp($segment, 'segment_number') === 1) {
  2029. Redis::sadd('anime_first_frame_urls', $segment_id);
  2030. }
  2031. if ($dubTaskId) {
  2032. // 请求远程服务器执行生成
  2033. $client = new Client(['timeout' => 300, 'verify' => false]);
  2034. $result = $client->get("http://122.9.129.83:5000/api/anime/genAudio?taskId={$dubTaskId}");
  2035. $response = $result->getBody()->getContents();
  2036. $response_arr = json_decode($response, true);
  2037. if (!isset($response_arr['code']) || (int)$response_arr['code'] !== 0) {
  2038. $error_msg = isset($response_arr['msg']) ? $response_arr['msg'] : '未知错误';
  2039. dLog('anime')->error('火山生成音频失败', ['error' => $error_msg, 'task_id' => $dubTaskId]);
  2040. logDB('anime', 'error', '火山生成音频失败', ['error' => $error_msg, 'task_id' => $dubTaskId]);
  2041. Utils::throwError('20003:火山生成音频失败');
  2042. }
  2043. }
  2044. } catch (\Exception $e) {
  2045. $failed_segments[] = [
  2046. 'segment_id' => $segment_id,
  2047. 'error' => $e->getMessage()
  2048. ];
  2049. }
  2050. // 创建任务之后先暂停10s等待异步任务完成
  2051. sleep(10);
  2052. $img_url = $this->loopGetPicTaskResult($task_id);
  2053. if (!$img_url) Utils::throwError('20003:图片生成中,请稍后刷新');
  2054. // 图片生成后新增对话记录
  2055. try {
  2056. $uid = Site::getUid();
  2057. $now = date('Y-m-d H:i:s');
  2058. // 使用AI反推图片提示词
  2059. $pic_prompt = $this->generateImagePromptFromUrl($img_url);
  2060. // 保存对话记录
  2061. $records = [
  2062. [
  2063. 'uid' => $uid,
  2064. 'anime_id' => $anime_id,
  2065. 'sequence' => $episode_number,
  2066. 'role' => 'user',
  2067. 'content' => '重新生成',
  2068. 'segment_id' => $segment_id,
  2069. 'pic_task_id' => $task_id,
  2070. 'image_url' => '',
  2071. 'created_at' => $now,
  2072. 'updated_at' => $now
  2073. ],
  2074. [
  2075. 'uid' => $uid,
  2076. 'anime_id' => $anime_id,
  2077. 'sequence' => $episode_number,
  2078. 'role' => 'assistant',
  2079. 'content' => $pic_prompt,
  2080. 'segment_id' => $segment_id,
  2081. 'pic_task_id' => $task_id,
  2082. 'image_url' => $img_url,
  2083. 'created_at' => $now,
  2084. 'updated_at' => $now
  2085. ]
  2086. ];
  2087. DB::table('mp_anime_records')->insert($records);
  2088. } catch (\Exception $e) {
  2089. // 记录日志但不影响主流程
  2090. dLog('anime')->error('保存对话记录失败: ' . $e->getMessage(), [
  2091. 'segment_id' => $segment_id,
  2092. 'img_url' => $img_url
  2093. ]);
  2094. }
  2095. return $img_url;
  2096. }
  2097. public function addSegment($data) {
  2098. $prev_segment_id = getProp($data, 'prev_segment_id');
  2099. $img_url = getProp($data, 'img_url');
  2100. $video_url = getProp($data, 'video_url');
  2101. $segment = DB::table('mp_episode_segments')->where('segment_id', $prev_segment_id)->first();
  2102. if (!$segment) Utils::throwError('20003:该分镜不存在');
  2103. $anime_id = getProp($segment, 'anime_id');
  2104. $episode_id = getProp($segment, 'episode_id');
  2105. $episode_number = getProp($segment, 'episode_number');
  2106. $segment_number = getProp($segment, 'segment_number');
  2107. $new_segment_number = $segment_number + 1;
  2108. $segment_id = date('YmdHis') . mt_rand(1000, 9999) . str_pad($new_segment_number, 3, "0", STR_PAD_LEFT);
  2109. // 分镜剧本数组
  2110. $insert_data = [
  2111. 'anime_id' => $anime_id,
  2112. 'episode_id' => $episode_id,
  2113. 'episode_number' => $episode_number,
  2114. 'act_number' => getProp($segment, 'act_number'),
  2115. 'act_title' => getProp($segment, 'act_title'),
  2116. 'segment_id' => $segment_id,
  2117. 'segment_number' => $new_segment_number,
  2118. 'segment_content' => '',
  2119. 'img_url' => '',
  2120. 'video_url' => '',
  2121. 'created_at' => date('Y-m-d H:i:s'),
  2122. 'updated_at' => date('Y-m-d H:i:s')
  2123. ];
  2124. if ($img_url) $insert_data['img_url'] = $img_url;
  2125. if ($video_url) {
  2126. $insert_data['origin_video_url'] = $video_url;
  2127. $insert_data['current_type'] = 2;
  2128. $compressed_video_url = compressVideo($video_url);
  2129. $insert_data['video_url'] = $compressed_video_url ?: $video_url;
  2130. }
  2131. try {
  2132. DB::beginTransaction();
  2133. // 先更新序号
  2134. DB::table('mp_episode_segments')->where('anime_id', $anime_id)->where('episode_id', $episode_id)->where('segment_number', '>', $segment_number)->increment('segment_number');
  2135. $id = DB::table('mp_episode_segments')->insertGetId($insert_data);
  2136. if (!$id) {
  2137. Utils::throwError('20003:新增分镜失败!');
  2138. }
  2139. }catch (\Exception $e) {
  2140. DB::rollBack();
  2141. Utils::throwError('20003:'.$e->getMessage());
  2142. }
  2143. DB::commit();
  2144. $segment = DB::table('mp_episode_segments')->where('id', $id)->first();
  2145. $segment = $segment ? (array)$segment : [];
  2146. return $segment;
  2147. // 以下代码暂弃用
  2148. $anime_id = getProp($segment, 'anime_id');
  2149. $episode_id = getProp($segment, 'episode_id');
  2150. $episode_number = getProp($segment, 'episode_number');
  2151. $segment_number = getProp($segment, 'segment_number');
  2152. $segment_content = getProp($data, 'segment_content');
  2153. $img_url = getProp($data, 'img_url');
  2154. $video_url = getProp($data, 'video_url');
  2155. $ratio = getProp($data, 'ratio');
  2156. $dimensions = $this->getRatioDimensions($ratio);
  2157. $width = $dimensions['width'];
  2158. $height = $dimensions['height'];
  2159. if (!$anime_id || !$episode_id) {
  2160. Utils::throwError('1002:请选择分镜');
  2161. }
  2162. // 使用文生文模型重新解析segment_content
  2163. if (!empty($segment_content)) {
  2164. $segment_content = $this->parseSegmentContentWithAI($segment_content);
  2165. }
  2166. // 获取动漫的角色信息(包含参考图)
  2167. $anime = DB::table('mp_animes')
  2168. ->where('id', $anime_id)
  2169. ->select('roles', 'scenes')
  2170. ->first();
  2171. if (!$anime || !$anime->roles) {
  2172. Utils::throwError('20003:未找到角色信息');
  2173. }
  2174. $roles = json_decode($anime->roles, true);
  2175. if (!$roles) {
  2176. Utils::throwError('20003:角色信息格式错误');
  2177. }
  2178. // 构建角色名称到参考图的映射
  2179. $role_map = [];
  2180. foreach ($roles as $role) {
  2181. $role_name = getProp($role, 'role');
  2182. $role_url = getProp($role, 'url');
  2183. if (!empty($role_name) && !empty($role_url)) {
  2184. $role_map[$role_name] = $role_url;
  2185. }
  2186. }
  2187. $scenes = json_decode($anime->scenes, true);
  2188. if (!$scenes) {
  2189. Utils::throwError('20003:角色信息格式错误');
  2190. }
  2191. // 构建角色名称到参考图的映射
  2192. $scene_map = [];
  2193. foreach ($scenes as $scene) {
  2194. $scene_name = getProp($scene, 'scene');
  2195. $scene_url = getProp($scene, 'url');
  2196. if (!empty($scene_name) && !empty($scene_url)) {
  2197. $scene_map[$scene_name] = $scene_url;
  2198. }
  2199. }
  2200. $segment_id = $segment->segment_id;
  2201. $original_segment_content = $segment->segment_content;
  2202. // 如果传入了新的segment_content,使用新的内容,否则使用原有内容
  2203. $final_segment_content = !empty($segment_content) ? $segment_content : $original_segment_content;
  2204. if (empty($final_segment_content)) {
  2205. Utils::throwError('20003:分镜内容不存在,请填写内容后重试');
  2206. }
  2207. try {
  2208. $dubTaskId = 0;
  2209. DB::beginTransaction();
  2210. $new_segment_number = $segment_number + 1;
  2211. $segment_id = date('YmdHis') . mt_rand(1000, 9999) . str_pad($new_segment_number, 3, "0", STR_PAD_LEFT);
  2212. // 分镜剧本数组
  2213. $insert_data = [
  2214. 'anime_id' => $anime_id,
  2215. 'episode_id' => $episode_id,
  2216. 'episode_number' => $episode_number,
  2217. 'act_number' => getProp($segment, 'act_number'),
  2218. 'act_title' => getProp($segment, 'act_title'),
  2219. 'segment_id' => $segment_id,
  2220. 'segment_number' => $new_segment_number,
  2221. 'segment_content' => $final_segment_content,
  2222. 'img_url' => $img_url,
  2223. 'video_url' => $video_url,
  2224. 'created_at' => date('Y-m-d H:i:s'),
  2225. 'updated_at' => date('Y-m-d H:i:s')
  2226. ];
  2227. // 更新分镜剧本信息
  2228. $this->handleSegmentContent($insert_data);
  2229. // 如果有对话内容,创建视频配音合成任务
  2230. $dialogue = getProp($insert_data, 'dialogue');
  2231. if (!empty($dialogue)) {
  2232. $now = date('Y-m-d H:i:s');
  2233. $generate_json = [
  2234. 'text' => $dialogue,
  2235. 'role' => getProp($insert_data, 'voice_actor'),
  2236. 'voice_type' => getProp($insert_data, 'voice_type'),
  2237. 'voice_name' => getProp($insert_data, 'voice_name'),
  2238. 'emotion' => getProp($insert_data, 'emotion'),
  2239. 'emotion_type' => getProp($insert_data, 'emotion_type'),
  2240. 'gender' => getProp($insert_data, 'gender'),
  2241. 'speed_ratio' => getProp($insert_data, 'speed_ratio', 0),
  2242. 'loudness_ratio' => getProp($insert_data, 'loudness_ratio', 0),
  2243. 'emotion_scale' => getProp($insert_data, 'emotion_scale', 0),
  2244. 'pitch' => getProp($insert_data, 'pitch', 0),
  2245. ];
  2246. // 插入视频配音合成任务
  2247. $dubTaskId = DB::table('mp_dub_video_tasks')->insertGetId([
  2248. 'alias_segment_id' => $segment_id,
  2249. 'generate_status' => '执行中',
  2250. 'audio_url' => '',
  2251. 'generate_json' => json_encode($generate_json, 256),
  2252. 'created_at' => $now,
  2253. 'updated_at' => $now,
  2254. ]);
  2255. if (!$dubTaskId) {
  2256. Utils::throwError('20003:创建配音任务失败!');
  2257. }
  2258. $insert_data['audio_url'] = '';
  2259. } else {
  2260. // dialogue为空时,直接写入默认音频信息
  2261. $insert_data['audio_url'] = 'https://zw-audiobook.tos-cn-beijing.volces.com/effects/ellipses_2s.mp3';
  2262. $insert_data['audio_duration'] = 2.0;
  2263. $insert_data['subtitle_info'] = json_encode(['duration' => 2.0, 'words' => []], 256);
  2264. }
  2265. // 如果没有上传图片则使用当前描述进行生成
  2266. if (!$img_url) {
  2267. // 解析分镜内容,提取画面描述作为主要提示词
  2268. $prompt = $final_segment_content;
  2269. $ref_img_urls = [];
  2270. // 分镜场景
  2271. $scene = getProp($insert_data, 'scene');
  2272. if ($scene) {
  2273. $matched_scene = '';
  2274. if (isset($scene_map[$scene])) {
  2275. $img_index = count($ref_img_urls) + 1;
  2276. $prompt = "场景:$scene(图$img_index)\n$prompt";
  2277. $ref_img_urls[] = $scene_map[$scene];
  2278. $matched_scene = $scene;
  2279. }
  2280. $update_data['scene'] = $scene;
  2281. }
  2282. // 分镜角色
  2283. $characters = getProp($insert_data, 'characters');
  2284. if ($characters) {
  2285. $update_data['characters'] = $characters;
  2286. $characters = str_replace(['、', ',', ';'], ',', $characters);
  2287. $characters = explode(',', $characters);
  2288. // 从分镜内容中提取涉及的角色
  2289. $segment_characters = $this->extractCharactersFromSegment($final_segment_content, array_keys($role_map), $characters);
  2290. // 获取匹配角色的参考图
  2291. foreach ($segment_characters as $character) {
  2292. if (isset($role_map[$character])) {
  2293. // 将$prompt中出现的角色替换成角色(图1、2、3,序号是$ref_img_urls的个数加1)
  2294. $img_index = count($ref_img_urls) + 1;
  2295. $prompt = str_replace($character, $character . '(图' . $img_index . ')', $prompt);
  2296. $ref_img_urls[] = $role_map[$character];
  2297. }
  2298. }
  2299. }
  2300. // 如果没有找到匹配的角色参考图,不使用参考图
  2301. if (empty($ref_img_urls)) {
  2302. $ref_img_urls = [];
  2303. }
  2304. // 准备生成任务参数
  2305. $params = [
  2306. 'alias_segment_id' => $segment_id,
  2307. 'prompt' => $prompt,
  2308. 'ref_img_urls' => $ref_img_urls,
  2309. 'width' => $width,
  2310. 'height' => $height,
  2311. ];
  2312. // 调用AI图片生成服务
  2313. $task = $this->aiImageGenerationService->createImageGenerationTask($params);
  2314. $task_id = $task->id;
  2315. // $task_id = 'whatever';
  2316. if (!$task_id) {
  2317. Utils::throwError('20003:创建生成任务失败!');
  2318. }
  2319. $insert_data['pic_task_status'] = '生成中';
  2320. $insert_data['pic_task_id'] = $task_id;
  2321. }
  2322. // 先更新序号
  2323. DB::table('mp_episode_segments')->where('anime_id', $anime_id)->where('episode_id', $episode_id)->where('segment_number', '>', $segment_number)->increment('segment_number');
  2324. $boolen = DB::table('mp_episode_segments')->insert($insert_data);
  2325. if (!$boolen) {
  2326. Utils::throwError('20003:新增分镜失败!');
  2327. }
  2328. // 如果是第一集的首帧图片,则存入待更新数组
  2329. if ($boolen && (int)$episode_number === 1 && (int)$new_segment_number === 1) {
  2330. Redis::sadd('anime_first_frame_urls', $segment_id);
  2331. }
  2332. if ($dubTaskId) {
  2333. // 请求远程服务器执行生成
  2334. $client = new Client(['timeout' => 300, 'verify' => false]);
  2335. $result = $client->get("http://122.9.129.83:5000/api/anime/genAudio?taskId={$dubTaskId}");
  2336. $response = $result->getBody()->getContents();
  2337. $response_arr = json_decode($response, true);
  2338. if (!isset($response_arr['code']) || (int)$response_arr['code'] !== 0) {
  2339. $error_msg = isset($response_arr['msg']) ? $response_arr['msg'] : '未知错误';
  2340. dLog('anime')->error('火山生成音频失败', ['error' => $error_msg, 'task_id' => $dubTaskId]);
  2341. Utils::throwError('20003:火山生成音频失败');
  2342. }
  2343. }
  2344. } catch (\Exception $e) {
  2345. DB::rollBack();
  2346. Utils::throwError('20003:'.$e->getMessage());
  2347. }
  2348. DB::commit();
  2349. // 创建任务之后先暂停10s等待异步任务完成
  2350. sleep(10);
  2351. if (isset($task_id)) $img_url = $this->loopGetPicTaskResult($task_id);
  2352. if (!$img_url) Utils::throwError('20003:图片生成中,请稍后刷新');
  2353. $segment = DB::table('mp_episode_segments')->where('segment_id', $segment_id)->first();
  2354. $segment = $segment ? (array)$segment : [];
  2355. return $segment;
  2356. }
  2357. public function copySegment($data) {
  2358. $segment_id = getProp($data, 'segment_id');
  2359. $segment = DB::table('mp_episode_segments')->where('segment_id', $segment_id)->first();
  2360. if (!$segment) Utils::throwError('20003:请选择分镜');
  2361. $anime_id = getProp($segment, 'anime_id');
  2362. $episode_id = getProp($segment, 'episode_id');
  2363. $episode_number = getProp($segment, 'episode_number');
  2364. $segment_number = getProp($segment, 'segment_number');
  2365. $new_segment_id = 0;
  2366. try {
  2367. DB::beginTransaction();
  2368. $segment = (array)$segment;
  2369. unset($segment['id']);
  2370. $segment['segment_number'] += 1;
  2371. $segment['segment_id'] = date('YmdHis') . mt_rand(1000, 9999) . str_pad($segment['segment_number'], 3, "0", STR_PAD_LEFT);
  2372. // $segment['pic_task_id'] = $segment['pic_task_status'] = $segment['video_task_id'] = $segment['video_task_status'] = '';
  2373. $segment['created_at'] = $segment['updated_at'] = date('Y-m-d H:i:s');
  2374. // 更新其他分镜序号
  2375. DB::table('mp_episode_segments')->where('anime_id', $anime_id)->where('episode_id', $episode_id)->where('segment_number', '>', $segment_number)->increment('segment_number');
  2376. // 复制分镜
  2377. $id = DB::table('mp_episode_segments')->insertGetId($segment);
  2378. if (!$id) {
  2379. Utils::throwError('20003:复制分镜失败');
  2380. }
  2381. }catch (\Exception $e) {
  2382. DB::rollBack();
  2383. Utils::throwError('20003:'.$e->getMessage());
  2384. }
  2385. DB::commit();
  2386. $segment = DB::table('mp_episode_segments')->where('id', $id)->first();
  2387. $segment = $segment ? (array)$segment : [];
  2388. return $segment;
  2389. }
  2390. public function moveSegment($data) {
  2391. $segment_id = getProp($data, 'segment_id');
  2392. $target_segment_id = getProp($data, 'target_segment_id');
  2393. // 获取源分镜信息
  2394. $source_segment = DB::table('mp_episode_segments')->where('segment_id', $segment_id)->first();
  2395. if (!$source_segment) Utils::throwError('20003:请选择分镜');
  2396. // 获取目标分镜信息
  2397. $target_segment = DB::table('mp_episode_segments')->where('segment_id', $target_segment_id)->first();
  2398. if (!$target_segment) Utils::throwError('20003:目标分镜不存在');
  2399. $anime_id = getProp($source_segment, 'anime_id');
  2400. $episode_id = getProp($source_segment, 'episode_id');
  2401. $episode_number = getProp($source_segment, 'episode_number');
  2402. $source_segment_number = getProp($source_segment, 'segment_number');
  2403. $target_segment_number = getProp($target_segment, 'segment_number');
  2404. // 验证源分镜和目标分镜必须属于同一个动漫的同一集
  2405. $target_anime_id = getProp($target_segment, 'anime_id');
  2406. $target_episode_number = getProp($target_segment, 'episode_number');
  2407. if ($anime_id != $target_anime_id || $episode_number != $target_episode_number) {
  2408. Utils::throwError('20003:只能在同一动漫的同一集内移动分镜');
  2409. }
  2410. // 如果源分镜和目标分镜相同,无需移动
  2411. if ($source_segment_number == $target_segment_number) {
  2412. return true;
  2413. }
  2414. try {
  2415. DB::beginTransaction();
  2416. if ($source_segment_number < $target_segment_number) {
  2417. // 向后移动:源分镜移动到目标分镜之后
  2418. // 1. 将源分镜和目标分镜之间的所有分镜序号减1
  2419. DB::table('mp_episode_segments')
  2420. ->where('anime_id', $anime_id)
  2421. ->where('episode_id', $episode_id)
  2422. ->where('segment_number', '>', $source_segment_number)
  2423. ->where('segment_number', '<=', $target_segment_number)
  2424. ->decrement('segment_number');
  2425. // 2. 将源分镜移动到目标分镜之后
  2426. $new_segment_number = $target_segment_number;
  2427. } else {
  2428. // 向前移动:源分镜移动到目标分镜之后
  2429. // 1. 将目标分镜之后到源分镜之前的所有分镜序号加1
  2430. DB::table('mp_episode_segments')
  2431. ->where('anime_id', $anime_id)
  2432. ->where('episode_id', $episode_id)
  2433. ->where('segment_number', '>', $target_segment_number)
  2434. ->where('segment_number', '<', $source_segment_number)
  2435. ->increment('segment_number');
  2436. // 2. 将源分镜移动到目标分镜之后
  2437. $new_segment_number = $target_segment_number + 1;
  2438. }
  2439. // 3. 更新源分镜的序号
  2440. $update_result = DB::table('mp_episode_segments')
  2441. ->where('segment_id', $segment_id)
  2442. ->update([
  2443. 'segment_number' => $new_segment_number,
  2444. 'updated_at' => date('Y-m-d H:i:s')
  2445. ]);
  2446. if (!$update_result) {
  2447. Utils::throwError('20003:更新分镜序号失败');
  2448. }
  2449. DB::commit();
  2450. return true;
  2451. } catch (\Exception $e) {
  2452. DB::rollBack();
  2453. Utils::throwError('20003:' . $e->getMessage());
  2454. }
  2455. }
  2456. public function delSegment($data) {
  2457. $segment_id = getProp($data, 'segment_id');
  2458. $segment = DB::table('mp_episode_segments')->where('segment_id', $segment_id)->first();
  2459. if (!$segment) Utils::throwError('20003:请选择分镜');
  2460. $anime_id = getProp($segment, 'anime_id');
  2461. $episode_id = getProp($segment, 'episode_id');
  2462. $episode_number = getProp($segment, 'episode_number');
  2463. $segment_number = getProp($segment, 'segment_number');
  2464. try {
  2465. DB::beginTransaction();
  2466. // 删除分镜
  2467. $boolen = DB::table('mp_episode_segments')->where('segment_id', $segment_id)->delete();
  2468. if (!$boolen) {
  2469. Utils::throwError('20003:删除分镜失败');
  2470. }
  2471. // 更新其他分镜序号
  2472. DB::table('mp_episode_segments')->where('anime_id', $anime_id)->where('episode_id', $episode_id)->where('segment_number', '>', $segment_number)->decrement('segment_number');
  2473. }catch (\Exception $e) {
  2474. DB::rollBack();
  2475. Utils::throwError('20003:'.$e->getMessage());
  2476. }
  2477. DB::commit();
  2478. return true;
  2479. }
  2480. public function applySegment($data) {
  2481. $segment_id = getProp($data, 'segment_id');
  2482. $url = getProp($data, 'url');
  2483. if (!$segment_id) Utils::throwError('20003:请选择分镜');
  2484. if (!$url) Utils::throwError('20003:URL不能为空');
  2485. // 获取URL的文件扩展名
  2486. $urlPath = parse_url($url, PHP_URL_PATH);
  2487. $extension = strtolower(pathinfo($urlPath, PATHINFO_EXTENSION));
  2488. // 定义图片和视频的扩展名
  2489. $imageExtensions = ['jpg', 'jpeg', 'png', 'gif', 'bmp', 'webp', 'svg'];
  2490. $videoExtensions = ['mp4', 'avi', 'mov', 'wmv', 'flv', 'mkv', 'webm', 'm4v'];
  2491. // 判断是图片还是视频
  2492. $updateData = ['updated_at' => date('Y-m-d H:i:s')];
  2493. if (in_array($extension, $imageExtensions)) {
  2494. // 图片类型
  2495. $updateData['img_url'] = $url;
  2496. $updateData['current_type'] = 1;
  2497. } elseif (in_array($extension, $videoExtensions)) {
  2498. // 视频类型
  2499. $updateData['video_url'] = $url;
  2500. $updateData['current_type'] = 2;
  2501. } else {
  2502. Utils::throwError('20003:不支持的文件类型');
  2503. }
  2504. // 更新分镜表
  2505. $result = DB::table('mp_episode_segments')
  2506. ->where('segment_id', $segment_id)
  2507. ->update($updateData);
  2508. if (!$result) {
  2509. Utils::throwError('20003:更新分镜失败');
  2510. }
  2511. return true;
  2512. }
  2513. public function segmentHistory($data) {
  2514. $segment_id = getProp($data, 'segment_id');
  2515. // 获取历史图片
  2516. $pics = [];
  2517. $pic_history = DB::table('mp_generate_pic_tasks')->where('alias_segment_id', $segment_id)->where('status', 'success')->orderBy('created_at', 'desc')->get();
  2518. foreach($pic_history as $task) {
  2519. $result_url = getProp($task, 'result_url');
  2520. if (is_json($result_url)) {
  2521. $pics = array_merge($pics, json_decode($result_url, true));
  2522. }else {
  2523. $pics[] = $result_url;
  2524. }
  2525. }
  2526. // 获取历史视频
  2527. $videos = [];
  2528. $video_history = DB::table('mp_generate_video_tasks')->where('alias_segment_id', $segment_id)->where('status', 'success')->orderBy('created_at', 'desc')->get();
  2529. foreach($video_history as $task) {
  2530. $result_url = getProp($task, 'result_url');
  2531. if (is_json($result_url)) {
  2532. $videos = array_merge($videos, json_decode($result_url, true));
  2533. }else {
  2534. $videos[] = $result_url;
  2535. }
  2536. }
  2537. return compact('pics', 'videos');
  2538. }
  2539. public function addAct($data) {
  2540. $prev_act_id = getProp($data, 'prev_act_id');
  2541. $act_title = getProp($data, 'act_title', '');
  2542. $act_content = getProp($data, 'act_content', '');
  2543. $act_duration = getProp($data, 'act_duration', 5);
  2544. $video_url = getProp($data, 'video_url');
  2545. // 根据prev_act_id获取记录
  2546. $prev_segment = DB::table('mp_episode_segments')->where('id', $prev_act_id)->first();
  2547. if (!$prev_segment) Utils::throwError('20003:该片段不存在');
  2548. $anime_id = getProp($prev_segment, 'anime_id');
  2549. $episode_id = getProp($prev_segment, 'episode_id');
  2550. $episode_number = getProp($prev_segment, 'episode_number');
  2551. $prev_act_number = getProp($prev_segment, 'act_number');
  2552. // 获取新的act_number
  2553. $new_act_number = $prev_act_number + 1;
  2554. try {
  2555. DB::beginTransaction();
  2556. // 更新后续所有act的act_number(全能模式下每个act只有一条记录)
  2557. DB::table('mp_episode_segments')
  2558. ->where('anime_id', $anime_id)
  2559. ->where('episode_id', $episode_id)
  2560. ->where('act_number', '>', $prev_act_number)
  2561. ->increment('act_number');
  2562. // 插入新片段记录
  2563. $insert_data = [
  2564. 'anime_id' => $anime_id,
  2565. 'episode_id' => $episode_id,
  2566. 'episode_number' => $episode_number,
  2567. 'act_number' => $new_act_number,
  2568. 'created_at' => date('Y-m-d H:i:s'),
  2569. 'updated_at' => date('Y-m-d H:i:s')
  2570. ];
  2571. if ($act_title) {
  2572. $insert_data['act_title'] = $act_title;
  2573. }
  2574. if ($act_content) {
  2575. $insert_data['act_content'] = $act_content;
  2576. }
  2577. if ($act_duration) {
  2578. $insert_data['act_duration'] = $act_duration;
  2579. }
  2580. if ($video_url) {
  2581. $insert_data['origin_video_url'] = $video_url;
  2582. $insert_data['current_type'] = 2;
  2583. $compressed_video_url = compressVideo($video_url);
  2584. $insert_data['video_url'] = $compressed_video_url ?: $video_url;
  2585. }
  2586. $id = DB::table('mp_episode_segments')->insertGetId($insert_data);
  2587. if (!$id) {
  2588. Utils::throwError('20003:新增片段失败!');
  2589. }
  2590. DB::commit();
  2591. }catch (\Exception $e) {
  2592. DB::rollBack();
  2593. Utils::throwError('20003:'.$e->getMessage());
  2594. }
  2595. $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();
  2596. $segment = $segment ? (array)$segment : [];
  2597. return $segment;
  2598. }
  2599. public function editAct($data) {
  2600. $act_id = getProp($data, 'act_id');
  2601. $act_content = getProp($data, 'act_content');
  2602. $act_duration = getProp($data, 'act_duration');
  2603. $act_title = getProp($data, 'act_title');
  2604. $image_url = getProp($data, 'image_url');
  2605. $video_url = getProp($data, 'video_url');
  2606. // 参数验证
  2607. if (!$act_id) Utils::throwError('20003:请提供片段ID');
  2608. // 验证片段是否存在(全能模式下每个act只有一条记录)
  2609. $segment = DB::table('mp_episode_segments')
  2610. ->where('id', $act_id)
  2611. ->first();
  2612. if (!$segment) Utils::throwError('20003:该片段不存在');
  2613. try {
  2614. DB::beginTransaction();
  2615. // 准备更新数据
  2616. $update_data = [
  2617. 'updated_at' => date('Y-m-d H:i:s')
  2618. ];
  2619. // 更新act相关字段
  2620. if (!empty($act_content)) {
  2621. $update_data['act_show_content'] = $act_content;
  2622. $update_data['act_content'] = str_replace(["@", "{", "}"], "", $act_content);
  2623. // 处理【镜头X】或【分镜X】重新编号为从1开始的连续整数【镜头X】
  2624. $shot_counter = 0;
  2625. $update_data['act_show_content'] = preg_replace_callback(
  2626. '/【(?:镜头|分镜)(\d+)】/u',
  2627. function($matches) use (&$shot_counter) {
  2628. $shot_counter++;
  2629. return '【镜头' . $shot_counter . '】';
  2630. },
  2631. $update_data['act_show_content']
  2632. );
  2633. }
  2634. if (!empty($act_duration)) {
  2635. $update_data['act_duration'] = $act_duration;
  2636. }
  2637. if (!empty($act_title)) {
  2638. $update_data['act_title'] = $act_title;
  2639. }
  2640. // 处理图片上传
  2641. if ($image_url) {
  2642. $update_data['img_url'] = $image_url;
  2643. $update_data['current_type'] = 1;
  2644. // 同时写入一个图片生成任务记录
  2645. if ($act_id) {
  2646. $pic_task = [
  2647. 'alias_act_id' => $act_id,
  2648. 'ref_img_url' => json_encode([]),
  2649. 'status' => 'success',
  2650. 'result_url' => json_encode([$image_url], 256),
  2651. 'model' => '',
  2652. 'created_at' => date('Y-m-d H:i:s'),
  2653. 'updated_at' => date('Y-m-d H:i:s'),
  2654. ];
  2655. DB::table('mp_generate_pic_tasks')->insert($pic_task);
  2656. }
  2657. }
  2658. // 处理视频上传
  2659. if ($video_url) {
  2660. $update_data['origin_video_url'] = $video_url;
  2661. $compressed_video_url = compressVideo($video_url);
  2662. $update_data['current_type'] = 2;
  2663. $update_data['video_url'] = $compressed_video_url ?: $video_url;
  2664. // 同时写入一个视频生成任务记录
  2665. if ($act_id) {
  2666. $video_task = [
  2667. 'alias_act_id' => $act_id,
  2668. 'status' => 'success',
  2669. 'result_url' => $update_data['origin_video_url'],
  2670. 'compressed_url' => $update_data['video_url'],
  2671. 'created_at' => date('Y-m-d H:i:s'),
  2672. 'updated_at' => date('Y-m-d H:i:s'),
  2673. ];
  2674. DB::table('mp_generate_video_tasks')->insert($video_task);
  2675. }
  2676. }
  2677. // 更新片段信息
  2678. $result = DB::table('mp_episode_segments')
  2679. ->where('id', $act_id)
  2680. ->update($update_data);
  2681. if ($result === false) {
  2682. Utils::throwError('20003:更新片段失败');
  2683. }
  2684. DB::commit();
  2685. // 返回新复制的记录
  2686. $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();
  2687. $new_segment = (array)$new_segment;
  2688. return $new_segment;
  2689. } catch (\Exception $e) {
  2690. DB::rollBack();
  2691. dLog('anime')->error('更新片段失败', [
  2692. 'act_id' => $act_id,
  2693. 'error' => $e->getMessage()
  2694. ]);
  2695. Utils::throwError('20003:更新片段失败 ' . $e->getMessage());
  2696. }
  2697. }
  2698. public function copyAct($data) {
  2699. $act_id = getProp($data, 'act_id');
  2700. // 根据act_id获取记录(全能模式下每个act只有一条记录)
  2701. $source_segment = DB::table('mp_episode_segments')->where('id', $act_id)->first();
  2702. if (!$source_segment) Utils::throwError('20003:请选择片段');
  2703. $anime_id = getProp($source_segment, 'anime_id');
  2704. $episode_id = getProp($source_segment, 'episode_id');
  2705. $episode_number = getProp($source_segment, 'episode_number');
  2706. $act_number = getProp($source_segment, 'act_number');
  2707. try {
  2708. DB::beginTransaction();
  2709. // 新act的编号
  2710. $new_act_number = $act_number + 1;
  2711. // 更新后续所有act的act_number
  2712. DB::table('mp_episode_segments')
  2713. ->where('anime_id', $anime_id)
  2714. ->where('episode_id', $episode_id)
  2715. ->where('act_number', '>', $act_number)
  2716. ->increment('act_number');
  2717. // 复制该片段记录
  2718. $segment_data = (array)$source_segment;
  2719. unset($segment_data['id']);
  2720. $segment_data['video_url'] = '';
  2721. $segment_data['video_task_id'] = '';
  2722. $segment_data['video_task_status'] = '';
  2723. $segment_data['act_number'] = $new_act_number;
  2724. $segment_data['created_at'] = $segment_data['updated_at'] = date('Y-m-d H:i:s');
  2725. $id = DB::table('mp_episode_segments')->insertGetId($segment_data);
  2726. if (!$id) {
  2727. Utils::throwError('20003:复制片段失败');
  2728. }
  2729. DB::commit();
  2730. }catch (\Exception $e) {
  2731. DB::rollBack();
  2732. Utils::throwError('20003:'.$e->getMessage());
  2733. }
  2734. // 返回新复制的记录
  2735. $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();
  2736. $new_segment = $new_segment ? (array)$new_segment : [];
  2737. $new_segment['act_id'] = $id;
  2738. return $new_segment;
  2739. }
  2740. public function moveAct($data) {
  2741. $act_id = getProp($data, 'act_id');
  2742. $target_act_id = getProp($data, 'target_act_id');
  2743. // 获取源片段信息
  2744. $source_segment = DB::table('mp_episode_segments')->where('id', $act_id)->first();
  2745. if (!$source_segment) Utils::throwError('20003:请选择片段');
  2746. // 获取目标片段信息
  2747. $target_segment = DB::table('mp_episode_segments')->where('id', $target_act_id)->first();
  2748. if (!$target_segment) Utils::throwError('20003:目标片段不存在');
  2749. $anime_id = getProp($source_segment, 'anime_id');
  2750. $episode_id = getProp($source_segment, 'episode_id');
  2751. $source_act_number = getProp($source_segment, 'act_number');
  2752. $target_act_number = getProp($target_segment, 'act_number');
  2753. // 验证源片段和目标片段必须属于同一个动漫的同一集
  2754. $target_anime_id = getProp($target_segment, 'anime_id');
  2755. $target_episode_id = getProp($target_segment, 'episode_id');
  2756. if ($anime_id != $target_anime_id || $episode_id != $target_episode_id) {
  2757. Utils::throwError('20003:只能在同一动漫的同一集内移动片段');
  2758. }
  2759. // 如果源片段和目标片段相同,无需移动
  2760. if ($source_act_number == $target_act_number) {
  2761. return true;
  2762. }
  2763. try {
  2764. DB::beginTransaction();
  2765. if ($source_act_number < $target_act_number) {
  2766. // 向后移动:源片段移动到目标片段之后
  2767. // 1. 将源片段和目标片段之间的所有片段编号减1
  2768. DB::table('mp_episode_segments')
  2769. ->where('anime_id', $anime_id)
  2770. ->where('episode_id', $episode_id)
  2771. ->where('act_number', '>', $source_act_number)
  2772. ->where('act_number', '<=', $target_act_number)
  2773. ->decrement('act_number');
  2774. // 2. 将源片段移动到目标片段之后
  2775. $new_act_number = $target_act_number;
  2776. } else {
  2777. // 向前移动:源片段移动到目标片段之后
  2778. // 1. 将目标片段之后到源片段之前的所有片段编号加1
  2779. DB::table('mp_episode_segments')
  2780. ->where('anime_id', $anime_id)
  2781. ->where('episode_id', $episode_id)
  2782. ->where('act_number', '>', $target_act_number)
  2783. ->where('act_number', '<', $source_act_number)
  2784. ->increment('act_number');
  2785. // 2. 将源片段移动到目标片段之后
  2786. $new_act_number = $target_act_number + 1;
  2787. }
  2788. // 3. 更新源片段的编号
  2789. $update_result = DB::table('mp_episode_segments')
  2790. ->where('id', $act_id)
  2791. ->update([
  2792. 'act_number' => $new_act_number,
  2793. 'updated_at' => date('Y-m-d H:i:s')
  2794. ]);
  2795. if (!$update_result) {
  2796. Utils::throwError('20003:更新片段编号失败');
  2797. }
  2798. DB::commit();
  2799. return true;
  2800. } catch (\Exception $e) {
  2801. DB::rollBack();
  2802. Utils::throwError('20003:' . $e->getMessage());
  2803. }
  2804. }
  2805. public function delAct($data) {
  2806. $act_id = getProp($data, 'act_id');
  2807. // 根据act_id获取记录(全能模式下每个act只有一条记录)
  2808. $segment = DB::table('mp_episode_segments')->where('id', $act_id)->first();
  2809. if (!$segment) Utils::throwError('20003:请选择片段');
  2810. $anime_id = getProp($segment, 'anime_id');
  2811. $episode_id = getProp($segment, 'episode_id');
  2812. $act_number = getProp($segment, 'act_number');
  2813. try {
  2814. DB::beginTransaction();
  2815. // 删除该片段记录
  2816. $deleted = DB::table('mp_episode_segments')->where('id', $act_id)->delete();
  2817. if (!$deleted) {
  2818. Utils::throwError('20003:删除片段失败');
  2819. }
  2820. // 更新后续act的编号
  2821. DB::table('mp_episode_segments')
  2822. ->where('anime_id', $anime_id)
  2823. ->where('episode_id', $episode_id)
  2824. ->where('act_number', '>', $act_number)
  2825. ->decrement('act_number');
  2826. DB::commit();
  2827. }catch (\Exception $e) {
  2828. DB::rollBack();
  2829. Utils::throwError('20003:'.$e->getMessage());
  2830. }
  2831. return true;
  2832. }
  2833. public function applyAct($data) {
  2834. $act_id = getProp($data, 'act_id');
  2835. $url = getProp($data, 'url');
  2836. if (!$act_id) Utils::throwError('20003:请选择片段');
  2837. if (!$url) Utils::throwError('20003:URL不能为空');
  2838. // 获取URL的文件扩展名
  2839. $urlPath = parse_url($url, PHP_URL_PATH);
  2840. $extension = strtolower(pathinfo($urlPath, PATHINFO_EXTENSION));
  2841. // 定义图片和视频的扩展名
  2842. $imageExtensions = ['jpg', 'jpeg', 'png', 'gif', 'bmp', 'webp', 'svg'];
  2843. $videoExtensions = ['mp4', 'avi', 'mov', 'wmv', 'flv', 'mkv', 'webm', 'm4v'];
  2844. // 判断是图片还是视频
  2845. $updateData = ['updated_at' => date('Y-m-d H:i:s')];
  2846. if (in_array($extension, $imageExtensions)) {
  2847. // 图片类型
  2848. $updateData['img_url'] = $url;
  2849. $updateData['current_type'] = 1;
  2850. } elseif (in_array($extension, $videoExtensions)) {
  2851. // 视频类型
  2852. $updateData['video_url'] = $url;
  2853. $updateData['current_type'] = 2;
  2854. } else {
  2855. Utils::throwError('20003:不支持的文件类型');
  2856. }
  2857. // 更新片段记录(全能模式下每个act只有一条记录)
  2858. $result = DB::table('mp_episode_segments')
  2859. ->where('id', $act_id)
  2860. ->update($updateData);
  2861. if (!$result) {
  2862. Utils::throwError('20003:更新片段失败');
  2863. }
  2864. return true;
  2865. }
  2866. public function actChatHistory($data) {
  2867. $act_id = getProp($data, 'act_id');
  2868. if (!$act_id) Utils::throwError('20003:请选择片段!');
  2869. $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');
  2870. $chat = $query->orderBy('id')->get()->map(function ($value) {
  2871. $value = (array)$value;
  2872. $value['created_at'] = transDate($value['created_at']);
  2873. if ($value['reference_images']) $value['reference_images'] = json_decode($value['reference_images'], 256);
  2874. else $value['reference_images'] = [];
  2875. return $value;
  2876. })->toArray();
  2877. // 获取历史图片
  2878. $url = [];
  2879. $pic_history = DB::table('mp_generate_pic_tasks')->where('alias_act_id', $act_id)->where('status', 'success')->orderBy('created_at', 'desc')->get();
  2880. foreach($pic_history as $task) {
  2881. $result_url = getProp($task, 'result_url');
  2882. if (is_json($result_url)) {
  2883. $url = array_merge($url, json_decode($result_url, true));
  2884. }else {
  2885. $url[] = $result_url;
  2886. }
  2887. }
  2888. // 获取历史视频
  2889. $video_history = DB::table('mp_generate_video_tasks')->where('alias_act_id', $act_id)->where('status', 'success')->orderBy('created_at', 'desc')->get();
  2890. foreach($video_history as $task) {
  2891. $result_url = getProp($task, 'result_url');
  2892. if (is_json($result_url)) {
  2893. $url = array_merge($url, json_decode($result_url, true));
  2894. }else {
  2895. $url[] = $result_url;
  2896. }
  2897. }
  2898. // 获取资产库
  2899. $products = [];
  2900. // 通过act_id查询片段信息获取episode_id
  2901. $segment = DB::table('mp_episode_segments')->where('id', $act_id)->first();
  2902. if ($segment) {
  2903. $episode_id = getProp($segment, 'episode_id');
  2904. // 查询剧集信息获取roles、scenes和extra_products
  2905. $episode = DB::table('mp_anime_episodes')->where('id', $episode_id)->first();
  2906. if ($episode) {
  2907. $roles = json_decode(getProp($episode, 'roles', '[]'), true) ?: [];
  2908. $scenes = json_decode(getProp($episode, 'scenes', '[]'), true) ?: [];
  2909. $props = json_decode(getProp($episode, 'props', '[]'), true) ?: [];
  2910. $extra_products = json_decode(getProp($episode, 'extra_products', '[]'), true) ?: [];
  2911. // 先合并roles、scenes和props
  2912. // 处理角色数组
  2913. foreach ($roles as $role) {
  2914. $product = $role;
  2915. // 将role字段重命名为product_name
  2916. if (is_array($product) && !empty($product['role'] ?? null)) {
  2917. $product['product_name'] = $product['role'];
  2918. unset($product['role']);
  2919. $product['product'] = 1; // 标记类型为角色
  2920. $products[$product['product_name']] = $product; // 使用product_name作为key便于后续覆盖
  2921. }
  2922. }
  2923. // 处理场景数组
  2924. foreach ($scenes as $scene) {
  2925. $product = $scene;
  2926. // 将scene字段重命名为product_name
  2927. if (is_array($product) && !empty($product['scene'] ?? null)) {
  2928. $product['product_name'] = $product['scene'];
  2929. unset($product['scene']);
  2930. $product['product'] = 2; // 标记类型为场景
  2931. $products[$product['product_name']] = $product; // 使用product_name作为key便于后续覆盖
  2932. }
  2933. }
  2934. // 处理道具数组
  2935. foreach ($props as $prop) {
  2936. $product = $prop;
  2937. // 将prop字段重命名为product_name
  2938. if (is_array($product) && !empty($product['prop'] ?? null)) {
  2939. $product['product_name'] = $product['prop'];
  2940. unset($product['prop']);
  2941. $product['product'] = 3; // 标记类型为道具
  2942. $products[$product['product_name']] = $product; // 使用product_name作为key便于后续覆盖
  2943. }
  2944. }
  2945. // extra_products优先级更高,直接覆盖同名的roles和scenes
  2946. foreach ($extra_products as $extra_product) {
  2947. $product_name = getProp($extra_product, 'product_name');
  2948. if ($product_name) {
  2949. $products[$product_name] = $extra_product; // 覆盖同名数据
  2950. }
  2951. }
  2952. // 重新索引数组(去除key)
  2953. $products = array_values($products);
  2954. }
  2955. }
  2956. // 获取执行中的任务
  2957. $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) {
  2958. $value = (array)$value;
  2959. if ($value['ref_image_url']) $value['ref_image_url'] = json_decode($value['ref_image_url'], true);
  2960. else $value['ref_image_url'] = [];
  2961. $value['status'] = $value['status'] == 'pending' ? '视频待生成' : '视频生成中';
  2962. // 处理prompt:删除人物音色部分,保留【镜头】开始的内容,并去掉<图片X>标记
  2963. if (!empty($value['prompt'])) {
  2964. $prompt = $value['prompt'];
  2965. // 查找第一个【镜头】的位置
  2966. if (preg_match('/【镜头\d+】/u', $prompt, $matches, PREG_OFFSET_CAPTURE)) {
  2967. // 从【镜头】开始截取
  2968. $prompt = substr($prompt, $matches[0][1]);
  2969. }
  2970. // 去除所有<图片X>格式的标记(X可以是任意数字)
  2971. $prompt = preg_replace('/<图片\d+>/u', '', $prompt);
  2972. $value['prompt'] = $prompt;
  2973. }
  2974. return $value;
  2975. })->toArray();
  2976. return compact('chat', 'url', 'products', 'tasks');
  2977. }
  2978. public function applyAudioData($data) {
  2979. $segment_id = getProp($data, 'segment_id');
  2980. $global_data = getProp($data, 'global_data');
  2981. $segment_data = getProp($data, 'segment_data');
  2982. if (!$segment_id) Utils::throwError('20003:请选择分镜');
  2983. $global_data = is_array($global_data) ? $global_data : [];
  2984. $segment_data = is_array($segment_data) ? $segment_data : [];
  2985. // dialogue只能在segment_data中,如果在global_data中则移到segment_data
  2986. $dialogue_item = null;
  2987. foreach ($global_data as $key => $item) {
  2988. if (trim((string)getProp($item, 'name')) === 'dialogue') {
  2989. $dialogue_item = $item;
  2990. unset($global_data[$key]);
  2991. break;
  2992. }
  2993. }
  2994. if ($dialogue_item) {
  2995. $segment_data[] = $dialogue_item;
  2996. }
  2997. // 特殊参数: audio_url,audio_duration,subtitle_info
  2998. // 这些特殊参数必须同时存在才对当前分镜有效,直接保存但不创建音频任务
  2999. // 如果不是全部存在,则仍需创建音频任务
  3000. $special_fields = ['audio_url', 'audio_duration', 'subtitle_info'];
  3001. $special_update_data = [];
  3002. $has_all_special_params = false;
  3003. // 从segment_data中提取特殊参数
  3004. $filtered_segment_data = [];
  3005. foreach ($segment_data as $item) {
  3006. $field_name = trim((string)getProp($item, 'name'));
  3007. if (in_array($field_name, $special_fields)) {
  3008. $special_update_data[$field_name] = getProp($item, 'value');
  3009. } else {
  3010. // 非特殊参数保留,继续后续处理
  3011. $filtered_segment_data[] = $item;
  3012. }
  3013. }
  3014. // 检查是否三个特殊参数都存在
  3015. if (count($special_update_data) === 3 &&
  3016. isset($special_update_data['audio_url']) &&
  3017. isset($special_update_data['audio_duration']) &&
  3018. isset($special_update_data['subtitle_info'])) {
  3019. $has_all_special_params = true;
  3020. // 立即更新到当前分镜
  3021. $special_update_data['updated_at'] = date('Y-m-d H:i:s');
  3022. DB::table('mp_episode_segments')
  3023. ->where('segment_id', $segment_id)
  3024. ->update($special_update_data);
  3025. }
  3026. // 使用过滤后的segment_data继续处理其他参数
  3027. $segment_data = $filtered_segment_data;
  3028. $allow_fields = ['dialogue', 'voice_type', 'speed_ratio', 'loudness_ratio', 'emotion_scale', 'pitch'];
  3029. $global_update_data = [];
  3030. $segment_update_data = [];
  3031. $global_voice_type = '';
  3032. $target_segment = DB::table('mp_episode_segments')->where('segment_id', $segment_id)->first();
  3033. if (!$target_segment) Utils::throwError('20003:分镜不存在');
  3034. $episode_id = getProp($target_segment, 'episode_id');
  3035. $target_voice_actor = trim((string)getProp($target_segment, 'voice_actor'));
  3036. $episode = DB::table('mp_anime_episodes')->where('id', $episode_id)->first();
  3037. if (!$episode) Utils::throwError('20003:分集不存在');
  3038. foreach ($global_data as $item) {
  3039. $field_name = trim((string)getProp($item, 'name'));
  3040. if (!$field_name || !in_array($field_name, $allow_fields)) {
  3041. continue;
  3042. }
  3043. $global_update_data[$field_name] = getProp($item, 'value');
  3044. if ($field_name === 'voice_type') {
  3045. $global_voice_type = trim((string)getProp($item, 'value'));
  3046. }
  3047. }
  3048. foreach ($segment_data as $item) {
  3049. $field_name = trim((string)getProp($item, 'name'));
  3050. if (!$field_name || !in_array($field_name, $allow_fields)) {
  3051. continue;
  3052. }
  3053. $segment_update_data[$field_name] = getProp($item, 'value');
  3054. }
  3055. if ($global_voice_type) {
  3056. $timbre_info = DB::table('mp_timbres')
  3057. ->where('timbre_type', $global_voice_type)
  3058. ->select('audio_url', 'timbre_name')
  3059. ->first();
  3060. if ($timbre_info) {
  3061. $global_update_data['voice_audio_url'] = getProp($timbre_info, 'audio_url');
  3062. $global_update_data['voice_name'] = str_replace('(多情感)', '', getProp($timbre_info, 'timbre_name'));
  3063. }
  3064. }
  3065. try {
  3066. DB::beginTransaction();
  3067. // 收集需要创建音频合成任务的segment_id和对应的分镜数据
  3068. $segment_ids_to_create_task = [];
  3069. $segments_data = [];
  3070. // 如果有全局更新,获取该角色的所有分镜数据并检查是否有变化
  3071. if (!empty($global_update_data)) {
  3072. // 如果角色不存在,则只更新当前分镜
  3073. if (!$target_voice_actor) {
  3074. // 只处理当前分镜
  3075. $affected_segments = DB::table('mp_episode_segments')
  3076. ->where('segment_id', $segment_id)
  3077. ->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')
  3078. ->get();
  3079. } else {
  3080. // 获取该角色的所有分镜
  3081. $affected_segments = DB::table('mp_episode_segments')
  3082. ->where('episode_id', $episode_id)
  3083. ->where('voice_actor', $target_voice_actor)
  3084. ->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')
  3085. ->get();
  3086. }
  3087. foreach ($affected_segments as $seg) {
  3088. $seg = (array)$seg;
  3089. $sid = getProp($seg, 'segment_id');
  3090. // 检查参数是否发生变化
  3091. $has_changed = false;
  3092. foreach ($global_update_data as $field => $new_value) {
  3093. $old_value = getProp($seg, $field);
  3094. if ($old_value != $new_value) {
  3095. $has_changed = true;
  3096. break;
  3097. }
  3098. }
  3099. if ($has_changed) {
  3100. $segment_ids_to_create_task[] = $sid;
  3101. $segments_data[$sid] = $seg;
  3102. }
  3103. }
  3104. // 只有在有变化的分镜时才更新
  3105. if (!empty($segment_ids_to_create_task)) {
  3106. $global_segment_update_data = $global_update_data;
  3107. $global_segment_update_data['audio_url'] = ''; // 清空音频URL
  3108. $global_segment_update_data['updated_at'] = date('Y-m-d H:i:s');
  3109. DB::table('mp_episode_segments')
  3110. ->where('episode_id', $episode_id)
  3111. ->where('voice_actor', $target_voice_actor)
  3112. ->whereIn('segment_id', $segment_ids_to_create_task)
  3113. ->update($global_segment_update_data);
  3114. }
  3115. if ($global_voice_type) {
  3116. $episode_roles = json_decode((string)getProp($episode, 'roles'), true);
  3117. $episode_roles = is_array($episode_roles) ? $episode_roles : [];
  3118. $roles_updated = false;
  3119. foreach ($episode_roles as &$role) {
  3120. // 通过 role 字段匹配角色名,而不是 voice_name
  3121. if (trim((string)getProp($role, 'role')) !== $target_voice_actor) {
  3122. continue;
  3123. }
  3124. $role['voice_type'] = $global_voice_type;
  3125. $role['voice_audio_url'] = getProp($global_update_data, 'voice_audio_url');
  3126. $role['voice_name'] = getProp($global_update_data, 'voice_name');
  3127. $roles_updated = true;
  3128. }
  3129. unset($role);
  3130. if ($roles_updated) {
  3131. DB::table('mp_anime_episodes')->where('id', $episode_id)->update([
  3132. 'roles' => json_encode($episode_roles, 256),
  3133. 'updated_at' => date('Y-m-d H:i:s'),
  3134. ]);
  3135. }
  3136. }
  3137. }
  3138. // 如果有单个分镜更新,检查是否有变化
  3139. if (!empty($segment_update_data)) {
  3140. // 获取当前分镜数据
  3141. $current_segment = DB::table('mp_episode_segments')
  3142. ->where('segment_id', $segment_id)
  3143. ->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')
  3144. ->first();
  3145. if ($current_segment) {
  3146. $current_segment = (array)$current_segment;
  3147. // 检查参数是否发生变化
  3148. $has_changed = false;
  3149. foreach ($segment_update_data as $field => $new_value) {
  3150. $old_value = getProp($current_segment, $field);
  3151. if ($old_value != $new_value) {
  3152. $has_changed = true;
  3153. break;
  3154. }
  3155. }
  3156. if ($has_changed) {
  3157. // 如果该分镜还未在列表中,添加进去
  3158. if (!in_array($segment_id, $segment_ids_to_create_task)) {
  3159. $segment_ids_to_create_task[] = $segment_id;
  3160. $segments_data[$segment_id] = $current_segment;
  3161. }
  3162. // 更新分镜数据并清空音频URL
  3163. $segment_update_data['audio_url'] = '';
  3164. $segment_update_data['updated_at'] = date('Y-m-d H:i:s');
  3165. DB::table('mp_episode_segments')->where('segment_id', $segment_id)->update($segment_update_data);
  3166. }
  3167. }
  3168. }
  3169. // 为所有有变化的分镜创建音频合成任务
  3170. // 但如果当前分镜同时设置了全部三个特殊参数(audio_url, audio_duration, subtitle_info),则跳过该分镜
  3171. if (!empty($segment_ids_to_create_task)) {
  3172. foreach ($segment_ids_to_create_task as $sid) {
  3173. // 如果当前分镜同时设置了全部三个特殊参数,则跳过音频任务创建
  3174. if ($sid === $segment_id && $has_all_special_params) {
  3175. continue;
  3176. }
  3177. // 重新获取更新后的分镜数据
  3178. $updated_segment = DB::table('mp_episode_segments')
  3179. ->where('segment_id', $sid)
  3180. ->select('voice_actor', 'dialogue', 'voice_type', 'voice_name', 'emotion', 'emotion_type', 'gender', 'speed_ratio', 'loudness_ratio', 'emotion_scale', 'pitch')
  3181. ->first();
  3182. if (!$updated_segment) continue;
  3183. $updated_segment = (array)$updated_segment;
  3184. // 检查dialogue是否为空
  3185. $dialogue = getProp($updated_segment, 'dialogue');
  3186. if (empty($dialogue)) {
  3187. // dialogue为空时,直接写入默认音频信息
  3188. DB::table('mp_episode_segments')->where('segment_id', $sid)->update([
  3189. 'audio_url' => 'https://zw-audiobook.tos-cn-beijing.volces.com/effects/ellipses_2s.mp3',
  3190. 'audio_duration' => 2.0,
  3191. 'subtitle_info' => json_encode(['duration' => 2.0, 'words' => []], 256),
  3192. 'updated_at' => date('Y-m-d H:i:s')
  3193. ]);
  3194. continue;
  3195. }
  3196. $generate_json = [
  3197. 'text' => $dialogue,
  3198. 'role' => getProp($updated_segment, 'voice_actor'),
  3199. 'voice_type' => getProp($updated_segment, 'voice_type'),
  3200. 'voice_name' => getProp($updated_segment, 'voice_name'),
  3201. 'emotion' => getProp($updated_segment, 'emotion'),
  3202. 'emotion_type' => getProp($updated_segment, 'emotion_type'),
  3203. 'gender' => getProp($updated_segment, 'gender'),
  3204. 'speed_ratio' => getProp($updated_segment, 'speed_ratio', 0),
  3205. 'loudness_ratio' => getProp($updated_segment, 'loudness_ratio', 0),
  3206. 'emotion_scale' => getProp($updated_segment, 'emotion_scale', 0),
  3207. 'pitch' => getProp($updated_segment, 'pitch', 0),
  3208. ];
  3209. // 插入视频配音合成任务
  3210. $dubTaskId = DB::table('mp_dub_video_tasks')->insertGetId([
  3211. 'alias_segment_id' => $sid,
  3212. 'generate_status' => '执行中',
  3213. 'audio_url' => '',
  3214. 'generate_json' => json_encode($generate_json, 256),
  3215. 'created_at' => date('Y-m-d H:i:s'),
  3216. 'updated_at' => date('Y-m-d H:i:s'),
  3217. ]);
  3218. if (!$dubTaskId) {
  3219. dLog('anime')->error('创建配音任务失败', ['segment_id' => $sid]);
  3220. continue;
  3221. }
  3222. // 将任务ID添加到Redis列表中
  3223. Redis::lpush('dub_video_task_queue', $dubTaskId);
  3224. // 请求远程服务器执行生成
  3225. try {
  3226. sleep(1);
  3227. $client = new Client(['timeout' => 300, 'verify' => false]);
  3228. $result = $client->get("http://122.9.129.83:5000/api/anime/genAudio?taskId={$dubTaskId}");
  3229. $response = $result->getBody()->getContents();
  3230. $response_arr = json_decode($response, true);
  3231. if (!isset($response_arr['code']) || (int)$response_arr['code'] !== 0) {
  3232. $error_msg = isset($response_arr['msg']) ? $response_arr['msg'] : '未知错误';
  3233. dLog('anime')->error('火山生成音频失败', ['error' => $error_msg, 'task_id' => $dubTaskId, 'segment_id' => $sid]);
  3234. logDB('anime', 'error', '火山生成音频失败', ['error' => $error_msg, 'task_id' => $dubTaskId, 'segment_id' => $sid]);
  3235. }
  3236. } catch (\Exception $e) {
  3237. dLog('anime')->error('调用音频生成API失败', ['error' => $e->getMessage(), 'task_id' => $dubTaskId, 'segment_id' => $sid]);
  3238. logDB('anime', 'error', '调用音频生成API失败', ['error' => $e->getMessage(), 'task_id' => $dubTaskId, 'segment_id' => $sid]);
  3239. }
  3240. }
  3241. }
  3242. DB::commit();
  3243. } catch (\Exception $e) {
  3244. DB::rollBack();
  3245. Utils::throwError('20003:'.$e->getMessage());
  3246. }
  3247. return true;
  3248. }
  3249. public function episodePicsInfo($data) {
  3250. $anime_id = getProp($data, 'anime_id');
  3251. $episode_id = getProp($data, 'episode_id');
  3252. // 参数验证
  3253. if (!$anime_id && !$episode_id) {
  3254. Utils::throwError('20003:请提供动漫ID或分集ID');
  3255. }
  3256. // 根据参数获取数据源
  3257. if ($episode_id) {
  3258. // 从剧集表获取
  3259. $source = DB::table('mp_anime_episodes')->where('id', $episode_id)->first();
  3260. if (!$source) Utils::throwError('20003:该剧集不存在');
  3261. $table_name = 'mp_anime_episodes';
  3262. $id_field = 'id';
  3263. $id_value = $episode_id;
  3264. // 获取剧集的anime_id用于继承全局数据
  3265. $anime_id = getProp($source, 'anime_id');
  3266. } else {
  3267. // 从动漫表获取
  3268. $source = DB::table('mp_animes')->where('id', $anime_id)->where('is_deleted', 0)->first();
  3269. if (!$source) Utils::throwError('20003:该动漫不存在');
  3270. $table_name = 'mp_animes';
  3271. $id_field = 'id';
  3272. $id_value = $anime_id;
  3273. }
  3274. $source = (array)$source;
  3275. $roles = json_decode(getProp($source, 'roles', '[]'), true) ?: [];
  3276. $scenes = json_decode(getProp($source, 'scenes', '[]'), true) ?: [];
  3277. $props = json_decode(getProp($source, 'props', '[]'), true) ?: [];
  3278. // 如果是分集数据,需要处理继承和任务创建逻辑
  3279. if ($episode_id) {
  3280. $this->processEpisodeRolesAndScenes($episode_id, $anime_id, $roles, $scenes, $source);
  3281. }
  3282. // 返回生成器函数,用于 SSE 流式输出
  3283. return function() use ($roles, $scenes, $props, $table_name, $id_field, $id_value) {
  3284. $startTime = time();
  3285. $maxDuration = 600; // 10分钟超时
  3286. $checkInterval = 3; // 每3秒检查一次
  3287. // Redis 缓存键
  3288. $cacheKey = "anime:pics_info:{$table_name}:{$id_value}";
  3289. // 生成当前数据的哈希值用于比较
  3290. $generateHash = function($roles, $scenes, $props) {
  3291. return md5(json_encode(['roles' => $roles, 'scenes' => $scenes, 'props' => $props], JSON_UNESCAPED_UNICODE));
  3292. };
  3293. // 发送初始数据
  3294. $currentHash = $generateHash($roles, $scenes, $props);
  3295. Redis::setex($cacheKey, 600, $currentHash); // 缓存10分钟
  3296. echo "data: " . json_encode([
  3297. 'type' => 'init',
  3298. 'data' => [
  3299. 'roles' => $roles,
  3300. 'scenes' => $scenes,
  3301. 'props' => $props,
  3302. 'start_time' => $startTime
  3303. ]
  3304. ], JSON_UNESCAPED_UNICODE) . "\n\n";
  3305. if (ob_get_level() > 0) {
  3306. ob_flush();
  3307. }
  3308. flush();
  3309. // 持续轮询任务状态
  3310. while (time() - $startTime < $maxDuration) {
  3311. $hasProcessing = false;
  3312. $updated = false;
  3313. // 检查角色任务状态
  3314. foreach ($roles as $index => &$role) {
  3315. $task_id = getProp($role, 'task_id');
  3316. $task_status = getProp($role, 'task_status');
  3317. $existing_url = getProp($role, 'url');
  3318. // 只处理有任务ID且状态为processing的角色,或者状态为processing但没有URL的角色
  3319. if ($task_id && ($task_status === 'processing' || (in_array($task_status, ['success', 'completed']) && empty($existing_url)))) {
  3320. $hasProcessing = ($task_status === 'processing');
  3321. // 查询任务状态
  3322. $task = DB::table('mp_generate_pic_tasks')
  3323. ->where('id', $task_id)
  3324. ->select('id', 'status', 'result_url', 'error_message')
  3325. ->first();
  3326. if ($task) {
  3327. $task = (array)$task;
  3328. $status = getProp($task, 'status');
  3329. // 如果任务完成或失败
  3330. if (in_array($status, ['success', 'failed'])) {
  3331. $role['task_status'] = $status;
  3332. if ($status === 'success') {
  3333. $result_url = getProp($task, 'result_url');
  3334. if ($result_url) {
  3335. $result_urls = is_json($result_url) ? json_decode($result_url, true) : [$result_url];
  3336. if (is_array($result_urls) && !empty($result_urls[0])) {
  3337. $role['url'] = $result_urls[0];
  3338. }
  3339. }
  3340. }
  3341. $updated = true;
  3342. } else if ($status === 'processing') {
  3343. $hasProcessing = true;
  3344. }
  3345. }
  3346. }
  3347. }
  3348. // 检查场景任务状态
  3349. foreach ($scenes as $index => &$scene) {
  3350. $task_id = getProp($scene, 'task_id');
  3351. $task_status = getProp($scene, 'task_status');
  3352. $existing_url = getProp($scene, 'url');
  3353. // 只处理有任务ID且状态为processing的场景,或者状态为success但没有URL的场景
  3354. if ($task_id && ($task_status === 'processing' || (in_array($task_status, ['success', 'completed']) && empty($existing_url)))) {
  3355. $hasProcessing = ($task_status === 'processing');
  3356. // 查询任务状态
  3357. $task = DB::table('mp_generate_pic_tasks')
  3358. ->where('id', $task_id)
  3359. ->select('id', 'status', 'result_url', 'error_message')
  3360. ->first();
  3361. if ($task) {
  3362. $task = (array)$task;
  3363. $status = getProp($task, 'status');
  3364. // 如果任务完成或失败
  3365. if (in_array($status, ['success', 'failed'])) {
  3366. $scene['task_status'] = $status;
  3367. if ($status === 'success') {
  3368. $result_url = getProp($task, 'result_url');
  3369. if ($result_url) {
  3370. $result_urls = is_json($result_url) ? json_decode($result_url, true) : [$result_url];
  3371. if (is_array($result_urls) && !empty($result_urls[0])) {
  3372. $scene['url'] = $result_urls[0];
  3373. }
  3374. }
  3375. }
  3376. $updated = true;
  3377. } else if ($status === 'processing') {
  3378. $hasProcessing = true;
  3379. }
  3380. }
  3381. }
  3382. }
  3383. // 检查道具任务状态
  3384. foreach ($props as $index => &$prop) {
  3385. $task_id = getProp($prop, 'task_id');
  3386. $task_status = getProp($prop, 'task_status');
  3387. $existing_url = getProp($prop, 'url');
  3388. // 只处理有任务ID且状态为processing的道具,或者状态为success但没有URL的道具
  3389. if ($task_id && ($task_status === 'processing' || (in_array($task_status, ['success', 'completed']) && empty($existing_url)))) {
  3390. $hasProcessing = ($task_status === 'processing');
  3391. // 查询任务状态
  3392. $task = DB::table('mp_generate_pic_tasks')
  3393. ->where('id', $task_id)
  3394. ->select('id', 'status', 'result_url', 'error_message')
  3395. ->first();
  3396. if ($task) {
  3397. $task = (array)$task;
  3398. $status = getProp($task, 'status');
  3399. // 如果任务完成或失败
  3400. if (in_array($status, ['success', 'failed'])) {
  3401. $prop['task_status'] = $status;
  3402. if ($status === 'success') {
  3403. $result_url = getProp($task, 'result_url');
  3404. if ($result_url) {
  3405. $result_urls = is_json($result_url) ? json_decode($result_url, true) : [$result_url];
  3406. if (is_array($result_urls) && !empty($result_urls[0])) {
  3407. $prop['url'] = $result_urls[0];
  3408. }
  3409. }
  3410. }
  3411. $updated = true;
  3412. } else if ($status === 'processing') {
  3413. $hasProcessing = true;
  3414. }
  3415. }
  3416. }
  3417. }
  3418. // 如果有更新,检查数据是否真的变化了(通过哈希对比)
  3419. if ($updated) {
  3420. $newHash = $generateHash($roles, $scenes, $props);
  3421. $cachedHash = Redis::get($cacheKey);
  3422. // 只有当数据真正变化时才更新数据库和发送事件
  3423. if ($newHash !== $cachedHash) {
  3424. try {
  3425. // 更新数据库
  3426. DB::table($table_name)->where($id_field, $id_value)->update([
  3427. 'roles' => json_encode($roles, JSON_UNESCAPED_UNICODE),
  3428. 'scenes' => json_encode($scenes, JSON_UNESCAPED_UNICODE),
  3429. 'props' => json_encode($props, JSON_UNESCAPED_UNICODE),
  3430. 'updated_at' => date('Y-m-d H:i:s')
  3431. ]);
  3432. // 更新缓存
  3433. Redis::setex($cacheKey, 600, $newHash);
  3434. // 发送更新事件
  3435. echo "data: " . json_encode([
  3436. 'type' => 'update',
  3437. 'data' => [
  3438. 'roles' => $roles,
  3439. 'scenes' => $scenes,
  3440. 'props' => $props,
  3441. 'elapsed_time' => time() - $startTime
  3442. ]
  3443. ], JSON_UNESCAPED_UNICODE) . "\n\n";
  3444. if (ob_get_level() > 0) {
  3445. ob_flush();
  3446. }
  3447. flush();
  3448. } catch (\Exception $e) {
  3449. dLog('anime')->error('更新角色/场景/道具信息失败: ' . $e->getMessage());
  3450. }
  3451. } else {
  3452. // 即使哈希相同,如果有URL更新也要发送事件
  3453. $hasUrlUpdate = false;
  3454. foreach ($roles as $role) {
  3455. if (!empty(getProp($role, 'url')) && getProp($role, 'task_status') === 'success') {
  3456. $hasUrlUpdate = true;
  3457. break;
  3458. }
  3459. }
  3460. if (!$hasUrlUpdate) {
  3461. foreach ($scenes as $scene) {
  3462. if (!empty(getProp($scene, 'url')) && getProp($scene, 'task_status') === 'success') {
  3463. $hasUrlUpdate = true;
  3464. break;
  3465. }
  3466. }
  3467. }
  3468. if (!$hasUrlUpdate) {
  3469. foreach ($props as $prop) {
  3470. if (!empty(getProp($prop, 'url')) && getProp($prop, 'task_status') === 'success') {
  3471. $hasUrlUpdate = true;
  3472. break;
  3473. }
  3474. }
  3475. }
  3476. if ($hasUrlUpdate) {
  3477. // 强制更新数据库和发送事件
  3478. try {
  3479. DB::table($table_name)->where($id_field, $id_value)->update([
  3480. 'roles' => json_encode($roles, JSON_UNESCAPED_UNICODE),
  3481. 'scenes' => json_encode($scenes, JSON_UNESCAPED_UNICODE),
  3482. 'props' => json_encode($props, JSON_UNESCAPED_UNICODE),
  3483. 'updated_at' => date('Y-m-d H:i:s')
  3484. ]);
  3485. // 更新缓存
  3486. Redis::setex($cacheKey, 600, $newHash);
  3487. // 发送更新事件
  3488. echo "data: " . json_encode([
  3489. 'type' => 'update',
  3490. 'data' => [
  3491. 'roles' => $roles,
  3492. 'scenes' => $scenes,
  3493. 'props' => $props,
  3494. 'elapsed_time' => time() - $startTime
  3495. ]
  3496. ], JSON_UNESCAPED_UNICODE) . "\n\n";
  3497. if (ob_get_level() > 0) {
  3498. ob_flush();
  3499. }
  3500. flush();
  3501. } catch (\Exception $e) {
  3502. dLog('anime')->error('强制更新角色/场景/道具信息失败: ' . $e->getMessage());
  3503. }
  3504. }
  3505. }
  3506. }
  3507. // 如果所有任务都已完成,发送完成事件并退出
  3508. if (!$hasProcessing) {
  3509. // 查询数据库中的最终数据,确保返回最新的完整数据
  3510. try {
  3511. $finalSource = DB::table($table_name)->where($id_field, $id_value)->first();
  3512. if ($finalSource) {
  3513. $finalSource = (array)$finalSource;
  3514. $finalRoles = json_decode(getProp($finalSource, 'roles', '[]'), true) ?: [];
  3515. $finalScenes = json_decode(getProp($finalSource, 'scenes', '[]'), true) ?: [];
  3516. $finalProps = json_decode(getProp($finalSource, 'props', '[]'), true) ?: [];
  3517. // 使用数据库中的最终数据
  3518. $roles = $finalRoles;
  3519. $scenes = $finalScenes;
  3520. $props = $finalProps;
  3521. }
  3522. } catch (\Exception $e) {
  3523. dLog('anime')->error('查询最终数据失败: ' . $e->getMessage());
  3524. // 如果查询失败,继续使用内存中的数据
  3525. }
  3526. // 清理缓存
  3527. Redis::del($cacheKey);
  3528. echo "data: " . json_encode([
  3529. 'type' => 'completed',
  3530. 'data' => [
  3531. 'roles' => $roles,
  3532. 'scenes' => $scenes,
  3533. 'props' => $props,
  3534. 'total_time' => time() - $startTime
  3535. ]
  3536. ], JSON_UNESCAPED_UNICODE) . "\n\n";
  3537. if (ob_get_level() > 0) {
  3538. ob_flush();
  3539. }
  3540. flush();
  3541. break;
  3542. }
  3543. // 等待下次检查
  3544. sleep($checkInterval);
  3545. }
  3546. // 超时处理
  3547. if (time() - $startTime >= $maxDuration) {
  3548. // 查询数据库中的最终数据,即使超时也要返回最新数据
  3549. try {
  3550. $finalSource = DB::table($table_name)->where($id_field, $id_value)->first();
  3551. if ($finalSource) {
  3552. $finalSource = (array)$finalSource;
  3553. $finalRoles = json_decode(getProp($finalSource, 'roles', '[]'), true) ?: [];
  3554. $finalScenes = json_decode(getProp($finalSource, 'scenes', '[]'), true) ?: [];
  3555. $finalProps = json_decode(getProp($finalSource, 'props', '[]'), true) ?: [];
  3556. // 使用数据库中的最终数据
  3557. $roles = $finalRoles;
  3558. $scenes = $finalScenes;
  3559. $props = $finalProps;
  3560. }
  3561. } catch (\Exception $e) {
  3562. dLog('anime')->error('超时时查询最终数据失败: ' . $e->getMessage());
  3563. // 如果查询失败,继续使用内存中的数据
  3564. }
  3565. // 清理缓存
  3566. Redis::del($cacheKey);
  3567. echo "data: " . json_encode([
  3568. 'type' => 'timeout',
  3569. 'message' => '轮询超时,请刷新页面查看最新状态',
  3570. 'data' => [
  3571. 'roles' => $roles,
  3572. 'scenes' => $scenes,
  3573. 'props' => $props
  3574. ]
  3575. ], JSON_UNESCAPED_UNICODE) . "\n\n";
  3576. if (ob_get_level() > 0) {
  3577. ob_flush();
  3578. }
  3579. flush();
  3580. }
  3581. };
  3582. }
  3583. public function clipSegmentVideo($data) {
  3584. $segment_id = getProp($data, 'segment_id');
  3585. $video_time_point_start = getProp($data, 'video_time_point_start');
  3586. $video_time_point_end = getProp($data, 'video_time_point_end');
  3587. if (!$segment_id || !$video_time_point_start || !$video_time_point_end) {
  3588. Utils::throwError('20003:参数异常');
  3589. }
  3590. if (!DB::table('mp_episode_segments')->where('segment_id', $segment_id)->value('video_url')) {
  3591. Utils::throwError('20003:该分镜没有视频,无法裁剪');
  3592. }
  3593. $video_duration = $video_time_point_end - $video_time_point_start;
  3594. if (!$video_duration < 0) Utils::throwError('20003:参数异常');
  3595. return DB::table('mp_episode_segments')->where('segment_id', $segment_id)->update([
  3596. 'video_duration' => $video_duration,
  3597. 'video_time_point_start' => $video_time_point_start,
  3598. 'video_time_point_end' => $video_time_point_end,
  3599. 'updated_at' => date('Y-m-d H:i:s')
  3600. ]);
  3601. }
  3602. // 轮训获取图片任务结果
  3603. private function loopGetPicTaskResult($task_id) {
  3604. $task = MpGeneratePicTask::where('id', $task_id)->first();
  3605. if (!$task) {
  3606. return '';
  3607. }
  3608. // 检查任务模型类型(火山模型和GPT模型都支持直接检查任务状态)
  3609. $model = getProp($task, 'model');
  3610. $isVolcModel = in_array($model, \App\Consts\BaseConst::VOLC_PIC_MODELS);
  3611. $isGptModel = in_array($model, \App\Consts\BaseConst::GPT_IMAGE2_MODELS);
  3612. $isSyncModel = $isVolcModel || $isGptModel;
  3613. // 轮询查询任务状态(火山API和即梦AI都需要轮询)
  3614. $start_count = 0;
  3615. $img_url = '';
  3616. while ($start_count <= 60) { // 循环20次请求,每3s一次
  3617. sleep(3);
  3618. $task = MpGeneratePicTask::where('id', $task_id)->first();
  3619. // 如果任务已经完成,直接返回结果
  3620. if ($task->status === 'success' && $task->result_url) {
  3621. $result_urls = is_array($task->result_url) ? $task->result_url : json_decode($task->result_url, true);
  3622. return is_array($result_urls) ? $result_urls[0] : $task->result_url;
  3623. }
  3624. // 如果任务已失败,返回空
  3625. if ($task->status === 'failed') {
  3626. return '';
  3627. }
  3628. if ($isSyncModel) continue;
  3629. // 查询任务状态
  3630. $statusInfo = $this->aiImageGenerationService->queryTaskStatus($task);
  3631. if ($statusInfo['status'] === 'success') {
  3632. $task->updateStatus('success', [
  3633. 'result_url' => $statusInfo['result_url'],
  3634. 'result_json' => $statusInfo['result_json'] ?? []
  3635. ]);
  3636. // 同步调整分镜图片状态和结果
  3637. if (getProp($task, 'alias_segment_id')) {
  3638. DB::table('mp_episode_segments')->where('segment_id', getProp($task, 'alias_segment_id'))->update([
  3639. 'img_url' => $statusInfo['result_url'][0],
  3640. 'pic_task_status' => '已完成',
  3641. ]);
  3642. }
  3643. $img_url = $statusInfo['result_url'][0];
  3644. break;
  3645. } elseif ($statusInfo['status'] === 'failed') {
  3646. $task->updateStatus('failed', [
  3647. 'error_message' => $statusInfo['error_message'],
  3648. 'result_json' => $statusInfo['result_json'] ?? []
  3649. ]);
  3650. if (getProp($task, 'alias_segment_id')) {
  3651. DB::table('mp_episode_segments')->where('segment_id', getProp($task, 'alias_segment_id'))->update([
  3652. 'pic_task_status' => '失败',
  3653. ]);
  3654. }
  3655. break;
  3656. }
  3657. $start_count++;
  3658. }
  3659. return $img_url;
  3660. }
  3661. /**
  3662. * 从分镜内容中提取涉及的角色
  3663. */
  3664. private function extractCharactersFromSegment($segment_content, $available_characters, $roles) {
  3665. $found_characters = [];
  3666. foreach ($available_characters as $character) {
  3667. // 检查角色名称是否在分镜内容中出现
  3668. if (strpos($segment_content, $character) !== false) {
  3669. $found_characters[] = $character;
  3670. }
  3671. }
  3672. if (!$found_characters) {
  3673. foreach ($roles as $character) {
  3674. // 检查角色名称是否在分镜内容中出现
  3675. if (strpos($segment_content, $character) !== false) {
  3676. $found_characters[] = $character;
  3677. }
  3678. }
  3679. }
  3680. return array_unique($found_characters);
  3681. }
  3682. // 从分镜剧本中提取关键字段
  3683. private function handleSegmentContent(&$data) {
  3684. $segmentContent = getProp($data, 'segment_content');
  3685. // 解析分镜详细信息 - 与 Helpers.php 中 handleEpisodeContent 的 segmentData 结构保持一致
  3686. $segmentData = [
  3687. 'description' => '',
  3688. 'composition' => '',
  3689. 'camera_movement' => '',
  3690. 'voice_actor' => '',
  3691. 'dialogue' => '',
  3692. 'frame_type' => '',
  3693. 'scene' => '', // 场景
  3694. 'characters' => '', // 出镜角色
  3695. 'tail_frame' => '', // 尾帧描述
  3696. 'emotion' => '中性', // 情感
  3697. 'gender' => '0', // 性别(0未知,1男,2女)
  3698. 'speed_ratio' => 0, // 语速
  3699. 'loudness_ratio' => 0, // 音量
  3700. 'emotion_scale' => 4, // 情感强度
  3701. 'pitch' => 0, // 音调
  3702. ];
  3703. // 用于存储需要从 segment_content 中移除的匹配项
  3704. $replaceEmptyArr = [];
  3705. // 提取各个字段 - 兼容中文冒号和英文冒号,支持多种表达方式
  3706. if (preg_match('/(?:画面描述|镜头描述|场景描述)[::]\s*([^\n]+)/u', $segmentContent, $descMatch)) {
  3707. $segmentData['description'] = trim($descMatch[1]);
  3708. $data['description'] = trim($descMatch[1]);
  3709. }
  3710. if (preg_match('/(?:构图设计|构图|镜头构图)[::]\s*([^\n]+)/u', $segmentContent, $compMatch)) {
  3711. $segmentData['composition'] = trim($compMatch[1]);
  3712. $data['composition'] = trim($compMatch[1]);
  3713. }
  3714. if (preg_match('/(?:运镜调度|运镜|镜头运动|摄影机运动)[::]\s*([^\n]+)/u', $segmentContent, $cameraMatch)) {
  3715. $segmentData['camera_movement'] = trim($cameraMatch[1]);
  3716. $data['camera_movement'] = trim($cameraMatch[1]);
  3717. }
  3718. if (preg_match('/(?:配音角色|配音|角色|声优)[::]\s*([^\n]+)/u', $segmentContent, $voiceMatch)) {
  3719. $segmentData['voice_actor'] = trim($voiceMatch[1]);
  3720. $data['voice_actor'] = trim($voiceMatch[1]);
  3721. }
  3722. if (preg_match('/(?:台词内容|台词|对白|对话)[::]\s*([^\n]+)/u', $segmentContent, $dialogueMatch)) {
  3723. $segmentData['dialogue'] = trim($dialogueMatch[1]);
  3724. $data['dialogue'] = trim($dialogueMatch[1]);
  3725. }
  3726. if (preg_match('/(?:画面类型|镜头类型|类型)[::]\s*([^\n]+)/u', $segmentContent, $frameMatch)) {
  3727. $segmentData['frame_type'] = trim($frameMatch[1]);
  3728. $data['frame_type'] = trim($frameMatch[1]);
  3729. }
  3730. // 场景字段
  3731. if (preg_match('/(?:场景|拍摄场景|背景场景|环境)[::]\s*([^\n]+)/u', $segmentContent, $sceneMatch)) {
  3732. $segmentData['scene'] = trim($sceneMatch[1]);
  3733. $data['scene'] = trim($sceneMatch[1]);
  3734. }
  3735. // 出镜角色字段
  3736. if (preg_match('/(?:出镜角色|角色出镜|登场角色|人物)[::]\s*([^\n]+)/u', $segmentContent, $charactersMatch)) {
  3737. $segmentData['characters'] = trim($charactersMatch[1]);
  3738. $data['characters'] = trim($charactersMatch[1]);
  3739. }
  3740. // 尾帧描述字段
  3741. if (preg_match('/(?:尾帧描述|尾帧|结束帧|最后一帧|结尾画面|结束画面)[::]\s*([^\n]+)/u', $segmentContent, $tailFrameMatch)) {
  3742. $segmentData['tail_frame'] = trim($tailFrameMatch[1]);
  3743. $data['tail_frame'] = trim($tailFrameMatch[1]);
  3744. }
  3745. // 情感字段
  3746. if (preg_match('/(?:情感|情绪|感情)[::]\s*([^\n]+)/u', $segmentContent, $emotionMatch)) {
  3747. $replaceEmptyArr[] = trim($emotionMatch[0]);
  3748. $segmentData['emotion'] = trim($emotionMatch[1]);
  3749. $data['emotion'] = trim($emotionMatch[1]);
  3750. }
  3751. // 性别字段
  3752. if (preg_match('/(?:性别)[::]\s*([^\n]+)/u', $segmentContent, $genderMatch)) {
  3753. $replaceEmptyArr[] = trim($genderMatch[0]);
  3754. $genderStr = trim($genderMatch[1]);
  3755. if (strpos($genderStr, '男') !== false || $genderStr === '1') {
  3756. $segmentData['gender'] = '1';
  3757. $data['gender'] = '1';
  3758. } elseif (strpos($genderStr, '女') !== false || $genderStr === '2') {
  3759. $segmentData['gender'] = '2';
  3760. $data['gender'] = '2';
  3761. } else {
  3762. $segmentData['gender'] = '0';
  3763. $data['gender'] = '0';
  3764. }
  3765. }
  3766. // 语速字段
  3767. if (preg_match('/(?:语速|说话速度)[::]\s*([-+]?[0-9]*\.?[0-9]+)/u', $segmentContent, $speedMatch)) {
  3768. $replaceEmptyArr[] = trim($speedMatch[0]);
  3769. $segmentData['speed_ratio'] = (float)trim($speedMatch[1]);
  3770. $data['speed_ratio'] = (float)trim($speedMatch[1]);
  3771. }
  3772. // 音量字段
  3773. if (preg_match('/(?:音量|声音大小)[::]\s*([-+]?[0-9]*\.?[0-9]+)/u', $segmentContent, $loudnessMatch)) {
  3774. $replaceEmptyArr[] = trim($loudnessMatch[0]);
  3775. $segmentData['loudness_ratio'] = (float)trim($loudnessMatch[1]);
  3776. $data['loudness_ratio'] = (float)trim($loudnessMatch[1]);
  3777. }
  3778. // 情感强度字段
  3779. if (preg_match('/(?:情感强度|情绪强度)[::]\s*([0-9]+)/u', $segmentContent, $scaleMatch)) {
  3780. $replaceEmptyArr[] = trim($scaleMatch[0]);
  3781. $segmentData['emotion_scale'] = (int)trim($scaleMatch[1]);
  3782. $data['emotion_scale'] = (int)trim($scaleMatch[1]);
  3783. }
  3784. // 音调字段
  3785. if (preg_match('/(?:音调|音高)[::]\s*([-+]?[0-9]+)/u', $segmentContent, $pitchMatch)) {
  3786. $replaceEmptyArr[] = trim($pitchMatch[0]);
  3787. $segmentData['pitch'] = (int)trim($pitchMatch[1]);
  3788. $data['pitch'] = (int)trim($pitchMatch[1]);
  3789. }
  3790. // 从 segment_content 中移除已提取的配音参数字段
  3791. if (!empty($replaceEmptyArr)) {
  3792. $data['segment_content'] = str_replace($replaceEmptyArr, '', $segmentContent);
  3793. }
  3794. // 如果有配音角色,查询音色信息并验证情感
  3795. $voice_actor = $segmentData['voice_actor'];
  3796. if (!empty($voice_actor) && $voice_actor !== '旁白') {
  3797. // 从当前分镜所属的剧集或动漫中查找角色音色信息
  3798. $anime_id = getProp($data, 'anime_id');
  3799. $episode_id = getProp($data, 'episode_id');
  3800. // 优先从剧集的角色列表中查找
  3801. $roles = [];
  3802. if ($episode_id) {
  3803. $episode = DB::table('mp_anime_episodes')->where('id', $episode_id)->first();
  3804. if ($episode && getProp($episode, 'roles')) {
  3805. $roles = json_decode(getProp($episode, 'roles'), true) ?: [];
  3806. }
  3807. }
  3808. // 如果剧集中没有,从动漫的角色列表中查找
  3809. if (empty($roles) && $anime_id) {
  3810. $anime = DB::table('mp_animes')->where('id', $anime_id)->first();
  3811. if ($anime && getProp($anime, 'roles')) {
  3812. $roles = json_decode(getProp($anime, 'roles'), true) ?: [];
  3813. }
  3814. }
  3815. // 查找匹配的角色音色信息
  3816. $timbre_info = null;
  3817. foreach ($roles as $role) {
  3818. if (getProp($role, 'role') === $voice_actor) {
  3819. $timbre_info = $role;
  3820. break;
  3821. }
  3822. }
  3823. // 如果找到音色信息,添加到数据中
  3824. if ($timbre_info) {
  3825. $voice_type = getProp($timbre_info, 'voice_type');
  3826. $voice_name = getProp($timbre_info, 'voice_name');
  3827. $voice_audio_url = getProp($timbre_info, 'voice_audio_url');
  3828. if ($voice_type) {
  3829. $data['voice_type'] = $voice_type;
  3830. $segmentData['voice_type'] = $voice_type;
  3831. }
  3832. if ($voice_name) {
  3833. $data['voice_name'] = $voice_name;
  3834. $segmentData['voice_name'] = $voice_name;
  3835. }
  3836. if ($voice_audio_url) {
  3837. $data['voice_audio_url'] = $voice_audio_url;
  3838. $segmentData['voice_audio_url'] = $voice_audio_url;
  3839. }
  3840. // 验证情感是否在音色支持的情感列表中
  3841. if ($voice_type) {
  3842. $timbre_emotion = DB::table('mp_timbres')->where('timbre_type', $voice_type)->value('emotion');
  3843. if ($timbre_emotion) {
  3844. $timbre_emotion = explode(',', $timbre_emotion);
  3845. } else {
  3846. $timbre_emotion = [];
  3847. }
  3848. $emotion = getProp($segmentData, 'emotion', '中性');
  3849. if (!in_array($emotion, $timbre_emotion)) {
  3850. $emotion = '中性';
  3851. }
  3852. $emotion_list = DB::table('mp_emotion_list')->where('is_enabled', 1)->pluck('emotion_name', 'emotion_code')->toArray();
  3853. $emotion_list = array_flip($emotion_list);
  3854. $emotion_type = isset($emotion_list[$emotion]) ? $emotion_list[$emotion] : 'neutral';
  3855. $data['emotion_type'] = $emotion_type;
  3856. $segmentData['emotion_type'] = $emotion_type;
  3857. }
  3858. }
  3859. }
  3860. return $segmentData;
  3861. }
  3862. public function createSegmentVideoTask($data) {
  3863. $segment_id = getProp($data, 'segment_id');
  3864. $tail_frame = getProp($data, 'tail_frame');
  3865. $first_frame_url = getProp($data, 'first_frame_url');
  3866. $tail_frame_url = getProp($data, 'tail_frame_url');
  3867. $generate_audio = getProp($data, 'generate_audio', 0);
  3868. if (!$segment_id) {
  3869. Utils::throwError('1002:分镜ID不能为空');
  3870. }
  3871. // 获取分镜信息
  3872. $segment = DB::table('mp_episode_segments')->where('segment_id', $segment_id)->first();
  3873. if (!$segment) {
  3874. Utils::throwError('20003:分镜不存在');
  3875. }
  3876. $segment = (array)$segment;
  3877. $episode_id = getProp($segment, 'episode_id');
  3878. $ratio = DB::table('mp_anime_episodes')->where('id', $episode_id)->value('ratio');
  3879. if (!$ratio) $ratio = '9:16';
  3880. // 获取分镜内容
  3881. $segmentContent = getProp($segment, 'segment_content', '');
  3882. // 检查 $segmentContent 中是否已有尾帧描述
  3883. $contentHasTailFrame = preg_match('/(?:尾帧描述|尾帧)[::]\s*([^\n]+)/u', $segmentContent, $contentTailFrameMatch);
  3884. // 确定最终使用的尾帧描述(优先级:用户输入 > segmentContent自带 > 分镜表字段)
  3885. $finalTailFrame = '';
  3886. if ($tail_frame) {
  3887. // 用户输入了尾帧描述,优先使用
  3888. $finalTailFrame = $tail_frame;
  3889. // 如果 segmentContent 中已有尾帧描述,需要替换
  3890. if ($contentHasTailFrame) {
  3891. $segmentContent = preg_replace('/(?:尾帧描述|尾帧)[::]\s*[^\n]+/u', "尾帧描述:$tail_frame", $segmentContent);
  3892. }
  3893. } elseif ($contentHasTailFrame) {
  3894. // segmentContent 中有尾帧描述,使用它
  3895. $finalTailFrame = trim($contentTailFrameMatch[1]);
  3896. } else {
  3897. // 两者都没有,使用分镜表中的尾帧描述
  3898. $finalTailFrame = getProp($segment, 'tail_frame', '');
  3899. }
  3900. // 判断 $segmentContent 是否有台词内容,如果有则确保使用中文左右双引号
  3901. $hasDialogue = false;
  3902. if (preg_match('/(?:台词内容|台词|对白|对话)[::]\s*([^\n]+)/u', $segmentContent, $dialogueMatch)) {
  3903. $dialogue = trim($dialogueMatch[1]);
  3904. // 如果台词不为空且不是"无"
  3905. if (!empty($dialogue) && $dialogue !== '无') {
  3906. // 过滤掉所有符号(引号、标点、空格等),只保留文字内容来判断是否有实际台词
  3907. $dialogueFiltered = preg_replace('/[""\'\',。!?、;:…—\-\s\p{P}\p{S}]/u', '', $dialogue);
  3908. if (!empty($dialogueFiltered) && $dialogueFiltered !== '无') {
  3909. $hasDialogue = true;
  3910. }
  3911. $dialogue = preg_replace('/^["”]/u', '“', $dialogue); // 替换句首英文双引号或中文右双引号
  3912. $dialogue = preg_replace('/["“]$/u', '”', $dialogue); // 替换句尾英文双引号或中文左双引号
  3913. // 句首或句尾没有中文双引号,则分别添加中文左右双引号
  3914. if (!preg_match('/^[“]/', $dialogue)) {
  3915. $dialogue = '“' . $dialogue;
  3916. }
  3917. if (!preg_match('/[”]$/', $dialogue)) {
  3918. $dialogue .= '”';
  3919. }
  3920. // 将修改后的台词替换回 $segmentContent
  3921. $originalDialogue = $dialogueMatch[1];
  3922. $segmentContent = str_replace($originalDialogue, $dialogue, $segmentContent);
  3923. }
  3924. }
  3925. // 构建完整的提示词
  3926. $fullPrompt = $segmentContent;
  3927. if ($finalTailFrame && !$contentHasTailFrame) {
  3928. // 只有当 segmentContent 中没有尾帧描述时才追加
  3929. $fullPrompt .= "\n尾帧描述:$finalTailFrame";
  3930. }
  3931. // 去除多余的换行符(将连续多个换行符替换为单个换行符)
  3932. $fullPrompt = preg_replace('/\n{2,}/', "\n", $fullPrompt);
  3933. $fullPrompt = trim($fullPrompt);
  3934. // 当前是否启用音效同出(没台词强制关闭音效同出,节省资源收费)
  3935. $current_generate_audio = $hasDialogue ? $generate_audio : 0;
  3936. // 智能选择视频时长
  3937. // $videoDuration = $this->calculateOptimalVideoDuration($segmentContent, $tail_frame);
  3938. $videoDuration = -1;
  3939. // 处理视频模型
  3940. $model = getProp($data, 'model');
  3941. if (!$model) {
  3942. // 用户没有输入,从episode表获取
  3943. $episode = DB::table('mp_anime_episodes')->where('id', getProp($segment, 'episode_id'))->first();
  3944. $model = getProp($episode, 'video_model');
  3945. if (!$model) {
  3946. // episode表也没有,使用默认值
  3947. $model = 'doubao-seedance-1-5-pro-251215';
  3948. }
  3949. }
  3950. // 验证模型是否在可用模型表中
  3951. if (!DB::table('mp_video_models')->where('model', $model)->where('is_enabled', 1)->exists()) {
  3952. $model = 'doubao-seedance-1-5-pro-251215';
  3953. }
  3954. // 保存到episode表
  3955. $episode_id = getProp($segment, 'episode_id');
  3956. DB::table('mp_anime_episodes')->where('id', $episode_id)->update([
  3957. 'video_model' => $model,
  3958. 'updated_at' => date('Y-m-d H:i:s')
  3959. ]);
  3960. // 构建视频生成参数
  3961. $videoParams = [
  3962. 'model' => $model,
  3963. 'alias_segment_id' => $segment_id,
  3964. 'prompt' => trim($fullPrompt),
  3965. 'video_duration' => $videoDuration,
  3966. 'video_resolution' => '720P',
  3967. 'seed' => -1,
  3968. 'ratio' => $ratio,
  3969. 'generate_audio' => (int)$current_generate_audio === 0 ? false : true,
  3970. 'draft' => false,
  3971. 'watermark' => false,
  3972. 'camera_fixed' => false,
  3973. // 'callback_url' => 'http://mpaudio.yqsd.cn/api/video/seedanceCallback'
  3974. ];
  3975. // 如果分镜有图片,作为首帧
  3976. $hasImage = !empty(getProp($segment, 'img_url')) || $first_frame_url;
  3977. $hasVideo = !empty(getProp($segment, 'video_url'));
  3978. if ($hasImage) {
  3979. if ($first_frame_url) {
  3980. $videoParams['first_frame_url'] = $first_frame_url;
  3981. }else {
  3982. $videoParams['first_frame_url'] = getProp($segment, 'img_url');
  3983. }
  3984. if ($tail_frame_url) $videoParams['tail_frame_url'] = $tail_frame_url;
  3985. }
  3986. // 构建content数组
  3987. $videoParams['content'] = [
  3988. [
  3989. 'type' => 'text',
  3990. 'text' => $videoParams['prompt'],
  3991. ]
  3992. ];
  3993. // 如果有首帧图片,添加到content中
  3994. if ($hasImage) {
  3995. if (in_array($model, ['doubao-seedance-2-0-260128', 'doubao-seedance-2-0-fast-260128'])) {
  3996. $videoParams['content'][] = [
  3997. 'type' => 'image_url',
  3998. 'image_url' => [
  3999. 'url' => $videoParams['first_frame_url'],
  4000. ],
  4001. 'role' => 'reference_image',
  4002. ];
  4003. if (isset($videoParams['tail_frame_url'])) {
  4004. $videoParams['content'][] = [
  4005. 'type' => 'image_url',
  4006. 'image_url' => [
  4007. 'url' => $videoParams['tail_frame_url'],
  4008. ],
  4009. 'role' => 'reference_image',
  4010. ];
  4011. }
  4012. }else {
  4013. $videoParams['content'][] = [
  4014. 'type' => 'image_url',
  4015. 'image_url' => [
  4016. 'url' => $videoParams['first_frame_url'],
  4017. ],
  4018. 'role' => 'first_frame',
  4019. ];
  4020. if (isset($videoParams['tail_frame_url'])) {
  4021. $videoParams['content'][] = [
  4022. 'type' => 'image_url',
  4023. 'image_url' => [
  4024. 'url' => $videoParams['tail_frame_url'],
  4025. ],
  4026. 'role' => 'last_frame',
  4027. ];
  4028. }
  4029. }
  4030. }
  4031. // 获取配音音频URL
  4032. $audioUrl = getProp($segment, 'audio_url');
  4033. $audioDuration = getProp($segment, 'audio_duration');
  4034. // 音频传入的前提:必须有至少一张图片或一个视频
  4035. $canUseAudio = ($hasImage || $hasVideo) && !empty($audioUrl);
  4036. // 余额预检:按预估时长计算所需积分,不足直接报错
  4037. $chargeDuration = (int)ceil((float)$audioDuration);
  4038. if ($chargeDuration <= 0) {
  4039. $chargeDuration = 5; // 无音频时长时按默认5秒预估
  4040. }
  4041. $this->pointsService->checkUserPointsEnough(
  4042. $this->pointsService->getVideoChargePoints([
  4043. 'model' => $model,
  4044. 'video_resolution' => strtolower($videoParams['video_resolution'] ?? '720P'),
  4045. 'video_duration' => $chargeDuration,
  4046. 'ratio' => $ratio,
  4047. 'generate_audio' => $current_generate_audio,
  4048. ])
  4049. );
  4050. // dd($videoParams);
  4051. // 根据模型选择不同的视频生成方法
  4052. if (strpos($model, 'jimeng') !== false) {
  4053. // 即梦模型参数调整
  4054. $videoParams['video_duration'] = $audioDuration > 5 ? 10 : 5; // 即梦只支持5s或10s
  4055. unset($videoParams['content']); // 即梦不使用content格式
  4056. $task = $this->aiVideoGenerationService->createJimengTask($videoParams);
  4057. } elseif (strpos($model, 'kling') !== false) {
  4058. // Keling模型参数调整
  4059. $videoParams['video_duration'] = max(3, min(15, ceil($audioDuration))); // Keling支持3-15秒
  4060. $videoParams['aspect_ratio'] = $videoParams['ratio']; // Keling使用aspect_ratio
  4061. unset($videoParams['ratio']);
  4062. unset($videoParams['content']); // Keling不使用content格式
  4063. $task = $this->aiVideoGenerationService->createKelingOmniTask($videoParams);
  4064. } elseif (strpos($model, 'zhizhen') !== false) {
  4065. // 智帧20等新模型使用统一API
  4066. // 构建统一API参数
  4067. $unifiedParams = [
  4068. 'model_code' => $model,
  4069. 'alias_segment_id' => $segment_id,
  4070. 'prompt' => trim($fullPrompt),
  4071. 'video_duration' => $audioDuration > 0 ? max(5, min(15, ceil($audioDuration))) : 5,
  4072. 'video_resolution' => strtolower($videoParams['video_resolution']),
  4073. 'video_ratio' => $ratio,
  4074. 'seed' => -1,
  4075. ];
  4076. // 构建parameters参数
  4077. $parameters = [
  4078. 'seconds' => $unifiedParams['video_duration'],
  4079. 'resolution' => $unifiedParams['video_resolution'],
  4080. 'ratio' => $ratio,
  4081. // 'video_mode' => 'multi_image',
  4082. // 'mode' => 'multi_image',
  4083. 'generate_audio' => (int)$current_generate_audio === 1 ? true : false,
  4084. ];
  4085. $hasImage = false;
  4086. // 处理首帧和尾帧(智帧20模型必须要有首帧图片)
  4087. if ($hasImage) {
  4088. $parameters['first_frame_url'] = $videoParams['first_frame_url'];
  4089. if (isset($videoParams['tail_frame_url'])) {
  4090. $parameters['last_frame_url'] = $videoParams['tail_frame_url'];
  4091. }
  4092. // 只有在有图片的情况下才能添加参考音频
  4093. if ($audioUrl) {
  4094. // $parameters['reference_audios'] = [$audioUrl];
  4095. }
  4096. } else {
  4097. // 没有图片时,记录错误日志
  4098. logDB('anime', 'error', '智帧20模型缺少首帧图片', [
  4099. 'segment_id' => $segment_id,
  4100. 'model' => $model
  4101. ]);
  4102. }
  4103. $unifiedParams['parameters'] = $parameters;
  4104. // 调用统一API创建任务
  4105. $task = $this->aiVideoGenerationService->createUnifiedApiTask($unifiedParams);
  4106. } else {
  4107. // Seedance模型(默认)
  4108. // 检查是否为 Seedance 2.0 模型,如果是则需要处理配音音频
  4109. if ($canUseAudio && in_array($model, ['doubao-seedance-2-0-260128', 'doubao-seedance-2-0-fast-260128'])) {
  4110. // 添加配音音频到content中
  4111. $videoParams['content'][] = [
  4112. 'type' => 'audio_url',
  4113. 'audio_url' => [
  4114. 'url' => $audioUrl,
  4115. ],
  4116. 'role' => 'reference_audio',
  4117. ];
  4118. // 优化提示词,增加音频相关描述
  4119. $audioPrompt = "全程使用音频1作为视频配音。" . $fullPrompt;
  4120. $videoParams['prompt'] = $audioPrompt;
  4121. $videoParams['content'][0]['text'] = $audioPrompt;
  4122. } else if ($audioDuration) { // 有音频时长则需将视频时长设置为比音频时长更长的整数
  4123. $videoParams['video_duration'] = max(4, min(12, ceil($audioDuration))); // seedance支持2-12s
  4124. }
  4125. $task = $this->aiVideoGenerationService->createSeedanceTask($videoParams);
  4126. }
  4127. // 更新分镜表的视频任务信息
  4128. DB::table('mp_episode_segments')->where('segment_id', $segment_id)->update([
  4129. 'video_task_id' => $task->id,
  4130. 'video_task_status' => '生成中',
  4131. 'generate_audio' => $generate_audio,
  4132. 'updated_at' => date('Y-m-d H:i:s')
  4133. ]);
  4134. return [
  4135. 'task_id' => $task->id,
  4136. 'status' => $task->status,
  4137. 'segment_id' => $segment_id,
  4138. 'video_duration' => $videoDuration
  4139. ];
  4140. }
  4141. public function createActVideoTask($data) {
  4142. $act_id = getProp($data, 'act_id');
  4143. $first_frame_url = getProp($data, 'first_frame_url');
  4144. $tail_frame_url = getProp($data, 'tail_frame_url');
  4145. $generate_audio = getProp($data, 'generate_audio', 1);
  4146. $video_duration = getProp($data, 'video_duration');
  4147. $video_resolution = getProp($data, 'video_resolution');
  4148. $ratio = getProp($data, 'ratio');
  4149. $products = getProp($data, 'products', []);
  4150. $reference_images = array_unique(getProp($data, 'reference_images', []));
  4151. if (!is_array($reference_images) || !is_array($products)) {
  4152. Utils::throwError('20003:传入的参考图或资产格式不正确');
  4153. }
  4154. if (!$act_id) {
  4155. Utils::throwError('1002:片段ID不能为空');
  4156. }
  4157. // 获取片段信息
  4158. $act = DB::table('mp_episode_segments')->where('id', $act_id)->first();
  4159. if (!$act) {
  4160. Utils::throwError('20003:片段不存在');
  4161. }
  4162. $act = (array)$act;
  4163. $anime_id = getProp($act, 'anime_id');
  4164. $episode_id = getProp($act, 'episode_id');
  4165. $anime = DB::table('mp_animes')->where('id', $anime_id)->first();
  4166. $ace_mode = getProp($anime, 'ace_mode');
  4167. $art_style_type = getProp($anime, 'art_style_type');
  4168. $art_style = getProp($anime, 'art_style');
  4169. $episode = DB::table('mp_anime_episodes')->where('id', $episode_id)->first();
  4170. if (!$ratio) $ratio = getProp($episode, 'ratio', '9:16');
  4171. if (!$video_resolution) $video_resolution = getProp($episode, 'video_resolution', '720p');
  4172. // 将资产中新出现的资产放到extra_products中
  4173. // 满足以下要求: 遍历传入的$products,将product_name与$episode中的roles、scenes和props做比对,如果不在其中,则与$episode中的extra_products做比对,如果有同名的则覆盖,没有则新增后存入$episode中的extra_products字段中
  4174. if (!empty($products) && $episode) {
  4175. // 获取剧集中的角色、场景和道具列表
  4176. $roles = json_decode(getProp($episode, 'roles', '[]'), true) ?: [];
  4177. $scenes = json_decode(getProp($episode, 'scenes', '[]'), true) ?: [];
  4178. $props = json_decode(getProp($episode, 'props', '[]'), true) ?: [];
  4179. $extra_products = json_decode(getProp($episode, 'extra_products', '[]'), true) ?: [];
  4180. // 构建角色名称列表
  4181. $role_names = array_column($roles, 'role');
  4182. // 构建场景名称列表
  4183. $scene_names = array_column($scenes, 'scene');
  4184. // 构建道具名称列表
  4185. $prop_names = array_column($props, 'prop');
  4186. // 遍历传入的products
  4187. foreach ($products as $product) {
  4188. $product_name = getProp($product, 'product_name');
  4189. // 如果product_name不在roles、scenes和props中
  4190. if (!in_array($product_name, $role_names) && !in_array($product_name, $scene_names) && !in_array($product_name, $prop_names)) {
  4191. // 查找是否在extra_products中存在同名的
  4192. $found = false;
  4193. foreach ($extra_products as $key => $extra_product) {
  4194. if (getProp($extra_product, 'product_name') === $product_name) {
  4195. // 有同名的则覆盖
  4196. $extra_products[$key] = $product;
  4197. $found = true;
  4198. break;
  4199. }
  4200. }
  4201. // 没有则新增
  4202. if (!$found) {
  4203. $extra_products[] = $product;
  4204. }
  4205. }
  4206. }
  4207. if ($extra_products) {
  4208. // 保存到数据库
  4209. DB::table('mp_anime_episodes')
  4210. ->where('id', $episode_id)
  4211. ->update([
  4212. 'extra_products' => json_encode($extra_products, 256),
  4213. 'updated_at' => date('Y-m-d H:i:s')
  4214. ]);
  4215. }
  4216. }
  4217. // 获取分镜内容
  4218. $actContent = getProp($act, 'act_show_content', '');
  4219. // 音效同出(默认使用)
  4220. $current_generate_audio = $generate_audio ? 1 : 0;
  4221. // 构建完整的提示词
  4222. $processResult = $this->processActContentWithProducts($actContent, $products);
  4223. $fullPrompt = $processResult['content'];
  4224. // if ($art_style_type == '3D真人风格') $fullPrompt = "美术风格: $art_style\n\n".$fullPrompt;
  4225. $reference_images = array_merge($processResult['reference_images'], $reference_images);
  4226. $videoDuration = $video_duration ? $video_duration : getProp($act, 'act_duration');
  4227. // 处理视频模型
  4228. $model = getProp($data, 'model');
  4229. if (!$model) {
  4230. $model = getProp($episode, 'video_model');
  4231. if (!$model) {
  4232. // episode表也没有,使用默认值
  4233. $model = 'zhizhen-20';
  4234. }
  4235. }
  4236. // 验证模型是否在可用模型表中
  4237. if (!DB::table('mp_video_models')->where('model', $model)->where('is_enabled', 1)->exists()) {
  4238. $model = 'zhizhen-20';
  4239. }
  4240. // 保存到episode表(仅在专用方法中更新模型)
  4241. // DB::table('mp_anime_episodes')->where('id', $episode_id)->update([
  4242. // 'video_model' => $model,
  4243. // 'updated_at' => date('Y-m-d H:i:s')
  4244. // ]);
  4245. // 余额预检:按预估时长计算所需积分,不足直接报错
  4246. $chargeDuration = (int)$videoDuration;
  4247. if ($chargeDuration <= 0) {
  4248. $chargeDuration = 5; // 无时长时按默认5秒预估
  4249. }
  4250. $this->pointsService->checkUserPointsEnough(
  4251. $this->pointsService->getVideoChargePoints([
  4252. 'model' => $model,
  4253. 'video_resolution' => strtolower($video_resolution ?? '720p'),
  4254. 'video_duration' => $chargeDuration,
  4255. 'ratio' => $ratio,
  4256. 'generate_audio' => $current_generate_audio,
  4257. ])
  4258. );
  4259. // 构建视频生成参数
  4260. $videoParams = [
  4261. 'model' => $model,
  4262. 'alias_act_id' => $act_id,
  4263. 'prompt' => trim($fullPrompt),
  4264. 'video_duration' => $videoDuration,
  4265. 'video_resolution' => $video_resolution,
  4266. 'seed' => -1,
  4267. 'ratio' => $ratio,
  4268. 'generate_audio' => (int)$current_generate_audio === 0 ? false : true,
  4269. 'draft' => false,
  4270. 'watermark' => false,
  4271. 'camera_fixed' => false,
  4272. // 'callback_url' => 'http://mpaudio.yqsd.cn/api/video/seedanceCallback'
  4273. ];
  4274. // 如果分镜有图片,作为首帧
  4275. $hasImage = !empty(getProp($act, 'img_url')) || $first_frame_url;
  4276. $hasVideo = !empty(getProp($act, 'video_url'));
  4277. if ($hasImage) {
  4278. if ($first_frame_url) {
  4279. $videoParams['first_frame_url'] = $first_frame_url;
  4280. }else {
  4281. $videoParams['first_frame_url'] = getProp($act, 'img_url');
  4282. }
  4283. if ($tail_frame_url) $videoParams['tail_frame_url'] = $tail_frame_url;
  4284. }
  4285. // 构建content数组
  4286. $videoParams['content'] = [
  4287. [
  4288. 'type' => 'text',
  4289. 'text' => $videoParams['prompt'],
  4290. ]
  4291. ];
  4292. // 如果有首帧图片,添加到content中
  4293. if ($hasImage) {
  4294. if (in_array($model, ['doubao-seedance-2-0-260128', 'doubao-seedance-2-0-fast-260128', 'doubao-seedance-2.0'])) {
  4295. $videoParams['content'][] = [
  4296. 'type' => 'image_url',
  4297. 'image_url' => [
  4298. 'url' => $videoParams['first_frame_url'],
  4299. ],
  4300. 'role' => 'reference_image',
  4301. ];
  4302. if (isset($videoParams['tail_frame_url'])) {
  4303. $videoParams['content'][] = [
  4304. 'type' => 'image_url',
  4305. 'image_url' => [
  4306. 'url' => $videoParams['tail_frame_url'],
  4307. ],
  4308. 'role' => 'reference_image',
  4309. ];
  4310. }
  4311. }else {
  4312. $videoParams['content'][] = [
  4313. 'type' => 'image_url',
  4314. 'image_url' => [
  4315. 'url' => $videoParams['first_frame_url'],
  4316. ],
  4317. 'role' => 'first_frame',
  4318. ];
  4319. if (isset($videoParams['tail_frame_url'])) {
  4320. $videoParams['content'][] = [
  4321. 'type' => 'image_url',
  4322. 'image_url' => [
  4323. 'url' => $videoParams['tail_frame_url'],
  4324. ],
  4325. 'role' => 'last_frame',
  4326. ];
  4327. }
  4328. }
  4329. }
  4330. // dd($videoParams);
  4331. // 根据模型选择不同的视频生成方法
  4332. if (strpos($model, 'jimeng') !== false) {
  4333. // 即梦模型参数调整
  4334. unset($videoParams['content']); // 即梦不使用content格式
  4335. $task = $this->aiVideoGenerationService->createJimengTask($videoParams);
  4336. } elseif (strpos($model, 'kling') !== false) {
  4337. // Keling模型参数调整
  4338. $videoParams['aspect_ratio'] = $videoParams['ratio']; // Keling使用aspect_ratio
  4339. unset($videoParams['ratio']);
  4340. unset($videoParams['content']); // Keling不使用content格式
  4341. $task = $this->aiVideoGenerationService->createKelingOmniTask($videoParams);
  4342. } elseif (strpos($model, 'zhizhen') !== false) {
  4343. // 智帧20等新模型使用统一API
  4344. // 构建统一API参数
  4345. $unifiedParams = [
  4346. 'model_code' => $model,
  4347. 'alias_act_id' => $act_id,
  4348. 'prompt' => trim($fullPrompt),
  4349. 'video_duration' => $videoDuration,
  4350. 'video_resolution' => strtolower($videoParams['video_resolution']),
  4351. 'video_ratio' => $ratio,
  4352. 'seed' => -1,
  4353. ];
  4354. // 构建parameters参数
  4355. $parameters = [
  4356. 'seconds' => $unifiedParams['video_duration'],
  4357. 'resolution' => $unifiedParams['video_resolution'],
  4358. 'ratio' => $ratio,
  4359. // 'video_mode' => 'multi_image',
  4360. // 'mode' => 'multi_image',
  4361. 'generate_audio' => (int)$current_generate_audio === 1 ? true : false,
  4362. ];
  4363. $hasImage = false;
  4364. // 处理首帧和尾帧(智帧20模型必须要有首帧图片)
  4365. if ($hasImage) {
  4366. $parameters['first_frame_url'] = $videoParams['first_frame_url'];
  4367. if (isset($videoParams['tail_frame_url'])) {
  4368. $parameters['last_frame_url'] = $videoParams['tail_frame_url'];
  4369. }
  4370. } else {
  4371. // 没有图片时,记录错误日志
  4372. logDB('anime', 'error', '智帧20模型缺少首帧图片', [
  4373. 'act_id' => $act_id,
  4374. 'model' => $model
  4375. ]);
  4376. }
  4377. if ($reference_images) {
  4378. // 限制只传入9张参考图
  4379. $reference_images = array_slice($reference_images, 0, 9);
  4380. // 在处理之前先保存原始reference_images到任务参数中
  4381. $unifiedParams['ref_image_url'] = json_encode($reference_images, 256);
  4382. $reference_images = $this->aiImageGenerationService->processReferenceImagesToAssets($reference_images, $unifiedParams['prompt']);
  4383. $parameters['reference_images'] = $reference_images;
  4384. $parameters['video_mode'] = 'multi_image';
  4385. $parameters['mode'] = 'multi_image';
  4386. }
  4387. $unifiedParams['parameters'] = $parameters;
  4388. // 调用统一API创建任务
  4389. $task = $this->aiVideoGenerationService->createUnifiedApiTask($unifiedParams);
  4390. } elseif (strpos($model, 'doubao-seedance-2.0') !== false) {
  4391. // 豆包Seedance 2.0(百度AI网关):图片需要先上传为素材
  4392. // 保存原始参考图用于任务记录
  4393. $videoParams['reference_images'] = $reference_images;
  4394. if ($reference_images) {
  4395. // 限制只传入9张参考图
  4396. $reference_images = array_slice($reference_images, 0, 9);
  4397. // 参考图上传为百度网关素材,上传失败时同步清理提示词中的<图片N>标记
  4398. $reference_image_assets = $this->aiVideoGenerationService->processReferenceImagesToSeedance20Assets($reference_images, $fullPrompt);
  4399. // 素材上传失败后提示词可能被清理,同步更新视频参数中的提示词
  4400. $videoParams['prompt'] = trim($fullPrompt);
  4401. $videoParams['content'][0]['text'] = trim($fullPrompt);
  4402. $videoParams['reference_image_assets'] = $reference_image_assets;
  4403. }
  4404. $task = $this->aiVideoGenerationService->createSeedance20Task($videoParams);
  4405. } else {
  4406. $task = $this->aiVideoGenerationService->createSeedanceTask($videoParams);
  4407. }
  4408. // 更新分镜表的视频任务信息
  4409. DB::table('mp_episode_segments')->where('id', $act_id)->update([
  4410. 'video_task_id' => $task->id,
  4411. 'video_task_status' => '生成中',
  4412. 'generate_audio' => $generate_audio,
  4413. 'updated_at' => date('Y-m-d H:i:s')
  4414. ]);
  4415. // 如果是全能模式,并且是第一集的第一个片段,将act_id存入Redis
  4416. $episode_number = getProp($act, 'episode_number');
  4417. $act_number = getProp($act, 'act_number');
  4418. if ((int)$ace_mode === 1 && (int)$episode_number === 1 && (int)$act_number === 1) {
  4419. Redis::sadd('anime_act_first_frame_urls', $act_id);
  4420. }
  4421. return [
  4422. 'task_id' => $task->id,
  4423. 'status' => $task->status,
  4424. 'act_id' => $act_id,
  4425. 'video_duration' => $videoDuration
  4426. ];
  4427. }
  4428. /**
  4429. * 文生视频通用方法
  4430. * 支持传入视频参数、提示词、参考图等信息,不支持products入参
  4431. * 用户提示词不做任何处理,直接组装参数后根据模型调用
  4432. *
  4433. * @param array $data 请求参数
  4434. * @return array
  4435. */
  4436. public function generateVideo($data) {
  4437. $prompt = getProp($data, 'prompt');
  4438. if (empty($prompt)) {
  4439. Utils::throwError('20003:提示词不能为空');
  4440. }
  4441. $model = getProp($data, 'model');
  4442. if (!$model) {
  4443. $model = 'zhizhen-20';
  4444. }
  4445. // 验证模型是否在可用模型表中
  4446. if (!DB::table('mp_video_models')->where('model', $model)->where('is_enabled', 1)->exists()) {
  4447. Utils::throwError('20003:该模型已不可用,请更换!');
  4448. }
  4449. $video_duration = getProp($data, 'video_duration', 5);
  4450. $video_resolution = getProp($data, 'video_resolution', '480p');
  4451. $ratio = getProp($data, 'ratio', '9:16');
  4452. $generate_audio = getProp($data, 'generate_audio', 1);
  4453. $seed = getProp($data, 'seed', -1);
  4454. $first_frame_url = getProp($data, 'first_frame_url');
  4455. $tail_frame_url = getProp($data, 'tail_frame_url');
  4456. // 参考图(支持数组或JSON字符串,最多9张)
  4457. $reference_images = getProp($data, 'reference_images', []);
  4458. if (is_string($reference_images)) {
  4459. $reference_images = json_decode($reference_images, true) ?: [];
  4460. }
  4461. if (!is_array($reference_images)) {
  4462. Utils::throwError('20003:参考图格式不正确');
  4463. }
  4464. $reference_images = array_values(array_unique(array_filter($reference_images)));
  4465. $reference_images = array_slice($reference_images, 0, 9);
  4466. // 参考视频(支持数组或JSON字符串,最多3个)
  4467. $reference_videos = getProp($data, 'reference_videos', []);
  4468. if (is_string($reference_videos)) {
  4469. $reference_videos = json_decode($reference_videos, true) ?: [];
  4470. }
  4471. if (!is_array($reference_videos)) {
  4472. Utils::throwError('20003:参考视频格式不正确');
  4473. }
  4474. $reference_videos = array_values(array_unique(array_filter($reference_videos)));
  4475. if (count($reference_videos) > 3) {
  4476. Utils::throwError('20003:参考视频最多选择3个');
  4477. }
  4478. $reference_videos = array_slice($reference_videos, 0, 3);
  4479. // 参考音频(支持数组或JSON字符串,最多3个)
  4480. $reference_audios = getProp($data, 'reference_audios', []);
  4481. if (is_string($reference_audios)) {
  4482. $reference_audios = json_decode($reference_audios, true) ?: [];
  4483. }
  4484. if (!is_array($reference_audios)) {
  4485. Utils::throwError('20003:参考音频格式不正确');
  4486. }
  4487. $reference_audios = array_values(array_unique(array_filter($reference_audios)));
  4488. if (count($reference_audios) > 3) {
  4489. Utils::throwError('20003:参考音频最多选择3个');
  4490. }
  4491. $reference_audios = array_slice($reference_audios, 0, 3);
  4492. // 构建视频生成参数(用户参数直接透传,提示词不做处理)
  4493. $videoParams = [
  4494. 'model' => $model,
  4495. 'prompt' => $prompt,
  4496. 'video_duration' => $video_duration,
  4497. 'video_resolution' => $video_resolution,
  4498. 'seed' => $seed,
  4499. 'ratio' => $ratio,
  4500. 'generate_audio' => (int)$generate_audio === 1 ? true : false,
  4501. 'draft' => getProp($data, 'draft', false),
  4502. 'watermark' => getProp($data, 'watermark', false),
  4503. 'camera_fixed' => getProp($data, 'camera_fixed', false),
  4504. ];
  4505. if ($first_frame_url) $videoParams['first_frame_url'] = $first_frame_url;
  4506. if ($tail_frame_url) $videoParams['tail_frame_url'] = $tail_frame_url;
  4507. // 构建content数组
  4508. $videoParams['content'] = [
  4509. [
  4510. 'type' => 'text',
  4511. 'text' => $prompt,
  4512. ]
  4513. ];
  4514. // 根据模型选择不同的视频生成方法
  4515. if (strpos($model, 'jimeng') !== false) {
  4516. // 即梦模型参数调整
  4517. unset($videoParams['content']); // 即梦不使用content格式
  4518. $task = $this->aiVideoGenerationService->createJimengTask($videoParams);
  4519. } elseif (strpos($model, 'kling') !== false) {
  4520. // 可灵模型参数调整
  4521. $videoParams['aspect_ratio'] = $videoParams['ratio']; // 可灵使用aspect_ratio
  4522. unset($videoParams['ratio']);
  4523. unset($videoParams['content']); // 可灵不使用content格式
  4524. $task = $this->aiVideoGenerationService->createKelingOmniTask($videoParams);
  4525. } elseif (strpos($model, 'zhizhen') !== false) {
  4526. // 智帧等新模型使用统一API
  4527. $unifiedParams = [
  4528. 'model_code' => $model,
  4529. 'prompt' => $prompt,
  4530. 'video_duration' => $video_duration,
  4531. 'video_resolution' => strtolower($video_resolution),
  4532. 'video_ratio' => $ratio,
  4533. 'seed' => $seed,
  4534. ];
  4535. // 构建parameters参数
  4536. $parameters = [
  4537. 'seconds' => $unifiedParams['video_duration'],
  4538. 'resolution' => $unifiedParams['video_resolution'],
  4539. 'ratio' => $ratio,
  4540. 'generate_audio' => (int)$generate_audio === 1 ? true : false,
  4541. ];
  4542. // 首帧和尾帧
  4543. if ($first_frame_url) $parameters['first_frame_url'] = $first_frame_url;
  4544. if ($tail_frame_url) $parameters['last_frame_url'] = $tail_frame_url;
  4545. // 维护ref_image_url字段(参考图+参考视频+参考音频URL,JSON数组,与参考图处理方式一致)
  4546. $refImageUrls = array_merge($reference_images, $reference_videos, $reference_audios);
  4547. if ($refImageUrls) {
  4548. $unifiedParams['ref_image_url'] = json_encode(array_values(array_filter($refImageUrls)), 256);
  4549. }
  4550. // 参考图处理
  4551. if ($reference_images) {
  4552. $reference_images = $this->aiImageGenerationService->processReferenceImagesToAssets($reference_images, $unifiedParams['prompt']);
  4553. $parameters['reference_images'] = $reference_images;
  4554. $parameters['video_mode'] = 'multi_image';
  4555. $parameters['mode'] = 'multi_image';
  4556. }
  4557. // 参考视频和参考音频(与参考图一致,先上传为智帧素材)
  4558. if ($reference_videos) {
  4559. $reference_videos = $this->aiImageGenerationService->processReferenceVideosToAssets($reference_videos, $unifiedParams['prompt']);
  4560. $parameters['reference_videos'] = $reference_videos;
  4561. }
  4562. if ($reference_audios) {
  4563. $reference_audios = $this->aiImageGenerationService->processReferenceAudiosToAssets($reference_audios, $unifiedParams['prompt']);
  4564. $parameters['reference_audios'] = $reference_audios;
  4565. }
  4566. $unifiedParams['parameters'] = $parameters;
  4567. // 调用统一API创建任务
  4568. $task = $this->aiVideoGenerationService->createUnifiedApiTask($unifiedParams);
  4569. } elseif (strpos($model, 'doubao-seedance-2.0') !== false) {
  4570. // 豆包Seedance 2.0(百度AI网关):图片/视频/音频需要先上传为素材
  4571. $videoParams['reference_images'] = $reference_images;
  4572. // 维护ref_image_url字段(参考图+参考视频+参考音频URL,JSON数组)
  4573. $refImageUrls = array_merge($reference_images, $reference_videos, $reference_audios);
  4574. if ($refImageUrls) {
  4575. $videoParams['ref_image_url'] = json_encode(array_values(array_filter($refImageUrls)), 256);
  4576. }
  4577. if ($reference_images) {
  4578. // 参考图上传为百度网关素材
  4579. $reference_image_assets = $this->aiVideoGenerationService->processReferenceImagesToSeedance20Assets($reference_images, $videoParams['prompt']);
  4580. $videoParams['reference_image_assets'] = $reference_image_assets;
  4581. }
  4582. // 参考视频上传为百度网关素材
  4583. if ($reference_videos) {
  4584. $reference_video_assets = $this->aiVideoGenerationService->processReferenceVideosToSeedance20Assets($reference_videos, $videoParams['prompt']);
  4585. $videoParams['reference_video_assets'] = $reference_video_assets;
  4586. }
  4587. // 参考音频上传为百度网关素材
  4588. if ($reference_audios) {
  4589. $reference_audio_assets = $this->aiVideoGenerationService->processReferenceAudiosToSeedance20Assets($reference_audios, $videoParams['prompt']);
  4590. $videoParams['reference_audio_assets'] = $reference_audio_assets;
  4591. }
  4592. // 参考素材上传失败时可能清理提示词中的素材标记,需要同步回content文本
  4593. if ($reference_images || $reference_videos || $reference_audios) {
  4594. $videoParams['content'][0]['text'] = $videoParams['prompt'];
  4595. }
  4596. $task = $this->aiVideoGenerationService->createSeedance20Task($videoParams);
  4597. } else {
  4598. // 官方Seedance模型:兼容参考视频和参考音频(content直接透传公网URL)
  4599. // 维护ref_image_url字段(参考图+参考视频+参考音频URL,JSON数组)
  4600. $refImageUrls = array_merge($reference_images, $reference_videos, $reference_audios);
  4601. if ($refImageUrls) {
  4602. $videoParams['ref_image_url'] = json_encode(array_values(array_filter($refImageUrls)), 256);
  4603. }
  4604. if ($reference_videos) {
  4605. foreach ($reference_videos as $videoUrl) {
  4606. $videoParams['content'][] = [
  4607. 'type' => 'video_url',
  4608. 'video_url' => [
  4609. 'url' => $videoUrl,
  4610. ],
  4611. 'role' => 'reference_video',
  4612. ];
  4613. }
  4614. }
  4615. if ($reference_audios) {
  4616. foreach ($reference_audios as $audioUrl) {
  4617. $videoParams['content'][] = [
  4618. 'type' => 'audio_url',
  4619. 'audio_url' => [
  4620. 'url' => $audioUrl,
  4621. ],
  4622. 'role' => 'reference_audio',
  4623. ];
  4624. }
  4625. }
  4626. $task = $this->aiVideoGenerationService->createSeedanceTask($videoParams);
  4627. }
  4628. return [
  4629. 'task_id' => $task->id,
  4630. 'status' => $task->status,
  4631. 'model' => $model,
  4632. 'video_duration' => $video_duration,
  4633. 'video_resolution' => $video_resolution,
  4634. 'ratio' => $ratio
  4635. ];
  4636. }
  4637. /**
  4638. * 预估生成所需积分(mode=chat/image/video,支持多数量总额)
  4639. *
  4640. * chat : count(默认1,AI对话单次10积分);批量分集可传 anime_id + generate_episode_number 按实际待创建集数估算
  4641. * image : model 必传;resolution(1k/2k/4k)或 width/height 自动归一化;image_num(默认1)
  4642. * video : model 必传;video_resolution(默认720p);video_duration(默认5秒);count(默认1);scene(默认video_generation)
  4643. *
  4644. * @param array $data
  4645. * @return array
  4646. */
  4647. public function previewCharge(array $data): array
  4648. {
  4649. $mode = (string)getProp($data, 'mode', '');
  4650. if (!in_array($mode, ['chat', 'image', 'video'])) {
  4651. Utils::throwError('1003:请传入mode参数(chat/image/video)');
  4652. }
  4653. // 视频计费场景(video_generation/video_to_video),默认视频生成
  4654. $scene = (string)getProp($data, 'scene', 'video_generation');
  4655. $items = [];
  4656. $model = '';
  4657. $resolution = '';
  4658. if ($mode === 'video') {
  4659. // 通用视频预估:单价/秒 × 时长 × 数量(多个视频计算总额)
  4660. $model = (string)getProp($data, 'model', '');
  4661. if (!$model) {
  4662. Utils::throwError('1002:model参数不能为空');
  4663. }
  4664. $resolution = strtolower((string)getProp($data, 'video_resolution', '720p'));
  4665. $duration = (int)getProp($data, 'video_duration', 5);
  4666. if ($duration <= 0) {
  4667. $duration = 5;
  4668. }
  4669. $count = max(1, (int)getProp($data, 'count', 1));
  4670. $pointsPerVideo = $this->pointsService->getVideoChargePoints([
  4671. 'model' => $model,
  4672. 'video_resolution' => $resolution,
  4673. 'video_duration' => $duration,
  4674. 'mode' => $scene,
  4675. ]);
  4676. $points = $pointsPerVideo * $count;
  4677. $items[] = [
  4678. 'type' => 'video',
  4679. 'model' => $model,
  4680. 'video_resolution' => $resolution,
  4681. 'video_duration' => $duration,
  4682. 'count' => $count,
  4683. 'points' => $points,
  4684. ];
  4685. } elseif ($mode === 'image') {
  4686. // 通用图片预估:单张价格 × 张数(resolution 可直传,或传 width/height 自动归一化)
  4687. $model = (string)getProp($data, 'model', '');
  4688. if (!$model) {
  4689. Utils::throwError('1002:model参数不能为空');
  4690. }
  4691. $resolution = strtolower((string)getProp($data, 'resolution', ''));
  4692. if (!$resolution) {
  4693. $width = (int)getProp($data, 'width', 0);
  4694. $height = (int)getProp($data, 'height', 0);
  4695. if ($width <= 0 || $height <= 0) {
  4696. $width = 1600;
  4697. $height = 2848;
  4698. }
  4699. $resolution = $this->pointsService->normalizeImageResolutionKey($width, $height);
  4700. }
  4701. $imageNum = max(1, (int)getProp($data, 'image_num', 1));
  4702. $points = $this->pointsService->getImageChargePoints([
  4703. 'model' => $model,
  4704. 'resolution' => $resolution,
  4705. ]) * $imageNum;
  4706. $items[] = [
  4707. 'type' => 'image',
  4708. 'model' => $model,
  4709. 'resolution' => $resolution,
  4710. 'image_num' => $imageNum,
  4711. 'points' => $points,
  4712. ];
  4713. } else {
  4714. // AI对话预估:单次10积分;批量生成分集传 anime_id + generate_episode_number 时按实际待创建集数估算
  4715. $count = max(1, (int)getProp($data, 'count', 1));
  4716. $animeId = getProp($data, 'anime_id');
  4717. $generateEpisodes = (int)getProp($data, 'generate_episode_number', 0);
  4718. if ($animeId && $generateEpisodes > 0) {
  4719. $currentMaxEpisode = DB::table('mp_anime_episodes')
  4720. ->where('anime_id', $animeId)
  4721. ->where('is_default', 1)
  4722. ->max('episode_number');
  4723. $currentMaxEpisode = $currentMaxEpisode ?: 0;
  4724. $startEpisodeNumber = $currentMaxEpisode + 1;
  4725. $endEpisodeNumber = $startEpisodeNumber + $generateEpisodes - 1;
  4726. $existingSkipped = DB::table('mp_batch_episode_generation_details')
  4727. ->where('anime_id', $animeId)
  4728. ->whereBetween('episode_number', [$startEpisodeNumber, $endEpisodeNumber])
  4729. ->whereIn('status', ['pending', 'processing', 'completed'])
  4730. ->count();
  4731. $count = ($endEpisodeNumber - $startEpisodeNumber + 1) - $existingSkipped;
  4732. if ($count < 0) {
  4733. $count = 0;
  4734. }
  4735. }
  4736. $points = $this->pointsService->getChatChargePoints((string)$model) * $count;
  4737. $items[] = [
  4738. 'type' => 'chat',
  4739. 'count' => $count,
  4740. 'points' => $points,
  4741. ];
  4742. }
  4743. $totalPoints = 0;
  4744. foreach ($items as $item) {
  4745. $totalPoints += $item['points'];
  4746. }
  4747. return [
  4748. 'mode' => $mode,
  4749. 'total_points' => $totalPoints,
  4750. 'items' => $items,
  4751. 'points_balance' => $this->pointsService->getUserPointsBalance(),
  4752. 'remark' => '积分为预估值,实际扣费以生成完成后的实际消耗为准',
  4753. ];
  4754. }
  4755. /**
  4756. * 根据提示词内容智能计算最优视频时长
  4757. *
  4758. * @param string $segmentContent 分镜内容
  4759. * @param string $tailFrame 尾帧描述
  4760. * @return int 视频时长(2-12秒)
  4761. */
  4762. public function calculateOptimalVideoDuration($segmentContent, $tailFrame = '') {
  4763. // 合并所有文本内容
  4764. $fullText = trim($segmentContent . ' ' . $tailFrame);
  4765. // 如果没有内容,返回默认时长
  4766. if (empty($fullText)) {
  4767. return 5;
  4768. }
  4769. // 计算文本长度(中文字符按2个字符计算)
  4770. $textLength = mb_strlen($fullText, 'UTF-8');
  4771. $chineseCharCount = preg_match_all('/[\x{4e00}-\x{9fff}]/u', $fullText);
  4772. $adjustedLength = $textLength + $chineseCharCount; // 中文字符权重更高
  4773. // 分析内容复杂度
  4774. $complexityScore = $this->analyzeContentComplexity($fullText);
  4775. // 基础时长计算(根据文本长度)
  4776. $baseDuration = 3; // 默认2秒
  4777. // if ($adjustedLength <= 20) {
  4778. // $baseDuration = 3;
  4779. // } elseif ($adjustedLength <= 40) {
  4780. // $baseDuration = 4;
  4781. // } elseif ($adjustedLength <= 60) {
  4782. // $baseDuration = 5;
  4783. // } elseif ($adjustedLength <= 80) {
  4784. // $baseDuration = 6;
  4785. // } elseif ($adjustedLength <= 100) {
  4786. // $baseDuration = 7;
  4787. // } elseif ($adjustedLength <= 120) {
  4788. // $baseDuration = 8;
  4789. // } else {
  4790. // $baseDuration = 9;
  4791. // }
  4792. // 根据内容复杂度调整时长
  4793. $finalDuration = $baseDuration + $complexityScore;
  4794. // 确保时长在2-12秒范围内
  4795. return max(4, min(12, $finalDuration));
  4796. }
  4797. /**
  4798. * 分析内容复杂度,返回时长调整值
  4799. *
  4800. * @param string $text 文本内容
  4801. * @return int 调整值(-2到+3)
  4802. */
  4803. private function analyzeContentComplexity($text) {
  4804. $score = 0;
  4805. // 动作关键词(需要更长时间展现)
  4806. $actionKeywords = [
  4807. '跑步', '奔跑', '飞行', '跳跃', '战斗', '打斗', '追逐', '逃跑', '舞蹈', '表演',
  4808. '变化', '变身', '爆炸', '崩塌', '建造', '制作', '烹饪', '绘画', '写字',
  4809. '移动', '旋转', '翻滚', '攀爬', '游泳', '潜水', '滑行', '飞翔'
  4810. ];
  4811. // 静态关键词(可以用较短时间)
  4812. $staticKeywords = [
  4813. '站立', '坐着', '躺着', '静止', '凝视', '思考', '沉思', '观察', '等待',
  4814. '睡觉', '休息', '静坐', '冥想', '阅读', '听音乐'
  4815. ];
  4816. // 复杂场景关键词(需要更长时间)
  4817. $complexSceneKeywords = [
  4818. '人群', '聚会', '会议', '战争', '庆典', '仪式', '表演', '比赛', '竞技',
  4819. '多人', '群体', '团队', '合作', '互动', '对话', '争论', '讨论'
  4820. ];
  4821. // 情感关键词(需要适中时间表现)
  4822. $emotionKeywords = [
  4823. '哭泣', '笑容', '愤怒', '惊讶', '恐惧', '悲伤', '喜悦', '兴奋', '紧张',
  4824. '感动', '震惊', '困惑', '失望', '希望', '绝望', '温柔', '严肃'
  4825. ];
  4826. // 检查动作关键词
  4827. foreach ($actionKeywords as $keyword) {
  4828. if (strpos($text, $keyword) !== false) {
  4829. $score += 1;
  4830. break; // 避免重复加分
  4831. }
  4832. }
  4833. // 检查静态关键词
  4834. foreach ($staticKeywords as $keyword) {
  4835. if (strpos($text, $keyword) !== false) {
  4836. $score -= 1;
  4837. break;
  4838. }
  4839. }
  4840. // 检查复杂场景关键词
  4841. foreach ($complexSceneKeywords as $keyword) {
  4842. if (strpos($text, $keyword) !== false) {
  4843. $score += 1;
  4844. break;
  4845. }
  4846. }
  4847. // 检查情感关键词
  4848. foreach ($emotionKeywords as $keyword) {
  4849. if (strpos($text, $keyword) !== false) {
  4850. $score += 1;
  4851. break;
  4852. }
  4853. }
  4854. // 检查时间相关词汇
  4855. if (preg_match('/缓慢|慢慢|渐渐|逐渐|慢动作/', $text)) {
  4856. $score += 1;
  4857. }
  4858. if (preg_match('/快速|迅速|急速|瞬间|立刻|马上/', $text)) {
  4859. $score -= 1;
  4860. }
  4861. // 检查转场词汇
  4862. if (preg_match('/然后|接着|随后|紧接着|同时|与此同时/', $text)) {
  4863. $score += 1;
  4864. }
  4865. // 检查环境描述(复杂环境需要更多时间)
  4866. if (preg_match('/风景|景色|环境|背景|氛围|光线|阴影|色彩|细节/', $text)) {
  4867. $score += 1;
  4868. }
  4869. // 检查对话内容(对话需要更多时间)
  4870. if (preg_match('/说|讲|告诉|回答|询问|问|对话|交谈/', $text)) {
  4871. $score += 1;
  4872. }
  4873. // 限制调整范围
  4874. return max(-1, min(4, $score));
  4875. }
  4876. /**
  4877. * 创建完整视频合成任务
  4878. *
  4879. * @param array $data
  4880. * @return array
  4881. */
  4882. public function createCompleteVideoTask($data)
  4883. {
  4884. $animeId = getProp($data, 'anime_id');
  4885. $episodeId = getProp($data, 'episode_id');
  4886. // 验证参数
  4887. if (!$animeId || !$episodeId) {
  4888. Utils::throwError('20003:anime_id 和 episode_id 不能为空');
  4889. }
  4890. // 检查是否已存在处理中的任务
  4891. $existingTask = DB::table('mp_complete_video_tasks')
  4892. ->where('anime_id', $animeId)
  4893. ->where('episode_id', $episodeId)
  4894. ->whereIn('generate_status', ['执行中'])
  4895. ->first();
  4896. if ($existingTask) {
  4897. Utils::throwError('20003:该剧集已有正在处理的视频合成任务');
  4898. }
  4899. // 获取全能模式状态
  4900. $ace_mode = DB::table('mp_animes')->where('id', $animeId)->value('ace_mode');
  4901. if ((int)$ace_mode === 1) {
  4902. // 获取所有片段的配音视频,按 act_number 排序
  4903. $segments = DB::table('mp_episode_segments')
  4904. ->where('anime_id', $animeId)
  4905. ->where('episode_id', $episodeId)
  4906. ->orderBy('segment_number')
  4907. ->select('id as act_id', 'act_number', 'video_url', 'audio_url', 'video_time_point_start', 'video_time_point_end')
  4908. ->get();
  4909. // 检查是否所有片段都有视频
  4910. $missingVideos = $segments->filter(function($segment) {
  4911. return empty($segment->video_url);
  4912. });
  4913. if ($missingVideos->isNotEmpty()) {
  4914. Utils::throwError('20003:存在未完成视频的片段,请确保所有片段都已完成配音');
  4915. }
  4916. }else {
  4917. // 获取所有分镜的配音视频,按 segment_number 排序
  4918. $segments = DB::table('mp_episode_segments')
  4919. ->where('anime_id', $animeId)
  4920. ->where('episode_id', $episodeId)
  4921. ->orderBy('segment_number')
  4922. ->select('segment_id', 'segment_number', 'video_url', 'audio_url', 'video_time_point_start', 'video_time_point_end')
  4923. ->get();
  4924. // 检查是否所有分镜都有配音和视频
  4925. $missingVideos = $segments->filter(function($segment) {
  4926. return empty($segment->audio_url) || empty($segment->video_url);
  4927. });
  4928. if ($missingVideos->isNotEmpty()) {
  4929. Utils::throwError('20003:存在未完成配音或视频的分镜,请确保所有分镜都已完成配音或视频');
  4930. }
  4931. }
  4932. if ($segments->isEmpty()) {
  4933. Utils::throwError('20003:未找到该剧集的分镜数据');
  4934. }
  4935. // 获取当前完整视频url
  4936. $completeVideoUrl = DB::table('mp_anime_episodes')
  4937. ->where('anime_id', $animeId)
  4938. ->where('id', $episodeId)
  4939. ->value('complete_video_url');
  4940. // 构建 generate_json
  4941. $generateJson = [];
  4942. $sequence = 1;
  4943. foreach ($segments as $segment) {
  4944. if ((int)$ace_mode === 1) {
  4945. $generateJson[] = [
  4946. 'sequence' => $sequence++,
  4947. 'video_url' => $segment->video_url,
  4948. 'video_time_point_start' => $segment->video_time_point_start,
  4949. 'video_time_point_end' => $segment->video_time_point_end
  4950. ];
  4951. }else {
  4952. $generateJson[] = [
  4953. 'sequence' => $sequence++,
  4954. 'video_url' => $segment->video_url,
  4955. 'audio_url' => $segment->audio_url,
  4956. 'video_time_point_start' => $segment->video_time_point_start,
  4957. 'video_time_point_end' => $segment->video_time_point_end
  4958. ];
  4959. }
  4960. }
  4961. // 创建任务
  4962. $now = date('Y-m-d H:i:s');
  4963. $taskId = DB::table('mp_complete_video_tasks')->insertGetId([
  4964. 'anime_id' => $animeId,
  4965. 'episode_id' => $episodeId,
  4966. 'generate_json' => json_encode($generateJson, 256),
  4967. 'generate_status' => '执行中',
  4968. 'complete_video_url' => '',
  4969. 'created_at' => $now,
  4970. 'updated_at' => $now
  4971. ]);
  4972. if (!$taskId) {
  4973. Utils::throwError('20003:创建任务失败');
  4974. }
  4975. // 更新剧集表的任务ID和状态
  4976. $boolen = DB::table('mp_anime_episodes')
  4977. ->where('anime_id', $animeId)
  4978. ->where('id', $episodeId)
  4979. ->update([
  4980. 'complete_video_task_id' => $taskId,
  4981. 'complete_video_task_status' => '执行中',
  4982. 'updated_at' => $now
  4983. ]);
  4984. if (!$boolen) {
  4985. Utils::throwError('20003:更新剧集表失败');
  4986. }
  4987. dLog('anime')->info('创建完整视频合成任务', [
  4988. 'task_id' => $taskId,
  4989. 'anime_id' => $animeId,
  4990. 'episode_id' => $episodeId,
  4991. 'segment_count' => count($generateJson)
  4992. ]);
  4993. // 请求远程服务器执行生成
  4994. $client = new Client(['timeout' => 600, 'verify' => false]);
  4995. try {
  4996. $result = $client->get("http://122.9.129.83:5000/api/anime/genVideo?taskId={$taskId}");
  4997. $response = $result->getBody()->getContents();
  4998. $response_arr = json_decode($response, true);
  4999. if (!isset($response_arr['code']) || (int)$response_arr['code'] !== 0) {
  5000. $error_msg = isset($response_arr['msg']) ? $response_arr['msg'] : '未知错误';
  5001. dLog('anime')->error('火山合成完整视频失败', ['error' => $error_msg, 'task_id' => $taskId]);
  5002. // // 更新任务状态为失败
  5003. // DB::table('mp_complete_video_tasks')
  5004. // ->where('id', $taskId)
  5005. // ->update([
  5006. // 'generate_status' => '执行失败',
  5007. // 'error_message' => $error_msg,
  5008. // 'updated_at' => date('Y-m-d H:i:s')
  5009. // ]);
  5010. // // 同步更新剧集表状态
  5011. // DB::table('mp_anime_episodes')
  5012. // ->where('complete_video_task_id', $taskId)
  5013. // ->update([
  5014. // 'complete_video_task_status' => '执行失败',
  5015. // 'updated_at' => date('Y-m-d H:i:s')
  5016. // ]);
  5017. Utils::throwError('20003:火山合成完整视频失败: ' . $error_msg);
  5018. }
  5019. } catch (\Exception $e) {
  5020. dLog('anime')->error('调用远程服务器失败', ['error' => $e->getMessage(), 'task_id' => $taskId]);
  5021. // 更新任务状态为失败
  5022. DB::table('mp_complete_video_tasks')
  5023. ->where('id', $taskId)
  5024. ->update([
  5025. 'generate_status' => '执行失败',
  5026. 'error_message' => $e->getMessage(),
  5027. 'updated_at' => date('Y-m-d H:i:s')
  5028. ]);
  5029. // 同步更新剧集表状态
  5030. DB::table('mp_anime_episodes')
  5031. ->where('complete_video_task_id', $taskId)
  5032. ->update([
  5033. 'complete_video_task_status' => '执行失败',
  5034. 'updated_at' => date('Y-m-d H:i:s')
  5035. ]);
  5036. Utils::throwError('20003:调用远程服务器失败: ' . $e->getMessage());
  5037. }
  5038. // 开始轮询任务状态
  5039. $maxAttempts = 60; // 5分钟 = 60次 * 5秒
  5040. $pollInterval = 5; // 每5秒轮询一次
  5041. $attempt = 0;
  5042. dLog('anime')->info('开始轮询任务状态', ['task_id' => $taskId]);
  5043. while ($attempt < $maxAttempts) {
  5044. sleep($pollInterval);
  5045. $attempt++;
  5046. // 查询任务状态
  5047. $task = DB::table('mp_complete_video_tasks')
  5048. ->where('id', $taskId)
  5049. ->first();
  5050. if (!$task) {
  5051. dLog('anime')->error('任务不存在', ['task_id' => $taskId]);
  5052. Utils::throwError('20003:任务不存在');
  5053. }
  5054. dLog('anime')->info('轮询任务状态', [
  5055. 'task_id' => $taskId,
  5056. 'attempt' => $attempt,
  5057. 'status' => $task->generate_status
  5058. ]);
  5059. // 检查任务是否完成
  5060. if ($task->generate_status === '执行成功') {
  5061. // 同步更新剧集表状态
  5062. $boolen3 = DB::table('mp_anime_episodes')
  5063. ->where('anime_id', $animeId)
  5064. ->where('id', $episodeId)
  5065. ->update([
  5066. 'complete_video_url' => $task->complete_video_url,
  5067. 'complete_video_task_status' => '执行成功',
  5068. 'updated_at' => date('Y-m-d H:i:s')
  5069. ]);
  5070. dLog('anime')->info('视频合成任务完成', [
  5071. 'task_id' => $taskId,
  5072. 'video_url' => $task->complete_video_url,
  5073. 'attempts' => $attempt
  5074. ]);
  5075. // 如果更新成功则远程删除之前的文件
  5076. if ($boolen3 && $completeVideoUrl) {
  5077. $encode_url = urlencode($completeVideoUrl);
  5078. $client = new Client(['timeout' => 300, 'verify' => false]);
  5079. // 根据ID通过API通知合成音频
  5080. // $result = $client->get("http://47.240.171.155:5000/api/fileDelete?url={$encode_url}");
  5081. $result = $client->get("http://122.9.129.83:5000/api/fileDelete?url={$encode_url}");
  5082. $response = $result->getBody()->getContents();
  5083. $response_arr = json_decode($response, true);
  5084. Log::info('火山删除音频返回: '.$response);
  5085. if (!isset($response_arr['status']) || (int)$response_arr['status'] !== 0) {
  5086. $error_msg = isset($response_arr['msg']) ? $response_arr['msg'] : '未知错误';
  5087. Log::info('火山删除音频失败: '.$error_msg);
  5088. // Utils::throwError('20003:火山删除音频失败');
  5089. }
  5090. }
  5091. return [
  5092. 'task_id' => $taskId,
  5093. 'anime_id' => $animeId,
  5094. 'episode_id' => $episodeId,
  5095. 'segment_count' => count($generateJson),
  5096. 'generate_status' => '执行成功',
  5097. 'complete_video_url' => $task->complete_video_url,
  5098. ];
  5099. }
  5100. // 检查任务是否失败
  5101. if ($task->generate_status === '执行失败') {
  5102. // 同步更新剧集表状态
  5103. DB::table('mp_anime_episodes')
  5104. ->where('anime_id', $animeId)
  5105. ->where('id', $episodeId)
  5106. ->update([
  5107. 'complete_video_task_status' => '执行失败',
  5108. 'updated_at' => date('Y-m-d H:i:s')
  5109. ]);
  5110. $errorMessage = $task->error_message ?? '未知错误';
  5111. dLog('anime')->error('视频合成任务失败', [
  5112. 'task_id' => $taskId,
  5113. 'error' => $errorMessage,
  5114. 'attempts' => $attempt
  5115. ]);
  5116. return [
  5117. 'task_id' => $taskId,
  5118. 'anime_id' => $animeId,
  5119. 'episode_id' => $episodeId,
  5120. 'segment_count' => count($generateJson),
  5121. 'generate_status' => '执行失败',
  5122. 'error_message' => $errorMessage
  5123. ];
  5124. }
  5125. }
  5126. // 超时处理
  5127. dLog('anime')->warning('视频合成任务超时', [
  5128. 'task_id' => $taskId,
  5129. 'max_attempts' => $maxAttempts,
  5130. 'timeout_seconds' => $maxAttempts * $pollInterval
  5131. ]);
  5132. // 更新任务状态为超时
  5133. DB::table('mp_complete_video_tasks')
  5134. ->where('id', $taskId)
  5135. ->update([
  5136. 'generate_status' => '超时',
  5137. 'error_message' => '任务执行超时(5分钟)',
  5138. 'updated_at' => date('Y-m-d H:i:s')
  5139. ]);
  5140. return [
  5141. 'task_id' => $taskId,
  5142. 'anime_id' => $animeId,
  5143. 'episode_id' => $episodeId,
  5144. 'segment_count' => count($generateJson),
  5145. 'generate_status' => '超时',
  5146. 'error_message' => '任务执行超时,请稍后查询任务状态'
  5147. ];
  5148. }
  5149. /**
  5150. * 根据 inner_prompt_type 附加内置提示词
  5151. *
  5152. * @param string $prompt 用户提示词
  5153. * @param int $innerPromptType 内置提示词类型(1=三视图, 2=九宫格)
  5154. * @return string 合并后的提示词
  5155. */
  5156. public static function appendInnerPrompt($prompt, $innerPromptType = 0)
  5157. {
  5158. $innerPromptMap = [
  5159. 1 => '基于参考图生成主体的标准正面、侧面、后面三视图,主体完整。在最左侧添加主体正视图的特写,主体清晰完整。背景修改成纯白色,整体保持与参考图一致的美术风格和色彩搭配。画面无说明文字',
  5160. 2 => '基于参考图及提示词内容,生成9张连贯的系列图片:9张图片围绕同一主体展开,保持角色形象、美术风格和色彩搭配完全一致,画面内容依次衔接、情节连贯,整体构成一组完整的系列图。每张图片主体完整清晰,构图合理,画面干净,无文字、无水印、无字幕。',
  5161. ];
  5162. if (!isset($innerPromptMap[$innerPromptType])) {
  5163. return $prompt;
  5164. }
  5165. return trim((string)$prompt) . "\n" . $innerPromptMap[$innerPromptType];
  5166. }
  5167. /**
  5168. * 根据 inner_prompt_type 获取生成图片数量
  5169. *
  5170. * @param int $innerPromptType 内置提示词类型
  5171. * @param int $imageNum 传入的图片张数
  5172. * @return int 图片数量
  5173. */
  5174. public static function getInnerImageNum($innerPromptType = 0, $imageNum)
  5175. {
  5176. return (int)$innerPromptType === 2 ? 9 : $imageNum;
  5177. }
  5178. /**
  5179. * 提取图片生成结果URL
  5180. *
  5181. * @param mixed $resultUrl 任务结果URL(数组、JSON字符串或普通字符串)
  5182. * @param int $innerPromptType 内置提示词类型
  5183. * @return mixed 类型2返回全部URL数组,其它类型返回首个URL
  5184. */
  5185. public static function extractResultUrls($resultUrl, $innerPromptType = 0)
  5186. {
  5187. $resultUrls = is_array($resultUrl) ? $resultUrl : json_decode((string)$resultUrl, true);
  5188. if (is_array($resultUrls) && !empty($resultUrls)) {
  5189. $resultUrls = array_values($resultUrls);
  5190. return (int)$innerPromptType === 2 ? $resultUrls : $resultUrls[0];
  5191. }
  5192. if (!empty($resultUrl)) {
  5193. return (int)$innerPromptType === 2 ? [$resultUrl] : $resultUrl;
  5194. }
  5195. return (int)$innerPromptType === 2 ? [] : '';
  5196. }
  5197. public function generateImg($data, $onTaskCreated = null, $onPoll = null) {
  5198. $prompt = getProp($data, 'prompt');
  5199. $episode_id = getProp($data, 'episode_id');
  5200. $ref_img_urls = getProp($data, 'ref_img_urls');
  5201. $ratio = getProp($data, 'ratio', '9:16');
  5202. $resolution = getProp($data, 'resolution', '2k');
  5203. $inner_prompt_type = getProp($data, 'inner_prompt_type', 0);
  5204. $imageNum = (int)getProp($data, 'image_num', 1);
  5205. // 定义分辨率和宽高比对应的尺寸映射表
  5206. $sizeMap = [
  5207. '2k' => [
  5208. '1:1' => ['width' => 2048, 'height' => 2048],
  5209. '4:3' => ['width' => 2304, 'height' => 1728],
  5210. '3:4' => ['width' => 1728, 'height' => 2304],
  5211. '16:9' => ['width' => 2848, 'height' => 1600],
  5212. '9:16' => ['width' => 1600, 'height' => 2848],
  5213. '3:2' => ['width' => 2496, 'height' => 1664],
  5214. '2:3' => ['width' => 1664, 'height' => 2496],
  5215. '21:9' => ['width' => 3136, 'height' => 1344],
  5216. ],
  5217. '3k' => [
  5218. '1:1' => ['width' => 3072, 'height' => 3072],
  5219. '4:3' => ['width' => 3456, 'height' => 2592],
  5220. '3:4' => ['width' => 2592, 'height' => 3456],
  5221. '16:9' => ['width' => 4096, 'height' => 2304],
  5222. '9:16' => ['width' => 2304, 'height' => 4096],
  5223. '2:3' => ['width' => 2496, 'height' => 3744],
  5224. '3:2' => ['width' => 3744, 'height' => 2496],
  5225. '21:9' => ['width' => 4704, 'height' => 2016],
  5226. ],
  5227. '4k' => [
  5228. '1:1' => ['width' => 4096, 'height' => 4096],
  5229. '3:4' => ['width' => 3520, 'height' => 4704],
  5230. '4:3' => ['width' => 4704, 'height' => 3520],
  5231. '16:9' => ['width' => 5504, 'height' => 3040],
  5232. '9:16' => ['width' => 3040, 'height' => 5504],
  5233. '2:3' => ['width' => 3328, 'height' => 4992],
  5234. '3:2' => ['width' => 4992, 'height' => 3328],
  5235. '21:9' => ['width' => 6240, 'height' => 2656],
  5236. ],
  5237. ];
  5238. // 参数验证
  5239. $resolution = strtolower($resolution);
  5240. if (!isset($sizeMap[$resolution])) {
  5241. Utils::throwError('20003:分辨率参数错误,仅支持 2k、3k、4k');
  5242. }
  5243. if (!isset($sizeMap[$resolution][$ratio])) {
  5244. Utils::throwError('20003:宽高比参数错误,该分辨率下不支持 ' . $ratio . ' 比例');
  5245. }
  5246. // 根据 ratio 和 resolution 确定宽高
  5247. $width = $sizeMap[$resolution][$ratio]['width'];
  5248. $height = $sizeMap[$resolution][$ratio]['height'];
  5249. if (!is_array($ref_img_urls) && !empty($ref_img_urls)) {
  5250. if (is_json($ref_img_urls)) {
  5251. $ref_img_urls = json_decode($ref_img_urls, true);
  5252. }else {
  5253. $ref_img_urls = explode(',', $ref_img_urls);
  5254. }
  5255. }
  5256. // 处理图片模型
  5257. $model = getProp($data, 'model');
  5258. if (!$model) {
  5259. // 用户没有输入,从episode表获取
  5260. if ($episode_id) {
  5261. $episode = DB::table('mp_anime_episodes')->where('id', $episode_id)->first();
  5262. $model = getProp($episode, 'image_model');
  5263. }
  5264. if (!$model) {
  5265. // episode表也没有,使用默认值
  5266. $model = 'doubao-seedream-5-0-lite-260128';
  5267. }
  5268. }
  5269. // 验证模型是否在可用模型表中
  5270. if (!DB::table('mp_image_models')->where('model', $model)->where('is_enabled', 1)->exists()) {
  5271. // $model = 'doubao-seedream-5-0-lite-260128';
  5272. Utils::throwError('20003:该模型已不可用,请更换!');
  5273. }
  5274. // 保存到episode表
  5275. if ($episode_id) {
  5276. DB::table('mp_anime_episodes')->where('id', $episode_id)->update([
  5277. 'image_model' => $model,
  5278. 'updated_at' => date('Y-m-d H:i:s')
  5279. ]);
  5280. }
  5281. // 参数验证
  5282. if (!$prompt) Utils::throwError('20003:请提供提示词');
  5283. // 根据 inner_prompt_type 附加内置提示词并确定生成图片数量
  5284. $prompt = self::appendInnerPrompt($prompt, $inner_prompt_type);
  5285. $imageNum = self::getInnerImageNum($inner_prompt_type, $imageNum);
  5286. try {
  5287. // 创建图片生成任务
  5288. $params = [
  5289. 'prompt' => $prompt,
  5290. 'model' => $model,
  5291. 'ref_img_urls' => '',
  5292. 'width' => $width,
  5293. 'height' => $height,
  5294. 'image_num' => $imageNum
  5295. ];
  5296. if ($ref_img_urls) $params['ref_img_urls'] = is_array($ref_img_urls) ? $ref_img_urls : [$ref_img_urls];
  5297. $task = $this->aiImageGenerationService->createImageGenerationTask($params);
  5298. $task_id = $task->id;
  5299. if (!$task_id) {
  5300. Utils::throwError('20003:创建图片生成任务失败');
  5301. }
  5302. // 创建任务中心记录并关联图片任务ID
  5303. $taskCenter = $this->taskCenterService->createTask('image', [
  5304. 'title' => '文生图',
  5305. 'ref_task_id' => $task_id,
  5306. // 'prompt' => $prompt,
  5307. // 'params' => json_encode($data, JSON_UNESCAPED_UNICODE),
  5308. ]);
  5309. $taskCenterId = $taskCenter->id;
  5310. // 组装本次任务信息(用于init消息,类似generateVideo)
  5311. $taskInfo = [
  5312. 'task_id' => $task_id,
  5313. 'status' => getProp($task, 'status', 'processing'),
  5314. 'model' => $model,
  5315. 'ratio' => $ratio,
  5316. 'resolution' => $resolution,
  5317. 'image_num' => $imageNum,
  5318. ];
  5319. // 创建图片任务后立即回调(类似generateVideo的init消息,返回任务中心ID和任务信息)
  5320. if (is_callable($onTaskCreated)) {
  5321. $onTaskCreated($taskCenterId, $taskInfo);
  5322. }
  5323. // 检查任务模型类型(火山模型和GPT模型都支持直接检查任务状态)
  5324. $model = getProp($task, 'model');
  5325. $isVolcModel = in_array($model, \App\Consts\BaseConst::VOLC_PIC_MODELS);
  5326. $isGptModel = in_array($model, \App\Consts\BaseConst::GPT_IMAGE2_MODELS);
  5327. $isSyncModel = $isVolcModel || $isGptModel;
  5328. // 即梦AI需要轮询获取结果(5分钟超时,每3秒查询一次)
  5329. $start_time = time();
  5330. $timeout = 300; // 5分钟
  5331. $img_url = '';
  5332. $img_urls = [];
  5333. $lastQueueMessageTime = $start_time; // 记录上次发送队列消息的时间
  5334. $queueMessageInterval = 60; // 队列消息发送间隔(秒)
  5335. while (time() - $start_time < $timeout) {
  5336. sleep(3);
  5337. // 每分钟发送一次队列状态消息(仅流式模式)
  5338. if (is_callable($onPoll)) {
  5339. $currentTime = time();
  5340. if ($currentTime - $lastQueueMessageTime >= $queueMessageInterval) {
  5341. $onPoll($taskCenterId, $task_id, $currentTime - $start_time);
  5342. $lastQueueMessageTime = $currentTime;
  5343. }
  5344. }
  5345. // 火山API和GPT-Image2 API是同步返回结果的,直接检查任务状态
  5346. if ($isSyncModel) {
  5347. // 刷新任务状态
  5348. $task = MpGeneratePicTask::where('id', $task_id)->first();
  5349. if ($task->status === 'success' && $task->result_url) {
  5350. $resultUrls = is_array($task->result_url) ? $task->result_url : json_decode((string)$task->result_url, true);
  5351. $resultUrls = is_array($resultUrls) ? array_values(array_filter($resultUrls)) : [];
  5352. if (!empty($resultUrls)) {
  5353. $img_urls = $resultUrls;
  5354. $img_url = $resultUrls[0];
  5355. } else {
  5356. $img_url = (string)$task->result_url;
  5357. }
  5358. break;
  5359. } elseif ($task->status === 'failed') {
  5360. $errorMsg = mapErrorMessage($task->error_message ?? '');
  5361. Utils::throwError('20003:图片生成失败,' . $errorMsg);
  5362. }
  5363. // // 如果还在处理中,提示用户稍后查看
  5364. // Utils::throwError('20003:图片生成中,请稍后刷新查看结果');
  5365. }else {
  5366. $task = MpGeneratePicTask::where('id', $task_id)->first();
  5367. $statusInfo = $this->aiImageGenerationService->queryTaskStatus($task);
  5368. if ($statusInfo['status'] === 'success') {
  5369. $task->updateStatus('success', [
  5370. 'result_url' => $statusInfo['result_url'],
  5371. 'result_json' => $statusInfo['result_json'] ?? []
  5372. ]);
  5373. $resultUrls = is_array($statusInfo['result_url']) ? $statusInfo['result_url'] : json_decode((string)$statusInfo['result_url'], true);
  5374. $resultUrls = is_array($resultUrls) ? array_values(array_filter($resultUrls)) : [];
  5375. if (!empty($resultUrls)) {
  5376. $img_urls = $resultUrls;
  5377. $img_url = $resultUrls[0];
  5378. } else {
  5379. $img_url = (string)$statusInfo['result_url'];
  5380. }
  5381. break;
  5382. } elseif ($statusInfo['status'] === 'failed') {
  5383. $task->updateStatus('failed', [
  5384. 'error_message' => $statusInfo['error_message'],
  5385. 'result_json' => $statusInfo['result_json'] ?? []
  5386. ]);
  5387. dLog('anime')->error('图片生成失败,', [
  5388. 'error' => $statusInfo['error_message'] ?? '未知错误'
  5389. ]);
  5390. $errorMsg = mapErrorMessage($statusInfo['error_message'] ?? '');
  5391. Utils::throwError('20003:图片生成失败,' . $errorMsg);
  5392. }
  5393. }
  5394. }
  5395. if (empty($img_url)) {
  5396. Utils::throwError('20003:图片生成超时,请稍后重试');
  5397. }
  5398. // 多张图片返回全部URL数组(配合控制器输出image_urls字段)
  5399. if (count($img_urls) > 1) {
  5400. return [
  5401. 'img_url' => $img_url,
  5402. 'image_urls' => $img_urls,
  5403. 'task_id' => $taskCenterId,
  5404. ];
  5405. }
  5406. return [
  5407. 'img_url' => $img_url,
  5408. 'task_id' => $taskCenterId,
  5409. ];
  5410. } catch (\Exception $e) {
  5411. dLog('anime')->error('更新角色或场景失败', [
  5412. 'error' => $e->getMessage()
  5413. ]);
  5414. logDB('anime', 'error', '更新角色或场景失败', ['error' => $e->getMessage()]);
  5415. Utils::throwError('20003:' . $e->getMessage());
  5416. }
  5417. }
  5418. /**
  5419. * 使用文生文模型解析分镜内容
  5420. */
  5421. private function parseSegmentContentWithAI($segment_content) {
  5422. try {
  5423. // 使用DeepSeek服务的公开方法解析分镜内容
  5424. return $this->DeepSeekService->parseSegmentContent($segment_content);
  5425. } catch (\Exception $e) {
  5426. // 如果AI解析失败,记录日志并返回原内容
  5427. dLog('anime')->error('AI解析分镜内容失败: ' . $e->getMessage());
  5428. return $segment_content;
  5429. }
  5430. }
  5431. /**
  5432. * 处理分集的角色和场景数据(继承全局数据或创建新任务)
  5433. *
  5434. * @param int $episode_id 分集ID
  5435. * @param int $anime_id 动漫ID
  5436. * @param array $roles 分集角色数组(引用传递)
  5437. * @param array $scenes 分集场景数组(引用传递)
  5438. * @param array $episode 分集数据
  5439. */
  5440. private function processEpisodeRolesAndScenes($episode_id, $anime_id, &$roles, &$scenes, $episode) {
  5441. // 获取全局动漫的角色和场景数据
  5442. $anime = DB::table('mp_animes')->where('id', $anime_id)->first();
  5443. if (!$anime) return;
  5444. $art_style_type = getProp($anime, 'art_style_type');
  5445. $character_prefix = '';
  5446. $scene_prefix = '';
  5447. if ($art_style_type) {
  5448. $art_style_arr = $this->DeepSeekService->getArtStyleShortPromptByInput($art_style_type);
  5449. $character_prefix = isset($art_style_arr['character_prefix']) ? $art_style_arr['character_prefix'] : '';
  5450. $scene_prefix = isset($art_style_arr['scene_prefix']) ? $art_style_arr['scene_prefix'] : '';
  5451. }
  5452. $global_roles = json_decode(getProp($anime, 'roles'), true) ?: [];
  5453. $global_scenes = json_decode(getProp($anime, 'scenes'), true) ?: [];
  5454. $roles_updated = false;
  5455. $scenes_updated = false;
  5456. // 处理角色
  5457. foreach ($roles as &$role) {
  5458. $role_name = getProp($role, 'role');
  5459. $role_description = getProp($role, 'description');
  5460. $role_pic_prompt = getProp($role, 'pic_prompt');
  5461. $role_url = getProp($role, 'url');
  5462. $role_task_id = getProp($role, 'task_id');
  5463. // 如果已有URL或已有任务ID,跳过
  5464. if (!empty($role_url) || !empty($role_task_id) || $role_name === '旁白') {
  5465. continue;
  5466. }
  5467. $url_inherited = false;
  5468. // 尝试从全局数据中继承
  5469. foreach ($global_roles as $global_role) {
  5470. $global_role_name = getProp($global_role, 'role');
  5471. $global_role_description = getProp($global_role, 'description');
  5472. $global_role_pic_prompt = getProp($global_role, 'pic_prompt');
  5473. $global_role_url = getProp($global_role, 'url');
  5474. $global_role_task_id = getProp($global_role, 'task_id');
  5475. $global_role_task_status = getProp($global_role, 'task_status');
  5476. // 满足条件:角色名相同、描述相同、pic_prompt相同、全局有URL
  5477. if ($role_name === $global_role_name
  5478. && $role_description === $global_role_description
  5479. && $role_pic_prompt === $global_role_pic_prompt
  5480. && !empty($global_role_url)) {
  5481. // 继承 task_id、task_status 和 url
  5482. $role['task_id'] = $global_role_task_id;
  5483. $role['task_status'] = $global_role_task_status;
  5484. $role['url'] = $global_role_url;
  5485. $roles_updated = true;
  5486. $url_inherited = true;
  5487. dLog('anime')->info("分集ID:{$episode_id} 角色:{$role_name} 继承全局数据");
  5488. break;
  5489. }
  5490. }
  5491. // 如果无法继承且没有任务ID,创建新任务
  5492. if (!$url_inherited && empty($role_task_id)) {
  5493. try {
  5494. $art_style = getProp($episode, 'art_style');
  5495. // 优先使用 pic_prompt,如果没有则使用 description
  5496. $description = !empty($role_pic_prompt) ? trim((string)$role_pic_prompt) : $role_description;
  5497. // if ($art_style) {
  5498. // // $description = "美术风格:\n{$art_style}\n主体描述:{$description}\n图片要求:图片侧重点是人物,不要出现场景或背景,并且只能生成一个人物";
  5499. // $description = "主体描述:{$description}\n图片要求:图片侧重点是人物,不要出现场景或背景,并且只能生成一个人物";
  5500. // }
  5501. $description = "{$character_prefix}。\n主体描述:{$description}\n超高清,高细节,主体突出,构图合理,画面干净,无场景或背景,单人物,无文字,无水印,无字幕,电影级光影,视觉焦点明确";
  5502. $params = [
  5503. 'prompt' => $description,
  5504. 'ref_img_urls' => []
  5505. ];
  5506. $task = $this->aiImageGenerationService->createImageGenerationTask($params);
  5507. $task_id = $task->id;
  5508. if ($task_id) {
  5509. $role['task_id'] = $task_id;
  5510. $role['task_status'] = 'processing';
  5511. $roles_updated = true;
  5512. dLog('anime')->info("分集ID:{$episode_id} 角色:{$role_name} 创建图片生成任务,任务ID:{$task_id}");
  5513. }
  5514. } catch (\Exception $e) {
  5515. dLog('anime')->error("分集ID:{$episode_id} 角色:{$role_name} 创建图片生成任务失败: " . $e->getMessage());
  5516. }
  5517. }
  5518. }
  5519. // 处理场景
  5520. foreach ($scenes as &$scene) {
  5521. $scene_name = getProp($scene, 'scene');
  5522. $scene_description = getProp($scene, 'description');
  5523. $scene_pic_prompt = getProp($scene, 'pic_prompt');
  5524. $scene_url = getProp($scene, 'url');
  5525. $scene_task_id = getProp($scene, 'task_id');
  5526. // 如果已有URL或已有任务ID,跳过
  5527. if (!empty($scene_url) || !empty($scene_task_id)) {
  5528. continue;
  5529. }
  5530. $url_inherited = false;
  5531. // 尝试从全局数据中继承
  5532. foreach ($global_scenes as $global_scene) {
  5533. $global_scene_name = getProp($global_scene, 'scene');
  5534. $global_scene_description = getProp($global_scene, 'description');
  5535. $global_scene_pic_prompt = getProp($global_scene, 'pic_prompt');
  5536. $global_scene_url = getProp($global_scene, 'url');
  5537. $global_scene_task_id = getProp($global_scene, 'task_id');
  5538. $global_scene_task_status = getProp($global_scene, 'task_status');
  5539. // 满足条件:场景名相同、描述相同、pic_prompt相同、全局有URL
  5540. if ($scene_name === $global_scene_name
  5541. && $scene_description === $global_scene_description
  5542. && $scene_pic_prompt === $global_scene_pic_prompt
  5543. && !empty($global_scene_url)) {
  5544. // 继承 task_id、task_status 和 url
  5545. $scene['task_id'] = $global_scene_task_id;
  5546. $scene['task_status'] = $global_scene_task_status;
  5547. $scene['url'] = $global_scene_url;
  5548. $scenes_updated = true;
  5549. $url_inherited = true;
  5550. dLog('anime')->info("分集ID:{$episode_id} 场景:{$scene_name} 继承全局数据");
  5551. break;
  5552. }
  5553. }
  5554. // 如果无法继承且没有任务ID,创建新任务
  5555. if (!$url_inherited && empty($scene_task_id)) {
  5556. try {
  5557. $art_style = getProp($episode, 'art_style');
  5558. // 优先使用 pic_prompt,如果没有则使用 description
  5559. $description = !empty($scene_pic_prompt) ? trim((string)$scene_pic_prompt) : $scene_description;
  5560. // if ($art_style) {
  5561. // // $description = "美术风格:\n{$art_style}\n场景描述:{$description}\n图片要求: 图片侧重点是场景,生成的是场景环境图片,不要出现人物(此为第一优先要求)";
  5562. // $description = "场景描述:{$description}\n图片要求: 图片侧重点是场景,生成的是场景环境图片,不要出现人物(此为第一优先要求)";
  5563. // }
  5564. $description = "{$scene_prefix}。\n场景描述:{$description}\n无人物,超高清,高细节,主体突出,构图合理,画面干净,无文字,无水印,无字幕,电影级光影,视觉焦点明确";
  5565. $params = [
  5566. 'prompt' => $description,
  5567. 'ref_img_urls' => []
  5568. ];
  5569. $task = $this->aiImageGenerationService->createImageGenerationTask($params);
  5570. $task_id = $task->id;
  5571. if ($task_id) {
  5572. $scene['task_id'] = $task_id;
  5573. $scene['task_status'] = 'processing';
  5574. $scenes_updated = true;
  5575. dLog('anime')->info("分集ID:{$episode_id} 场景:{$scene_name} 创建图片生成任务,任务ID:{$task_id}");
  5576. }
  5577. } catch (\Exception $e) {
  5578. dLog('anime')->error("分集ID:{$episode_id} 场景:{$scene_name} 创建图片生成任务失败: " . $e->getMessage());
  5579. }
  5580. }
  5581. }
  5582. // 如果有更新,保存到数据库
  5583. if ($roles_updated || $scenes_updated) {
  5584. $update_data = ['updated_at' => date('Y-m-d H:i:s')];
  5585. if ($roles_updated) {
  5586. $update_data['roles'] = json_encode($roles, JSON_UNESCAPED_UNICODE);
  5587. }
  5588. if ($scenes_updated) {
  5589. $update_data['scenes'] = json_encode($scenes, JSON_UNESCAPED_UNICODE);
  5590. }
  5591. DB::table('mp_anime_episodes')->where('id', $episode_id)->update($update_data);
  5592. dLog('anime')->info("分集ID:{$episode_id} 角色和场景数据已更新");
  5593. }
  5594. }
  5595. /**
  5596. * 根据图片URL使用AI反推图片提示词
  5597. *
  5598. * @param string $img_url 图片URL
  5599. * @return string 反推的提示词
  5600. */
  5601. private function generateImagePromptFromUrl($img_url) {
  5602. try {
  5603. // 获取默认模型
  5604. $model = 'doubao-seed-2-0-mini-260215';
  5605. // 构建messages参数
  5606. $messages = [
  5607. [
  5608. 'role' => 'user',
  5609. 'content' => [
  5610. [
  5611. 'type' => 'text',
  5612. 'text' => '请解析这张参考图,并直接输出一段专业中文反推提示词。提示词用于短剧分镜图片生成,必须聚焦角色和场景本身,可包含姿态、镜头视角、构图、画风、色彩氛围、光线、景深或光圈质感等要素。不要输出解释、标题、列表或无关背景,只输出可直接用于文生图的分镜图片提示词'
  5613. ],
  5614. [
  5615. 'type' => 'image_url',
  5616. 'image_url' => [
  5617. 'url' => $img_url
  5618. ]
  5619. ]
  5620. ]
  5621. ]
  5622. ];
  5623. // 构建请求参数
  5624. $params = [
  5625. 'model' => $model,
  5626. 'messages' => $messages,
  5627. 'stream' => false,
  5628. 'thinking' => ['type' => 'disabled'] // 不使用思考模式
  5629. ];
  5630. // 调用DeepSeek服务的volcEngineChatCompletion方法(非流式)
  5631. $result = $this->DeepSeekService->volcEngineChatCompletion($params);
  5632. // 仅记录 token 使用明细(不扣积分)
  5633. $uid = 0;
  5634. try {
  5635. $uid = (int)Site::getUid();
  5636. } catch (\Throwable $e) {
  5637. // 非请求上下文(如命令行)下可能无法获取用户ID,置为0跳过记录
  5638. }
  5639. $this->pointsService->recordTokenOnlyDetail(
  5640. $uid,
  5641. $this->pointsService->getTokensFromUsage($result['usage'] ?? []),
  5642. [
  5643. 'model' => $model,
  5644. 'img_url' => $img_url,
  5645. 'source' => 'generateImagePromptFromUrl',
  5646. ],
  5647. 'chat',
  5648. $model,
  5649. ''
  5650. );
  5651. // 返回生成的内容
  5652. return getProp($result, 'fullContent', '图片描述生成失败');
  5653. } catch (\Exception $e) {
  5654. dLog('anime')->error('AI反推图片提示词失败: ' . $e->getMessage(), [
  5655. 'img_url' => $img_url
  5656. ]);
  5657. logDB('anime', 'error', 'AI反推图片提示词失败', [
  5658. 'error' => $e->getMessage(),
  5659. 'img_url' => $img_url
  5660. ]);
  5661. return '图片描述生成失败: ' . $e->getMessage();
  5662. }
  5663. }
  5664. /**
  5665. * 音频试听接口
  5666. * 创建音频任务并轮询获取结果
  5667. *
  5668. * @param array $data 参数数组
  5669. * @return array 返回音频URL或错误信息
  5670. */
  5671. public function previewAudio($data) {
  5672. $dialogue = getProp($data, 'dialogue');
  5673. // 必填参数验证
  5674. if (!$dialogue) Utils::throwError('20003:dialogue不能为空');
  5675. // 获取参数,优先使用传入的参数,否则使用分镜中的参数
  5676. $voice_type = getProp($data, 'voice_type');
  5677. $voice_name = getProp($data, 'voice_name');
  5678. $voice_actor = getProp($data, 'voice_actor');
  5679. $emotion_type = getProp($data, 'emotion_type');
  5680. $gender = getProp($data, 'gender', 0);
  5681. $emotion = getProp($data, 'emotion');
  5682. $speed_ratio = getProp($data, 'speed_ratio', 0);
  5683. $loudness_ratio = getProp($data, 'loudness_ratio', 0);
  5684. $emotion_scale = getProp($data, 'emotion_scale', 0);
  5685. $pitch = getProp($data, 'pitch', 0);
  5686. try {
  5687. $now = date('Y-m-d H:i:s');
  5688. // 构建生成参数
  5689. $generate_json = json_encode([
  5690. 'text' => $dialogue,
  5691. 'role' => $voice_actor,
  5692. 'voice_type' => $voice_type,
  5693. 'voice_name' => $voice_name,
  5694. 'emotion' => $emotion,
  5695. 'emotion_type' => $emotion_type,
  5696. 'gender' => $gender,
  5697. 'speed_ratio' => $speed_ratio,
  5698. 'loudness_ratio' => $loudness_ratio,
  5699. 'emotion_scale' => $emotion_scale,
  5700. 'pitch' => $pitch,
  5701. ], 256);
  5702. // 请求远程服务器执行生成
  5703. $client = new Client(['timeout' => 600, 'verify' => false]);
  5704. $result = $client->get("http://122.9.129.83:5000/api/anime/audioPreview?generateJson={$generate_json}");
  5705. $response = $result->getBody()->getContents();
  5706. $response_arr = json_decode($response, true);
  5707. if (!isset($response_arr['code']) || (int)$response_arr['code'] !== 0) {
  5708. $error_msg = isset($response_arr['msg']) ? $response_arr['msg'] : '未知错误';
  5709. dLog('anime')->error('音频试听任务创建失败', ['error' => $error_msg, 'response_arr' => $response_arr]);
  5710. Utils::throwError('20003:音频试听任务创建失败: ' . $error_msg);
  5711. }
  5712. $arr = $response_arr['data'];
  5713. $subtitle_info = $arr['subtitle_info'];
  5714. $audio_duration = json_decode($subtitle_info, true)['duration'];
  5715. if (!isset($arr['url']) || !$audio_duration || !$subtitle_info) Utils::throwError('20003:音频参数生成异常');
  5716. return [
  5717. 'audio_url' => $arr['url'],
  5718. 'subtitle_info' => $subtitle_info,
  5719. 'audio_duration' => round($audio_duration, 2)
  5720. ];
  5721. } catch (\Exception $e) {
  5722. dLog('anime')->error('音频试听失败', ['error' => $e->getMessage()]);
  5723. Utils::throwError('20003:' . $e->getMessage());
  5724. }
  5725. }
  5726. /**
  5727. * 获取角色库列表(支持文件夹递归查询)
  5728. * @param array $data 包含 parent_id(父文件夹ID,默认0表示最外层)、role(搜索关键词)、is_public(筛选类型)
  5729. * @return array 返回当前目录下的所有子目录和角色列表(递归)
  5730. */
  5731. public function globalProducts($data) {
  5732. $uid = Site::getUid();
  5733. $cpid = Site::getCpid();
  5734. $role = Site::getRole();
  5735. $id = getProp($data, 'id', 0);
  5736. $parent_id = getProp($data, 'parent_id', 0);
  5737. $product_name = getProp($data, 'product_name');
  5738. $product = getProp($data, 'product'); // 1.角色 2.场景 3.道具
  5739. $is_public = getProp($data, 'public_type', 2); // 0=仅个人库 1=仅公共库 2=个人库+公共库
  5740. if (!$product) {
  5741. Utils::throwError('20003:请选择产品类型');
  5742. }
  5743. // 根据角色和is_public参数确定查询范围
  5744. // admin角色:获取所有个人库+公共库(忽略is_public参数)
  5745. // user角色:根据is_public参数筛选
  5746. $query_user_ids = [];
  5747. if ($role === 'admin') {
  5748. // admin获取所有个人库和公共库
  5749. $query_user_ids = [$uid, 0];
  5750. } else {
  5751. // user角色根据is_public参数筛选
  5752. if ($is_public == 2) {
  5753. // 个人库+公共库
  5754. $query_user_ids = [$uid, 0];
  5755. } elseif ($is_public == 0) {
  5756. // 仅个人库
  5757. $query_user_ids = [$uid];
  5758. } elseif ($is_public == 1) {
  5759. // 仅公共库
  5760. $query_user_ids = [0];
  5761. }
  5762. }
  5763. // 如果有搜索条件(product_name 或 id),按条件搜索文件夹和产品
  5764. if ($id || $product_name) {
  5765. $query = DB::table('mp_products')
  5766. ->where('cpid', $cpid)
  5767. ->whereIn('user_id', $query_user_ids)
  5768. ->where('is_deleted', 0);
  5769. // 如果指定了 id,按 id 精确查询
  5770. if ($id) {
  5771. $query->where('id', $id);
  5772. }
  5773. // 如果指定了 product_name,按名称模糊查询
  5774. if ($product_name) {
  5775. $query->where('product_name', 'like', "%{$product_name}%");
  5776. }
  5777. // 如果指定了 product,添加筛选条件
  5778. if ($product) {
  5779. $query->where('product', $product);
  5780. }
  5781. $result = $query->select('id', 'type', 'parent_id', 'level', 'product_name', 'url', 'pic_prompt', 'three_view_image_url', 'versions', 'product', 'user_id', 'created_at')
  5782. ->orderByRaw('type DESC, CASE WHEN user_id = '.$uid.' THEN 0 ELSE 1 END ASC, sort_order DESC, created_at DESC')
  5783. ->get()
  5784. ->map(function($value) {
  5785. $value = (array)$value;
  5786. $value['created_at'] = transDate($value['created_at'], 'Y-m-d');
  5787. $value['type'] = (int)$value['type'];
  5788. $value['parent_id'] = (int)$value['parent_id'];
  5789. $value['level'] = (int)$value['level'];
  5790. $value['product'] = (int)($value['product'] ?? 1);
  5791. $value['is_public'] = (int)$value['user_id'] === 0 ? 1 : 0;
  5792. $value['versions'] = json_decode($value['versions'], true) ?: [];
  5793. unset($value['user_id']);
  5794. return $value;
  5795. })
  5796. ->toArray();
  5797. return $result;
  5798. }
  5799. // 递归获取所有子目录和角色
  5800. return $this->getChildrenRecursive($cpid, $parent_id, $product, $query_user_ids, $uid);
  5801. }
  5802. /**
  5803. * 递归获取指定目录下的所有子目录和角色
  5804. * @param int $cpid 公司ID
  5805. * @param int $parent_id 父目录ID
  5806. * @param int|null $product 产品类型筛选 1.角色 2.场景 3.道具
  5807. * @param array $query_user_ids 用户ID数组(支持多个)
  5808. * @param int $current_uid 当前用户ID(用于排序)
  5809. * @return array
  5810. */
  5811. private function getChildrenRecursive($cpid, $parent_id, $product = null, $query_user_ids = [], $current_uid = 0) {
  5812. // 查询当前层级的所有项(文件夹和角色)
  5813. $query = DB::table('mp_products')
  5814. ->where('cpid', $cpid)
  5815. ->where('is_deleted', 0)
  5816. ->where('parent_id', $parent_id);
  5817. // 添加用户ID验证(支持多个user_id)
  5818. if (!empty($query_user_ids)) {
  5819. $query->whereIn('user_id', $query_user_ids);
  5820. }
  5821. // 如果指定了 product,添加筛选条件(文件夹和角色都需要筛选)
  5822. if ($product) {
  5823. $query->where('product', $product);
  5824. }
  5825. // 排序规则:
  5826. // 1. 文件夹在前(type DESC)
  5827. // 2. 个人库在前,公共库在后(CASE WHEN user_id = current_uid)
  5828. // 3. 其他排序规则
  5829. $items = $query->select('id', 'type', 'parent_id', 'level', 'product_name', 'url', 'pic_prompt', 'three_view_image_url', 'versions', 'product', 'user_id', 'created_at')
  5830. ->orderByRaw('type DESC, CASE WHEN user_id = '.$current_uid.' THEN 0 ELSE 1 END ASC, sort_order DESC, created_at DESC')
  5831. ->get();
  5832. $result = [];
  5833. foreach ($items as $item) {
  5834. $itemArray = [
  5835. 'id' => $item->id,
  5836. 'type' => (int)$item->type,
  5837. 'parent_id' => (int)$item->parent_id,
  5838. 'level' => (int)$item->level,
  5839. 'product_name' => $item->product_name,
  5840. 'url' => $item->url,
  5841. 'pic_prompt' => $item->pic_prompt ?? '',
  5842. 'three_view_image_url' => $item->three_view_image_url,
  5843. 'product' => (int)($item->product ?? 1),
  5844. 'is_public' => (int)$item->user_id === 0 ? 1 : 0,
  5845. 'created_at' => transDate($item->created_at, 'Y-m-d')
  5846. ];
  5847. $itemArray['versions'] = json_decode($item->versions, true) ?: [];
  5848. // 如果是文件夹,递归获取其子项
  5849. if ($item->type == 2) {
  5850. $children = $this->getChildrenRecursive($cpid, $item->id, $product, $query_user_ids, $current_uid);
  5851. if (!empty($children)) {
  5852. $itemArray['children'] = $children;
  5853. }
  5854. }
  5855. $result[] = $itemArray;
  5856. }
  5857. return $result;
  5858. }
  5859. /**
  5860. * 创建文件夹
  5861. * @param array $data 包含 parent_id(父文件夹ID)、product_name(文件夹名称)、product(产品类型)
  5862. * @return int 返回新建文件夹ID
  5863. */
  5864. public function createFolder($data) {
  5865. $uid = Site::getUid();
  5866. $cpid = Site::getCpid();
  5867. $role = Site::getRole();
  5868. $parent_id = getProp($data, 'parent_id', 0);
  5869. $folder_name = getProp($data, 'product_name', '新建文件夹');
  5870. $is_public = getProp($data, 'is_public', 0); // 0=个人资产库 1=公共资产库
  5871. // 如果是公共库操作,需要admin权限
  5872. if ($is_public && $role !== 'admin') {
  5873. Utils::throwError('20003:只有管理员才能操作公共资产库');
  5874. }
  5875. // 根据is_public参数确定存储的user_id(公共库user_id=0,cpid保持不变)
  5876. $store_uid = $is_public ? 0 : $uid;
  5877. // 获取 product 字段:1.角色 2.场景 3.道具,默认为1
  5878. $product = getProp($data, 'product');
  5879. if (!in_array($product, [1, 2, 3])) {
  5880. // Utils::throwError('20003:product 参数错误,只能是 1(角色)、2(场景) 或 3(道具)');
  5881. }
  5882. // 验证父文件夹
  5883. $parent_level = 0;
  5884. if ($parent_id > 0) {
  5885. $parent = DB::table('mp_products')
  5886. ->where('id', $parent_id)
  5887. ->where('cpid', $cpid)
  5888. ->where('user_id', $store_uid)
  5889. ->where('type', 2)
  5890. ->where('is_deleted', 0)
  5891. ->first();
  5892. if (!$parent) {
  5893. Utils::throwError('20003:父文件夹不存在');
  5894. }
  5895. // 检查父文件夹的 product 类型是否一致
  5896. if ($parent->product != $product) {
  5897. Utils::throwError('20003:文件夹类型必须与父文件夹一致');
  5898. }
  5899. $parent_level = $parent->level;
  5900. // 检查层级限制(最多3层)
  5901. if ($parent_level >= 3) {
  5902. Utils::throwError('20003:文件夹层级不能超过3层');
  5903. }
  5904. }
  5905. // 检查当前目录下是否已存在空白文件夹
  5906. $empty_folder_exists = DB::table('mp_products')
  5907. ->where('parent_id', $parent_id)
  5908. ->where('cpid', $cpid)
  5909. ->where('user_id', $store_uid)
  5910. ->where('type', 2)
  5911. ->where('product', $product)
  5912. ->where('product_name', '新建文件夹')
  5913. ->where('is_deleted', 0)
  5914. ->exists();
  5915. if ($empty_folder_exists && $folder_name == '新建文件夹') {
  5916. Utils::throwError('20003:不允许创建多个空白文件夹,请先重命名现有文件夹');
  5917. }
  5918. // 创建文件夹
  5919. $folder_id = DB::table('mp_products')->insertGetId([
  5920. 'user_id' => $store_uid,
  5921. 'cpid' => $cpid,
  5922. 'type' => 2,
  5923. 'parent_id' => $parent_id,
  5924. 'level' => $parent_level + 1,
  5925. 'product_name' => $folder_name,
  5926. 'product' => $product,
  5927. 'sort_order' => time(), // 使用时间戳作为排序权重
  5928. 'is_deleted' => 0,
  5929. 'created_at' => date('Y-m-d H:i:s'),
  5930. 'updated_at' => date('Y-m-d H:i:s')
  5931. ]);
  5932. return [
  5933. 'id' => $folder_id,
  5934. 'type' => 2,
  5935. 'parent_id' => $parent_id,
  5936. 'level' => $parent_level + 1,
  5937. 'product_name' => $folder_name,
  5938. 'product' => $product,
  5939. ];
  5940. }
  5941. /**
  5942. * 重命名文件夹或角色
  5943. * @param array $data 包含 id、product_name(新名称)
  5944. * @return bool
  5945. */
  5946. public function renameFolder($data) {
  5947. $uid = Site::getUid();
  5948. $cpid = Site::getCpid();
  5949. $role = Site::getRole();
  5950. $id = getProp($data, 'id');
  5951. $new_name = getProp($data, 'product_name');
  5952. $is_public = getProp($data, 'is_public', 0); // 0=个人资产库 1=公共资产库
  5953. if (!$id || !$new_name) {
  5954. Utils::throwError('20003:参数不完整');
  5955. }
  5956. // 根据is_public参数确定查询的user_id(公共库user_id=0,cpid保持不变)
  5957. $query_uid = $is_public ? 0 : $uid;
  5958. // 如果是公共库操作,需要admin权限
  5959. if ($is_public && $role !== 'admin') {
  5960. Utils::throwError('20003:只有管理员才能操作公共资产库');
  5961. }
  5962. // 检查是否存在
  5963. $item = DB::table('mp_products')
  5964. ->where('id', $id)
  5965. ->where('cpid', $cpid)
  5966. ->where('user_id', $query_uid)
  5967. ->where('is_deleted', 0)
  5968. ->first();
  5969. if (!$item) {
  5970. Utils::throwError('20003:项目不存在');
  5971. }
  5972. return DB::table('mp_products')
  5973. ->where('id', $id)
  5974. ->where('cpid', $cpid)
  5975. ->where('user_id', $query_uid)
  5976. ->update([
  5977. 'product_name' => $new_name,
  5978. 'updated_at' => date('Y-m-d H:i:s')
  5979. ]);
  5980. }
  5981. /**
  5982. * 移动角色或文件夹到指定文件夹
  5983. * @param array $data 包含 id(要移动的项目ID)、target_parent_id(目标父文件夹ID)
  5984. * @return bool
  5985. */
  5986. public function moveProductOrFolder($data) {
  5987. $uid = Site::getUid();
  5988. $cpid = Site::getCpid();
  5989. $role = Site::getRole();
  5990. $id = getProp($data, 'id');
  5991. $target_parent_id = getProp($data, 'target_parent_id', 0);
  5992. $is_public = getProp($data, 'is_public', 0); // 0=个人资产库 1=公共资产库
  5993. if (!$id) {
  5994. Utils::throwError('20003:请选择要移动的项目');
  5995. }
  5996. // 根据is_public参数确定查询的user_id(公共库user_id=0,cpid保持不变)
  5997. $query_uid = $is_public ? 0 : $uid;
  5998. // 如果是公共库操作,需要admin权限
  5999. if ($is_public && $role !== 'admin') {
  6000. Utils::throwError('20003:只有管理员才能操作公共资产库');
  6001. }
  6002. // 检查要移动的项目
  6003. $item = DB::table('mp_products')
  6004. ->where('id', $id)
  6005. ->where('cpid', $cpid)
  6006. ->where('user_id', $query_uid)
  6007. ->where('is_deleted', 0)
  6008. ->first();
  6009. if (!$item) {
  6010. Utils::throwError('20003:项目不存在');
  6011. }
  6012. // 验证目标文件夹
  6013. $target_level = 0;
  6014. $target_product = $item->product; // 默认使用当前项目的 product
  6015. if ($target_parent_id > 0) {
  6016. $target_parent = DB::table('mp_products')
  6017. ->where('id', $target_parent_id)
  6018. ->where('cpid', $cpid)
  6019. ->where('user_id', $query_uid)
  6020. ->where('type', 2)
  6021. ->where('is_deleted', 0)
  6022. ->first();
  6023. if (!$target_parent) {
  6024. Utils::throwError('20003:目标文件夹不存在');
  6025. }
  6026. // 检查 product 类型是否一致
  6027. if ($target_parent->product != $item->product) {
  6028. Utils::throwError('20003:不能移动到不同类型的文件夹下');
  6029. }
  6030. $target_level = $target_parent->level;
  6031. $target_product = $target_parent->product;
  6032. // 如果移动的是文件夹,需要检查层级
  6033. if ($item->type == 2) {
  6034. // 计算移动后的最大层级
  6035. $max_child_level = $this->getMaxChildLevel($id);
  6036. $depth = $max_child_level - $item->level;
  6037. if ($target_level + 1 + $depth > 3) {
  6038. Utils::throwError('20003:移动后文件夹层级将超过3层限制');
  6039. }
  6040. // 不能移动到自己或自己的子文件夹下
  6041. if ($this->isDescendant($target_parent_id, $id)) {
  6042. Utils::throwError('20003:不能移动到自己或子文件夹下');
  6043. }
  6044. }
  6045. }
  6046. // 更新父文件夹和层级
  6047. $new_level = $target_level + 1;
  6048. DB::table('mp_products')
  6049. ->where('id', $id)
  6050. ->update([
  6051. 'parent_id' => $target_parent_id,
  6052. 'level' => $new_level,
  6053. 'updated_at' => date('Y-m-d H:i:s')
  6054. ]);
  6055. // 如果是文件夹,需要递归更新所有子项的层级
  6056. if ($item->type == 2) {
  6057. $this->updateChildrenLevel($id, $new_level);
  6058. }
  6059. return true;
  6060. }
  6061. /**
  6062. * 获取文件夹下最大子层级
  6063. * @param int $folder_id
  6064. * @return int
  6065. */
  6066. private function getMaxChildLevel($folder_id) {
  6067. $max_level = DB::table('mp_products')
  6068. ->where('parent_id', $folder_id)
  6069. ->where('is_deleted', 0)
  6070. ->max('level');
  6071. if (!$max_level) {
  6072. return DB::table('mp_products')->where('id', $folder_id)->value('level');
  6073. }
  6074. // 递归查找子文件夹
  6075. $children = DB::table('mp_products')
  6076. ->where('parent_id', $folder_id)
  6077. ->where('type', 2)
  6078. ->where('is_deleted', 0)
  6079. ->pluck('id');
  6080. foreach ($children as $child_id) {
  6081. $child_max = $this->getMaxChildLevel($child_id);
  6082. if ($child_max > $max_level) {
  6083. $max_level = $child_max;
  6084. }
  6085. }
  6086. return $max_level;
  6087. }
  6088. /**
  6089. * 检查 target_id 是否是 folder_id 的后代
  6090. * @param int $target_id
  6091. * @param int $folder_id
  6092. * @return bool
  6093. */
  6094. private function isDescendant($target_id, $folder_id) {
  6095. if ($target_id == $folder_id) {
  6096. return true;
  6097. }
  6098. $parent = DB::table('mp_products')
  6099. ->where('id', $target_id)
  6100. ->where('is_deleted', 0)
  6101. ->first();
  6102. if (!$parent || $parent->parent_id == 0) {
  6103. return false;
  6104. }
  6105. return $this->isDescendant($parent->parent_id, $folder_id);
  6106. }
  6107. /**
  6108. * 递归更新子项层级
  6109. * @param int $parent_id
  6110. * @param int $parent_level
  6111. */
  6112. private function updateChildrenLevel($parent_id, $parent_level) {
  6113. $children = DB::table('mp_products')
  6114. ->where('parent_id', $parent_id)
  6115. ->where('is_deleted', 0)
  6116. ->get();
  6117. foreach ($children as $child) {
  6118. $new_level = $parent_level + 1;
  6119. DB::table('mp_products')
  6120. ->where('id', $child->id)
  6121. ->update([
  6122. 'level' => $new_level,
  6123. 'updated_at' => date('Y-m-d H:i:s')
  6124. ]);
  6125. // 如果是文件夹,继续递归
  6126. if ($child->type == 2) {
  6127. $this->updateChildrenLevel($child->id, $new_level);
  6128. }
  6129. }
  6130. }
  6131. /**
  6132. * 获取文件夹路径(面包屑导航)
  6133. * @param array $data 包含 folder_id
  6134. * @return array 返回路径数组
  6135. */
  6136. public function getFolderPath($data) {
  6137. $uid = Site::getUid();
  6138. $cpid = Site::getCpid();
  6139. $folder_id = getProp($data, 'id', 0);
  6140. $is_public = getProp($data, 'is_public', 0); // 0=个人资产库 1=公共资产库
  6141. if ($folder_id == 0) {
  6142. return [
  6143. ['id' => 0, 'name' => '根目录']
  6144. ];
  6145. }
  6146. // 根据is_public参数确定查询的user_id(公共库user_id=0,cpid保持不变)
  6147. $query_uid = $is_public ? 0 : $uid;
  6148. $path = [];
  6149. $current_id = $folder_id;
  6150. while ($current_id > 0) {
  6151. $folder = DB::table('mp_products')
  6152. ->where('id', $current_id)
  6153. ->where('cpid', $cpid)
  6154. ->where('user_id', $query_uid)
  6155. ->where('type', 2)
  6156. ->where('is_deleted', 0)
  6157. ->first();
  6158. if (!$folder) {
  6159. break;
  6160. }
  6161. array_unshift($path, [
  6162. 'id' => $folder->id,
  6163. 'name' => $folder->product_name
  6164. ]);
  6165. $current_id = $folder->parent_id;
  6166. }
  6167. // 添加根目录
  6168. array_unshift($path, ['id' => 0, 'name' => '根目录']);
  6169. return $path;
  6170. }
  6171. public function createProduct($data) {
  6172. $uid = Site::getUid();
  6173. $cpid = Site::getCpid();
  6174. $role = Site::getRole();
  6175. $is_public = getProp($data, 'is_public', 0); // 0=个人资产库 1=公共资产库
  6176. // 如果是公共库操作,需要admin权限
  6177. if ($is_public && $role !== 'admin') {
  6178. Utils::throwError('20003:只有管理员才能操作公共资产库');
  6179. }
  6180. // 根据is_public参数确定存储的user_id(公共库user_id=0,cpid保持不变)
  6181. $store_uid = $is_public ? 0 : $uid;
  6182. // 新增参数:剧本ID和剧集序号(支持数组传参,多个序号也可用英文逗号隔开)
  6183. $script_id = (int)getProp($data, 'script_id', 0);
  6184. $episode_numbers = $this->normalizeEpisodeNumbers(getProp($data, 'episode_number', []));
  6185. if ($script_id && empty($episode_numbers)) {
  6186. Utils::throwError('20003:剧集序号不能为空');
  6187. }
  6188. if (!$script_id && !empty($episode_numbers)) {
  6189. Utils::throwError('20003:请提供剧本ID');
  6190. }
  6191. $product_name = trim(getProp($data, 'product_name'));
  6192. if (!$product_name) Utils::throwError('20003:名称不能为空');
  6193. $product_name = preg_replace('/^[\s*\[\]【】[]{}{}\x{3000}]+|[\s*\[\]【】[]{}{}\x{3000}]+$/u', '', $product_name);
  6194. // $exists_id = DB::table('mp_products')->where('cpid', $cpid)->where('type', 1)->where('product_name', $product_name)->where('is_deleted', 0)->value('id');
  6195. // if ($exists_id) Utils::throwError('20003:名称不能重复,请修改');
  6196. $url = trim(getProp($data, 'url'));
  6197. if (!$url) Utils::throwError('20003:图片地址不能为空');
  6198. $versions = getProp($data, 'versions');
  6199. // 检查是否是正确的图片格式
  6200. $allowedExtensions = ['jpg', 'jpeg', 'png', 'gif', 'webp', 'bmp'];
  6201. $urlPath = parse_url($url, PHP_URL_PATH);
  6202. $extension = strtolower(pathinfo($urlPath, PATHINFO_EXTENSION));
  6203. if (!in_array($extension, $allowedExtensions)) {
  6204. Utils::throwError('20003:图片格式不正确,仅支持 jpg、jpeg、png、gif、webp、bmp 格式');
  6205. }
  6206. $pic_prompt = trim(getProp($data, 'pic_prompt'));
  6207. if (!$pic_prompt) Utils::throwError('20003:提示词不能为空');
  6208. // 获取 product 字段:1.角色 2.场景 3.道具,默认为1
  6209. $product = getProp($data, 'product');
  6210. if (!in_array($product, [1, 2, 3])) {
  6211. // Utils::throwError('20003:产品类型只能是 1(角色)、2(场景) 或 3(道具)');
  6212. }
  6213. // 获取父文件夹ID和层级
  6214. $parent_id = getProp($data, 'parent_id', 0);
  6215. $parent_level = 0;
  6216. if ($parent_id > 0) {
  6217. $parent = DB::table('mp_products')
  6218. ->where('id', $parent_id)
  6219. ->where('cpid', $cpid)
  6220. ->where('user_id', $store_uid)
  6221. ->where('type', 2)
  6222. ->where('is_deleted', 0)
  6223. ->first();
  6224. if (!$parent) {
  6225. Utils::throwError('20003:父文件夹不存在');
  6226. }
  6227. $parent_level = $parent->level;
  6228. }
  6229. // 创建资产并保存剧本资产关联关系(同一事务)
  6230. DB::beginTransaction();
  6231. try {
  6232. $id = DB::table('mp_products')->insertGetId([
  6233. 'user_id' => $store_uid,
  6234. 'cpid' => $cpid,
  6235. 'type' => 1, // 1=角色图片
  6236. 'parent_id' => $parent_id,
  6237. 'level' => $parent_level + 1,
  6238. 'product_name' => $product_name,
  6239. 'url' => $url,
  6240. 'pic_prompt' => $pic_prompt,
  6241. 'product' => $product,
  6242. 'versions' => json_encode($versions, 256),
  6243. 'sort_order' => time(), // 使用时间戳作为排序权重
  6244. 'created_at' => date('Y-m-d H:i:s'),
  6245. 'updated_at' => date('Y-m-d H:i:s')
  6246. ]);
  6247. if (!$id) Utils::throwError('20003:创建失败');
  6248. // 保存剧本资产关联关系
  6249. if ($script_id) {
  6250. $this->saveProductScriptMapping($id, $script_id, $episode_numbers);
  6251. }
  6252. DB::commit();
  6253. } catch (\Exception $e) {
  6254. DB::rollback();
  6255. throw $e;
  6256. }
  6257. return [
  6258. 'id' => $id,
  6259. 'type' => 1,
  6260. 'parent_id' => $parent_id,
  6261. 'level' => $parent_level + 1,
  6262. 'product_name' => $product_name,
  6263. 'url' => $url,
  6264. 'pic_prompt' => $pic_prompt,
  6265. 'product' => $product,
  6266. 'versions' => $versions
  6267. ];
  6268. }
  6269. public function editProduct($data) {
  6270. $uid = Site::getUid();
  6271. $cpid = Site::getCpid();
  6272. $role = Site::getRole();
  6273. $id = getProp($data, 'id');
  6274. if (!$id) Utils::throwError('20003:ID不能为空');
  6275. $versions = getProp($data, 'versions');
  6276. $is_public = getProp($data, 'is_public', 0); // 0=个人资产库 1=公共资产库
  6277. // 新增参数:剧本ID和剧集序号(支持数组传参,多个序号也可用英文逗号隔开)
  6278. $script_id = (int)getProp($data, 'script_id', 0);
  6279. $episode_numbers = $this->normalizeEpisodeNumbers(getProp($data, 'episode_number', []));
  6280. if ($script_id && empty($episode_numbers)) {
  6281. Utils::throwError('20003:剧集序号不能为空');
  6282. }
  6283. if (!$script_id && !empty($episode_numbers)) {
  6284. Utils::throwError('20003:请提供剧本ID');
  6285. }
  6286. // 根据is_public参数确定查询的user_id(公共库user_id=0,cpid保持不变)
  6287. $query_uid = $is_public ? 0 : $uid;
  6288. // 如果是公共库操作,需要admin权限
  6289. if ($is_public && $role !== 'admin') {
  6290. Utils::throwError('20003:只有管理员才能操作公共资产库');
  6291. }
  6292. // 检查是否存在且属于当前用户或公共库
  6293. $role = DB::table('mp_products')
  6294. ->where('id', $id)
  6295. ->where('cpid', $cpid)
  6296. ->where('user_id', $query_uid)
  6297. ->where('type', 1)->first();
  6298. if (!$role) Utils::throwError('20003:记录不存在');
  6299. $updateData = [];
  6300. // $needVersionRecord = false; // 是否需要记录版本
  6301. // 名称
  6302. $product_name = trim(getProp($data, 'product_name'));
  6303. if ($product_name) {
  6304. $product_name = preg_replace('/^[\s*\[\]【】[]{}{}\x{3000}]+|[\s*\[\]【】[]{}{}\x{3000}]+$/u', '', $product_name);
  6305. $updateData['product_name'] = $product_name;
  6306. }
  6307. // $exists_id = DB::table('mp_products')->where('cpid', $cpid)->where('type', 1)->where('product_name', $product_name)->where('is_deleted', 0)->value('id');
  6308. // if ($exists_id && $exists_id != $id) Utils::throwError('20003:名称不能重复,请修改');
  6309. // 图片地址
  6310. $url = trim(getProp($data, 'url'));
  6311. if ($url) {
  6312. // 检查是否是正确的图片格式
  6313. $allowedExtensions = ['jpg', 'jpeg', 'png', 'gif', 'webp', 'bmp'];
  6314. $urlPath = parse_url($url, PHP_URL_PATH);
  6315. $extension = strtolower(pathinfo($urlPath, PATHINFO_EXTENSION));
  6316. if (!in_array($extension, $allowedExtensions)) {
  6317. Utils::throwError('20003:图片格式不正确,仅支持 jpg、jpeg、png、gif、webp、bmp 格式');
  6318. }
  6319. // // 如果 url 有变更,记录版本
  6320. // if ($url !== $role->url) {
  6321. // $needVersionRecord = true;
  6322. // }
  6323. $updateData['url'] = $url;
  6324. }
  6325. // 提示词
  6326. $pic_prompt = trim(getProp($data, 'pic_prompt'));
  6327. if ($pic_prompt) {
  6328. // // 如果 pic_prompt 有变更,记录版本
  6329. // if ($pic_prompt !== $role->pic_prompt) {
  6330. // $needVersionRecord = true;
  6331. // }
  6332. $updateData['pic_prompt'] = $pic_prompt;
  6333. }
  6334. if (empty($updateData) && !$script_id) {
  6335. Utils::throwError('20003:没有需要更新的数据');
  6336. }
  6337. // // 如果需要记录版本,将数据添加到 versions 数组
  6338. // if ($needVersionRecord) {
  6339. // // 获取现有的 versions 数据
  6340. // $versions = json_decode($role->versions, true) ?: [];
  6341. // $isFirstVersion = empty($versions); // 判断是否是第一次记录版本
  6342. // // 如果是第一次记录版本,先添加旧版本(变更前)
  6343. // if ($isFirstVersion) {
  6344. // $oldVersion = [
  6345. // 'url' => $role->url,
  6346. // 'description' => $role->pic_prompt,
  6347. // ];
  6348. // // 旧版本添加到数组末尾
  6349. // $versions[] = $oldVersion;
  6350. // }
  6351. // // 构建新版本(变更后)
  6352. // $newVersion = [
  6353. // 'url' => isset($updateData['url']) ? $updateData['url'] : $role->url,
  6354. // 'description' => isset($updateData['pic_prompt']) ? $updateData['pic_prompt'] : $role->pic_prompt,
  6355. // ];
  6356. // // 检查新版本是否已存在于历史版本中
  6357. // $existingIndex = -1;
  6358. // foreach ($versions as $index => $version) {
  6359. // if ($version['url'] === $newVersion['url'] && $version['description'] === $newVersion['description']) {
  6360. // $existingIndex = $index;
  6361. // break;
  6362. // }
  6363. // }
  6364. // if ($existingIndex !== -1) {
  6365. // // 如果已存在,移除旧的位置
  6366. // array_splice($versions, $existingIndex, 1);
  6367. // }
  6368. // // 新版本添加到数组开头(最新的在前)
  6369. // array_unshift($versions, $newVersion);
  6370. // // // 限制版本数量(可选,例如只保留最近10个版本)
  6371. // // if (count($versions) > 10) {
  6372. // // $versions = array_slice($versions, 0, 10);
  6373. // // }
  6374. // $updateData['versions'] = json_encode($versions, 256);
  6375. // }
  6376. if ($versions) {
  6377. $updateData['versions'] = json_encode($versions, 256);
  6378. }
  6379. if (!empty($updateData)) {
  6380. $updateData['updated_at'] = date('Y-m-d H:i:s');
  6381. }
  6382. // 更新资产并保存剧本资产关联关系(同一事务)
  6383. DB::beginTransaction();
  6384. try {
  6385. $updated = true;
  6386. if (!empty($updateData)) {
  6387. $updated = DB::table('mp_products')
  6388. ->where('cpid', $cpid)
  6389. ->where('id', $id)
  6390. ->update($updateData);
  6391. }
  6392. // 保存剧本资产关联关系
  6393. if ($script_id) {
  6394. $this->saveProductScriptMapping($id, $script_id, $episode_numbers);
  6395. }
  6396. DB::commit();
  6397. } catch (\Exception $e) {
  6398. DB::rollback();
  6399. throw $e;
  6400. }
  6401. return $updated;
  6402. }
  6403. /**
  6404. * 保存单一资产与剧本剧集的关联关系
  6405. *
  6406. * @param int $product_id 资产ID
  6407. * @param int $script_id 剧本ID
  6408. * @param array $episode_numbers 剧集序号数组(序号从1开始)
  6409. * @return int 新增关联数量
  6410. */
  6411. private function saveProductScriptMapping($product_id, $script_id, $episode_numbers) {
  6412. $uid = Site::getUid();
  6413. // 验证剧本是否存在
  6414. $script = DB::table('mp_scripts')
  6415. ->where('id', $script_id)
  6416. ->where('is_deleted', 0)
  6417. ->first();
  6418. if (!$script) {
  6419. Utils::throwError('20003:剧本不存在');
  6420. }
  6421. // 验证剧本归属:只能关联自己的剧本
  6422. if ((int)$script->user_id !== (int)$uid) {
  6423. Utils::throwError('20003:只能添加到自己的剧本');
  6424. }
  6425. // 使用 splitContent 拆分剧本内容获取总集数
  6426. $totalEpisodes = $this->getScriptTotalEpisodeCount($script);
  6427. // 解析剧集序号(数组)
  6428. $episodes = [];
  6429. foreach ($episode_numbers as $item) {
  6430. if (is_array($item)) {
  6431. continue;
  6432. }
  6433. $item = trim((string)$item);
  6434. if ($item === '' || !is_numeric($item)) {
  6435. Utils::throwError('20003:剧集序号格式不正确,仅支持数字数组或英文逗号分隔的数字');
  6436. }
  6437. $episodes[] = (int)$item;
  6438. }
  6439. // 去重并校验序号范围(序号从1开始)
  6440. $episodes = array_values(array_unique($episodes));
  6441. if (empty($episodes)) {
  6442. Utils::throwError('20003:剧集序号不能为空');
  6443. }
  6444. foreach ($episodes as $episode) {
  6445. if ($episode < 1 || $episode > $totalEpisodes) {
  6446. Utils::throwError('20003:剧集序号 ' . $episode . ' 超出范围,剧本共 ' . $totalEpisodes . ' 集(序号从1开始)');
  6447. }
  6448. }
  6449. $now = now();
  6450. // 过滤已存在的关联,避免重复
  6451. $existingEpisodes = DB::table('mp_script_product_mappings')
  6452. ->where('script_id', $script_id)
  6453. ->where('product_id', $product_id)
  6454. ->whereIn('episode_number', $episodes)
  6455. ->pluck('episode_number')
  6456. ->all();
  6457. $mappingRecords = [];
  6458. foreach ($episodes as $episode) {
  6459. if (in_array($episode, $existingEpisodes)) {
  6460. continue;
  6461. }
  6462. $mappingRecords[] = [
  6463. 'script_id' => $script_id,
  6464. 'product_id' => $product_id,
  6465. 'episode_number' => $episode,
  6466. 'created_at' => $now,
  6467. 'updated_at' => $now,
  6468. ];
  6469. }
  6470. $insertedCount = 0;
  6471. if (!empty($mappingRecords)) {
  6472. $insertedCount = DB::table('mp_script_product_mappings')->insert($mappingRecords) ? count($mappingRecords) : 0;
  6473. }
  6474. return $insertedCount;
  6475. }
  6476. /**
  6477. * 规范化剧集序号参数,统一为数组
  6478. * 兼容传入数组(如 [1, 3, 5])、逗号分隔字符串(如 "1,3,5")以及字符串数组(如 ["1,3", 5])
  6479. *
  6480. * @param mixed $episode_number 剧集序号参数
  6481. * @return array
  6482. */
  6483. private function normalizeEpisodeNumbers($episode_number) {
  6484. if (!is_array($episode_number)) {
  6485. $episode_number = explode(',', (string)$episode_number);
  6486. }
  6487. $items = [];
  6488. foreach ($episode_number as $item) {
  6489. if (is_array($item)) {
  6490. continue;
  6491. }
  6492. foreach (explode(',', (string)$item) as $part) {
  6493. $part = trim($part);
  6494. if ($part !== '') {
  6495. $items[] = $part;
  6496. }
  6497. }
  6498. }
  6499. return $items;
  6500. }
  6501. /**
  6502. * 获取剧本总集数(通过 splitContent 拆分剧本内容)
  6503. *
  6504. * @param object $script 剧本记录
  6505. * @return int 总集数
  6506. */
  6507. private function getScriptTotalEpisodeCount($script) {
  6508. if (empty($script->content)) {
  6509. Utils::throwError('20003:剧本内容为空,无法确定剧集数量');
  6510. }
  6511. $totalEpisodes = count(splitContent($script->content));
  6512. if ($totalEpisodes < 1) {
  6513. Utils::throwError('20003:剧本内容无法拆分出剧集');
  6514. }
  6515. return $totalEpisodes;
  6516. }
  6517. /**
  6518. * 获取剧本总集数
  6519. *
  6520. * @param array $data 包含 script_id(剧本ID)
  6521. * @return array
  6522. */
  6523. public function getScriptTotalEpisodes($data) {
  6524. $script_id = (int)getProp($data, 'script_id', 0);
  6525. if (!$script_id) {
  6526. Utils::throwError('20003:请提供剧本ID');
  6527. }
  6528. // 验证剧本是否存在
  6529. $script = DB::table('mp_scripts')
  6530. ->where('id', $script_id)
  6531. ->where('is_deleted', 0)
  6532. ->first();
  6533. if (!$script) {
  6534. Utils::throwError('20003:剧本不存在');
  6535. }
  6536. return [
  6537. 'script_id' => $script_id,
  6538. 'script_name' => $script->script_name ?? 'script_' . $script_id,
  6539. 'episode_num' => $this->getScriptTotalEpisodeCount($script),
  6540. ];
  6541. }
  6542. /**
  6543. * 获取角色版本历史
  6544. * @param array $data 包含 id(角色ID)
  6545. * @return array 返回版本历史列表
  6546. */
  6547. public function getProductVersions($data) {
  6548. $cpid = Site::getCpid();
  6549. $id = getProp($data, 'id');
  6550. if (!$id) Utils::throwError('20003:角色ID不能为空');
  6551. $role = DB::table('mp_products')
  6552. ->where('id', $id)
  6553. ->where('cpid', $cpid)
  6554. ->where('type', 1)
  6555. ->first();
  6556. if (!$role) Utils::throwError('20003:角色不存在');
  6557. // 获取版本历史
  6558. $versions = json_decode($role->versions, true) ?: [];
  6559. // 添加当前版本作为最新版本
  6560. $currentVersion = [
  6561. 'version' => 0, // 0 表示当前版本
  6562. 'url' => $role->url,
  6563. 'pic_prompt' => $role->pic_prompt,
  6564. 'updated_at' => $role->updated_at,
  6565. 'is_current' => true
  6566. ];
  6567. array_unshift($versions, $currentVersion);
  6568. return $versions;
  6569. }
  6570. /**
  6571. * 恢复到指定版本
  6572. * @param array $data 包含 id(角色ID)、version(版本号)
  6573. * @return bool
  6574. */
  6575. public function restoreProductVersion($data) {
  6576. $uid = Site::getUid();
  6577. $cpid = Site::getCpid();
  6578. $id = getProp($data, 'id');
  6579. $version = getProp($data, 'version');
  6580. if (!$id) Utils::throwError('20003:角色ID不能为空');
  6581. if (!$version) Utils::throwError('20003:版本号不能为空');
  6582. $role = DB::table('mp_products')
  6583. ->where('id', $id)
  6584. ->where('cpid', $cpid)
  6585. ->where('type', 1)
  6586. ->first();
  6587. if (!$role) Utils::throwError('20003:角色不存在');
  6588. // 获取版本历史
  6589. $versions = json_decode($role->versions, true) ?: [];
  6590. // 查找指定版本
  6591. $targetVersion = null;
  6592. foreach ($versions as $v) {
  6593. if ($v['version'] == $version) {
  6594. $targetVersion = $v;
  6595. break;
  6596. }
  6597. }
  6598. if (!$targetVersion) Utils::throwError('20003:版本不存在');
  6599. // 先将当前版本保存到历史
  6600. $newVersion = [
  6601. 'version' => count($versions) + 1,
  6602. 'url' => $role->url,
  6603. 'pic_prompt' => $role->pic_prompt,
  6604. 'updated_at' => date('Y-m-d H:i:s'),
  6605. 'updated_by' => $uid
  6606. ];
  6607. array_unshift($versions, $newVersion);
  6608. // 限制版本数量
  6609. if (count($versions) > 10) {
  6610. $versions = array_slice($versions, 0, 10);
  6611. }
  6612. // 恢复到指定版本
  6613. return DB::table('mp_products')
  6614. ->where('id', $id)
  6615. ->where('cpid', $cpid)
  6616. ->update([
  6617. 'url' => $targetVersion['url'],
  6618. 'pic_prompt' => $targetVersion['pic_prompt'],
  6619. 'versions' => json_encode($versions, JSON_UNESCAPED_UNICODE),
  6620. 'updated_at' => date('Y-m-d H:i:s')
  6621. ]);
  6622. }
  6623. public function deleteProduct($data) {
  6624. $uid = Site::getUid();
  6625. $cpid = Site::getCpid();
  6626. $role = Site::getRole();
  6627. $id = getProp($data, 'id');
  6628. if (!$id) Utils::throwError('20003:ID不能为空');
  6629. $ids = explode(',', $id);
  6630. $is_public = getProp($data, 'is_public', 0); // 0=个人资产库 1=公共资产库
  6631. // 根据is_public参数确定查询的user_id(公共库user_id=0,cpid保持不变)
  6632. $query_uid = $is_public ? 0 : $uid;
  6633. // 如果是公共库操作,需要admin权限
  6634. if ($is_public && $role !== 'admin') {
  6635. Utils::throwError('20003:只有管理员才能操作公共资产库');
  6636. }
  6637. // 检查是否存在且属于当前用户或公共库
  6638. $role = DB::table('mp_products')
  6639. ->whereIn('id', $ids)
  6640. ->where('cpid', $cpid)
  6641. ->where('user_id', $query_uid)
  6642. ->get();
  6643. if (!$role) Utils::throwError('20003:记录不存在');
  6644. return DB::table('mp_products')
  6645. ->where('cpid', $cpid)
  6646. ->where('user_id', $query_uid)
  6647. ->whereIn('id', $ids)
  6648. ->update([
  6649. 'is_deleted' => 1,
  6650. 'updated_at' => date('Y-m-d H:i:s')
  6651. ]);
  6652. }
  6653. public function generateThreeView($data) {
  6654. $uid = Site::getUid();
  6655. $cpid = Site::getCpid();
  6656. $role = Site::getRole();
  6657. $id = getProp($data, 'id');
  6658. if (!$id) Utils::throwError('20003:ID不能为空');
  6659. $is_public = getProp($data, 'is_public', 0); // 0=个人资产库 1=公共资产库
  6660. // 根据is_public参数确定查询的user_id(公共库user_id=0,cpid保持不变)
  6661. $query_uid = $is_public ? 0 : $uid;
  6662. // 如果是公共库操作,需要admin权限
  6663. if ($is_public && $role !== 'admin') {
  6664. Utils::throwError('20003:只有管理员才能操作公共资产库');
  6665. }
  6666. // 检查是否存在且属于当前用户或公共库
  6667. $product = DB::table('mp_products')
  6668. ->where('id', $id)
  6669. ->where('cpid', $cpid)
  6670. ->where('user_id', $query_uid)
  6671. ->where('type', 1)->first();
  6672. if (!$product) Utils::throwError('20003:资产不存在');
  6673. $prompt = trim(getProp($data, 'prompt', '基于参考图生成主体的标准正面、侧面、后面三视图,主体完整。在最左侧添加主体正视图的特写,主体清晰完整。背景修改成纯白色,整体保持与参考图一致的美术风格和色彩搭配。画面无说明文字'));
  6674. $ref_img_url = trim(getProp($data, 'ref_img_url'));
  6675. if (!$ref_img_url) {
  6676. // 如果没有传入参考图,使用角色表中的图片
  6677. $ref_img_url = $product->url ?? '';
  6678. if (!$ref_img_url) {
  6679. Utils::throwError('20003:参考图不能为空');
  6680. }
  6681. }
  6682. $pic_prompt = getProp($product, 'pic_prompt');
  6683. if ($pic_prompt) {
  6684. $prompt .= '\n参考图原始提示词: '.$pic_prompt;
  6685. }
  6686. // 检查参考图是否是正确的图片格式
  6687. $allowedExtensions = ['jpg', 'jpeg', 'png', 'gif', 'webp', 'bmp'];
  6688. $urlPath = parse_url($ref_img_url, PHP_URL_PATH);
  6689. $extension = strtolower(pathinfo($urlPath, PATHINFO_EXTENSION));
  6690. if (!in_array($extension, $allowedExtensions)) {
  6691. Utils::throwError('20003:参考图格式不正确,仅支持 jpg、jpeg、png、gif、webp、bmp 格式');
  6692. }
  6693. // 处理图片模型
  6694. $model = getProp($data, 'model');
  6695. if (!$model) {
  6696. // 使用默认模型
  6697. $model = 'doubao-seedream-5-0-lite-260128';
  6698. }
  6699. // 验证模型是否在可用模型表中
  6700. if (!DB::table('mp_image_models')->where('model', $model)->where('is_enabled', 1)->exists()) {
  6701. Utils::throwError('20003:该模型已不可用,请更换!');
  6702. }
  6703. $ratio = getProp($data, 'ratio', '16:9');
  6704. $resolution = getProp($data, 'resolution', '2k');
  6705. // 定义分辨率和宽高比对应的尺寸映射表
  6706. $sizeMap = [
  6707. '2k' => [
  6708. '1:1' => ['width' => 2048, 'height' => 2048],
  6709. '4:3' => ['width' => 2304, 'height' => 1728],
  6710. '3:4' => ['width' => 1728, 'height' => 2304],
  6711. '16:9' => ['width' => 2848, 'height' => 1600],
  6712. '9:16' => ['width' => 1600, 'height' => 2848],
  6713. '3:2' => ['width' => 2496, 'height' => 1664],
  6714. '2:3' => ['width' => 1664, 'height' => 2496],
  6715. '21:9' => ['width' => 3136, 'height' => 1344],
  6716. ],
  6717. '3k' => [
  6718. '1:1' => ['width' => 3072, 'height' => 3072],
  6719. '4:3' => ['width' => 3456, 'height' => 2592],
  6720. '3:4' => ['width' => 2592, 'height' => 3456],
  6721. '16:9' => ['width' => 4096, 'height' => 2304],
  6722. '9:16' => ['width' => 2304, 'height' => 4096],
  6723. '2:3' => ['width' => 2496, 'height' => 3744],
  6724. '3:2' => ['width' => 3744, 'height' => 2496],
  6725. '21:9' => ['width' => 4704, 'height' => 2016],
  6726. ],
  6727. '4k' => [
  6728. '1:1' => ['width' => 4096, 'height' => 4096],
  6729. '3:4' => ['width' => 3520, 'height' => 4704],
  6730. '4:3' => ['width' => 4704, 'height' => 3520],
  6731. '16:9' => ['width' => 5504, 'height' => 3040],
  6732. '9:16' => ['width' => 3040, 'height' => 5504],
  6733. '2:3' => ['width' => 3328, 'height' => 4992],
  6734. '3:2' => ['width' => 4992, 'height' => 3328],
  6735. '21:9' => ['width' => 6240, 'height' => 2656],
  6736. ],
  6737. ];
  6738. // 参数验证
  6739. $resolution = strtolower($resolution);
  6740. if (!isset($sizeMap[$resolution])) {
  6741. Utils::throwError('20003:分辨率参数错误,仅支持 2k、3k、4k');
  6742. }
  6743. if (!isset($sizeMap[$resolution][$ratio])) {
  6744. Utils::throwError('20003:宽高比参数错误,该分辨率下不支持 ' . $ratio . ' 比例');
  6745. }
  6746. // 根据 ratio 和 resolution 确定宽高
  6747. $width = $sizeMap[$resolution][$ratio]['width'];
  6748. $height = $sizeMap[$resolution][$ratio]['height'];
  6749. try {
  6750. // 创建图片生成任务
  6751. $params = [
  6752. 'prompt' => $prompt,
  6753. 'model' => $model,
  6754. 'ref_img_urls' => [$ref_img_url],
  6755. 'width' => $width,
  6756. 'height' => $height
  6757. ];
  6758. $task = $this->aiImageGenerationService->createImageGenerationTask($params);
  6759. $task_id = $task->id;
  6760. if (!$task_id) {
  6761. Utils::throwError('20003:创建图片生成任务失败');
  6762. }
  6763. // 轮询获取结果
  6764. // 只查询数据库,不调用API,不更新任务表
  6765. $start_time = time();
  6766. $timeout = 1800;
  6767. $img_url = '';
  6768. while (time() - $start_time < $timeout) {
  6769. sleep(5);
  6770. // 只查询数据库中的任务状态,不调用API,不更新任务表
  6771. $task = DB::table('mp_generate_pic_tasks')
  6772. ->where('id', $task_id)
  6773. ->first();
  6774. if (!$task) {
  6775. Utils::throwError('20003:任务不存在');
  6776. }
  6777. if ($task->status === 'success' && $task->result_url) {
  6778. $result_urls = is_string($task->result_url)
  6779. ? json_decode($task->result_url, true)
  6780. : $task->result_url;
  6781. $img_url = is_array($result_urls) ? $result_urls[0] : $task->result_url;
  6782. break;
  6783. } elseif ($task->status === 'failed') {
  6784. Utils::throwError('20003:三视图生成失败,' . ($task->error_message ?? '未知错误'));
  6785. }
  6786. // 其他状态继续轮询
  6787. }
  6788. if (empty($img_url)) {
  6789. Utils::throwError('20003:三视图生成超时,请稍后重试');
  6790. }
  6791. // 更新 mp_products 表(不是任务表)
  6792. DB::table('mp_products')
  6793. ->where('id', $id)
  6794. ->where('cpid', $cpid)
  6795. ->update([
  6796. 'three_view_image_url' => $img_url,
  6797. 'updated_at' => date('Y-m-d H:i:s')
  6798. ]);
  6799. return ['three_view_image_url' => $img_url];
  6800. } catch (\Exception $e) {
  6801. dLog('anime')->error('生成三视图失败', [
  6802. 'error' => $e->getMessage()
  6803. ]);
  6804. logDB('anime', 'error', '生成三视图失败', ['error' => $e->getMessage()]);
  6805. Utils::throwError('20003:' . $e->getMessage());
  6806. }
  6807. }
  6808. /**
  6809. * 推送(复制)资产或文件夹到目标位置
  6810. * @param array $data 包含 product_id(要推送的资产或文件夹ID)、target_parent_id(目标父文件夹ID,0表示根目录)
  6811. * @return array 返回推送结果
  6812. */
  6813. public function pushProductOrFolder($data) {
  6814. $uid = Site::getUid();
  6815. $cpid = Site::getCpid();
  6816. $role = Site::getRole();
  6817. $product_id = getProp($data, 'product_id');
  6818. $target_parent_id = getProp($data, 'target_parent_id', 0);
  6819. $target_product = getProp($data, 'product'); // 目标 product 类型,用于跨类型推送
  6820. if (!$product_id) {
  6821. Utils::throwError('20003:请选择要推送的项目');
  6822. }
  6823. // 查询源项目(只通过cpid查询,不限制user_id)
  6824. $sourceItem = DB::table('mp_products')
  6825. ->where('id', $product_id)
  6826. ->where('cpid', $cpid)
  6827. ->where('is_deleted', 0)
  6828. ->first();
  6829. if (!$sourceItem) {
  6830. Utils::throwError('20003:要推送的项目不存在');
  6831. }
  6832. // 通过user_id判断源是公共库还是个人库
  6833. $source_uid = $sourceItem->user_id;
  6834. $source_is_public = ($source_uid == 0) ? 1 : 0;
  6835. // 验证目标文件夹并确定目标是公共库还是个人库
  6836. $target_level = 0;
  6837. $target_uid = $uid; // 默认推送到个人库
  6838. $target_is_public = 0;
  6839. $final_product_type = $sourceItem->product; // 默认使用源的 product 类型
  6840. if ($target_parent_id > 0) {
  6841. // 查询目标文件夹(只通过cpid查询,不限制user_id)
  6842. $targetParent = DB::table('mp_products')
  6843. ->where('id', $target_parent_id)
  6844. ->where('cpid', $cpid)
  6845. ->where('type', 2)
  6846. ->where('is_deleted', 0)
  6847. ->first();
  6848. if (!$targetParent) {
  6849. Utils::throwError('20003:目标文件夹不存在');
  6850. }
  6851. // 通过user_id判断目标是公共库还是个人库
  6852. $target_level = $targetParent->level;
  6853. $target_uid = $targetParent->user_id;
  6854. $target_is_public = ($target_uid == 0) ? 1 : 0;
  6855. // 使用目标文件夹的 product 类型
  6856. $final_product_type = $targetParent->product;
  6857. }
  6858. // 如果 target_parent_id = 0(推送到根目录),需要通过参数判断推送到个人库还是公共库
  6859. else {
  6860. $push_to_public = getProp($data, 'push_to_public');
  6861. if ($push_to_public === '') {
  6862. Utils::throwError('20003:请选择是否推送到公共库');
  6863. }
  6864. if ($push_to_public) {
  6865. $target_uid = 0;
  6866. $target_is_public = 1;
  6867. }
  6868. // 推送到根目录时,必须指定 product 类型
  6869. if ($target_product === null || $target_product === '') {
  6870. Utils::throwError('20003:推送到根目录时必须指定目标类型(product)');
  6871. }
  6872. $final_product_type = $target_product;
  6873. }
  6874. // 如果目标是公共库,需要admin权限
  6875. if ($target_is_public && $role !== 'admin') {
  6876. Utils::throwError('20003:只有管理员才能推送到公共资产库');
  6877. }
  6878. // 权限验证:验证是否符合允许的推送规则
  6879. $this->validatePushPermission($source_uid, $target_uid, $uid);
  6880. try {
  6881. DB::beginTransaction();
  6882. // 如果是资产,直接复制(支持跨类型推送,更新 product 字段)
  6883. if ($sourceItem->type == 1) {
  6884. $newId = $this->copyProduct($sourceItem, $target_parent_id, $target_level + 1, $cpid, $target_uid, $final_product_type);
  6885. DB::commit();
  6886. return [
  6887. 'product_id' => $newId,
  6888. ];
  6889. }
  6890. // 如果是文件夹,递归复制(支持跨类型推送)
  6891. $newFolderId = $this->copyFolderRecursive($sourceItem, $target_parent_id, $target_level + 1, $cpid, $target_uid, $source_uid, $final_product_type);
  6892. DB::commit();
  6893. return [
  6894. 'product_id' => $newFolderId,
  6895. ];
  6896. } catch (\Exception $e) {
  6897. DB::rollBack();
  6898. dLog('anime')->error('推送失败', [
  6899. 'error' => $e->getMessage(),
  6900. 'product_id' => $product_id
  6901. ]);
  6902. Utils::throwError('20003:' . $e->getMessage());
  6903. }
  6904. }
  6905. /**
  6906. * 验证推送权限
  6907. * 允许的推送规则:
  6908. * 1. 自己推送给自己的个人库(个人库 → 个人库,同一用户)
  6909. * 2. 公共库推送给自己的个人库(公共库 → 个人库)
  6910. * 3. 公共库推送给公共库(公共库 → 公共库)
  6911. *
  6912. * @param int $source_uid 源的user_id
  6913. * @param int $target_uid 目标的user_id
  6914. * @param int $current_uid 当前用户ID
  6915. * @throws \Exception
  6916. */
  6917. private function validatePushPermission($source_uid, $target_uid, $current_uid) {
  6918. // 规则1:自己推送给自己的个人库(个人库 → 个人库,同一用户)
  6919. if ($source_uid == $current_uid && $target_uid == $current_uid) {
  6920. return; // 允许
  6921. }
  6922. // 规则2:公共库推送给自己的个人库(公共库 → 个人库)
  6923. if ($source_uid == 0 && $target_uid == $current_uid) {
  6924. return; // 允许
  6925. }
  6926. // 规则3:公共库推送给公共库(公共库 → 公共库)
  6927. if ($source_uid == 0 && $target_uid == 0) {
  6928. return; // 允许
  6929. }
  6930. // 其他情况都不允许
  6931. if ($source_uid != 0 && $source_uid != $current_uid) {
  6932. // 源是别人的个人库
  6933. Utils::throwError('20003:无权限访问该资产');
  6934. } elseif ($source_uid == $current_uid && $target_uid == 0) {
  6935. // 个人库推送给公共库(不允许)
  6936. Utils::throwError('20003:不允许将个人资产推送到公共库');
  6937. } elseif ($source_uid != 0 && $target_uid != 0 && $source_uid != $target_uid) {
  6938. // 不同用户的个人库之间推送(不允许)
  6939. Utils::throwError('20003:不允许推送到其他用户的个人库');
  6940. } else {
  6941. // 其他未知情况
  6942. Utils::throwError('20003:不允许的推送操作');
  6943. }
  6944. }
  6945. /**
  6946. * 复制单个资产
  6947. * @param object $sourceProduct 源资产对象
  6948. * @param int $targetParentId 目标父文件夹ID
  6949. * @param int $targetLevel 目标层级
  6950. * @param int $cpid 公司ID
  6951. * @param int $targetUid 目标用户ID
  6952. * @return int 返回新资产ID
  6953. */
  6954. private function copyProduct($sourceProduct, $targetParentId, $targetLevel, $cpid, $targetUid, $productType = null) {
  6955. // 如果指定了 productType,使用指定的;否则使用源的 product 类型
  6956. $finalProductType = ($productType !== null) ? $productType : $sourceProduct->product;
  6957. $newProductData = [
  6958. 'user_id' => $targetUid,
  6959. 'cpid' => $cpid,
  6960. 'type' => 1,
  6961. 'parent_id' => $targetParentId,
  6962. 'level' => $targetLevel,
  6963. 'product_name' => $sourceProduct->product_name,
  6964. 'url' => $sourceProduct->url,
  6965. 'pic_prompt' => $sourceProduct->pic_prompt ?? '',
  6966. 'three_view_image_url' => $sourceProduct->three_view_image_url ?? '',
  6967. 'product' => $finalProductType,
  6968. 'versions' => $sourceProduct->versions ?? '',
  6969. 'sort_order' => time(),
  6970. 'is_deleted' => 0,
  6971. 'created_at' => date('Y-m-d H:i:s'),
  6972. 'updated_at' => date('Y-m-d H:i:s')
  6973. ];
  6974. return DB::table('mp_products')->insertGetId($newProductData);
  6975. }
  6976. /**
  6977. * 递归复制文件夹及其子项
  6978. * @param object $sourceFolder 源文件夹对象
  6979. * @param int $targetParentId 目标父文件夹ID
  6980. * @param int $targetLevel 目标层级
  6981. * @param int $cpid 公司ID
  6982. * @param int $targetUid 目标用户ID
  6983. * @param int $sourceUid 源用户ID
  6984. * @return int 返回新文件夹ID
  6985. */
  6986. private function copyFolderRecursive($sourceFolder, $targetParentId, $targetLevel, $cpid, $targetUid, $sourceUid, $productType = null) {
  6987. // 如果指定了 productType,使用指定的;否则使用源的 product 类型
  6988. $finalProductType = ($productType !== null) ? $productType : $sourceFolder->product;
  6989. // 创建新文件夹
  6990. $newFolderData = [
  6991. 'user_id' => $targetUid,
  6992. 'cpid' => $cpid,
  6993. 'type' => 2,
  6994. 'parent_id' => $targetParentId,
  6995. 'level' => $targetLevel,
  6996. 'product_name' => $sourceFolder->product_name,
  6997. 'product' => $finalProductType,
  6998. 'sort_order' => time(),
  6999. 'is_deleted' => 0,
  7000. 'created_at' => date('Y-m-d H:i:s'),
  7001. 'updated_at' => date('Y-m-d H:i:s')
  7002. ];
  7003. $newFolderId = DB::table('mp_products')->insertGetId($newFolderData);
  7004. // 获取源文件夹下的所有子项
  7005. $children = DB::table('mp_products')
  7006. ->where('parent_id', $sourceFolder->id)
  7007. ->where('cpid', $cpid)
  7008. ->where('user_id', $sourceUid)
  7009. ->where('is_deleted', 0)
  7010. ->orderByRaw('type DESC, sort_order DESC, created_at DESC')
  7011. ->get();
  7012. // 递归复制子项(子项继承目标文件夹的 product 类型)
  7013. foreach ($children as $child) {
  7014. if ($child->type == 1) {
  7015. // 资产
  7016. $this->copyProduct($child, $newFolderId, $targetLevel + 1, $cpid, $targetUid, $finalProductType);
  7017. } else {
  7018. // 文件夹
  7019. $this->copyFolderRecursive($child, $newFolderId, $targetLevel + 1, $cpid, $targetUid, $sourceUid, $finalProductType);
  7020. }
  7021. }
  7022. return $newFolderId;
  7023. }
  7024. /**
  7025. * 保存剧本资产关联关系
  7026. * @param array $data 请求参数
  7027. * @return bool
  7028. */
  7029. public function saveScriptProducts($data) {
  7030. $uid = Site::getUid();
  7031. $cpid = Site::getCpid();
  7032. $script_id = getProp($data, 'script_id');
  7033. $products = getProp($data, 'products', []);
  7034. $auto_generate_images = getProp($data, 'auto_generate_images', true); // 是否自动生成图片,默认true
  7035. if (!$script_id) {
  7036. Utils::throwError('20003:请提供剧本ID');
  7037. }
  7038. // 验证剧本是否存在
  7039. $script = DB::table('mp_scripts')
  7040. ->where('id', $script_id)
  7041. ->where('is_deleted', 0)
  7042. ->first();
  7043. if (!$script) {
  7044. Utils::throwError('20003:剧本不存在');
  7045. }
  7046. // 处理图片模型
  7047. $model = getProp($data, 'model');
  7048. if (!$model) {
  7049. // 使用默认模型
  7050. $model = 'doubao-seedream-5-0-lite-260128';
  7051. }
  7052. // 验证模型是否在可用模型表中
  7053. if (!DB::table('mp_image_models')->where('model', $model)->where('is_enabled', 1)->exists()) {
  7054. Utils::throwError('20003:该模型已不可用,请更换!');
  7055. }
  7056. $ratio = getProp($data, 'ratio', '9:16');
  7057. $resolution = getProp($data, 'resolution', '2k');
  7058. // 定义分辨率和宽高比对应的尺寸映射表
  7059. $sizeMap = [
  7060. '2k' => [
  7061. '1:1' => ['width' => 2048, 'height' => 2048],
  7062. '4:3' => ['width' => 2304, 'height' => 1728],
  7063. '3:4' => ['width' => 1728, 'height' => 2304],
  7064. '16:9' => ['width' => 2848, 'height' => 1600],
  7065. '9:16' => ['width' => 1600, 'height' => 2848],
  7066. '3:2' => ['width' => 2496, 'height' => 1664],
  7067. '2:3' => ['width' => 1664, 'height' => 2496],
  7068. '21:9' => ['width' => 3136, 'height' => 1344],
  7069. ],
  7070. '3k' => [
  7071. '1:1' => ['width' => 3072, 'height' => 3072],
  7072. '4:3' => ['width' => 3456, 'height' => 2592],
  7073. '3:4' => ['width' => 2592, 'height' => 3456],
  7074. '16:9' => ['width' => 4096, 'height' => 2304],
  7075. '9:16' => ['width' => 2304, 'height' => 4096],
  7076. '2:3' => ['width' => 2496, 'height' => 3744],
  7077. '3:2' => ['width' => 3744, 'height' => 2496],
  7078. '21:9' => ['width' => 4704, 'height' => 2016],
  7079. ],
  7080. '4k' => [
  7081. '1:1' => ['width' => 4096, 'height' => 4096],
  7082. '3:4' => ['width' => 3520, 'height' => 4704],
  7083. '4:3' => ['width' => 4704, 'height' => 3520],
  7084. '16:9' => ['width' => 5504, 'height' => 3040],
  7085. '9:16' => ['width' => 3040, 'height' => 5504],
  7086. '2:3' => ['width' => 3328, 'height' => 4992],
  7087. '3:2' => ['width' => 4992, 'height' => 3328],
  7088. '21:9' => ['width' => 6240, 'height' => 2656],
  7089. ],
  7090. ];
  7091. // 参数验证
  7092. $resolution = strtolower($resolution);
  7093. if (!isset($sizeMap[$resolution])) {
  7094. Utils::throwError('20003:分辨率参数错误,仅支持 2k、3k、4k');
  7095. }
  7096. if (!isset($sizeMap[$resolution][$ratio])) {
  7097. Utils::throwError('20003:宽高比参数错误,该分辨率下不支持 ' . $ratio . ' 比例');
  7098. }
  7099. // 根据 ratio 和 resolution 确定宽高
  7100. $width = $sizeMap[$resolution][$ratio]['width'];
  7101. $height = $sizeMap[$resolution][$ratio]['height'];
  7102. $script_name = $script->script_name ?? 'script_' . $script_id;
  7103. // 检查是否已经有该剧本的资产数据
  7104. $existingMappings = DB::table('mp_script_product_mappings')
  7105. ->where('script_id', $script_id)
  7106. ->get();
  7107. if ($existingMappings->isNotEmpty()) {
  7108. // 已存在资产映射,检查是否所有资产都有图片生成任务
  7109. $productIds = $existingMappings->pluck('product_id')->unique()->toArray();
  7110. // 查询这些资产的图片生成任务状态
  7111. $productsWithTasks = DB::table('mp_products')
  7112. ->whereIn('id', $productIds)
  7113. ->where('is_deleted', 0)
  7114. ->get();
  7115. $productTaskMap = [];
  7116. $typeFolderIds = [];
  7117. $hasAllTasks = true;
  7118. foreach ($productsWithTasks as $product) {
  7119. // 收集类型文件夹ID
  7120. if ($product->parent_id > 0 && !in_array($product->parent_id, $typeFolderIds)) {
  7121. $parentFolder = DB::table('mp_products')
  7122. ->where('id', $product->parent_id)
  7123. ->where('type', 2)
  7124. ->first();
  7125. if ($parentFolder) {
  7126. $typeFolderIds[$parentFolder->product] = $parentFolder->id;
  7127. }
  7128. }
  7129. // 检查是否有图片生成任务
  7130. if (!empty($product->pic_task_id)) {
  7131. $productTaskMap[$product->id] = $product->pic_task_id;
  7132. } else if($product->url && $product->pic_task_status == '生成成功') {
  7133. continue;
  7134. } else {
  7135. // 有资产没有图片任务
  7136. $hasAllTasks = false;
  7137. }
  7138. }
  7139. // 如果所有资产都有任务ID,直接轮询返回结果
  7140. if ($hasAllTasks && !empty($productTaskMap)) {
  7141. dLog('anime')->info('剧本资产已存在且都有图片任务,直接轮询结果', [
  7142. 'script_id' => $script_id,
  7143. 'script_name' => $script_name,
  7144. 'product_count' => count($productTaskMap)
  7145. ]);
  7146. // 直接返回 SSE 流轮询结果
  7147. return $this->pollProductImageTasks($script_id, $script_name, $productTaskMap, $typeFolderIds);
  7148. }
  7149. // 如果部分资产没有任务ID,只为这些资产创建任务
  7150. if (!$hasAllTasks && $auto_generate_images) {
  7151. dLog('anime')->info('剧本资产已存在,但部分资产没有图片任务,为缺失的资产创建任务', [
  7152. 'script_id' => $script_id,
  7153. 'script_name' => $script_name
  7154. ]);
  7155. // 开启事务
  7156. DB::beginTransaction();
  7157. try {
  7158. foreach ($productsWithTasks as $product) {
  7159. // 跳过已有任务的资产
  7160. if (!empty($product->pic_task_id)) {
  7161. continue;
  7162. }
  7163. // 跳过没有提示词的资产
  7164. if (empty($product->pic_prompt)) {
  7165. dLog('anime')->warning('资产没有提示词,跳过图片生成', [
  7166. 'product_id' => $product->id,
  7167. 'product_name' => $product->product_name
  7168. ]);
  7169. continue;
  7170. }
  7171. try {
  7172. // 创建图片生成任务
  7173. $params = [
  7174. 'prompt' => $product->pic_prompt,
  7175. 'model' => $model,
  7176. 'ref_img_urls' => [],
  7177. 'width' => $width,
  7178. 'height' => $height
  7179. ];
  7180. $task = $this->aiImageGenerationService->createImageGenerationTask($params);
  7181. $task_id = $task->id;
  7182. if ($task_id) {
  7183. $productTaskMap[$product->id] = $task_id;
  7184. // 在事务中更新资产表的任务ID和状态
  7185. DB::table('mp_products')
  7186. ->where('id', $product->id)
  7187. ->update([
  7188. 'pic_task_id' => $task_id,
  7189. 'pic_task_status' => '生成中',
  7190. 'updated_at' => now()
  7191. ]);
  7192. dLog('anime')->info('为已存在资产创建图片生成任务', [
  7193. 'product_id' => $product->id,
  7194. 'task_id' => $task_id
  7195. ]);
  7196. }
  7197. } catch (\Exception $e) {
  7198. dLog('anime')->error('创建资产图片生成任务失败', [
  7199. 'product_id' => $product->id,
  7200. 'error' => $e->getMessage()
  7201. ]);
  7202. // 标记为失败(仍在事务中)
  7203. DB::table('mp_products')
  7204. ->where('id', $product->id)
  7205. ->update([
  7206. 'pic_task_status' => '生成失败',
  7207. 'updated_at' => now()
  7208. ]);
  7209. }
  7210. }
  7211. // 提交事务
  7212. DB::commit();
  7213. // 如果有新创建的任务,返回 SSE 流
  7214. if (!empty($productTaskMap)) {
  7215. return $this->pollProductImageTasks($script_id, $script_name, $productTaskMap, $typeFolderIds);
  7216. }
  7217. } catch (\Exception $e) {
  7218. // 回滚事务
  7219. DB::rollback();
  7220. dLog('anime')->error('为已存在资产创建图片任务失败', [
  7221. 'script_id' => $script_id,
  7222. 'error' => $e->getMessage()
  7223. ]);
  7224. Utils::throwError('20003:创建图片任务失败:' . $e->getMessage());
  7225. }
  7226. }
  7227. // 如果不需要生成图片,返回已存在的信息
  7228. return [
  7229. 'success' => true,
  7230. 'message' => '剧本资产已存在',
  7231. 'script_id' => $script_id,
  7232. 'script_name' => $script_name,
  7233. 'type_folder_ids' => $typeFolderIds,
  7234. 'existing_products' => count($productIds),
  7235. 'tasks_count' => count($productTaskMap)
  7236. ];
  7237. }
  7238. // 解析 products(可能是 JSON 字符串或数组)
  7239. if (is_string($products)) {
  7240. $products = json_decode($products, true);
  7241. if (json_last_error() !== JSON_ERROR_NONE) {
  7242. Utils::throwError('20003:产品数据格式错误');
  7243. }
  7244. }
  7245. if (!is_array($products) || empty($products)) {
  7246. Utils::throwError('20003:产品数据不能为空');
  7247. }
  7248. // 以下是原有的创建逻辑...
  7249. // 开启事务
  7250. DB::beginTransaction();
  7251. try {
  7252. $now = now();
  7253. $mappingRecords = [];
  7254. $createdProductIds = []; // 记录所有创建的资产ID
  7255. // 获取剧本名称
  7256. $script_name = $script->script_name ?? 'script_' . $script_id;
  7257. // 存储每个类型的根文件夹ID
  7258. $typeFolderIds = [];
  7259. // 遍历每个产品类型(type: 1=角色, 2=场景, 3=道具)
  7260. foreach ($products as $productGroup) {
  7261. $type = getProp($productGroup, 'type');
  7262. $title = getProp($productGroup, 'title', '');
  7263. $content = getProp($productGroup, 'content', []);
  7264. if (!in_array($type, [1, 2, 3]) || empty($content) || count($content) < 2) {
  7265. continue;
  7266. }
  7267. // 为当前类型创建根文件夹(如果还未创建)
  7268. if (!isset($typeFolderIds[$type])) {
  7269. $typeFolderIds[$type] = DB::table('mp_products')->insertGetId([
  7270. 'user_id' => $uid,
  7271. 'cpid' => $cpid,
  7272. 'type' => 2, // 1.资产 2文件夹
  7273. 'product' => $type, // 1.主体 2.场景 3.道具
  7274. 'parent_id' => 0, // 根文件夹,parent_id=0
  7275. 'level' => 1, // 第一层级
  7276. 'product_name' => $script_name,
  7277. 'sort_order' => time() + $type,
  7278. 'is_deleted' => 0,
  7279. 'created_at' => $now,
  7280. 'updated_at' => $now
  7281. ]);
  7282. }
  7283. $folder_id = $typeFolderIds[$type];
  7284. // 获取表头(第一行)并查找关键列的位置
  7285. $headers = $content[0];
  7286. $nameColumnIndex = -1; // 资产名称列索引
  7287. $sequenceColumnIndex = -1; // 使用范围列索引
  7288. $promptColumnIndex = -1; // 参考提示词列索引
  7289. foreach ($headers as $index => $header) {
  7290. // 查找"资产名称"列
  7291. if (strpos($header, '资产名称') !== false || strpos($header, '名称') !== false) {
  7292. $nameColumnIndex = $index;
  7293. }
  7294. // 查找"使用范围"列
  7295. if (strpos($header, '使用范围') !== false || strpos($header, '范围') !== false) {
  7296. $sequenceColumnIndex = $index;
  7297. }
  7298. // 查找"参考提示词"列(可能是"干净参考图提示词"、"参考提示词"等)
  7299. if (strpos($header, '参考') !== false && strpos($header, '提示词') !== false) {
  7300. $promptColumnIndex = $index;
  7301. }
  7302. }
  7303. // 验证必要的列是否都找到了
  7304. if ($nameColumnIndex === -1) {
  7305. dLog('anime')->warning('未找到资产名称列', ['type' => $type, 'headers' => $headers]);
  7306. continue;
  7307. }
  7308. if ($sequenceColumnIndex === -1) {
  7309. dLog('anime')->warning('未找到使用范围列', ['type' => $type, 'headers' => $headers]);
  7310. continue;
  7311. }
  7312. // 跳过表头,解析每一行数据
  7313. for ($i = 1; $i < count($content); $i++) {
  7314. $row = $content[$i];
  7315. // 确保行数据有效
  7316. if (empty($row) || count($row) <= max($nameColumnIndex, $sequenceColumnIndex)) {
  7317. continue;
  7318. }
  7319. // 根据动态查找的列索引提取数据
  7320. $product_name = isset($row[$nameColumnIndex]) ? trim((string)$row[$nameColumnIndex]) : '';
  7321. $sequence_str = isset($row[$sequenceColumnIndex]) ? trim($row[$sequenceColumnIndex]) : '';
  7322. $pic_prompt = '';
  7323. // 提取参考提示词(如果找到了该列)
  7324. if ($promptColumnIndex >= 0 && isset($row[$promptColumnIndex])) {
  7325. $pic_prompt = trim($row[$promptColumnIndex]);
  7326. }
  7327. // 解析使用范围(逗号分隔的序号)
  7328. $sequences = [];
  7329. if (!empty($sequence_str)) {
  7330. $sequenceParts = array_map('trim', explode(',', $sequence_str));
  7331. foreach ($sequenceParts as $part) {
  7332. if (is_numeric($part)) {
  7333. $sequences[] = (int)$part;
  7334. }
  7335. }
  7336. }
  7337. if (empty($product_name)) {
  7338. continue;
  7339. }
  7340. // 处理product_name两边的符号
  7341. $product_name = preg_replace('/^[\s*\[\]【】[]{}{}\x{3000}]+|[\s*\[\]【】[]{}{}\x{3000}]+$/u', '', $product_name);
  7342. // 如果名称不存在或仅剩占位符号,则跳过
  7343. if (!$product_name || preg_match('/^[-—_]+$/u', $product_name)) {
  7344. dLog('anime')->warning('资产名称无效,跳过保存', [
  7345. 'script_id' => $script_id,
  7346. 'type' => $type,
  7347. 'product_name' => $product_name
  7348. ]);
  7349. continue;
  7350. }
  7351. // 直接插入新资产到 mp_products 表(parent_id 指向对应类型的根文件夹)
  7352. $product_id = DB::table('mp_products')->insertGetId([
  7353. 'product_name' => $product_name,
  7354. 'type' => 1, // 1=资产 2.文件夹
  7355. 'product' => $type, // 1=角色, 2=场景, 3=道具
  7356. 'parent_id' => $folder_id, // 父文件夹是该类型的根文件夹
  7357. 'level' => 2, // 第二层级
  7358. 'pic_prompt' => $pic_prompt,
  7359. 'user_id' => $uid,
  7360. 'cpid' => $cpid,
  7361. 'sort_order' => time(),
  7362. 'is_deleted' => 0,
  7363. 'created_at' => $now,
  7364. 'updated_at' => $now,
  7365. ]);
  7366. // 记录创建的资产ID
  7367. $createdProductIds[] = $product_id;
  7368. // 为每个序号创建映射记录
  7369. if (!empty($sequences)) {
  7370. foreach ($sequences as $sequence) {
  7371. $mappingRecords[] = [
  7372. 'script_id' => $script_id,
  7373. 'product_id' => $product_id,
  7374. 'episode_number' => $sequence,
  7375. 'created_at' => $now,
  7376. 'updated_at' => $now,
  7377. ];
  7378. }
  7379. } else {
  7380. // 如果没有指定序号,创建一个默认映射(序号为0)
  7381. $mappingRecords[] = [
  7382. 'script_id' => $script_id,
  7383. 'product_id' => $product_id,
  7384. 'episode_number' => 0,
  7385. 'created_at' => $now,
  7386. 'updated_at' => $now,
  7387. ];
  7388. }
  7389. }
  7390. }
  7391. if (empty($mappingRecords)) {
  7392. Utils::throwError('20003:没有有效的产品数据');
  7393. }
  7394. // 批量插入映射数据(使用 insertOrIgnore 避免重复插入)
  7395. $insertedCount = DB::table('mp_script_product_mappings')->insertOrIgnore($mappingRecords);
  7396. // 剧本已有资产,同步更新is_products标记
  7397. DB::table('mp_scripts')->where('id', $script_id)->update([
  7398. 'is_products' => 1,
  7399. 'updated_at' => $now
  7400. ]);
  7401. // 如果需要自动生成图片,在事务中创建图片生成任务
  7402. $productTaskMap = [];
  7403. if ($auto_generate_images && !empty($createdProductIds)) {
  7404. // 查询所有创建的资产
  7405. $productsToGenerate = DB::table('mp_products')
  7406. ->whereIn('id', $createdProductIds)
  7407. ->where('is_deleted', 0)
  7408. ->get();
  7409. foreach ($productsToGenerate as $product) {
  7410. if (empty($product->pic_prompt)) {
  7411. dLog('anime')->warning('资产没有提示词,跳过图片生成', [
  7412. 'product_id' => $product->id,
  7413. 'product_name' => $product->product_name
  7414. ]);
  7415. continue;
  7416. }
  7417. try {
  7418. // 创建图片生成任务
  7419. $params = [
  7420. 'prompt' => $product->pic_prompt,
  7421. 'model' => $model,
  7422. 'ref_img_urls' => [],
  7423. 'width' => $width,
  7424. 'height' => $height
  7425. ];
  7426. $task = $this->aiImageGenerationService->createImageGenerationTask($params);
  7427. $task_id = $task->id;
  7428. if ($task_id) {
  7429. $productTaskMap[$product->id] = $task_id;
  7430. // 在事务中更新资产表的任务ID和状态
  7431. DB::table('mp_products')
  7432. ->where('id', $product->id)
  7433. ->update([
  7434. 'pic_task_id' => $task_id,
  7435. 'pic_task_status' => '生成中',
  7436. 'updated_at' => now()
  7437. ]);
  7438. dLog('anime')->info('创建资产图片生成任务', [
  7439. 'product_id' => $product->id,
  7440. 'task_id' => $task_id
  7441. ]);
  7442. }
  7443. } catch (\Exception $e) {
  7444. dLog('anime')->error('创建资产图片生成任务失败', [
  7445. 'product_id' => $product->id,
  7446. 'error' => $e->getMessage()
  7447. ]);
  7448. // 标记为失败(仍在事务中)
  7449. DB::table('mp_products')
  7450. ->where('id', $product->id)
  7451. ->update([
  7452. 'pic_task_status' => '生成失败',
  7453. 'updated_at' => now()
  7454. ]);
  7455. }
  7456. }
  7457. }
  7458. // 提交事务
  7459. DB::commit();
  7460. // 事务提交成功后,如果有图片生成任务,则返回 SSE 流
  7461. if ($auto_generate_images && !empty($productTaskMap)) {
  7462. // 返回 SSE 流(事务外轮询)
  7463. return $this->pollProductImageTasks($script_id, $script_name, $productTaskMap, $typeFolderIds);
  7464. }
  7465. // 如果不需要生成图片,返回普通结果
  7466. return [
  7467. 'success' => true,
  7468. 'type_folder_ids' => $typeFolderIds,
  7469. 'inserted_count' => $insertedCount,
  7470. 'total_records' => count($mappingRecords),
  7471. 'created_products' => count($createdProductIds),
  7472. 'image_tasks_created' => count($productTaskMap)
  7473. ];
  7474. } catch (\Exception $e) {
  7475. // 回滚事务
  7476. DB::rollback();
  7477. // 记录错误日志
  7478. dLog('anime')->error('保存剧本资产失败: ' . $e->getMessage(), [
  7479. 'script_id' => $script_id,
  7480. 'error' => $e->getMessage(),
  7481. 'trace' => $e->getTraceAsString()
  7482. ]);
  7483. // 统一使用 Utils::throwError 抛出错误
  7484. Utils::throwError('20003:保存剧本资产失败:' . $e->getMessage());
  7485. }
  7486. }
  7487. /**
  7488. * 批量为剧本资产生成图片
  7489. *
  7490. * @param array $data 请求参数
  7491. * @return \Generator 返回 SSE 流
  7492. */
  7493. public function batchGenerateProductImages($data) {
  7494. $script_id = getProp($data, 'script_id');
  7495. $type_folder_ids = getProp($data, 'type_folder_ids', []); // {1: 角色文件夹ID, 2: 场景文件夹ID, 3: 道具文件夹ID}
  7496. if (!$script_id) {
  7497. Utils::throwError('20003:请提供剧本ID');
  7498. }
  7499. // 验证剧本是否存在
  7500. $script = DB::table('mp_scripts')
  7501. ->where('id', $script_id)
  7502. ->where('is_deleted', 0)
  7503. ->first();
  7504. if (!$script) {
  7505. Utils::throwError('20003:剧本不存在');
  7506. }
  7507. $script_name = $script->script_name ?? 'script_' . $script_id;
  7508. // 获取需要生成图片的所有资产
  7509. $products = DB::table('mp_products')
  7510. ->whereIn('parent_id', array_values($type_folder_ids))
  7511. ->where('is_deleted', 0)
  7512. ->whereIn('type', [1, 2, 3]) // 只处理资产,不处理文件夹
  7513. ->get();
  7514. if ($products->isEmpty()) {
  7515. Utils::throwError('20003:没有找到需要生成图片的资产');
  7516. }
  7517. // 默认参数
  7518. $model = 'doubao-seedream-5-0-lite-260128';
  7519. $width = 1600;
  7520. $height = 2848;
  7521. // 开始为每个资产创建图片生成任务
  7522. $taskIds = [];
  7523. $productTaskMap = []; // 资产ID到任务ID的映射
  7524. foreach ($products as $product) {
  7525. if (empty($product->pic_prompt)) {
  7526. dLog('anime')->warning('资产没有提示词,跳过', ['product_id' => $product->id, 'product_name' => $product->product_name]);
  7527. continue;
  7528. }
  7529. try {
  7530. // 创建图片生成任务
  7531. $params = [
  7532. 'prompt' => $product->pic_prompt,
  7533. 'model' => $model,
  7534. 'ref_img_urls' => [],
  7535. 'width' => $width,
  7536. 'height' => $height
  7537. ];
  7538. $task = $this->aiImageGenerationService->createImageGenerationTask($params);
  7539. $task_id = $task->id;
  7540. if ($task_id) {
  7541. $taskIds[] = $task_id;
  7542. $productTaskMap[$product->id] = $task_id;
  7543. // 更新资产表的任务ID和状态
  7544. DB::table('mp_products')
  7545. ->where('id', $product->id)
  7546. ->update([
  7547. 'pic_task_id' => $task_id,
  7548. 'pic_task_status' => '生成中',
  7549. 'updated_at' => now()
  7550. ]);
  7551. dLog('anime')->info('创建资产图片生成任务', ['product_id' => $product->id, 'task_id' => $task_id]);
  7552. }
  7553. } catch (\Exception $e) {
  7554. dLog('anime')->error('创建资产图片生成任务失败', [
  7555. 'product_id' => $product->id,
  7556. 'error' => $e->getMessage()
  7557. ]);
  7558. // 标记为失败
  7559. DB::table('mp_products')
  7560. ->where('id', $product->id)
  7561. ->update([
  7562. 'pic_task_status' => '生成失败',
  7563. 'updated_at' => now()
  7564. ]);
  7565. }
  7566. }
  7567. if (empty($taskIds)) {
  7568. Utils::throwError('20003:没有成功创建任何图片生成任务');
  7569. }
  7570. // 返回 SSE 流
  7571. return $this->pollProductImageTasks($script_id, $script_name, $productTaskMap, $type_folder_ids);
  7572. }
  7573. /**
  7574. * 轮询资产图片生成任务状态(SSE流式返回)
  7575. * 只通过查询数据库获取任务状态,不主动调用API
  7576. *
  7577. * @param int $script_id 剧本ID
  7578. * @param string $script_name 剧本名称
  7579. * @param array $productTaskMap 资产ID到任务ID的映射
  7580. * @param array $type_folder_ids 类型文件夹ID映射
  7581. * @return \Generator
  7582. */
  7583. private function pollProductImageTasks($script_id, $script_name, $productTaskMap, $type_folder_ids) {
  7584. $startTime = time();
  7585. $timeout = 1800; // 30分钟超时
  7586. $pollInterval = 10; // 10秒轮询一次
  7587. $lastStatus = []; // 记录上次的状态,用于判断是否有变化
  7588. // 定义类型名称映射
  7589. $typeNames = [
  7590. 1 => 'roles', // 角色
  7591. 2 => 'scenes', // 场景
  7592. 3 => 'props' // 道具
  7593. ];
  7594. while (time() - $startTime < $timeout) {
  7595. sleep($pollInterval);
  7596. // 从 mp_script_product_mappings 表获取该剧本的所有资产ID
  7597. $mappings = DB::table('mp_script_product_mappings')
  7598. ->where('script_id', $script_id)
  7599. ->pluck('product_id')
  7600. ->unique()
  7601. ->toArray();
  7602. if (empty($mappings)) {
  7603. dLog('anime')->warning('该剧本没有关联的资产', [
  7604. 'script_id' => $script_id,
  7605. 'script_name' => $script_name
  7606. ]);
  7607. break;
  7608. }
  7609. // 查询所有资产的当前状态
  7610. $products = DB::table('mp_products')
  7611. ->whereIn('id', $mappings)
  7612. ->where('is_deleted', 0)
  7613. ->get();
  7614. // 统计各类型的状态(使用类型名称作为键名)
  7615. $stats = [
  7616. 'character' => ['total' => 0, 'success' => 0, 'completed' => 0], // 角色
  7617. 'scene' => ['total' => 0, 'success' => 0, 'completed' => 0], // 场景
  7618. 'prop' => ['total' => 0, 'success' => 0, 'completed' => 0], // 道具
  7619. ];
  7620. $allCompleted = true;
  7621. $hasStatusChange = false;
  7622. foreach ($products as $product) {
  7623. $type = $product->product;
  7624. $typeName = $typeNames[$type] ?? 'unknown'; // 使用 unknown 作为未知类型
  7625. // 如果类型名称不在 stats 中,初始化
  7626. if (!isset($stats[$typeName])) {
  7627. $stats[$typeName] = ['total' => 0, 'success' => 0, 'completed' => 0];
  7628. }
  7629. $stats[$typeName]['total']++;
  7630. $task_id = $product->pic_task_id;
  7631. $currentStatus = $product->pic_task_status;
  7632. // 检查状态是否有变化
  7633. if (!isset($lastStatus[$product->id]) || $lastStatus[$product->id] !== $currentStatus) {
  7634. $hasStatusChange = true;
  7635. $lastStatus[$product->id] = $currentStatus;
  7636. }
  7637. // 如果是生成中,查询任务表状态
  7638. if ($currentStatus === '生成中' && $task_id) {
  7639. // 只查询数据库,不调用API
  7640. $task = DB::table('mp_generate_pic_tasks')
  7641. ->where('id', $task_id)
  7642. ->first();
  7643. if ($task) {
  7644. // 检查任务状态
  7645. if ($task->status === 'success' && $task->result_url) {
  7646. // 解析图片URL
  7647. $result_urls = $task->result_url;
  7648. if (is_string($result_urls)) {
  7649. $result_urls = json_decode($result_urls, true);
  7650. }
  7651. $img_url = is_array($result_urls) ? $result_urls[0] : $task->result_url;
  7652. // 更新资产表状态
  7653. DB::table('mp_products')
  7654. ->where('id', $product->id)
  7655. ->update([
  7656. 'pic_task_status' => '生成成功',
  7657. 'url' => $img_url,
  7658. 'updated_at' => now()
  7659. ]);
  7660. $stats[$typeName]['success']++;
  7661. $stats[$typeName]['completed']++;
  7662. $hasStatusChange = true;
  7663. dLog('anime')->info('资产图片生成成功', [
  7664. 'product_id' => $product->id,
  7665. 'task_id' => $task_id,
  7666. 'img_url' => $img_url
  7667. ]);
  7668. } elseif ($task->status === 'failed') {
  7669. // 更新资产表状态
  7670. DB::table('mp_products')
  7671. ->where('id', $product->id)
  7672. ->update([
  7673. 'pic_task_status' => '生成失败',
  7674. 'updated_at' => now()
  7675. ]);
  7676. $stats[$typeName]['completed']++;
  7677. $hasStatusChange = true;
  7678. dLog('anime')->warning('资产图片生成失败', [
  7679. 'product_id' => $product->id,
  7680. 'task_id' => $task_id,
  7681. 'error' => $task->error_message ?? '未知错误'
  7682. ]);
  7683. } else {
  7684. // 任务还在处理中
  7685. $allCompleted = false;
  7686. }
  7687. } else {
  7688. // 任务不存在,标记为失败
  7689. DB::table('mp_products')
  7690. ->where('id', $product->id)
  7691. ->update([
  7692. 'pic_task_status' => '生成失败',
  7693. 'updated_at' => now()
  7694. ]);
  7695. $stats[$type]['completed']++;
  7696. $hasStatusChange = true;
  7697. dLog('anime')->error('图片生成任务不存在', [
  7698. 'product_id' => $product->id,
  7699. 'task_id' => $task_id
  7700. ]);
  7701. }
  7702. } elseif ($currentStatus === '生成成功') {
  7703. $stats[$typeName]['success']++;
  7704. $stats[$typeName]['completed']++;
  7705. } elseif ($currentStatus === '生成失败') {
  7706. $stats[$typeName]['completed']++;
  7707. } else {
  7708. // 其他状态也认为未完成
  7709. $allCompleted = false;
  7710. }
  7711. }
  7712. // 移除没有数据的类型(total=0)
  7713. foreach ($stats as $typeName => $stat) {
  7714. if ($stat['total'] === 0) {
  7715. unset($stats[$typeName]);
  7716. }
  7717. }
  7718. // 如果有状态变化,发送 SSE 更新
  7719. if ($hasStatusChange) {
  7720. $eventType = $allCompleted ? 'complete' : 'update';
  7721. $response = [
  7722. 'type' => $eventType,
  7723. 'script_id' => $script_id,
  7724. 'script_name' => $script_name,
  7725. 'stats' => $stats,
  7726. 'timestamp' => date('Y-m-d H:i:s')
  7727. ];
  7728. yield "data: " . json_encode($response, JSON_UNESCAPED_UNICODE) . "\n\n";
  7729. dLog('anime')->info('SSE更新', [
  7730. 'event_type' => $eventType,
  7731. 'script_id' => $script_id,
  7732. 'script_name' => $script_name,
  7733. 'stats' => $stats
  7734. ]);
  7735. if ($allCompleted) {
  7736. dLog('anime')->info('所有资产图片生成任务已完成', [
  7737. 'script_id' => $script_id,
  7738. 'script_name' => $script_name,
  7739. 'stats' => $stats
  7740. ]);
  7741. break;
  7742. }
  7743. }
  7744. }
  7745. // 超时处理
  7746. if (time() - $startTime >= $timeout && !$allCompleted) {
  7747. $response = [
  7748. 'type' => 'timeout',
  7749. 'message' => '部分任务超时,请稍后查看结果',
  7750. 'script_id' => $script_id,
  7751. 'script_name' => $script_name,
  7752. 'timestamp' => date('Y-m-d H:i:s')
  7753. ];
  7754. yield "data: " . json_encode($response, JSON_UNESCAPED_UNICODE) . "\n\n";
  7755. dLog('anime')->warning('资产图片生成任务超时', [
  7756. 'script_id' => $script_id,
  7757. 'script_name' => $script_name,
  7758. 'timeout' => $timeout
  7759. ]);
  7760. }
  7761. }
  7762. /**
  7763. * 定时任务:检查产品图片生成任务状态并更新产品记录
  7764. * 扫描 mp_products 中 pic_task_id 非空且 pic_task_status 为生成中的记录,
  7765. * 通过 pic_task_id 查询 mp_generate_pic_tasks 获取生成结果,按结果更新状态
  7766. *
  7767. * @return array ['total' => 总数, 'success' => 成功数, 'failed' => 失败数, 'pending' => 待处理数]
  7768. */
  7769. public function checkProductPicTasks() {
  7770. // 查询所有生成中的产品图片任务
  7771. $products = DB::table('mp_products')
  7772. ->whereNotNull('pic_task_id')
  7773. ->where('pic_task_status', '生成中')
  7774. ->where('is_deleted', 0)
  7775. ->get();
  7776. $stats = [
  7777. 'total' => $products->count(),
  7778. 'success' => 0,
  7779. 'failed' => 0,
  7780. 'pending' => 0,
  7781. ];
  7782. foreach ($products as $product) {
  7783. try {
  7784. $task_id = $product->pic_task_id;
  7785. // 通过 pic_task_id 查询图片生成任务结果
  7786. $task = DB::table('mp_generate_pic_tasks')
  7787. ->where('id', $task_id)
  7788. ->first();
  7789. if ($task) {
  7790. if ($task->status === 'success' && $task->result_url) {
  7791. // 解析图片URL
  7792. $result_urls = $task->result_url;
  7793. if (is_string($result_urls)) {
  7794. $result_urls = json_decode($result_urls, true);
  7795. }
  7796. $img_url = is_array($result_urls) ? ($result_urls[0] ?? $task->result_url) : $task->result_url;
  7797. // 更新资产表状态
  7798. DB::table('mp_products')
  7799. ->where('id', $product->id)
  7800. ->update([
  7801. 'pic_task_status' => '生成成功',
  7802. 'url' => $img_url,
  7803. 'updated_at' => now()
  7804. ]);
  7805. $stats['success']++;
  7806. dLog('anime')->info('资产图片生成成功', [
  7807. 'product_id' => $product->id,
  7808. 'task_id' => $task_id,
  7809. 'img_url' => $img_url
  7810. ]);
  7811. } elseif ($task->status === 'failed') {
  7812. // 更新资产表状态
  7813. DB::table('mp_products')
  7814. ->where('id', $product->id)
  7815. ->update([
  7816. 'pic_task_status' => '生成失败',
  7817. 'updated_at' => now()
  7818. ]);
  7819. $stats['failed']++;
  7820. dLog('anime')->warning('资产图片生成失败', [
  7821. 'product_id' => $product->id,
  7822. 'task_id' => $task_id,
  7823. 'error' => $task->error_message ?? '未知错误'
  7824. ]);
  7825. } else {
  7826. // 任务还在处理中
  7827. $stats['pending']++;
  7828. }
  7829. } else {
  7830. // 任务不存在,标记为失败
  7831. DB::table('mp_products')
  7832. ->where('id', $product->id)
  7833. ->update([
  7834. 'pic_task_status' => '生成失败',
  7835. 'updated_at' => now()
  7836. ]);
  7837. $stats['failed']++;
  7838. dLog('anime')->error('图片生成任务不存在', [
  7839. 'product_id' => $product->id,
  7840. 'task_id' => $task_id
  7841. ]);
  7842. }
  7843. } catch (\Exception $e) {
  7844. dLog('anime')->error('检查产品图片生成任务异常', [
  7845. 'product_id' => $product->id,
  7846. 'task_id' => $product->pic_task_id ?? null,
  7847. 'error' => $e->getMessage()
  7848. ]);
  7849. }
  7850. }
  7851. return $stats;
  7852. }
  7853. /**
  7854. * 获取剧本关联的资产列表
  7855. * @param array $data 请求参数
  7856. * @return array
  7857. */
  7858. public function getScriptProducts($data) {
  7859. $uid = Site::getUid();
  7860. $cpid = Site::getCpid();
  7861. $script_id = getProp($data, 'script_id');
  7862. $episode_number = getProp($data, 'episode_number');
  7863. if (!$script_id) {
  7864. Utils::throwError('20003:请提供剧本ID');
  7865. }
  7866. // 验证剧本是否存在
  7867. $script = DB::table('mp_scripts')
  7868. ->where('id', $script_id)
  7869. ->where('is_deleted', 0)
  7870. ->first();
  7871. if (!$script) {
  7872. Utils::throwError('20003:剧本不存在');
  7873. }
  7874. // 联表查询资产信息
  7875. $query = DB::table('mp_script_product_mappings as mapping')
  7876. ->join('mp_products as product', 'mapping.product_id', '=', 'product.id')
  7877. ->where('mapping.script_id', $script_id)
  7878. ->where('product.cpid', $cpid)
  7879. ->where('product.is_deleted', 0);
  7880. // 如果提供了 episode_number,则过滤指定集数
  7881. if ($episode_number !== null && $episode_number !== '') {
  7882. $query->where('mapping.episode_number', $episode_number);
  7883. }
  7884. $mappings = $query->select(
  7885. 'mapping.script_id',
  7886. 'mapping.product_id',
  7887. 'mapping.episode_number',
  7888. 'product.product_name',
  7889. 'product.type',
  7890. 'product.product',
  7891. 'product.pic_prompt',
  7892. 'product.url',
  7893. 'product.pic_task_id',
  7894. 'product.pic_task_status',
  7895. 'product.three_view_image_url',
  7896. 'mapping.created_at'
  7897. )
  7898. ->orderBy('mapping.product_id', 'asc')
  7899. ->orderBy('mapping.episode_number', 'asc')
  7900. ->get();
  7901. // 按 product_id 分组,合并 episode_number
  7902. $productMap = [];
  7903. foreach ($mappings as $item) {
  7904. $product_id = $item->product_id;
  7905. if (!isset($productMap[$product_id])) {
  7906. $productMap[$product_id] = [
  7907. 'product_id' => $product_id,
  7908. 'product_name' => $item->product_name,
  7909. 'type' => (int)$item->type,
  7910. 'product' => (int)$item->product,
  7911. 'pic_prompt' => $item->pic_prompt,
  7912. 'url' => $item->url,
  7913. 'pic_task_id' => $item->pic_task_id,
  7914. 'pic_task_status' => $item->pic_task_status,
  7915. 'episode_numbers' => [],
  7916. 'created_at' => $item->created_at,
  7917. ];
  7918. }
  7919. // 添加 episode_number(去重)
  7920. if (!in_array($item->episode_number, $productMap[$product_id]['episode_numbers'])) {
  7921. $productMap[$product_id]['episode_numbers'][] = $item->episode_number;
  7922. }
  7923. }
  7924. // 按类型分组
  7925. $roles = []; // type=1 角色/主体
  7926. $scenes = []; // type=2 场景
  7927. $props = []; // type=3 道具
  7928. foreach ($productMap as $product) {
  7929. // 将 episode_numbers 数组转换为逗号分隔的字符串
  7930. $episodeNumbersStr = implode(',', $product['episode_numbers']);
  7931. // 构造返回数据
  7932. $productData = [
  7933. 'product_id' => $product['product_id'],
  7934. 'product_name' => $product['product_name'],
  7935. 'product' => $product['product'],
  7936. 'pic_prompt' => $product['pic_prompt'],
  7937. 'url' => $product['url'],
  7938. 'pic_task_id' => $product['pic_task_id'],
  7939. 'pic_task_status' => $product['pic_task_status'],
  7940. 'episode_numbers' => $episodeNumbersStr,
  7941. 'created_at' => $product['created_at'],
  7942. ];
  7943. // 根据 type 分类(注意:type 字段表示资产类型,不是文件夹)
  7944. // 根据 product 字段分类(1=角色, 2=场景, 3=道具)
  7945. switch ($product['product']) {
  7946. case 1:
  7947. $roles[] = $productData;
  7948. break;
  7949. case 2:
  7950. $scenes[] = $productData;
  7951. break;
  7952. case 3:
  7953. $props[] = $productData;
  7954. break;
  7955. }
  7956. }
  7957. return [
  7958. 'script_id' => $script_id,
  7959. 'script_name' => $script->script_name ?? '',
  7960. 'roles' => $roles, // 主体
  7961. 'scenes' => $scenes, // 场景
  7962. 'props' => $props, // 道具
  7963. ];
  7964. }
  7965. /**
  7966. * 处理act_content中的{}标记,替换为product_name(图+序号)格式,并收集参考图片
  7967. * @param string $actContent 原始内容
  7968. * @param array $products 产品数组(包含product_name和url)
  7969. * @return array ['content' => 处理后的内容, 'reference_images' => 参考图片数组]
  7970. */
  7971. public function processActContentWithProducts($actContent, $products) {
  7972. if (empty($actContent) || empty($products)) {
  7973. return [
  7974. 'content' => $actContent,
  7975. 'reference_images' => []
  7976. ];
  7977. }
  7978. // 构建产品名称到产品信息的映射
  7979. $product_dict = [];
  7980. foreach ($products as $product) {
  7981. $product_name = getProp($product, 'product_name');
  7982. if ($product_name) {
  7983. $product_dict[$product_name] = [
  7984. 'url' => getProp($product, 'url'),
  7985. 'voice_prompt' => getProp($product, 'voice_prompt')
  7986. ];
  7987. }
  7988. }
  7989. // 第一步:查找内容中所有 {产品名称} 格式的标记(按出现顺序,去重)
  7990. preg_match_all('/\{([^}]+)\}/u', $actContent, $matches);
  7991. $reference_images = [];
  7992. $product_index_map = []; // 产品名称 => 图片序号的映射
  7993. $voice_prompts = []; // 存储需要添加到开头的voice_prompt信息
  7994. $narrator_voice_prompt = ''; // 单独存储旁白的voice_prompt
  7995. $current_index = 1;
  7996. if (!empty($matches[1])) {
  7997. // 按照在内容中第一次出现的顺序,为每个产品分配序号
  7998. $seen_products = []; // 用于去重
  7999. foreach ($matches[1] as $product_name) {
  8000. // 跳过已处理的产品
  8001. if (isset($seen_products[$product_name])) {
  8002. continue;
  8003. }
  8004. $seen_products[$product_name] = true;
  8005. // 检查产品是否在字典中
  8006. if (isset($product_dict[$product_name])) {
  8007. $url = $product_dict[$product_name]['url'];
  8008. $voice_prompt = $product_dict[$product_name]['voice_prompt'];
  8009. // 处理voice_prompt(旁白不在这里处理,旁白是公共的在后面单独处理)
  8010. if (!empty($voice_prompt) && $product_name !== '旁白') {
  8011. $voice_prompts[] = $product_name . ':' . $voice_prompt . "\n";
  8012. }
  8013. // 只有URL非空才分配序号和添加到参考图片
  8014. if (!empty($url)) {
  8015. // 检查URL是否已经在reference_images中(去重)
  8016. if (!in_array($url, $reference_images)) {
  8017. $reference_images[] = $url;
  8018. $product_index_map[$product_name] = $current_index;
  8019. $current_index++;
  8020. } else {
  8021. // URL重复,找到已有的序号
  8022. $existing_index = array_search($url, $reference_images) + 1;
  8023. $product_index_map[$product_name] = $existing_index;
  8024. }
  8025. } else {
  8026. // URL为空,不分配序号(后续直接去掉{})
  8027. $product_index_map[$product_name] = 0;
  8028. }
  8029. } else {
  8030. // 产品不在字典中,不分配序号
  8031. $product_index_map[$product_name] = 0;
  8032. }
  8033. }
  8034. }
  8035. // 第二步:替换内容中的 {产品名称}
  8036. $processedContent = $actContent;
  8037. foreach ($product_index_map as $product_name => $index) {
  8038. $escaped_name = preg_quote($product_name, '/');
  8039. if ($index > 0) {
  8040. // 有图片,替换为:产品名称(图X)
  8041. $replacement = $product_name . '<图片' . $index . '>';
  8042. } else {
  8043. // 无图片,只保留产品名称
  8044. $replacement = $product_name;
  8045. }
  8046. // 替换所有 {产品名称} 为处理后的格式
  8047. $processedContent = preg_replace('/\{' . $escaped_name . '\}/u', $replacement, $processedContent);
  8048. }
  8049. // 第三步:单独处理旁白的voice_prompt(旁白是公共的,不依赖product_dict)
  8050. foreach ($products as $product) {
  8051. $product_name = getProp($product, 'product_name');
  8052. $voice_prompt = getProp($product, 'voice_prompt');
  8053. if ($product_name === '旁白' && !empty($voice_prompt)) {
  8054. $narrator_voice_prompt = $product_name . ':' . $voice_prompt . "\n";
  8055. break; // 找到旁白后退出循环
  8056. }
  8057. }
  8058. // 第四步:将voice_prompt信息添加到内容最前面
  8059. $voice_prompt_prefix = '';
  8060. if (!empty($voice_prompts)) {
  8061. $voice_prompt_prefix .= implode('', $voice_prompts);
  8062. }
  8063. // 旁白的voice_prompt放在最后
  8064. if (!empty($narrator_voice_prompt)) {
  8065. $voice_prompt_prefix .= $narrator_voice_prompt;
  8066. }
  8067. // 如果有voice_prompt信息,添加到内容开头
  8068. if (!empty($voice_prompt_prefix)) {
  8069. $processedContent = "人物音色:\n" . $voice_prompt_prefix . "\n" . $processedContent;
  8070. }
  8071. return [
  8072. 'content' => $processedContent,
  8073. 'reference_images' => $reference_images
  8074. ];
  8075. }
  8076. public function saveActVideoGenerateParams($data) {
  8077. $episode_id = getProp($data, 'episode_id');
  8078. $model = getProp($data, 'video_model');
  8079. if (!in_array($model, ['zhizhen-20', 'zhizhen-20-fas', 'zhizhen-20-mini'])) {
  8080. Utils::throwError('20003:该模型不可用');
  8081. }
  8082. if (!$model) {
  8083. // 使用默认模型
  8084. $model = 'zhizhen-20';
  8085. }
  8086. // 验证模型是否在可用模型表中
  8087. if (!DB::table('mp_video_models')->where('model', $model)->where('is_enabled', 1)->exists()) {
  8088. Utils::throwError('20003:该模型已不可用,请更换!');
  8089. }
  8090. $video_resolution = getProp($data, 'video_resolution', '720p');
  8091. $ratio = getProp($data, 'ratio');
  8092. if (!$ratio) $ratio = '9:16';
  8093. $episode = DB::table('mp_anime_episodes')->where('id', $episode_id)->first(['anime_id']);
  8094. if (!$episode) {
  8095. Utils::throwError('20003:分集不存在');
  8096. }
  8097. try {
  8098. DB::beginTransaction();
  8099. $result = DB::table('mp_anime_episodes')->where('id', $episode_id)->update([
  8100. 'video_model' => $model,
  8101. 'video_resolution' => $video_resolution,
  8102. 'ratio' => $ratio,
  8103. 'updated_at' => date('Y-m-d H:i:s')
  8104. ]);
  8105. if ($result === false) {
  8106. Utils::throwError('20003:分集视频参数保存失败');
  8107. }
  8108. // 同步更新mp_animes表
  8109. $anime_result = DB::table('mp_animes')->where('id', $episode->anime_id)->update([
  8110. 'video_model' => $model,
  8111. 'video_resolution' => $video_resolution,
  8112. 'video_ratio' => $ratio,
  8113. 'updated_at' => date('Y-m-d H:i:s')
  8114. ]);
  8115. if ($anime_result === false) {
  8116. Utils::throwError('20003:动漫视频参数保存失败');
  8117. }
  8118. } catch (\Exception $e) {
  8119. DB::rollBack();
  8120. Utils::throwError('20003:'.$e->getMessage());
  8121. }
  8122. DB::commit();
  8123. return $result;
  8124. }
  8125. public function confirmActs($data) {
  8126. $episode_id = getProp($data, 'episode_id');
  8127. $episode = DB::table('mp_anime_episodes')->where('id', $episode_id)->first();
  8128. if (!$episode) {
  8129. Utils::throwError('20003:分集不存在');
  8130. }
  8131. $roles = json_decode(getProp($episode, 'roles'), true) ?: [];
  8132. $scenes = json_decode(getProp($episode, 'scenes'), true) ?: [];
  8133. $props = json_decode(getProp($episode, 'props'), true) ?: [];
  8134. // 获取所有片段数据
  8135. $acts = DB::table('mp_episode_segments')->where('episode_id', $episode_id)->orderBy('act_number')->get();
  8136. // 收集所有资产名称(角色、场景、道具)
  8137. $product_names = [];
  8138. // 收集角色名称
  8139. foreach ($roles as $role) {
  8140. $role_name = getProp($role, 'role');
  8141. if ($role_name && $role_name != '旁白') {
  8142. $product_names[] = $role_name;
  8143. }
  8144. }
  8145. // 收集场景名称
  8146. foreach ($scenes as $scene) {
  8147. $scene_name = getProp($scene, 'scene');
  8148. if ($scene_name) {
  8149. $product_names[] = $scene_name;
  8150. }
  8151. }
  8152. // 收集道具名称
  8153. foreach ($props as $prop) {
  8154. $prop_name = getProp($prop, 'prop');
  8155. if ($prop_name) {
  8156. $product_names[] = $prop_name;
  8157. }
  8158. }
  8159. // 去重并按长度降序排序(避免短名称先匹配到长名称的一部分)
  8160. $product_names = array_unique($product_names);
  8161. usort($product_names, function($a, $b) {
  8162. return mb_strlen($b) - mb_strlen($a);
  8163. });
  8164. try {
  8165. DB::beginTransaction();
  8166. // 处理每个片段
  8167. foreach ($acts as $act) {
  8168. $act_content = getProp($act, 'act_content');
  8169. if (!$act_content) continue;
  8170. $processed_content = $act_content;
  8171. // 统一替换所有资产名称为 {资产名} 格式
  8172. // 使用占位符避免嵌套替换问题
  8173. $placeholder_map = [];
  8174. $placeholder_index = 0;
  8175. foreach ($product_names as $product_name) {
  8176. // 转义特殊字符
  8177. $escaped_product = preg_quote($product_name, '/');
  8178. // 检查是否匹配且未被 {} 包裹
  8179. $processed_content = preg_replace_callback(
  8180. '/(?<![{])(' . $escaped_product . ')(?![}])/u',
  8181. function($matches) use (&$placeholder_map, &$placeholder_index) {
  8182. // 使用唯一占位符
  8183. $placeholder = '<<<PLACEHOLDER_' . $placeholder_index . '>>>';
  8184. $placeholder_map[$placeholder] = '{' . $matches[1] . '}';
  8185. $placeholder_index++;
  8186. return $placeholder;
  8187. },
  8188. $processed_content
  8189. );
  8190. }
  8191. // 将所有占位符替换回实际内容
  8192. foreach ($placeholder_map as $placeholder => $replacement) {
  8193. $processed_content = str_replace($placeholder, $replacement, $processed_content);
  8194. }
  8195. // 处理【镜头X】或【分镜X】重新编号为从1开始的连续整数【镜头X】
  8196. $shot_counter = 0;
  8197. $processed_content = preg_replace_callback(
  8198. '/【(?:镜头|分镜)(\d+)】/u',
  8199. function($matches) use (&$shot_counter) {
  8200. $shot_counter++;
  8201. return '【镜头' . $shot_counter . '】';
  8202. },
  8203. $processed_content
  8204. );
  8205. // 更新数据库
  8206. $boolen = DB::table('mp_episode_segments')
  8207. ->where('id', $act->id)
  8208. ->update([
  8209. 'act_show_content' => $processed_content,
  8210. 'updated_at' => date('Y-m-d H:i:s')
  8211. ]);
  8212. if (!$boolen) {
  8213. Utils::throwError('20003:片段处理失败');
  8214. }
  8215. }
  8216. }catch (\Exception $e) {
  8217. DB::rollBack();
  8218. Utils::throwError('20003:'.$e->getMessage());
  8219. }
  8220. $boolen1 = DB::table('mp_anime_episodes')->where('id', $episode_id)->update([
  8221. 'is_generated' => 1,
  8222. 'updated_at' => date('Y-m-d H:i:s')
  8223. ]);
  8224. if (!$boolen1) {
  8225. DB::rollBack();
  8226. Utils::throwError('20003:分集处理失败!');
  8227. }
  8228. DB::commit();
  8229. // 重新查询更新后的片段数据
  8230. $acts = DB::table('mp_episode_segments')->where('episode_id', $episode_id)->orderBy('act_number')->get();
  8231. // 合并角色、场景、道具和extra_products作为products,统一字段名为product_name
  8232. // extra_products优先级更高,会覆盖同名的roles、scenes和props
  8233. $products = [];
  8234. // 先处理角色数组
  8235. foreach ($roles as $role) {
  8236. $product = $role;
  8237. // 将role字段重命名为product_name
  8238. if (isset($product['role'])) {
  8239. $product['product_name'] = $product['role'];
  8240. unset($product['role']);
  8241. $product['product'] = 1; // 标记类型为角色
  8242. $products[$product['product_name']] = $product; // 使用product_name作为key便于后续覆盖
  8243. }
  8244. }
  8245. // 处理场景数组
  8246. foreach ($scenes as $scene) {
  8247. $product = $scene;
  8248. // 将scene字段重命名为product_name
  8249. if (isset($product['scene'])) {
  8250. $product['product_name'] = $product['scene'];
  8251. unset($product['scene']);
  8252. $product['product'] = 2; // 标记类型为场景
  8253. $products[$product['product_name']] = $product; // 使用product_name作为key便于后续覆盖
  8254. }
  8255. }
  8256. // 处理道具数组(逻辑与场景一致)
  8257. foreach ($props as $prop) {
  8258. $product = $prop;
  8259. // 将prop字段重命名为product_name
  8260. if (isset($product['prop'])) {
  8261. $product['product_name'] = $product['prop'];
  8262. unset($product['prop']);
  8263. $product['product'] = 3; // 标记类型为道具
  8264. $products[$product['product_name']] = $product; // 使用product_name作为key便于后续覆盖
  8265. }
  8266. }
  8267. // extra_products优先级更高,直接覆盖同名的roles和scenes
  8268. $extra_products = json_decode(getProp($episode, 'extra_products', '[]'), true) ?: [];
  8269. foreach ($extra_products as $extra_product) {
  8270. $product_name = getProp($extra_product, 'product_name');
  8271. if ($product_name) {
  8272. $products[$product_name] = $extra_product; // 覆盖同名数据
  8273. }
  8274. }
  8275. // 重新索引数组(去除key)
  8276. $products = array_values($products);
  8277. // 构建返回的acts数组
  8278. $return_acts = [];
  8279. foreach ($acts as $act) {
  8280. $return_acts[] = [
  8281. 'act_id' => getProp($act, 'id'),
  8282. 'act_number' => getProp($act, 'act_number'),
  8283. 'act_duration' => getProp($act, 'video_duration') ? getProp($act, 'video_duration') : getProp($act, 'act_duration'),
  8284. 'act_show_content' => getProp($act, 'act_show_content'),
  8285. 'video_url' => getProp($act, 'video_url'),
  8286. 'video_duration' => getProp($act, 'video_duration'),
  8287. 'video_time_point_start' => getProp($act, 'video_time_point_start'),
  8288. 'video_time_point_end' => getProp($act, 'video_time_point_end'),
  8289. ];
  8290. }
  8291. return [
  8292. 'anime_id' => getProp($episode, 'anime_id'),
  8293. 'episode_id' => $episode_id,
  8294. 'title' => getProp($episode, 'title'),
  8295. 'episode_number' => getProp($episode, 'episode_number'),
  8296. 'is_generated' => getProp($episode, 'is_generated'),
  8297. 'video_params' => [
  8298. 'video_model' => getProp($episode, 'video_model'),
  8299. 'video_resolution' => getProp($episode, 'video_resolution'),
  8300. 'ratio' => getProp($episode, 'ratio'),
  8301. ],
  8302. 'products' => $products,
  8303. 'acts' => $return_acts
  8304. ];
  8305. }
  8306. /**
  8307. * 导出动漫剧本为PDF(参照示例PDF版式)
  8308. * @param int $animeId 动漫ID
  8309. * @param int $episodeCount 导出集数,默认8,传-1表示全部
  8310. * @param string|null $savePath 指定保存路径(为空则直接下载输出)
  8311. * @return string|null
  8312. */
  8313. public function exportAnimeScriptAsPdf($animeId, $episodeCount = 8, $savePath = null) {
  8314. // 图片下载与转换可能占用较多内存
  8315. ini_set('memory_limit', '512M');
  8316. $anime = DB::table('mp_animes')->where('id', $animeId)->where('is_deleted', 0)->first();
  8317. if (!$anime) Utils::throwError('20003:该动漫不存在!');
  8318. $anime = (array)$anime;
  8319. // 剧本名去掉末尾"_数字"标识后缀,只保留剧名本身
  8320. $anime['anime_name'] = trim((string)preg_replace('/_\d+$/u', '', getProp($anime, 'anime_name', '')));
  8321. // 获取分集(默认展示版本,按集数升序)
  8322. $episodeQuery = DB::table('mp_anime_episodes')
  8323. ->where('anime_id', $animeId)
  8324. ->where('is_default', 1)
  8325. ->orderBy('episode_number')
  8326. ->orderBy('id');
  8327. if ($episodeCount > 0) {
  8328. $episodeQuery->limit($episodeCount);
  8329. }
  8330. $episodes = $episodeQuery->get()->map(function ($value) {
  8331. return (array)$value;
  8332. })->toArray();
  8333. if (!$episodes) Utils::throwError('20003:该动漫暂无分集数据');
  8334. // 聚合主体/场景/道具列表(前N集内容,按名称去重)
  8335. $roles = $this->mergeEpisodeItems($episodes, 'role');
  8336. $scenes = $this->mergeEpisodeItems($episodes, 'scene');
  8337. $props = $this->mergeEpisodeItems($episodes, 'prop');
  8338. // 组装分集剧本数据
  8339. $episodeScripts = [];
  8340. foreach ($episodes as $episode) {
  8341. $segments = DB::table('mp_episode_segments')
  8342. ->where('anime_id', $animeId)
  8343. ->where('episode_id', $episode['id'])
  8344. ->get();
  8345. // 按act_number分组,同一片段多版本时取最新一条(id最大)
  8346. $acts = [];
  8347. foreach ($segments as $segment) {
  8348. $segment = (array)$segment;
  8349. $actNumber = (int)getProp($segment, 'act_number', 0);
  8350. if ($actNumber <= 0) continue;
  8351. if (!isset($acts[$actNumber]) || (int)$segment['id'] > (int)$acts[$actNumber]['id']) {
  8352. $acts[$actNumber] = [
  8353. 'id' => (int)$segment['id'],
  8354. 'act_number' => $actNumber,
  8355. 'duration' => getProp($segment, 'act_duration', ''),
  8356. 'content' => getProp($segment, 'act_content', ''),
  8357. ];
  8358. }
  8359. }
  8360. ksort($acts);
  8361. // 分镜序号按出现先后重新编号(整集范围内保持连续,兼容【镜头N】/【分镜N】两种格式)
  8362. $segmentCounter = 0;
  8363. foreach ($acts as &$act) {
  8364. $act['content'] = $this->renumberSegmentBlocks($act['content'], $segmentCounter);
  8365. }
  8366. unset($act);
  8367. // 旁白音色:优先取分集roles中"旁白"的voice_prompt,否则从片段内容解析
  8368. $narratorVoice = '';
  8369. $episodeRoles = json_decode(getProp($episode, 'roles', ''), true) ?: [];
  8370. foreach ($episodeRoles as $role) {
  8371. if (getProp($role, 'role') === '旁白') {
  8372. $narratorVoice = trim((string)getProp($role, 'voice_prompt', ''));
  8373. break;
  8374. }
  8375. }
  8376. if ($narratorVoice === '') {
  8377. foreach ($acts as $act) {
  8378. if (preg_match('/旁白音色[::]\s*([^\n]+)/u', $act['content'], $match)) {
  8379. $narratorVoice = trim($match[1]);
  8380. break;
  8381. }
  8382. }
  8383. }
  8384. $episodeScripts[] = [
  8385. 'episode_number' => getProp($episode, 'episode_number'),
  8386. 'title' => getProp($episode, 'title', ''),
  8387. 'act_count' => count($acts),
  8388. 'narrator_voice' => $narratorVoice,
  8389. 'acts' => array_values($acts),
  8390. ];
  8391. }
  8392. // 并发下载列表图片(主体/场景/道具),url => 临时文件
  8393. $imageCache = $this->downloadImagesConcurrently(array_merge($roles, $scenes, $props));
  8394. // 构建PDF
  8395. $pdf = $this->buildAnimeScriptPdf($anime, $roles, $scenes, $props, $episodeScripts, $imageCache);
  8396. // 图片已嵌入PDF,清理临时文件
  8397. foreach ($imageCache as $imgFile) {
  8398. @unlink($imgFile);
  8399. }
  8400. $filename = $anime['anime_name'] . '_' . date('YmdHis');
  8401. if ($savePath) {
  8402. $pdf->Output($savePath, 'F');
  8403. return $savePath;
  8404. }
  8405. // 直接下载输出
  8406. header('Content-Type: application/pdf');
  8407. header("Content-Disposition: attachment; filename*=UTF-8''" . rawurlencode($filename . '.pdf'));
  8408. $pdf->Output($filename . '.pdf', 'D');
  8409. exit();
  8410. }
  8411. /**
  8412. * 聚合分集的主体/场景/道具列表,按名称去重(保留首次出现)
  8413. * @param array $episodes 分集数据
  8414. * @param string $nameKey role|scene|prop
  8415. * @return array
  8416. */
  8417. private function mergeEpisodeItems(array $episodes, $nameKey) {
  8418. $fieldMap = [
  8419. 'role' => 'roles',
  8420. 'scene' => 'scenes',
  8421. 'prop' => 'props',
  8422. ];
  8423. $field = isset($fieldMap[$nameKey]) ? $fieldMap[$nameKey] : $nameKey;
  8424. $items = [];
  8425. foreach ($episodes as $episode) {
  8426. $list = json_decode(getProp($episode, $field, ''), true) ?: [];
  8427. foreach ($list as $item) {
  8428. if (!is_array($item)) continue;
  8429. $name = trim((string)getProp($item, $nameKey, ''));
  8430. if ($name === '') continue;
  8431. // 旁白不进入主体列表(仅作为旁白音色来源)
  8432. if ($nameKey === 'role' && $name === '旁白') continue;
  8433. if (!isset($items[$name])) {
  8434. $items[$name] = $item;
  8435. }
  8436. }
  8437. }
  8438. return array_values($items);
  8439. }
  8440. /**
  8441. * 构建动漫剧本PDF
  8442. * @param array $anime 动漫信息
  8443. * @param array $roles 主体列表
  8444. * @param array $scenes 场景列表
  8445. * @param array $props 道具列表
  8446. * @param array $episodeScripts 分集剧本数据
  8447. * @param array $imageCache 图片缓存(url => 临时文件路径)
  8448. * @return \TCPDF
  8449. */
  8450. private function buildAnimeScriptPdf($anime, $roles, $scenes, $props, $episodeScripts, $imageCache = []) {
  8451. $pdf = new \TCPDF('P', 'mm', 'A4', true, 'UTF-8', false);
  8452. $pdf->SetCreator('动漫剧本导出系统');
  8453. $pdf->SetAuthor('系统');
  8454. $pdf->SetTitle(getProp($anime, 'anime_name', '动漫剧本'));
  8455. $pdf->SetSubject('动漫剧本导出');
  8456. $pdf->SetMargins(15, 15, 15);
  8457. $pdf->SetAutoPageBreak(true, 15);
  8458. // 剧本名
  8459. $pdf->AddPage();
  8460. $pdf->SetFont('simsun', 'B', 20);
  8461. $pdf->Cell(0, 15, getProp($anime, 'anime_name', ''), 0, 1, 'C');
  8462. $pdf->Ln(5);
  8463. // 故事梗概
  8464. $intro = trim((string)getProp($anime, 'intro', ''));
  8465. if ($intro !== '') {
  8466. $this->pdfSectionTitle($pdf, '故事梗概');
  8467. $this->pdfBody($pdf, $intro);
  8468. }
  8469. // 美术风格
  8470. $artStyle = trim((string)getProp($anime, 'art_style', ''));
  8471. if ($artStyle !== '') {
  8472. $this->pdfSectionTitle($pdf, '美术风格');
  8473. $this->pdfBody($pdf, $artStyle);
  8474. }
  8475. // 主体列表(文字+图片)
  8476. $this->pdfSectionTitle($pdf, '主体列表');
  8477. foreach ($roles as $index => $role) {
  8478. $this->pdfBody($pdf, ($index + 1) . '. ' . getProp($role, 'role', '') . ':' . getProp($role, 'description', ''));
  8479. }
  8480. $this->pdfItemImages($pdf, $roles, 'role', $imageCache);
  8481. // 场景列表(文字+图片)
  8482. $this->pdfSectionTitle($pdf, '场景列表');
  8483. foreach ($scenes as $index => $scene) {
  8484. $this->pdfBody($pdf, ($index + 1) . '. ' . getProp($scene, 'scene', '') . ':' . getProp($scene, 'description', ''));
  8485. }
  8486. $this->pdfItemImages($pdf, $scenes, 'scene', $imageCache);
  8487. // 道具列表(文字+图片)
  8488. $this->pdfSectionTitle($pdf, '道具列表');
  8489. foreach ($props as $index => $prop) {
  8490. $this->pdfBody($pdf, ($index + 1) . '. ' . getProp($prop, 'prop', '') . ':' . getProp($prop, 'description', ''));
  8491. }
  8492. $this->pdfItemImages($pdf, $props, 'prop', $imageCache);
  8493. // 分镜剧本
  8494. $this->pdfSectionTitle($pdf, '分镜剧本');
  8495. foreach ($episodeScripts as $episodeScript) {
  8496. $episodeTitle = '第' . getProp($episodeScript, 'episode_number') . '集';
  8497. $episodeTitleRaw = trim((string)getProp($episodeScript, 'title', ''));
  8498. if ($episodeTitleRaw !== '') {
  8499. // title 字段可能已带"第N集"前缀,避免重复
  8500. if (preg_match('/^第\d+集[::\s]/u', $episodeTitleRaw)) {
  8501. $episodeTitle = $episodeTitleRaw;
  8502. } else {
  8503. $episodeTitle .= ':' . $episodeTitleRaw;
  8504. }
  8505. }
  8506. $this->pdfSubTitle($pdf, $episodeTitle, 13);
  8507. $this->pdfBody($pdf, '片段数量:' . getProp($episodeScript, 'act_count', 0));
  8508. if (getProp($episodeScript, 'narrator_voice') !== '') {
  8509. $this->pdfBody($pdf, '旁白音色:' . getProp($episodeScript, 'narrator_voice'));
  8510. }
  8511. foreach (getProp($episodeScript, 'acts', []) as $act) {
  8512. $actTitle = '片段' . getProp($act, 'act_number');
  8513. if (getProp($act, 'duration') !== '' && getProp($act, 'duration') !== null) {
  8514. $actTitle .= ' 时长 ' . getProp($act, 'duration') . 's';
  8515. }
  8516. $this->pdfSubTitle($pdf, $actTitle, 12);
  8517. if (getProp($act, 'content') !== '') {
  8518. $this->pdfBody($pdf, getProp($act, 'content'));
  8519. }
  8520. }
  8521. }
  8522. return $pdf;
  8523. }
  8524. /**
  8525. * PDF章节标题(带分隔线)
  8526. */
  8527. private function pdfSectionTitle($pdf, $title) {
  8528. if ($pdf->GetY() > 230) {
  8529. $pdf->AddPage();
  8530. }
  8531. $pdf->SetFont('simsun', 'B', 15);
  8532. $pdf->Cell(0, 10, $title, 0, 1, 'L');
  8533. $y = $pdf->GetY();
  8534. $pdf->SetLineWidth(0.4);
  8535. $pdf->Line(15, $y, 195, $y);
  8536. $pdf->Ln(4);
  8537. }
  8538. /**
  8539. * PDF子标题(集数/片段标题)
  8540. */
  8541. private function pdfSubTitle($pdf, $title, $size = 13) {
  8542. if ($pdf->GetY() > 240) {
  8543. $pdf->AddPage();
  8544. }
  8545. $pdf->SetFont('simsun', 'B', $size);
  8546. $pdf->Cell(0, 8, $title, 0, 1, 'L');
  8547. $pdf->Ln(1);
  8548. }
  8549. /**
  8550. * PDF正文段落
  8551. */
  8552. private function pdfBody($pdf, $text) {
  8553. $pdf->SetFont('simsun', '', 11);
  8554. $pdf->MultiCell(0, 6, $text, 0, 'L');
  8555. $pdf->Ln(2);
  8556. }
  8557. /**
  8558. * 输出列表项图片(每张图单独一页,图下标注名称)
  8559. * @param \TCPDF $pdf
  8560. * @param array $items 列表项
  8561. * @param string $nameKey role|scene|prop
  8562. * @param array $imageCache 图片缓存(url => 临时文件路径)
  8563. */
  8564. private function pdfItemImages($pdf, array $items, $nameKey, array $imageCache) {
  8565. foreach ($items as $item) {
  8566. $url = trim((string)getProp($item, 'url', ''));
  8567. $name = trim((string)getProp($item, $nameKey, ''));
  8568. if ($url === '' || !isset($imageCache[$url])) continue;
  8569. $imgPath = $imageCache[$url];
  8570. $size = @getimagesize($imgPath);
  8571. if (!$size || $size[0] <= 0 || $size[1] <= 0) {
  8572. continue;
  8573. }
  8574. $pdf->AddPage();
  8575. // 图片按比例缩放,居中偏上,为底部名称标注预留空间
  8576. $maxW = 160;
  8577. $maxH = 170;
  8578. $ratio = min($maxW / $size[0], $maxH / $size[1], 1);
  8579. $drawW = $size[0] * $ratio;
  8580. $drawH = $size[1] * $ratio;
  8581. $x = (210 - $drawW) / 2;
  8582. $y = max(15, (297 - $drawH) / 2 - 10);
  8583. $pdf->Image($imgPath, $x, $y, $drawW, $drawH, '', '', '', false, 300, '', false, false, 0, false, false, false);
  8584. // 图下标注名称
  8585. $pdf->SetFont('simsun', 'B', 13);
  8586. $pdf->SetY(297 - 28);
  8587. $pdf->Cell(0, 8, $name, 0, 1, 'C');
  8588. }
  8589. }
  8590. /**
  8591. * 并发下载远程图片到临时文件,并统一缩放转为JPEG
  8592. * @param array $items 包含url字段的列表项
  8593. * @return array url => 临时文件路径
  8594. */
  8595. private function downloadImagesConcurrently(array $items) {
  8596. // 收集唯一的图片URL
  8597. $urls = [];
  8598. foreach ($items as $item) {
  8599. $url = trim((string)getProp($item, 'url', ''));
  8600. if ($url !== '') $urls[$url] = true;
  8601. }
  8602. if (!$urls) return [];
  8603. $urls = array_keys($urls);
  8604. $tmpDir = sys_get_temp_dir();
  8605. $rawFiles = [];
  8606. foreach ($urls as $url) {
  8607. $rawFile = $tmpDir . '/anime_pdf_raw_' . md5($url) . '.img';
  8608. $rawFiles[$url] = $rawFile;
  8609. }
  8610. $client = new Client(['timeout' => 180, 'verify' => false]);
  8611. // 低并发下载,sink写入文件避免大图占用内存
  8612. $generator = (function () use ($urls, $client, $rawFiles) {
  8613. foreach ($urls as $url) {
  8614. yield $url => $client->getAsync($url, ['sink' => $rawFiles[$url]]);
  8615. }
  8616. })();
  8617. $errors = [];
  8618. $each = new \GuzzleHttp\Promise\EachPromise($generator, [
  8619. 'concurrency' => 4,
  8620. 'rejected' => function ($reason, $url) use (&$errors) {
  8621. $errors[$url] = $reason ? $reason->getMessage() : 'unknown';
  8622. },
  8623. ]);
  8624. $each->promise()->wait();
  8625. // 失败的图片串行重试一次(独占带宽,提高成功率)
  8626. foreach ($urls as $url) {
  8627. if (!isset($errors[$url])) continue;
  8628. try {
  8629. $client->get($url, ['sink' => $rawFiles[$url], 'timeout' => 300]);
  8630. unset($errors[$url]);
  8631. } catch (\Throwable $e) {
  8632. // 重试仍失败
  8633. }
  8634. }
  8635. $cache = [];
  8636. foreach ($urls as $url) {
  8637. $rawFile = $rawFiles[$url];
  8638. if (isset($errors[$url])) {
  8639. dLog('anime')->error('导出PDF图片下载失败', [
  8640. 'url' => $url,
  8641. 'error' => $errors[$url],
  8642. ]);
  8643. @unlink($rawFile);
  8644. continue;
  8645. }
  8646. $converted = $this->convertImageFile($rawFile, $url);
  8647. if ($converted !== null) {
  8648. $cache[$url] = $converted;
  8649. } else {
  8650. @unlink($rawFile);
  8651. }
  8652. }
  8653. return $cache;
  8654. }
  8655. /**
  8656. * 将已下载的图片文件缩放并转为JPEG
  8657. * @param string $rawFile 原始图片临时文件
  8658. * @param string $url 图片地址(用于命名)
  8659. * @return string|null 转换后的文件路径,转换失败返回null
  8660. */
  8661. private function convertImageFile($rawFile, $url) {
  8662. $content = @file_get_contents($rawFile);
  8663. if ($content === false || $content === '') return null;
  8664. if (!function_exists('imagecreatefromstring')) return null;
  8665. $image = @imagecreatefromstring($content);
  8666. if ($image === false) return null;
  8667. $jpeg = $this->compressImageForPdf($image, $rawFile, $url);
  8668. imagedestroy($image);
  8669. if ($jpeg !== null) {
  8670. @unlink($rawFile);
  8671. }
  8672. return $jpeg;
  8673. }
  8674. /**
  8675. * 图片压缩:白底合成后转JPEG,分级缩小尺寸与降低质量,保证每张不超过2MB
  8676. * @param resource $srcImage GD图片资源
  8677. * @param string $rawFile 原始图片临时文件
  8678. * @param string $url 图片地址(用于命名)
  8679. * @return string|null 压缩后的JPEG文件路径
  8680. */
  8681. private function compressImageForPdf($srcImage, $rawFile, $url) {
  8682. $maxBytes = 2 * 1024 * 1024; // 2MB
  8683. $sizes = [2048, 1600, 1280, 1024, 800];
  8684. $qualities = [85, 70, 55, 40];
  8685. $jpeg = dirname($rawFile) . '/anime_pdf_img_' . md5($url) . '.jpg';
  8686. foreach ($sizes as $size) {
  8687. $resized = $this->copyAndResize($srcImage, $size);
  8688. $flat = $this->flattenToWhite($resized);
  8689. imagedestroy($resized);
  8690. foreach ($qualities as $quality) {
  8691. ob_start();
  8692. $saved = imagejpeg($flat, null, $quality);
  8693. $data = ob_get_clean();
  8694. if ($saved && $data !== false && $data !== '' && strlen($data) <= $maxBytes) {
  8695. file_put_contents($jpeg, $data);
  8696. imagedestroy($flat);
  8697. dLog('anime')->info('导出PDF图片压缩完成', [
  8698. 'url' => $url,
  8699. 'size' => filesize($jpeg),
  8700. 'edge' => $size,
  8701. 'quality' => $quality,
  8702. ]);
  8703. return $jpeg;
  8704. }
  8705. }
  8706. imagedestroy($flat);
  8707. }
  8708. // 兜底:最小尺寸、最低质量强制输出
  8709. $resized = $this->copyAndResize($srcImage, 800);
  8710. $flat = $this->flattenToWhite($resized);
  8711. imagedestroy($resized);
  8712. $saved = imagejpeg($flat, $jpeg, 30);
  8713. imagedestroy($flat);
  8714. if (!$saved) return null;
  8715. dLog('anime')->info('导出PDF图片压缩完成(兜底)', [
  8716. 'url' => $url,
  8717. 'size' => filesize($jpeg),
  8718. ]);
  8719. return $jpeg;
  8720. }
  8721. /**
  8722. * 等比缩放图片副本(不销毁原图)
  8723. * @param resource $srcImage GD图片资源
  8724. * @param int $maxEdge 最大边长
  8725. * @return resource
  8726. */
  8727. private function copyAndResize($srcImage, $maxEdge) {
  8728. $width = imagesx($srcImage);
  8729. $height = imagesy($srcImage);
  8730. $max = max($width, $height);
  8731. if ($max <= $maxEdge) {
  8732. $copy = imagecreatetruecolor($width, $height);
  8733. imagecopy($copy, $srcImage, 0, 0, 0, 0, $width, $height);
  8734. return $copy;
  8735. }
  8736. $ratio = $maxEdge / $max;
  8737. $newWidth = max(1, (int)round($width * $ratio));
  8738. $newHeight = max(1, (int)round($height * $ratio));
  8739. $resized = imagecreatetruecolor($newWidth, $newHeight);
  8740. imagealphablending($resized, false);
  8741. imagesavealpha($resized, true);
  8742. imagecopyresampled($resized, $srcImage, 0, 0, 0, 0, $newWidth, $newHeight, $width, $height);
  8743. return $resized;
  8744. }
  8745. /**
  8746. * 将GD图片合成到白色背景上(处理透明通道,输出RGB)
  8747. * @param resource $image GD图片资源
  8748. * @return resource
  8749. */
  8750. private function flattenToWhite($image) {
  8751. $width = imagesx($image);
  8752. $height = imagesy($image);
  8753. $flat = imagecreatetruecolor($width, $height);
  8754. $white = imagecolorallocate($flat, 255, 255, 255);
  8755. imagefill($flat, 0, 0, $white);
  8756. imagecopy($flat, $image, 0, 0, 0, 0, $width, $height);
  8757. return $flat;
  8758. }
  8759. /**
  8760. * 将片段内容中的分镜序号按出现先后重新编号(保证整集连续)
  8761. * @param string $content 片段内容
  8762. * @param int $counter 当前已编号数量(引用传递,整集累计)
  8763. * @return string
  8764. */
  8765. private function renumberSegmentBlocks($content, &$counter) {
  8766. return preg_replace_callback('/^【(分镜|镜头)\d+】/mu', function ($match) use (&$counter) {
  8767. $counter++;
  8768. return '【' . $match[1] . $counter . '】';
  8769. }, $content);
  8770. }
  8771. }