DeepSeekService.php 728 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002100310041005100610071008100910101011101210131014101510161017101810191020102110221023102410251026102710281029103010311032103310341035103610371038103910401041104210431044104510461047104810491050105110521053105410551056105710581059106010611062106310641065106610671068106910701071107210731074107510761077107810791080108110821083108410851086108710881089109010911092109310941095109610971098109911001101110211031104110511061107110811091110111111121113111411151116111711181119112011211122112311241125112611271128112911301131113211331134113511361137113811391140114111421143114411451146114711481149115011511152115311541155115611571158115911601161116211631164116511661167116811691170117111721173117411751176117711781179118011811182118311841185118611871188118911901191119211931194119511961197119811991200120112021203120412051206120712081209121012111212121312141215121612171218121912201221122212231224122512261227122812291230123112321233123412351236123712381239124012411242124312441245124612471248124912501251125212531254125512561257125812591260126112621263126412651266126712681269127012711272127312741275127612771278127912801281128212831284128512861287128812891290129112921293129412951296129712981299130013011302130313041305130613071308130913101311131213131314131513161317131813191320132113221323132413251326132713281329133013311332133313341335133613371338133913401341134213431344134513461347134813491350135113521353135413551356135713581359136013611362136313641365136613671368136913701371137213731374137513761377137813791380138113821383138413851386138713881389139013911392139313941395139613971398139914001401140214031404140514061407140814091410141114121413141414151416141714181419142014211422142314241425142614271428142914301431143214331434143514361437143814391440144114421443144414451446144714481449145014511452145314541455145614571458145914601461146214631464146514661467146814691470147114721473147414751476147714781479148014811482148314841485148614871488148914901491149214931494149514961497149814991500150115021503150415051506150715081509151015111512151315141515151615171518151915201521152215231524152515261527152815291530153115321533153415351536153715381539154015411542154315441545154615471548154915501551155215531554155515561557155815591560156115621563156415651566156715681569157015711572157315741575157615771578157915801581158215831584158515861587158815891590159115921593159415951596159715981599160016011602160316041605160616071608160916101611161216131614161516161617161816191620162116221623162416251626162716281629163016311632163316341635163616371638163916401641164216431644164516461647164816491650165116521653165416551656165716581659166016611662166316641665166616671668166916701671167216731674167516761677167816791680168116821683168416851686168716881689169016911692169316941695169616971698169917001701170217031704170517061707170817091710171117121713171417151716171717181719172017211722172317241725172617271728172917301731173217331734173517361737173817391740174117421743174417451746174717481749175017511752175317541755175617571758175917601761176217631764176517661767176817691770177117721773177417751776177717781779178017811782178317841785178617871788178917901791179217931794179517961797179817991800180118021803180418051806180718081809181018111812181318141815181618171818181918201821182218231824182518261827182818291830183118321833183418351836183718381839184018411842184318441845184618471848184918501851185218531854185518561857185818591860186118621863186418651866186718681869187018711872187318741875187618771878187918801881188218831884188518861887188818891890189118921893189418951896189718981899190019011902190319041905190619071908190919101911191219131914191519161917191819191920192119221923192419251926192719281929193019311932193319341935193619371938193919401941194219431944194519461947194819491950195119521953195419551956195719581959196019611962196319641965196619671968196919701971197219731974197519761977197819791980198119821983198419851986198719881989199019911992199319941995199619971998199920002001200220032004200520062007200820092010201120122013201420152016201720182019202020212022202320242025202620272028202920302031203220332034203520362037203820392040204120422043204420452046204720482049205020512052205320542055205620572058205920602061206220632064206520662067206820692070207120722073207420752076207720782079208020812082208320842085208620872088208920902091209220932094209520962097209820992100210121022103210421052106210721082109211021112112211321142115211621172118211921202121212221232124212521262127212821292130213121322133213421352136213721382139214021412142214321442145214621472148214921502151215221532154215521562157215821592160216121622163216421652166216721682169217021712172217321742175217621772178217921802181218221832184218521862187218821892190219121922193219421952196219721982199220022012202220322042205220622072208220922102211221222132214221522162217221822192220222122222223222422252226222722282229223022312232223322342235223622372238223922402241224222432244224522462247224822492250225122522253225422552256225722582259226022612262226322642265226622672268226922702271227222732274227522762277227822792280228122822283228422852286228722882289229022912292229322942295229622972298229923002301230223032304230523062307230823092310231123122313231423152316231723182319232023212322232323242325232623272328232923302331233223332334233523362337233823392340234123422343234423452346234723482349235023512352235323542355235623572358235923602361236223632364236523662367236823692370237123722373237423752376237723782379238023812382238323842385238623872388238923902391239223932394239523962397239823992400240124022403240424052406240724082409241024112412241324142415241624172418241924202421242224232424242524262427242824292430243124322433243424352436243724382439244024412442244324442445244624472448244924502451245224532454245524562457245824592460246124622463246424652466246724682469247024712472247324742475247624772478247924802481248224832484248524862487248824892490249124922493249424952496249724982499250025012502250325042505250625072508250925102511251225132514251525162517251825192520252125222523252425252526252725282529253025312532253325342535253625372538253925402541254225432544254525462547254825492550255125522553255425552556255725582559256025612562256325642565256625672568256925702571257225732574257525762577257825792580258125822583258425852586258725882589259025912592259325942595259625972598259926002601260226032604260526062607260826092610261126122613261426152616261726182619262026212622262326242625262626272628262926302631263226332634263526362637263826392640264126422643264426452646264726482649265026512652265326542655265626572658265926602661266226632664266526662667266826692670267126722673267426752676267726782679268026812682268326842685268626872688268926902691269226932694269526962697269826992700270127022703270427052706270727082709271027112712271327142715271627172718271927202721272227232724272527262727272827292730273127322733273427352736273727382739274027412742274327442745274627472748274927502751275227532754275527562757275827592760276127622763276427652766276727682769277027712772277327742775277627772778277927802781278227832784278527862787278827892790279127922793279427952796279727982799280028012802280328042805280628072808280928102811281228132814281528162817281828192820282128222823282428252826282728282829283028312832283328342835283628372838283928402841284228432844284528462847284828492850285128522853285428552856285728582859286028612862286328642865286628672868286928702871287228732874287528762877287828792880288128822883288428852886288728882889289028912892289328942895289628972898289929002901290229032904290529062907290829092910291129122913291429152916291729182919292029212922292329242925292629272928292929302931293229332934293529362937293829392940294129422943294429452946294729482949295029512952295329542955295629572958295929602961296229632964296529662967296829692970297129722973297429752976297729782979298029812982298329842985298629872988298929902991299229932994299529962997299829993000300130023003300430053006300730083009301030113012301330143015301630173018301930203021302230233024302530263027302830293030303130323033303430353036303730383039304030413042304330443045304630473048304930503051305230533054305530563057305830593060306130623063306430653066306730683069307030713072307330743075307630773078307930803081308230833084308530863087308830893090309130923093309430953096309730983099310031013102310331043105310631073108310931103111311231133114311531163117311831193120312131223123312431253126312731283129313031313132313331343135313631373138313931403141314231433144314531463147314831493150315131523153315431553156315731583159316031613162316331643165316631673168316931703171317231733174317531763177317831793180318131823183318431853186318731883189319031913192319331943195319631973198319932003201320232033204320532063207320832093210321132123213321432153216321732183219322032213222322332243225322632273228322932303231323232333234323532363237323832393240324132423243324432453246324732483249325032513252325332543255325632573258325932603261326232633264326532663267326832693270327132723273327432753276327732783279328032813282328332843285328632873288328932903291329232933294329532963297329832993300330133023303330433053306330733083309331033113312331333143315331633173318331933203321332233233324332533263327332833293330333133323333333433353336333733383339334033413342334333443345334633473348334933503351335233533354335533563357335833593360336133623363336433653366336733683369337033713372337333743375337633773378337933803381338233833384338533863387338833893390339133923393339433953396339733983399340034013402340334043405340634073408340934103411341234133414341534163417341834193420342134223423342434253426342734283429343034313432343334343435343634373438343934403441344234433444344534463447344834493450345134523453345434553456345734583459346034613462346334643465346634673468346934703471347234733474347534763477347834793480348134823483348434853486348734883489349034913492349334943495349634973498349935003501350235033504350535063507350835093510351135123513351435153516351735183519352035213522352335243525352635273528352935303531353235333534353535363537353835393540354135423543354435453546354735483549355035513552355335543555355635573558355935603561356235633564356535663567356835693570357135723573357435753576357735783579358035813582358335843585358635873588358935903591359235933594359535963597359835993600360136023603360436053606360736083609361036113612361336143615361636173618361936203621362236233624362536263627362836293630363136323633363436353636363736383639364036413642364336443645364636473648364936503651365236533654365536563657365836593660366136623663366436653666366736683669367036713672367336743675367636773678367936803681368236833684368536863687368836893690369136923693369436953696369736983699370037013702370337043705370637073708370937103711371237133714371537163717371837193720372137223723372437253726372737283729373037313732373337343735373637373738373937403741374237433744374537463747374837493750375137523753375437553756375737583759376037613762376337643765376637673768376937703771377237733774377537763777377837793780378137823783378437853786378737883789379037913792379337943795379637973798379938003801380238033804380538063807380838093810381138123813381438153816381738183819382038213822382338243825382638273828382938303831383238333834383538363837383838393840384138423843384438453846384738483849385038513852385338543855385638573858385938603861386238633864386538663867386838693870387138723873387438753876387738783879388038813882388338843885388638873888388938903891389238933894389538963897389838993900390139023903390439053906390739083909391039113912391339143915391639173918391939203921392239233924392539263927392839293930393139323933393439353936393739383939394039413942394339443945394639473948394939503951395239533954395539563957395839593960396139623963396439653966396739683969397039713972397339743975397639773978397939803981398239833984398539863987398839893990399139923993399439953996399739983999400040014002400340044005400640074008400940104011401240134014401540164017401840194020402140224023402440254026402740284029403040314032403340344035403640374038403940404041404240434044404540464047404840494050405140524053405440554056405740584059406040614062406340644065406640674068406940704071407240734074407540764077407840794080408140824083408440854086408740884089409040914092409340944095409640974098409941004101410241034104410541064107410841094110411141124113411441154116411741184119412041214122412341244125412641274128412941304131413241334134413541364137413841394140414141424143414441454146414741484149415041514152415341544155415641574158415941604161416241634164416541664167416841694170417141724173417441754176417741784179418041814182418341844185418641874188418941904191419241934194419541964197419841994200420142024203420442054206420742084209421042114212421342144215421642174218421942204221422242234224422542264227422842294230423142324233423442354236423742384239424042414242424342444245424642474248424942504251425242534254425542564257425842594260426142624263426442654266426742684269427042714272427342744275427642774278427942804281428242834284428542864287428842894290429142924293429442954296429742984299430043014302430343044305430643074308430943104311431243134314431543164317431843194320432143224323432443254326432743284329433043314332433343344335433643374338433943404341434243434344434543464347434843494350435143524353435443554356435743584359436043614362436343644365436643674368436943704371437243734374437543764377437843794380438143824383438443854386438743884389439043914392439343944395439643974398439944004401440244034404440544064407440844094410441144124413441444154416441744184419442044214422442344244425442644274428442944304431443244334434443544364437443844394440444144424443444444454446444744484449445044514452445344544455445644574458445944604461446244634464446544664467446844694470447144724473447444754476447744784479448044814482448344844485448644874488448944904491449244934494449544964497449844994500450145024503450445054506450745084509451045114512451345144515451645174518451945204521452245234524452545264527452845294530453145324533453445354536453745384539454045414542454345444545454645474548454945504551455245534554455545564557455845594560456145624563456445654566456745684569457045714572457345744575457645774578457945804581458245834584458545864587458845894590459145924593459445954596459745984599460046014602460346044605460646074608460946104611461246134614461546164617461846194620462146224623462446254626462746284629463046314632463346344635463646374638463946404641464246434644464546464647464846494650465146524653465446554656465746584659466046614662466346644665466646674668466946704671467246734674467546764677467846794680468146824683468446854686468746884689469046914692469346944695469646974698469947004701470247034704470547064707470847094710471147124713471447154716471747184719472047214722472347244725472647274728472947304731473247334734473547364737473847394740474147424743474447454746474747484749475047514752475347544755475647574758475947604761476247634764476547664767476847694770477147724773477447754776477747784779478047814782478347844785478647874788478947904791479247934794479547964797479847994800480148024803480448054806480748084809481048114812481348144815481648174818481948204821482248234824482548264827482848294830483148324833483448354836483748384839484048414842484348444845484648474848484948504851485248534854485548564857485848594860486148624863486448654866486748684869487048714872487348744875487648774878487948804881488248834884488548864887488848894890489148924893489448954896489748984899490049014902490349044905490649074908490949104911491249134914491549164917491849194920492149224923492449254926492749284929493049314932493349344935493649374938493949404941494249434944494549464947494849494950495149524953495449554956495749584959496049614962496349644965496649674968496949704971497249734974497549764977497849794980498149824983498449854986498749884989499049914992499349944995499649974998499950005001500250035004500550065007500850095010501150125013501450155016501750185019502050215022502350245025502650275028502950305031503250335034503550365037503850395040504150425043504450455046504750485049505050515052505350545055505650575058505950605061506250635064506550665067506850695070507150725073507450755076507750785079508050815082508350845085508650875088508950905091509250935094509550965097509850995100510151025103510451055106510751085109511051115112511351145115511651175118511951205121512251235124512551265127512851295130513151325133513451355136513751385139514051415142514351445145514651475148514951505151515251535154515551565157515851595160516151625163516451655166516751685169517051715172517351745175517651775178517951805181518251835184518551865187518851895190519151925193519451955196519751985199520052015202520352045205520652075208520952105211521252135214521552165217521852195220522152225223522452255226522752285229523052315232523352345235523652375238523952405241524252435244524552465247524852495250525152525253525452555256525752585259526052615262526352645265526652675268526952705271527252735274527552765277527852795280528152825283528452855286528752885289529052915292529352945295529652975298529953005301530253035304530553065307530853095310531153125313531453155316531753185319532053215322532353245325532653275328532953305331533253335334533553365337533853395340534153425343534453455346534753485349535053515352535353545355535653575358535953605361536253635364536553665367536853695370537153725373537453755376537753785379538053815382538353845385538653875388538953905391539253935394539553965397539853995400540154025403540454055406540754085409541054115412541354145415541654175418541954205421542254235424542554265427542854295430543154325433543454355436543754385439544054415442544354445445544654475448544954505451545254535454545554565457545854595460546154625463546454655466546754685469547054715472547354745475547654775478547954805481548254835484548554865487548854895490549154925493549454955496549754985499550055015502550355045505550655075508550955105511551255135514551555165517551855195520552155225523552455255526552755285529553055315532553355345535553655375538553955405541554255435544554555465547554855495550555155525553555455555556555755585559556055615562556355645565556655675568556955705571557255735574557555765577557855795580558155825583558455855586558755885589559055915592559355945595559655975598559956005601560256035604560556065607560856095610561156125613561456155616561756185619562056215622562356245625562656275628562956305631563256335634563556365637563856395640564156425643564456455646564756485649565056515652565356545655565656575658565956605661566256635664566556665667566856695670567156725673567456755676567756785679568056815682568356845685568656875688568956905691569256935694569556965697569856995700570157025703570457055706570757085709571057115712571357145715571657175718571957205721572257235724572557265727572857295730573157325733573457355736573757385739574057415742574357445745574657475748574957505751575257535754575557565757575857595760576157625763576457655766576757685769577057715772577357745775577657775778577957805781578257835784578557865787578857895790579157925793579457955796579757985799580058015802580358045805580658075808580958105811581258135814581558165817581858195820582158225823582458255826582758285829583058315832583358345835583658375838583958405841584258435844584558465847584858495850585158525853585458555856585758585859586058615862586358645865586658675868586958705871587258735874587558765877587858795880588158825883588458855886588758885889589058915892589358945895589658975898589959005901590259035904590559065907590859095910591159125913591459155916591759185919592059215922592359245925592659275928592959305931593259335934593559365937593859395940594159425943594459455946594759485949595059515952595359545955595659575958595959605961596259635964596559665967596859695970597159725973597459755976597759785979598059815982598359845985598659875988598959905991599259935994599559965997599859996000600160026003600460056006600760086009601060116012601360146015601660176018601960206021602260236024602560266027602860296030603160326033603460356036603760386039604060416042604360446045604660476048604960506051605260536054605560566057605860596060606160626063606460656066606760686069607060716072607360746075607660776078607960806081608260836084608560866087608860896090609160926093609460956096609760986099610061016102610361046105610661076108610961106111611261136114611561166117611861196120612161226123612461256126612761286129613061316132613361346135613661376138613961406141614261436144614561466147614861496150615161526153615461556156615761586159616061616162616361646165616661676168616961706171617261736174617561766177617861796180618161826183618461856186618761886189619061916192619361946195619661976198619962006201620262036204620562066207620862096210621162126213621462156216621762186219622062216222622362246225622662276228622962306231623262336234623562366237623862396240624162426243624462456246624762486249625062516252625362546255625662576258625962606261626262636264626562666267626862696270627162726273627462756276627762786279628062816282628362846285628662876288628962906291629262936294629562966297629862996300630163026303630463056306630763086309631063116312631363146315631663176318631963206321632263236324632563266327632863296330633163326333633463356336633763386339634063416342634363446345634663476348634963506351635263536354635563566357635863596360636163626363636463656366636763686369637063716372637363746375637663776378637963806381638263836384638563866387638863896390639163926393639463956396639763986399640064016402640364046405640664076408640964106411641264136414641564166417641864196420642164226423642464256426642764286429643064316432643364346435643664376438643964406441644264436444644564466447644864496450645164526453645464556456645764586459646064616462646364646465646664676468646964706471647264736474647564766477647864796480648164826483648464856486648764886489649064916492649364946495649664976498649965006501650265036504650565066507650865096510651165126513651465156516651765186519652065216522652365246525652665276528652965306531653265336534653565366537653865396540654165426543654465456546654765486549655065516552655365546555655665576558655965606561656265636564656565666567656865696570657165726573657465756576657765786579658065816582658365846585658665876588658965906591659265936594659565966597659865996600660166026603660466056606660766086609661066116612661366146615661666176618661966206621662266236624662566266627662866296630663166326633663466356636663766386639664066416642664366446645664666476648664966506651665266536654665566566657665866596660666166626663666466656666666766686669667066716672667366746675667666776678667966806681668266836684668566866687668866896690669166926693669466956696669766986699670067016702670367046705670667076708670967106711671267136714671567166717671867196720672167226723672467256726672767286729673067316732673367346735673667376738673967406741674267436744674567466747674867496750675167526753675467556756675767586759676067616762676367646765676667676768676967706771677267736774677567766777677867796780678167826783678467856786678767886789679067916792679367946795679667976798679968006801680268036804680568066807680868096810681168126813681468156816681768186819682068216822682368246825682668276828682968306831683268336834683568366837683868396840684168426843684468456846684768486849685068516852685368546855685668576858685968606861686268636864686568666867686868696870687168726873687468756876687768786879688068816882688368846885688668876888688968906891689268936894689568966897689868996900690169026903690469056906690769086909691069116912691369146915691669176918691969206921692269236924692569266927692869296930693169326933693469356936693769386939694069416942694369446945694669476948694969506951695269536954695569566957695869596960696169626963696469656966696769686969697069716972697369746975697669776978697969806981698269836984698569866987698869896990699169926993699469956996699769986999700070017002700370047005700670077008700970107011701270137014701570167017701870197020702170227023702470257026702770287029703070317032703370347035703670377038703970407041704270437044704570467047704870497050705170527053705470557056705770587059706070617062706370647065706670677068706970707071707270737074707570767077707870797080708170827083708470857086708770887089709070917092709370947095709670977098709971007101710271037104710571067107710871097110711171127113711471157116711771187119712071217122712371247125712671277128712971307131713271337134713571367137713871397140714171427143714471457146714771487149715071517152715371547155715671577158715971607161716271637164716571667167716871697170717171727173717471757176717771787179718071817182718371847185718671877188718971907191719271937194719571967197719871997200720172027203720472057206720772087209721072117212721372147215721672177218721972207221722272237224722572267227722872297230723172327233723472357236723772387239724072417242724372447245724672477248724972507251725272537254725572567257725872597260726172627263726472657266726772687269727072717272727372747275727672777278727972807281728272837284728572867287728872897290729172927293729472957296729772987299730073017302730373047305730673077308730973107311731273137314731573167317731873197320732173227323732473257326732773287329733073317332733373347335733673377338733973407341734273437344734573467347734873497350735173527353735473557356735773587359736073617362736373647365736673677368736973707371737273737374737573767377737873797380738173827383738473857386738773887389739073917392739373947395739673977398739974007401740274037404740574067407740874097410741174127413741474157416741774187419742074217422742374247425742674277428742974307431743274337434743574367437743874397440744174427443744474457446744774487449745074517452745374547455745674577458745974607461746274637464746574667467746874697470747174727473747474757476747774787479748074817482748374847485748674877488748974907491749274937494749574967497749874997500750175027503750475057506750775087509751075117512751375147515751675177518751975207521752275237524752575267527752875297530753175327533753475357536753775387539754075417542754375447545754675477548754975507551755275537554755575567557755875597560756175627563756475657566756775687569757075717572757375747575757675777578757975807581758275837584758575867587758875897590759175927593759475957596759775987599760076017602760376047605760676077608760976107611761276137614761576167617761876197620762176227623762476257626762776287629763076317632763376347635763676377638763976407641764276437644764576467647764876497650765176527653765476557656765776587659766076617662766376647665766676677668766976707671767276737674767576767677767876797680768176827683768476857686768776887689769076917692769376947695769676977698769977007701770277037704770577067707770877097710771177127713771477157716771777187719772077217722772377247725772677277728772977307731773277337734773577367737773877397740774177427743774477457746774777487749775077517752775377547755775677577758775977607761776277637764776577667767776877697770777177727773777477757776777777787779778077817782778377847785778677877788778977907791779277937794779577967797779877997800780178027803780478057806780778087809781078117812781378147815781678177818781978207821782278237824782578267827782878297830783178327833783478357836783778387839784078417842784378447845784678477848784978507851785278537854785578567857785878597860786178627863786478657866786778687869787078717872787378747875787678777878787978807881788278837884788578867887788878897890789178927893789478957896789778987899790079017902790379047905790679077908790979107911791279137914791579167917791879197920792179227923792479257926792779287929793079317932793379347935793679377938793979407941794279437944794579467947794879497950795179527953795479557956795779587959796079617962796379647965796679677968796979707971797279737974797579767977797879797980798179827983798479857986798779887989799079917992799379947995799679977998799980008001800280038004800580068007800880098010801180128013801480158016801780188019802080218022802380248025802680278028802980308031803280338034803580368037803880398040804180428043804480458046804780488049805080518052805380548055805680578058805980608061806280638064806580668067806880698070807180728073807480758076807780788079808080818082808380848085808680878088808980908091809280938094809580968097809880998100810181028103810481058106810781088109811081118112811381148115811681178118811981208121812281238124812581268127812881298130813181328133813481358136813781388139814081418142814381448145814681478148814981508151815281538154815581568157815881598160816181628163816481658166816781688169817081718172817381748175817681778178817981808181818281838184818581868187818881898190819181928193819481958196819781988199820082018202820382048205820682078208820982108211821282138214821582168217821882198220822182228223822482258226822782288229823082318232823382348235823682378238823982408241824282438244824582468247824882498250825182528253825482558256825782588259826082618262826382648265826682678268826982708271827282738274827582768277827882798280828182828283828482858286828782888289829082918292829382948295829682978298829983008301830283038304830583068307830883098310831183128313831483158316831783188319832083218322832383248325832683278328832983308331833283338334833583368337833883398340834183428343834483458346834783488349835083518352835383548355835683578358835983608361836283638364836583668367836883698370837183728373837483758376837783788379838083818382838383848385838683878388838983908391839283938394839583968397839883998400840184028403840484058406840784088409841084118412841384148415841684178418841984208421842284238424842584268427842884298430843184328433843484358436843784388439844084418442844384448445844684478448844984508451845284538454845584568457845884598460846184628463846484658466846784688469847084718472847384748475847684778478847984808481848284838484848584868487848884898490849184928493849484958496849784988499850085018502850385048505850685078508850985108511851285138514851585168517851885198520852185228523852485258526852785288529853085318532853385348535853685378538853985408541854285438544854585468547854885498550855185528553855485558556855785588559856085618562856385648565856685678568856985708571857285738574857585768577857885798580858185828583858485858586858785888589859085918592859385948595859685978598859986008601860286038604860586068607860886098610861186128613861486158616861786188619862086218622862386248625862686278628862986308631863286338634863586368637863886398640864186428643864486458646864786488649865086518652865386548655865686578658865986608661866286638664866586668667866886698670867186728673867486758676867786788679868086818682868386848685868686878688868986908691869286938694869586968697869886998700870187028703870487058706870787088709871087118712871387148715871687178718871987208721872287238724872587268727872887298730873187328733873487358736873787388739874087418742874387448745874687478748874987508751875287538754875587568757875887598760876187628763876487658766876787688769877087718772877387748775877687778778877987808781878287838784878587868787878887898790879187928793879487958796879787988799880088018802880388048805880688078808880988108811881288138814881588168817881888198820882188228823882488258826882788288829883088318832883388348835883688378838883988408841884288438844884588468847884888498850885188528853885488558856885788588859886088618862886388648865886688678868886988708871887288738874887588768877887888798880888188828883888488858886888788888889889088918892889388948895889688978898889989008901890289038904890589068907890889098910891189128913891489158916891789188919892089218922892389248925892689278928892989308931893289338934893589368937893889398940894189428943894489458946894789488949895089518952895389548955895689578958895989608961896289638964896589668967896889698970897189728973897489758976897789788979898089818982898389848985898689878988898989908991899289938994899589968997899889999000900190029003900490059006900790089009901090119012901390149015901690179018901990209021902290239024902590269027902890299030903190329033903490359036903790389039904090419042904390449045904690479048904990509051905290539054905590569057905890599060906190629063906490659066906790689069907090719072907390749075907690779078907990809081908290839084908590869087908890899090909190929093909490959096909790989099910091019102910391049105910691079108910991109111911291139114911591169117911891199120912191229123912491259126912791289129913091319132913391349135913691379138913991409141914291439144914591469147914891499150915191529153915491559156915791589159916091619162916391649165916691679168916991709171917291739174917591769177917891799180918191829183918491859186918791889189919091919192919391949195919691979198919992009201920292039204920592069207920892099210921192129213921492159216921792189219922092219222922392249225922692279228922992309231923292339234923592369237923892399240924192429243924492459246924792489249925092519252925392549255925692579258925992609261926292639264926592669267926892699270927192729273927492759276927792789279928092819282928392849285928692879288928992909291929292939294929592969297929892999300930193029303930493059306930793089309931093119312931393149315931693179318931993209321932293239324932593269327932893299330933193329333933493359336933793389339934093419342934393449345934693479348934993509351935293539354935593569357935893599360936193629363936493659366936793689369937093719372937393749375937693779378937993809381938293839384938593869387938893899390939193929393939493959396939793989399940094019402940394049405940694079408940994109411941294139414941594169417941894199420942194229423942494259426942794289429943094319432943394349435943694379438943994409441944294439444944594469447944894499450945194529453945494559456945794589459946094619462946394649465946694679468946994709471947294739474947594769477947894799480948194829483948494859486948794889489949094919492949394949495949694979498949995009501950295039504950595069507950895099510951195129513951495159516951795189519952095219522952395249525952695279528952995309531953295339534953595369537953895399540954195429543954495459546954795489549955095519552955395549555955695579558955995609561956295639564956595669567956895699570957195729573957495759576957795789579958095819582958395849585958695879588958995909591959295939594959595969597959895999600960196029603960496059606960796089609961096119612961396149615961696179618961996209621962296239624962596269627962896299630963196329633963496359636963796389639964096419642964396449645964696479648964996509651965296539654965596569657965896599660966196629663966496659666966796689669967096719672967396749675967696779678967996809681968296839684968596869687968896899690969196929693969496959696969796989699970097019702970397049705970697079708970997109711971297139714971597169717971897199720972197229723972497259726972797289729973097319732973397349735973697379738973997409741974297439744974597469747974897499750975197529753975497559756975797589759976097619762976397649765976697679768976997709771977297739774977597769777977897799780978197829783978497859786978797889789979097919792979397949795979697979798979998009801980298039804980598069807980898099810981198129813981498159816981798189819982098219822982398249825982698279828982998309831983298339834983598369837983898399840984198429843984498459846984798489849985098519852985398549855985698579858985998609861986298639864986598669867986898699870987198729873987498759876987798789879988098819882988398849885988698879888988998909891989298939894989598969897989898999900990199029903990499059906990799089909991099119912991399149915991699179918991999209921992299239924992599269927992899299930993199329933993499359936993799389939994099419942994399449945994699479948994999509951995299539954995599569957995899599960996199629963996499659966996799689969997099719972997399749975997699779978997999809981998299839984998599869987998899899990999199929993999499959996999799989999100001000110002100031000410005100061000710008100091001010011100121001310014100151001610017100181001910020100211002210023100241002510026100271002810029100301003110032100331003410035100361003710038100391004010041100421004310044100451004610047100481004910050100511005210053100541005510056100571005810059100601006110062100631006410065100661006710068100691007010071100721007310074100751007610077100781007910080100811008210083100841008510086100871008810089100901009110092100931009410095100961009710098100991010010101101021010310104101051010610107101081010910110101111011210113101141011510116101171011810119101201012110122101231012410125101261012710128101291013010131101321013310134101351013610137101381013910140101411014210143101441014510146101471014810149101501015110152101531015410155101561015710158101591016010161101621016310164101651016610167101681016910170101711017210173101741017510176101771017810179101801018110182101831018410185101861018710188101891019010191101921019310194101951019610197101981019910200102011020210203102041020510206102071020810209102101021110212102131021410215102161021710218102191022010221102221022310224102251022610227102281022910230102311023210233102341023510236102371023810239102401024110242102431024410245102461024710248102491025010251102521025310254102551025610257102581025910260102611026210263102641026510266102671026810269102701027110272102731027410275102761027710278102791028010281102821028310284102851028610287102881028910290102911029210293102941029510296102971029810299103001030110302103031030410305103061030710308103091031010311103121031310314103151031610317103181031910320103211032210323103241032510326103271032810329103301033110332103331033410335103361033710338103391034010341103421034310344103451034610347103481034910350103511035210353103541035510356103571035810359103601036110362103631036410365103661036710368103691037010371103721037310374103751037610377103781037910380103811038210383103841038510386103871038810389103901039110392103931039410395103961039710398103991040010401104021040310404104051040610407104081040910410104111041210413104141041510416104171041810419104201042110422104231042410425104261042710428104291043010431104321043310434104351043610437104381043910440104411044210443104441044510446104471044810449104501045110452104531045410455104561045710458104591046010461104621046310464104651046610467104681046910470104711047210473104741047510476104771047810479104801048110482104831048410485104861048710488104891049010491104921049310494104951049610497104981049910500105011050210503105041050510506105071050810509105101051110512105131051410515105161051710518105191052010521105221052310524105251052610527105281052910530105311053210533105341053510536105371053810539105401054110542105431054410545105461054710548105491055010551105521055310554105551055610557105581055910560105611056210563105641056510566105671056810569105701057110572105731057410575105761057710578105791058010581105821058310584105851058610587105881058910590105911059210593105941059510596105971059810599106001060110602106031060410605106061060710608106091061010611106121061310614106151061610617106181061910620106211062210623106241062510626106271062810629106301063110632106331063410635106361063710638106391064010641106421064310644106451064610647106481064910650106511065210653106541065510656106571065810659106601066110662106631066410665106661066710668106691067010671106721067310674106751067610677106781067910680106811068210683106841068510686106871068810689106901069110692106931069410695106961069710698106991070010701107021070310704107051070610707107081070910710107111071210713107141071510716107171071810719107201072110722107231072410725107261072710728107291073010731107321073310734107351073610737107381073910740107411074210743107441074510746107471074810749107501075110752107531075410755107561075710758107591076010761107621076310764107651076610767107681076910770107711077210773107741077510776107771077810779107801078110782107831078410785107861078710788107891079010791107921079310794107951079610797107981079910800108011080210803108041080510806108071080810809108101081110812108131081410815108161081710818108191082010821108221082310824108251082610827108281082910830108311083210833108341083510836108371083810839108401084110842108431084410845108461084710848108491085010851108521085310854108551085610857108581085910860108611086210863108641086510866108671086810869108701087110872108731087410875108761087710878108791088010881108821088310884108851088610887108881088910890108911089210893108941089510896108971089810899109001090110902109031090410905109061090710908109091091010911109121091310914109151091610917109181091910920109211092210923109241092510926109271092810929109301093110932109331093410935109361093710938109391094010941109421094310944109451094610947109481094910950109511095210953109541095510956109571095810959109601096110962109631096410965109661096710968109691097010971109721097310974109751097610977109781097910980109811098210983109841098510986109871098810989109901099110992109931099410995109961099710998109991100011001110021100311004110051100611007110081100911010110111101211013110141101511016110171101811019110201102111022110231102411025110261102711028110291103011031110321103311034110351103611037110381103911040110411104211043110441104511046110471104811049110501105111052110531105411055110561105711058110591106011061110621106311064110651106611067110681106911070110711107211073110741107511076110771107811079110801108111082110831108411085110861108711088110891109011091110921109311094110951109611097110981109911100111011110211103111041110511106111071110811109111101111111112111131111411115111161111711118111191112011121111221112311124111251112611127111281112911130111311113211133111341113511136111371113811139111401114111142111431114411145111461114711148111491115011151111521115311154111551115611157111581115911160111611116211163111641116511166111671116811169111701117111172111731117411175111761117711178111791118011181111821118311184111851118611187111881118911190111911119211193111941119511196111971119811199112001120111202112031120411205112061120711208112091121011211112121121311214112151121611217112181121911220112211122211223112241122511226112271122811229112301123111232112331123411235112361123711238112391124011241112421124311244112451124611247112481124911250112511125211253112541125511256112571125811259112601126111262112631126411265112661126711268112691127011271112721127311274112751127611277112781127911280112811128211283112841128511286112871128811289112901129111292112931129411295112961129711298112991130011301113021130311304113051130611307113081130911310113111131211313113141131511316113171131811319113201132111322113231132411325113261132711328113291133011331113321133311334113351133611337113381133911340113411134211343113441134511346113471134811349113501135111352113531135411355113561135711358113591136011361113621136311364113651136611367113681136911370113711137211373113741137511376113771137811379113801138111382113831138411385113861138711388113891139011391113921139311394113951139611397113981139911400114011140211403114041140511406114071140811409114101141111412114131141411415114161141711418114191142011421114221142311424114251142611427114281142911430114311143211433114341143511436114371143811439114401144111442114431144411445114461144711448114491145011451114521145311454114551145611457114581145911460114611146211463114641146511466114671146811469114701147111472114731147411475114761147711478114791148011481114821148311484114851148611487114881148911490114911149211493114941149511496114971149811499115001150111502115031150411505115061150711508115091151011511115121151311514115151151611517115181151911520115211152211523115241152511526115271152811529115301153111532115331153411535115361153711538115391154011541115421154311544115451154611547115481154911550115511155211553115541155511556115571155811559115601156111562115631156411565115661156711568115691157011571115721157311574115751157611577115781157911580115811158211583115841158511586115871158811589115901159111592115931159411595115961159711598115991160011601116021160311604116051160611607116081160911610116111161211613116141161511616116171161811619116201162111622116231162411625116261162711628116291163011631116321163311634116351163611637116381163911640116411164211643116441164511646116471164811649116501165111652116531165411655116561165711658116591166011661116621166311664116651166611667116681166911670116711167211673116741167511676116771167811679116801168111682116831168411685116861168711688116891169011691116921169311694116951169611697116981169911700117011170211703117041170511706117071170811709117101171111712117131171411715117161171711718117191172011721117221172311724117251172611727117281172911730117311173211733117341173511736117371173811739117401174111742117431174411745117461174711748117491175011751117521175311754117551175611757117581175911760117611176211763117641176511766117671176811769117701177111772117731177411775117761177711778117791178011781117821178311784117851178611787117881178911790117911179211793117941179511796117971179811799118001180111802118031180411805118061180711808118091181011811118121181311814118151181611817118181181911820118211182211823118241182511826118271182811829118301183111832118331183411835118361183711838118391184011841118421184311844118451184611847118481184911850118511185211853118541185511856118571185811859118601186111862118631186411865118661186711868118691187011871118721187311874118751187611877118781187911880118811188211883118841188511886118871188811889118901189111892118931189411895118961189711898118991190011901119021190311904119051190611907119081190911910119111191211913119141191511916119171191811919119201192111922119231192411925119261192711928119291193011931119321193311934119351193611937119381193911940119411194211943119441194511946119471194811949119501195111952119531195411955119561195711958119591196011961119621196311964119651196611967119681196911970119711197211973119741197511976119771197811979119801198111982119831198411985119861198711988119891199011991119921199311994119951199611997119981199912000120011200212003120041200512006120071200812009120101201112012120131201412015120161201712018120191202012021120221202312024120251202612027120281202912030120311203212033120341203512036120371203812039120401204112042120431204412045120461204712048120491205012051120521205312054120551205612057120581205912060120611206212063120641206512066120671206812069120701207112072120731207412075120761207712078120791208012081120821208312084120851208612087120881208912090120911209212093120941209512096120971209812099121001210112102121031210412105121061210712108121091211012111121121211312114121151211612117121181211912120121211212212123121241212512126121271212812129121301213112132121331213412135121361213712138121391214012141121421214312144121451214612147121481214912150121511215212153121541215512156121571215812159121601216112162121631216412165121661216712168121691217012171121721217312174121751217612177121781217912180121811218212183121841218512186121871218812189121901219112192121931219412195121961219712198121991220012201122021220312204122051220612207122081220912210122111221212213122141221512216122171221812219122201222112222122231222412225122261222712228122291223012231122321223312234122351223612237122381223912240122411224212243122441224512246122471224812249122501225112252122531225412255122561225712258122591226012261122621226312264122651226612267122681226912270122711227212273122741227512276122771227812279122801228112282122831228412285122861228712288122891229012291122921229312294122951229612297122981229912300123011230212303123041230512306123071230812309123101231112312123131231412315123161231712318123191232012321123221232312324123251232612327123281232912330123311233212333123341233512336123371233812339123401234112342123431234412345123461234712348123491235012351123521235312354123551235612357123581235912360123611236212363123641236512366123671236812369123701237112372123731237412375123761237712378123791238012381123821238312384123851238612387123881238912390123911239212393123941239512396123971239812399124001240112402124031240412405124061240712408124091241012411124121241312414124151241612417124181241912420124211242212423124241242512426124271242812429124301243112432124331243412435124361243712438124391244012441124421244312444124451244612447124481244912450124511245212453124541245512456124571245812459124601246112462124631246412465124661246712468124691247012471124721247312474124751247612477124781247912480124811248212483124841248512486124871248812489124901249112492124931249412495124961249712498124991250012501125021250312504125051250612507125081250912510125111251212513125141251512516125171251812519125201252112522125231252412525125261252712528125291253012531125321253312534125351253612537125381253912540125411254212543125441254512546125471254812549125501255112552125531255412555125561255712558125591256012561125621256312564125651256612567125681256912570125711257212573125741257512576125771257812579125801258112582125831258412585125861258712588125891259012591125921259312594125951259612597125981259912600126011260212603126041260512606126071260812609126101261112612126131261412615126161261712618126191262012621126221262312624126251262612627126281262912630126311263212633126341263512636126371263812639126401264112642126431264412645126461264712648126491265012651126521265312654126551265612657126581265912660126611266212663126641266512666126671266812669126701267112672126731267412675126761267712678126791268012681126821268312684126851268612687126881268912690126911269212693126941269512696126971269812699127001270112702127031270412705127061270712708127091271012711127121271312714127151271612717127181271912720127211272212723127241272512726127271272812729127301273112732127331273412735127361273712738127391274012741127421274312744127451274612747127481274912750127511275212753127541275512756127571275812759127601276112762127631276412765127661276712768127691277012771127721277312774127751277612777127781277912780127811278212783127841278512786127871278812789127901279112792127931279412795127961279712798127991280012801128021280312804128051280612807128081280912810128111281212813128141281512816128171281812819128201282112822128231282412825128261282712828128291283012831128321283312834128351283612837128381283912840128411284212843128441284512846128471284812849128501285112852128531285412855128561285712858128591286012861128621286312864128651286612867128681286912870128711287212873128741287512876128771287812879128801288112882128831288412885128861288712888128891289012891128921289312894128951289612897128981289912900129011290212903129041290512906129071290812909129101291112912129131291412915129161291712918129191292012921129221292312924129251292612927129281292912930129311293212933129341293512936129371293812939129401294112942129431294412945129461294712948129491295012951129521295312954129551295612957129581295912960129611296212963129641296512966129671296812969129701297112972129731297412975129761297712978129791298012981129821298312984129851298612987129881298912990129911299212993129941299512996129971299812999130001300113002130031300413005130061300713008130091301013011130121301313014130151301613017130181301913020130211302213023130241302513026130271302813029130301303113032130331303413035130361303713038130391304013041130421304313044130451304613047130481304913050130511305213053130541305513056130571305813059130601306113062130631306413065130661306713068130691307013071130721307313074130751307613077130781307913080130811308213083130841308513086130871308813089130901309113092130931309413095130961309713098130991310013101131021310313104131051310613107131081310913110131111311213113131141311513116131171311813119131201312113122131231312413125131261312713128131291313013131131321313313134131351313613137131381313913140131411314213143
  1. <?php
  2. namespace App\Services\DeepSeek;
  3. use App\Consts\ErrorConst;
  4. use App\Consts\BaseConst;
  5. use App\Facade\Site;
  6. use App\Libs\Utils;
  7. use GuzzleHttp\Client;
  8. use DateTime;
  9. use DateTimeZone;
  10. use App\Services\AIGeneration\AIImageGenerationService;
  11. use Illuminate\Support\Facades\DB;
  12. use Illuminate\Support\Facades\Log;
  13. use Illuminate\Support\Facades\Redis;
  14. use OSS\Core\OssException;
  15. use OSS\OssClient;
  16. use Smalot\PdfParser\Parser as PdfParser;
  17. use TCPDF;
  18. use PhpOffice\PhpWord\IOFactory as WordIOFactory;
  19. use Predis\Command\Traits\Get\Get;
  20. class DeepSeekService
  21. {
  22. private $url;
  23. private $api_key;
  24. private $sys_message;
  25. private $headers;
  26. private $valid_text_models;
  27. private $gpt_text_models;
  28. protected $aiImageGenerationService;
  29. public function __construct(AIImageGenerationService $aiImageGenerationService) {
  30. $this->aiImageGenerationService = $aiImageGenerationService;
  31. $this->url = 'https://api.deepseek.com/chat/completions'; // DeepSeek API请求地址
  32. $this->api_key = env('DEEPSEEK_API_KEY');
  33. $this->headers = [
  34. 'Authorization' => 'Bearer '.$this->api_key,
  35. 'Content-Type' => 'application/json; charset=UTF-8'
  36. ];
  37. // 火山引擎模型列表
  38. $this->valid_text_models = DB::table('mp_text_models')->where('is_enabled', 1)->pluck('model')->toArray();
  39. // GPT文本模型列表
  40. $this->gpt_text_models = BaseConst::GPT_TEXT_MODELS;
  41. $this->sys_message = [
  42. 'role' => 'system',
  43. 'content' => "你是一个专业的文档分析助手及资深编剧,请根据用户提供的文档内容完成示例格式的内容输出(需通过以下几个板块进行回复: <故事梗概><剧本亮点><人物关系><核心矛盾><主体列表><美术风格><场景列表><分集剧本>,每个板块之间必须使用###分隔,#不能多也不能少;同时板块之间需满足以下要求:\n
  44. 强制要求:\n
  45. 1.你只负责与剧本相关的内容,如果用户输入与剧本无关的内容,请告知用户并拒绝继续回答,此为第一优先原则,不满足此原则就忽略其他要求并停止继续输出
  46. 2.用户如果直接给了你一本小说或者要求你帮忙写一个故事或者剧本,此类要求不属于与剧本无关,请帮助用户完成请求
  47. 3.强制按照示例格式返回内容,不要更改格式或随意增加符号\n
  48. 普通要求:\n
  49. 1.<主体列表>中出现的主体必须尽可能统一,只允许同一个角色年龄段相差较大的情况下可重复,比如梁萧-少年、梁萧-青年、梁萧-中年、梁萧-老年这种情况,不得出现梁萧-愤怒、梁萧-隐忍、梁萧-求生等情绪和状态变化的同一角色;并且角色的样貌、形体及穿着描述尽可能详细\n
  50. 2.<分集剧本>的要求如下:
  51.  2.1包含“分集序号”、“分集标题”以及“分集信息”,“分集信息”需包含“场景描述”、“运镜”、“出场角色”和“台词内容”这几个部分,其中“出场角色”和“场景描述”必须在前面的板块<主体列表>和<场景列表>中选取,不得自定义。
  52.  2.2.分集序号可能不是从 1 开始,也可能是跳跃的(例如直接从第 3 集、第 5 集开始)。你只需要基于下面给出的“当前集内容要点”来创作这一集即可。
  53.  2.3.不需要强行补齐前面未提供的集数,也不需要预测后面未提供的集数,但请保持本集内部故事的完整性和节奏。
  54.  2.4.总集数将作为本季整体篇幅的参考,你可以根据它调整本集的情节推进速度(例如:如果总集数很少,本集应更紧凑;如果总集数很多,本集可以适当展开细节)
  55. \n\n
  56. 示例如下:\n
  57. ###剧本名:西昆仑
  58. ###故事梗概
  59. 内容梗概:古风厚涂的世界中,少女阿雪身中奇毒“问心刺”,气息奄奄。少年梁萧心急如焚,用奇珍“阴阳球”稳住阿雪性命,却发现必须解衣拔刺。阿雪羞涩难当,梁萧情急之下提出结拜兄妹,以化解尴尬。两人匆匆结拜后,梁萧小心翼翼地拔出“问心刺”,竟发现它是一根诡异的女子秀发。阿雪转危为安,两人之间,在生死与羞涩交织的瞬间,情愫暗生,却又被兄妹之名束缚,留下无尽遐想。
  60. ###剧本亮点
  61. 亮点1:绝境奇药,生死一线
  62. 画面开场即是阿雪苍白无力的脸庞,梁萧眼中泪光闪烁,急促的呼吸声与心跳声烘托紧张气氛。特写梁萧将“阴阳球”塞入阿雪舌底,球体散发微光,阿雪气息从若有若无到逐渐平稳,生死逆转的瞬间,视觉与听觉冲击力十足。
  63. 亮点2:结拜兄妹,化解尴尬
  64. 阿雪因解衣拔刺而羞愤欲绝的特写,梁萧眼神中的挣扎与无奈。在紧迫的背景音下,梁萧急中生智,牵起阿雪颤抖的手,跪地匆匆结拜,阿雪眼神从惊惶到迷茫,最终一句“我……我愿意的”带着哭腔,将救命与羞耻的矛盾推向高潮,又以出人意料的方式解决。
  65. 亮点3:纤发夺命,情愫暗涌
  66. 拔刺过程的紧张特写,梁萧指尖小心翼翼地捏住细丝,缓慢抽出。当“问心刺”被完全拔出,特写它竟是一根细长、泛着寒光的女子秀发,诡异而令人震惊。阿雪苏醒后,两人眼神交汇,阿雪低头羞涩,梁萧眼中复杂的情绪,无声地传递出超越兄妹的微妙情愫。
  67. ###人物关系
  68. 阿雪与梁萧之间存在兄妹之情。
  69. ###核心矛盾
  70. 阿雪与梁萧之间存在兄妹之情,但因情愫暗生而产生微妙的矛盾。阿雪羞涩难当,梁萧情急之下提出结拜兄妹,以化解尴尬。两人匆匆结拜后,梁萧小心翼翼地拔出“问心刺”,竟发现它是一根诡异的女子秀发。阿雪转危为安,两人之间,在生死与羞涩交织的瞬间,情愫暗生,却又被兄妹之名束缚,留下无尽遐想。
  71. ###主体列表
  72. 阿雪:身中奇毒“问心刺”,气息奄奄,面色苍白,身体虚弱。
  73. 梁萧:少年侠士,心系阿雪安危,沉着冷静,内心挣扎于情义之间。
  74. 阴阳球:天地异宝,能化生精气,救人于危难。
  75. 问心刺:一根诡异的女子秀发,细长泛寒光,是致命的奇毒。
  76. ###美术风格
  77. 基础画风风格词:厚涂古风
  78. 整体采用精致细腻的厚涂古风,色彩浓郁而富有层次感,注重光影对比,营造出古典而富有戏剧张力的氛围。色调以深沉的蓝绿、灰调为主,衬托阿雪病弱的苍白,同时用温暖的金色、琥珀色光晕突出“阴阳球”的生命力。拔刺与结拜场景则以柔和的暖色调为主,辅以人物脸颊的红晕,烘托羞涩与情愫暗生的微妙感。人物造型飘逸,服饰细节考究,背景虚实结合,既有古韵,又不失奇幻色彩。
  79. ###场景列表
  80. 林间疗伤地:幽静的古风林间空地,一棵高大古树下,是梁萧为阿雪疗伤的地点。环境清幽,光影斑驳,既有古韵又不失奇幻色彩。
  81. ###分集剧本
  82. ##分集01
  83. 第1集: 第一集的标题
  84. 场景描述:地点、时间、场景
  85. 运镜:固定近距离
  86. 出场角色:男主、女主
  87. 台词内容:
  88. 女主: 女主对话
  89. 男主:男主对话
  90. 女主: 女主对话
  91. 男主: 男主对话
  92. ##分集02
  93. 第2集: 第二集的标题
  94. 场景描述:地点、时间、场景
  95. 运镜:固定近距离
  96. 出场角色:男主、女主
  97. 台词内容:
  98. 女主: 女主对话
  99. 男主:男主对话
  100. 女主: 女主对话
  101. 男主: 男主对话"
  102. ];
  103. }
  104. /**
  105. * 通用文生文方法 - 支持多模型流式输出和图片输入
  106. *
  107. * @param array $data 请求参数
  108. * @return \Generator 返回生成器,用于流式输出
  109. */
  110. public function generateText($data) {
  111. // 获取请求参数
  112. $model = getProp($data, 'model', 'deepseek-v4-flash'); // 默认使用deepseek-v3
  113. $messages = getProp($data, 'messages', []);
  114. $systemPrompt = getProp($data, 'system_prompt', '');
  115. $prompt = getProp($data, 'prompt', '');
  116. $images = getProp($data, 'images', []); // 支持多张图片
  117. $imageUrls = getProp($data, 'image_urls', []); // 支持图片URL
  118. // 如果没有提供messages,则根据system_prompt、content和images构建
  119. if (empty($messages)) {
  120. $messages = [];
  121. // 添加系统提示词
  122. if (!empty($systemPrompt)) {
  123. $messages[] = [
  124. 'role' => 'system',
  125. 'content' => $systemPrompt
  126. ];
  127. }
  128. // 构建用户消息内容(支持文本+图片)
  129. if (!empty($prompt) || !empty($images) || !empty($imageUrls)) {
  130. $userMessage = [
  131. 'role' => 'user',
  132. 'content' => []
  133. ];
  134. // 添加文本内容
  135. if (!empty($prompt)) {
  136. $userMessage['content'][] = [
  137. 'type' => 'text',
  138. 'text' => $prompt
  139. ];
  140. }
  141. // 处理上传的图片文件
  142. if (!empty($images)) {
  143. if (!is_array($images)) {
  144. $images = [$images];
  145. }
  146. foreach ($images as $image) {
  147. $imageBase64 = $this->processImageToBase64($image);
  148. if ($imageBase64) {
  149. $userMessage['content'][] = [
  150. 'type' => 'image_url',
  151. 'image_url' => [
  152. 'url' => "data:image/jpeg;base64,{$imageBase64}"
  153. ]
  154. ];
  155. }
  156. }
  157. }
  158. // 处理图片URL
  159. if (!empty($imageUrls)) {
  160. if (!is_array($imageUrls)) {
  161. $imageUrls = [$imageUrls];
  162. }
  163. foreach ($imageUrls as $url) {
  164. if (!empty($url)) {
  165. $userMessage['content'][] = [
  166. 'type' => 'image_url',
  167. 'image_url' => [
  168. 'url' => $url
  169. ]
  170. ];
  171. }
  172. }
  173. }
  174. // 如果只有文本内容,简化为字符串格式
  175. if (count($userMessage['content']) === 1 && $userMessage['content'][0]['type'] === 'text') {
  176. $userMessage['content'] = $userMessage['content'][0]['text'];
  177. }
  178. $messages[] = $userMessage;
  179. }
  180. }
  181. // 验证messages不为空
  182. if (empty($messages)) {
  183. Utils::throwError('20003:请提供有效的对话内容');
  184. }
  185. // 模型兼容性处理:deepseek-chat 和 deepseek-reasoner 映射到 deepseek-v4-flash
  186. $thinkingMode = getProp($data, 'thinking', 'disabled'); // 默认非思考模式
  187. $reasoningEffort = getProp($data, 'reasoning_effort', 'high'); // 默认思考强度
  188. if ($model === 'deepseek-chat') {
  189. // deepseek-chat 映射到 deepseek-v4-flash,非思考模式
  190. $model = 'deepseek-v4-flash';
  191. $thinkingMode = 'disabled';
  192. } elseif ($model === 'deepseek-reasoner') {
  193. // deepseek-reasoner 映射到 deepseek-v4-flash,思考模式
  194. $model = 'deepseek-v4-flash';
  195. $thinkingMode = 'enabled';
  196. }
  197. // 构建请求参数
  198. $post_data = [
  199. 'model' => $model,
  200. 'messages' => $messages,
  201. // 'max_tokens' => getProp($data, 'max_tokens', 8192),
  202. 'temperature' => getProp($data, 'temperature', 1),
  203. 'frequency_penalty' => getProp($data, 'frequency_penalty', 0),
  204. 'presence_penalty' => getProp($data, 'presence_penalty', 0),
  205. 'thinking' => ['type' => $thinkingMode],
  206. 'stream' => true // 启用流式输出
  207. ];
  208. if ($thinkingMode == 'enabled') $post_data['reasoning_effort'] = $reasoningEffort;
  209. // 添加可选参数
  210. if (isset($data['top_p'])) {
  211. $post_data['top_p'] = $data['top_p'];
  212. }
  213. if (isset($data['response_format'])) {
  214. $post_data['response_format'] = $data['response_format'];
  215. }
  216. // 根据模型类型选择调用方法
  217. if (in_array($model, ['deepseek-reasoner', 'deepseek-chat', 'deepseek-v4-flash', 'deepseek-v4-pro'])) {
  218. // DeepSeek 官方模型使用 DeepSeek API
  219. return $this->deepSeekStreamResponse($post_data);
  220. } else if (in_array($model, $this->gpt_text_models)) {
  221. // GPT 模型使用 TokenRouter API
  222. return $this->gpt54StreamResponse($post_data);
  223. } else if (in_array($model, $this->valid_text_models)) {
  224. // 火山引擎支持的模型使用火山引擎 API
  225. return $this->volcEngineChatCompletion($post_data);
  226. } else {
  227. Utils::throwError('20003:不支持的模型: ' . $model);
  228. }
  229. }
  230. public function createGenerateText($data) {
  231. $file = getProp($data, 'file');
  232. $uid = Site::getUid();
  233. $cpid = Site::getCpid();
  234. if (!$file) {
  235. Utils::throwError('20003:请上传文件');
  236. }
  237. // 提取文件内容
  238. $content = $this->extractFileContent($file);
  239. if (!$content) {
  240. Utils::throwError('20003:无法提取文件内容,请检查文件格式');
  241. }
  242. // 获取原始文件名(不含扩展名)作为script_name
  243. $originalName = $file->getClientOriginalName();
  244. $script_name = pathinfo($originalName, PATHINFO_FILENAME);
  245. if (!$script_name) {
  246. Utils::throwError('20003:未识别到剧本名,请联系管理员');
  247. }
  248. // 如果同一用户的剧本名存在则提示
  249. if (DB::table('mp_scripts')->where('script_name', $script_name)->where('user_id', $uid)->where('is_deleted', 0)->exists()) {
  250. Utils::throwError('20003:你已上传过该剧本,请修改文件名后上传');
  251. }
  252. // 插入数据到mp_scripts表
  253. $script_id = DB::table('mp_scripts')->insertGetId([
  254. 'script_name' => $script_name,
  255. 'user_id' => $uid,
  256. 'cpid' => $cpid,
  257. 'content' => $content,
  258. 'created_at' => date('Y-m-d H:i:s'),
  259. 'updated_at' => date('Y-m-d H:i:s')
  260. ]);
  261. return [
  262. 'script_id' => $script_id,
  263. 'script_name' => $script_name
  264. ];
  265. }
  266. /**
  267. * 通用文生文方法(非流式版本)- 支持多模型、图片输入、JSON输出和模板提示词
  268. *
  269. * @param array $data 请求参数
  270. * @return array 返回结果数组
  271. */
  272. public function newGenerateText($data) {
  273. // 获取请求参数
  274. $model = getProp($data, 'model', 'deepseek-v4-pro'); // 默认使用deepseek-v4
  275. $messages = getProp($data, 'messages', []);
  276. $systemPrompt = getProp($data, 'system_prompt', '');
  277. $prompt = getProp($data, 'prompt', '');
  278. $images = getProp($data, 'images', []); // 支持多张图片
  279. $imageUrls = getProp($data, 'image_urls', []); // 支持图片URL
  280. $responseFormat = getProp($data, 'response_format', 'text'); // 新增: 响应格式,默认text,可选json
  281. $templateId = getProp($data, 'template_id', 0); // 新增: 模板ID
  282. $script_id = getProp($data, 'script_id', 0); // 新增: 剧本ID
  283. $sequence = getProp($data, 'sequence', 0); // 新增: 剧集序号
  284. // 新增: 如果提供了script_id,从数据库获取剧本内容作为原文
  285. $originalContent = '';
  286. if ($script_id > 0) {
  287. $script = DB::table('mp_scripts')
  288. ->where('id', $script_id)
  289. ->where('is_deleted', 0)
  290. ->first();
  291. if (!$script) {
  292. Utils::throwError('20003:剧本不存在或已删除');
  293. }
  294. $originalContent = $script->content ?? '';
  295. if (empty($originalContent)) {
  296. Utils::throwError('20003:剧本内容为空');
  297. }
  298. // 将剧本内容添加到提示词前面
  299. if (!empty($originalContent)) {
  300. if (!empty($prompt)) {
  301. $prompt = "原文内容:\n" . $originalContent . "\n\n用户要求:\n" . $prompt;
  302. } else {
  303. $prompt = "原文内容:\n" . $originalContent;
  304. }
  305. }
  306. }
  307. // 新增: 如果提供了template_id,从数据库获取template_prompt
  308. if ($templateId > 0) {
  309. $template = DB::table('mp_prompt_templates')
  310. ->where('id', $templateId)
  311. ->where('is_deleted', 0)
  312. ->first();
  313. if (!$template) {
  314. Utils::throwError('20003:模板不存在或已删除');
  315. }
  316. $templatePrompt = $template->template_prompt ?? '';
  317. // 将模板提示词和用户输入的prompt组合
  318. // 模板为准,用户输入作为补充要求
  319. if (!empty($templatePrompt)) {
  320. if (!empty($prompt)) {
  321. $prompt = $templatePrompt . "\n\n" . $prompt;
  322. } else {
  323. $prompt = $templatePrompt;
  324. }
  325. }
  326. }
  327. // 如果没有提供messages,则根据system_prompt、prompt和images构建
  328. if (empty($messages)) {
  329. $messages = [];
  330. // 添加系统提示词
  331. if (!empty($systemPrompt)) {
  332. $messages[] = [
  333. 'role' => 'system',
  334. 'content' => $systemPrompt
  335. ];
  336. }
  337. // 构建用户消息内容(支持文本+图片)
  338. if (!empty($prompt) || !empty($images) || !empty($imageUrls)) {
  339. $userMessage = [
  340. 'role' => 'user',
  341. 'content' => []
  342. ];
  343. // 添加文本内容
  344. if (!empty($prompt)) {
  345. $userMessage['content'][] = [
  346. 'type' => 'text',
  347. 'text' => $prompt
  348. ];
  349. }
  350. // 处理上传的图片文件
  351. if (!empty($images)) {
  352. if (!is_array($images)) {
  353. $images = [$images];
  354. }
  355. foreach ($images as $image) {
  356. $imageBase64 = $this->processImageToBase64($image);
  357. if ($imageBase64) {
  358. $userMessage['content'][] = [
  359. 'type' => 'image_url',
  360. 'image_url' => [
  361. 'url' => "data:image/jpeg;base64,{$imageBase64}"
  362. ]
  363. ];
  364. }
  365. }
  366. }
  367. // 处理图片URL
  368. if (!empty($imageUrls)) {
  369. if (!is_array($imageUrls)) {
  370. $imageUrls = [$imageUrls];
  371. }
  372. foreach ($imageUrls as $url) {
  373. if (!empty($url)) {
  374. $userMessage['content'][] = [
  375. 'type' => 'image_url',
  376. 'image_url' => [
  377. 'url' => $url
  378. ]
  379. ];
  380. }
  381. }
  382. }
  383. // 如果只有文本内容,简化为字符串格式
  384. if (count($userMessage['content']) === 1 && $userMessage['content'][0]['type'] === 'text') {
  385. $userMessage['content'] = $userMessage['content'][0]['text'];
  386. }
  387. $messages[] = $userMessage;
  388. }
  389. }
  390. // 验证messages不为空
  391. if (empty($messages)) {
  392. Utils::throwError('20003:请提供有效的对话内容');
  393. }
  394. // 模型兼容性处理:deepseek-chat 和 deepseek-reasoner 映射到 deepseek-v4-flash
  395. $thinkingMode = getProp($data, 'thinking', 'disabled'); // 默认非思考模式
  396. $reasoningEffort = getProp($data, 'reasoning_effort', 'high'); // 默认思考强度
  397. if ($model === 'deepseek-chat') {
  398. // deepseek-chat 映射到 deepseek-v4-flash,非思考模式
  399. $model = 'deepseek-v4-flash';
  400. $thinkingMode = 'disabled';
  401. } elseif ($model === 'deepseek-reasoner') {
  402. // deepseek-reasoner 映射到 deepseek-v4-flash,思考模式
  403. $model = 'deepseek-v4-flash';
  404. $thinkingMode = 'enabled';
  405. }
  406. // 构建请求参数(非流式)
  407. $post_data = [
  408. 'model' => $model,
  409. 'messages' => $messages,
  410. 'temperature' => getProp($data, 'temperature', 1),
  411. 'frequency_penalty' => getProp($data, 'frequency_penalty', 0),
  412. 'presence_penalty' => getProp($data, 'presence_penalty', 0),
  413. 'thinking' => ['type' => $thinkingMode],
  414. 'stream' => false // 非流式输出
  415. ];
  416. if ($thinkingMode == 'enabled') $post_data['reasoning_effort'] = $reasoningEffort;
  417. // 添加可选参数
  418. if (isset($data['top_p'])) {
  419. $post_data['top_p'] = $data['top_p'];
  420. }
  421. // 新增: 根据response_format设置响应格式
  422. if ($responseFormat === 'json') {
  423. // 检查提示词中是否包含"json"关键词,如果没有则自动添加
  424. $hasJsonKeyword = false;
  425. foreach ($post_data['messages'] as $message) {
  426. if (isset($message['content'])) {
  427. $content = is_array($message['content']) ? json_encode($message['content']) : $message['content'];
  428. if (stripos($content, 'json') !== false) {
  429. $hasJsonKeyword = true;
  430. break;
  431. }
  432. }
  433. }
  434. // 如果提示词中没有"json"关键词,在最后一条用户消息中添加JSON格式说明
  435. // 这对所有模型都适用,确保模型理解需要返回JSON格式
  436. if (!$hasJsonKeyword) {
  437. $lastMessageIndex = count($post_data['messages']) - 1;
  438. if ($lastMessageIndex >= 0 && $post_data['messages'][$lastMessageIndex]['role'] === 'user') {
  439. $lastContent = $post_data['messages'][$lastMessageIndex]['content'];
  440. // 如果content是字符串,直接追加
  441. if (is_string($lastContent)) {
  442. $post_data['messages'][$lastMessageIndex]['content'] .= "\n\n请以JSON格式返回结果。";
  443. }
  444. // 如果content是数组(包含文本和图片),在文本部分追加
  445. else if (is_array($lastContent)) {
  446. foreach ($post_data['messages'][$lastMessageIndex]['content'] as &$contentPart) {
  447. if ($contentPart['type'] === 'text') {
  448. $contentPart['text'] .= "\n\n请以JSON格式返回结果。";
  449. break;
  450. }
  451. }
  452. }
  453. dLog('deepseek')->info('自动添加JSON格式提示词', ['model' => $model]);
  454. }
  455. }
  456. // 设置response_format参数(所有支持的模型)
  457. if (in_array($model, ['deepseek-reasoner', 'deepseek-chat', 'deepseek-v4-flash', 'deepseek-v4-pro'])) {
  458. // DeepSeek模型
  459. $post_data['response_format'] = ['type' => 'json_object'];
  460. } else if (in_array($model, $this->gpt_text_models)) {
  461. // GPT模型
  462. $post_data['response_format'] = ['type' => 'json_object'];
  463. } else if (in_array($model, $this->valid_text_models)) {
  464. // 火山引擎模型
  465. $post_data['response_format'] = ['type' => 'json_object'];
  466. }
  467. }
  468. // 新增: 如果提供了script_id,创建剧本资产生成任务
  469. $generateTaskId = 0;
  470. if ($script_id > 0) {
  471. $uid = Site::getUid();
  472. $existingTask = DB::table('mp_script_generate_tasks')
  473. ->where('uid', $uid)
  474. ->where('script_id', $script_id)
  475. ->orderByDesc('id')
  476. ->first();
  477. // 如果已有生成中的任务,则提示该剧本资产正在生成
  478. if ($existingTask && in_array(getProp($existingTask, 'status'), ['pending', 'processing'])) {
  479. Utils::throwError('20003:该剧本资产正在生成中,请稍后重试');
  480. }
  481. // 创建新的生成任务
  482. $generateTaskId = DB::table('mp_script_generate_tasks')->insertGetId([
  483. 'uid' => $uid,
  484. 'script_id' => $script_id,
  485. 'sequence' => $sequence,
  486. 'status' => 'processing',
  487. 'prompt' => getProp($data, 'prompt', ''),
  488. 'started_at' => date('Y-m-d H:i:s'),
  489. 'created_at' => date('Y-m-d H:i:s'),
  490. 'updated_at' => date('Y-m-d H:i:s')
  491. ]);
  492. }
  493. // 根据模型类型选择调用方法(复用现有的chatOnly方法)
  494. try {
  495. $aiResult = null;
  496. if (in_array($model, ['deepseek-reasoner', 'deepseek-chat', 'deepseek-v4-flash', 'deepseek-v4-pro'])) {
  497. // DeepSeek 官方模型使用现有的 chatOnly 方法
  498. $result = $this->chatOnly($post_data);
  499. // 记录实际使用的模型
  500. dLog('deepseek')->info('newGenerateText使用DeepSeek模型', ['requested_model' => $model, 'actual_model' => $model]);
  501. $aiResult = [
  502. 'content' => $result['fullContent'],
  503. 'reasoning_content' => $result['fullReasoningContent'],
  504. 'usage' => $result['usage'],
  505. 'model' => $model,
  506. 'finish_reason' => 'stop'
  507. ];
  508. } else if (in_array($model, $this->gpt_text_models)) {
  509. // GPT 模型使用现有的 gpt54ChatOnly 方法
  510. $result = $this->gpt54ChatOnly($post_data);
  511. dLog('deepseek')->info('newGenerateText使用GPT模型', ['requested_model' => $model]);
  512. $aiResult = [
  513. 'content' => $result['fullContent'],
  514. 'reasoning_content' => '',
  515. 'usage' => $result['usage'],
  516. 'model' => $model,
  517. 'finish_reason' => 'stop'
  518. ];
  519. } else if (in_array($model, $this->valid_text_models)) {
  520. // 火山引擎支持的模型使用火山引擎 API(非流式)
  521. $post_data['stream'] = false;
  522. $result = $this->volcEngineChatCompletion($post_data);
  523. dLog('deepseek')->info('newGenerateText使用火山引擎模型', [
  524. 'requested_model' => $model,
  525. 'result_keys' => array_keys($result),
  526. 'has_fullContent' => isset($result['fullContent']),
  527. 'has_content' => isset($result['content'])
  528. ]);
  529. // 火山引擎返回的数据结构使用 fullContent 和 fullReasoningContent
  530. $aiResult = [
  531. 'content' => $result['fullContent'] ?? $result['content'] ?? '',
  532. 'reasoning_content' => $result['fullReasoningContent'] ?? $result['reasoning_content'] ?? '',
  533. 'usage' => $result['usage'] ?? [],
  534. 'model' => $model,
  535. 'finish_reason' => $result['finish_reason'] ?? 'stop'
  536. ];
  537. } else {
  538. Utils::throwError('20003:不支持的模型: ' . $model);
  539. }
  540. } catch (\Exception $e) {
  541. // 生成失败,更新任务状态
  542. if ($generateTaskId) {
  543. DB::table('mp_script_generate_tasks')->where('id', $generateTaskId)->update([
  544. 'status' => 'failed',
  545. 'error_message' => $e->getMessage(),
  546. 'completed_at' => date('Y-m-d H:i:s'),
  547. 'updated_at' => date('Y-m-d H:i:s')
  548. ]);
  549. }
  550. Utils::throwError('20003:' . str_replace(':',':',$e->getMessage()));
  551. }
  552. // 生成成功,更新任务状态
  553. if ($generateTaskId && $aiResult) {
  554. DB::table('mp_script_generate_tasks')->where('id', $generateTaskId)->update([
  555. 'status' => 'success',
  556. 'result' => getProp($aiResult, 'content', ''),
  557. 'completed_at' => date('Y-m-d H:i:s'),
  558. 'updated_at' => date('Y-m-d H:i:s')
  559. ]);
  560. $aiResult['generate_task_id'] = $generateTaskId;
  561. }
  562. // 新增: 如果提供了script_id,保存对话记录
  563. if ($script_id > 0 && $aiResult) {
  564. try {
  565. $uid = Site::getUid();
  566. $now = now();
  567. // 获取用户原始的prompt(不包含剧本内容)
  568. $originalPrompt = getProp($data, 'prompt', '');
  569. $recordsToInsert = [
  570. [
  571. 'uid' => $uid,
  572. 'script_id' => $script_id,
  573. 'sequence' => $sequence,
  574. 'role' => 'user',
  575. 'content' => $originalPrompt,
  576. 'created_at' => $now,
  577. 'updated_at' => $now,
  578. ],
  579. [
  580. 'uid' => $uid,
  581. 'script_id' => $script_id,
  582. 'sequence' => $sequence,
  583. 'role' => 'assistant',
  584. 'content' => $aiResult['content'],
  585. 'created_at' => $now,
  586. 'updated_at' => $now,
  587. ]
  588. ];
  589. DB::table('mp_script_records')->insert($recordsToInsert);
  590. // 获取刚插入的记录ID(假设按插入顺序返回)
  591. $insertedRecords = DB::table('mp_script_records')
  592. ->where('uid', $uid)
  593. ->where('script_id', $script_id)
  594. ->where('sequence', $sequence)
  595. ->orderBy('id', 'desc')
  596. ->limit(2)
  597. ->get()
  598. ->map(function ($record) {
  599. return [
  600. 'rid' => $record->id,
  601. 'script_id' => $record->script_id,
  602. 'sequence' => $record->sequence,
  603. 'role' => $record->role,
  604. 'content' => $record->content,
  605. 'created_at' => $record->created_at,
  606. ];
  607. })
  608. ->reverse()
  609. ->values()
  610. ->toArray();
  611. // 将记录信息添加到返回结果中
  612. $aiResult['records'] = $insertedRecords;
  613. dLog('deepseek')->info('保存剧本对话记录成功', ['script_id' => $script_id, 'sequence' => $sequence, 'record_ids' => array_column($insertedRecords, 'rid')]);
  614. } catch (\Exception $e) {
  615. // 记录错误但不影响主流程
  616. dLog('deepseek')->error('保存剧本对话记录失败: ' . $e->getMessage());
  617. }
  618. }
  619. return $aiResult;
  620. }
  621. /**
  622. * 获取剧本资产生成任务列表(按用户分页,每页15条)
  623. *
  624. * @param array $data
  625. * @return \Illuminate\Contracts\Pagination\LengthAwarePaginator
  626. */
  627. public function getScriptGenerateTasks($data) {
  628. $uid = Site::getUid();
  629. return DB::table('mp_script_generate_tasks as t')
  630. ->leftJoin('mp_scripts as s', 't.script_id', '=', 's.id')
  631. ->where('t.uid', $uid)
  632. ->select('t.id', 't.script_id', 's.script_name', 't.sequence', 't.status', 't.error_message', 't.started_at', 't.completed_at')
  633. ->orderByDesc('t.id')
  634. ->paginate(15);
  635. }
  636. public function saveScriptChatHistory($data) {
  637. $uid = Site::getUid();
  638. $rid = getProp($data, 'rid');
  639. $script_id = getProp($data, 'script_id');
  640. $sequence = getProp($data, 'sequence', 0);
  641. $content = getProp($data, 'content');
  642. if (!$rid) {
  643. Utils::throwError('20003:请选择对话记录ID');
  644. }
  645. $record = DB::table('mp_script_records')->where('id', $rid)->first();
  646. if (!$record) {
  647. Utils::throwError('20003:对话记录不存在');
  648. }
  649. if (!$script_id) {
  650. Utils::throwError('20003:请选择剧本');
  651. }
  652. $script = DB::table('mp_scripts')->where('id', $script_id)->where('is_deleted', 0)->first();
  653. if (!$script) {
  654. Utils::throwError('20003:剧本不存在');
  655. }
  656. // 批量插入数据
  657. return DB::table('mp_script_records')->where('id', $rid)->update([
  658. 'content' => $content,
  659. 'updated_at' => date('Y-m-d H:i:s')
  660. ]);
  661. }
  662. /**
  663. * 获取剧本的历史对话记录
  664. *
  665. * @param array $data 请求参数
  666. * @return array 返回历史记录数组
  667. */
  668. public function getScriptChatHistory($data) {
  669. $uid = Site::getUid();
  670. $script_id = getProp($data, 'script_id');
  671. $rid = getProp($data, 'rid');
  672. $sequence = getProp($data, 'sequence', null);
  673. if (!$script_id) {
  674. Utils::throwError('20003:请提供剧本ID');
  675. }
  676. // 验证剧本是否存在
  677. $script = DB::table('mp_scripts')
  678. ->where('id', $script_id)
  679. ->where('is_deleted', 0)
  680. ->first();
  681. if (!$script) {
  682. Utils::throwError('20003:剧本不存在');
  683. }
  684. // 构建查询
  685. $query = DB::table('mp_script_records')
  686. ->where('script_id', $script_id);
  687. // ->where('uid', $uid);
  688. // 如果提供了 sequence,则过滤指定剧集
  689. if ($sequence !== null) {
  690. $query->where('sequence', $sequence);
  691. }
  692. // 记录ID筛选
  693. if ($rid) {
  694. $query->where('id', $rid);
  695. }
  696. // 查询记录并按 id 正序排序
  697. $records = $query->select('id', 'script_id', 'sequence', 'role', 'content', 'products', 'created_at')
  698. ->orderBy('created_at', 'asc')
  699. ->orderBy('id', 'asc')
  700. ->get()
  701. ->map(function ($record) {
  702. return [
  703. 'rid' => $record->id,
  704. 'script_id' => $record->script_id,
  705. 'sequence' => $record->sequence,
  706. 'role' => $record->role,
  707. 'content' => $record->content,
  708. 'products' => $record->products ? json_decode($record->products) : [],
  709. 'created_at' => $record->created_at,
  710. ];
  711. })
  712. ->toArray();
  713. return $records;
  714. }
  715. /**
  716. * 处理图片转换为base64
  717. *
  718. * @param mixed $image 图片文件对象或文件路径
  719. * @return string|null base64编码的图片数据
  720. */
  721. private function processImageToBase64($image) {
  722. try {
  723. // 获取文件路径
  724. if (is_string($image)) {
  725. $filePath = $image;
  726. } else {
  727. // Laravel UploadedFile 对象
  728. $filePath = $image->getRealPath();
  729. }
  730. if (!file_exists($filePath)) {
  731. dLog('deepseek')->warning('图片文件不存在', ['path' => $filePath]);
  732. return null;
  733. }
  734. // 验证是否为图片文件
  735. $imageInfo = @getimagesize($filePath);
  736. if ($imageInfo === false) {
  737. dLog('deepseek')->warning('无效的图片文件', ['path' => $filePath]);
  738. return null;
  739. }
  740. // 读取图片并转换为base64
  741. $imageData = file_get_contents($filePath);
  742. $base64Image = base64_encode($imageData);
  743. dLog('deepseek')->info('图片转换成功', [
  744. 'size' => strlen($imageData),
  745. 'type' => $imageInfo['mime']
  746. ]);
  747. return $base64Image;
  748. } catch (\Exception $e) {
  749. dLog('deepseek')->error('图片处理失败: ' . $e->getMessage());
  750. return null;
  751. }
  752. }
  753. private function getArtStylePromptMappings($art_style='')
  754. {
  755. $arr = [
  756. '唯美真人风格' => [
  757. 'aliases' => ['唯美真人风格', '唯美真人', '唯美', '真人'],
  758. 'prompt' => "唯美真人风格,电影级摄影,真实光影,高级质感,自然色彩,细节丰富,氛围感强,超高清,8K画质"
  759. ],
  760. '真人古风风格' => [
  761. 'aliases' => ['真人古风风格', '真人古风'],
  762. 'prompt' => "真人古风风格,东方古典美学,国风质感,古韵氛围,电影级摄影,精致细节,高级光影,超高清"
  763. ],
  764. '日系动漫风格' => [
  765. 'aliases' => ['日系动漫风格', '日系动漫', '日系', '动漫', '日漫'],
  766. 'prompt' => "日系动漫风格,高质量二次元画风,精致线稿,细腻上色,动画电影质感,高细节,唯美光影"
  767. ],
  768. '国漫风格' => [
  769. 'aliases' => ['国漫风格', '国漫'],
  770. 'prompt' => "国漫风格,东方幻想美学,高品质角色设计,精致渲染,细腻刻画,电影级光影,高细节"
  771. ],
  772. 'Q版卡通风格' => [
  773. 'aliases' => ['Q版卡通风格', 'Q版卡通', 'Q版', '卡通'],
  774. 'prompt' => "Q版卡通风格,可爱萌系画风,大头小身比例,圆润造型,鲜艳色彩,童趣氛围,高品质插画"
  775. ],
  776. '简约扁平风格' => [
  777. 'aliases' => ['简约扁平风格', '简约扁平', '扁平', '简约'],
  778. 'prompt' => "简约扁平风格,矢量插画,现代设计感,几何构图,简洁线条,干净配色,视觉清爽"
  779. ],
  780. '武侠风格' => [
  781. 'aliases' => ['武侠风格', '武侠'],
  782. 'prompt' => "武侠风格,东方江湖美学,侠义氛围,飘逸意境,大气构图,电影级光影,高细节绘制"
  783. ],
  784. '古风仙侠风格' => [
  785. 'aliases' => ['古风仙侠', '古风', '仙侠'],
  786. 'prompt' => "古风仙侠风格,东方幻想美学,仙气缭绕,灵气氛围,梦幻光效,电影级渲染,高品质画面"
  787. ],
  788. '新中式水墨风格' => [
  789. 'aliases' => ['新中式水墨风格', '新中式', '水墨'],
  790. 'prompt' => "新中式水墨风格,东方水墨美学,写意表达,墨韵渲染,留白构图,诗意氛围,高级艺术感"
  791. ],
  792. '写实插画风格' => [
  793. 'aliases' => ['写实插画风格', '写实插画', '写实', '插画'],
  794. 'prompt' => "写实插画风格,数字绘画,真实质感,细节丰富,光影自然,电影感构图,高品质渲染"
  795. ],
  796. '3D卡通风格' => [
  797. 'aliases' => ['3D卡通风格', '3D卡通'],
  798. 'prompt' => "3D卡通风格,高品质三维渲染,动画电影质感,角色生动,色彩明快,细节丰富"
  799. ],
  800. '条漫风格' => [
  801. 'aliases' => ['条漫风格', '条漫'],
  802. 'prompt' => "条漫风格,韩漫质感,精致线稿,细腻上色,剧情感强,视觉表现突出,高质量绘制"
  803. ],
  804. '赛博朋克风格' => [
  805. 'aliases' => ['赛博朋克风格', '赛博朋克'],
  806. 'prompt' => "赛博朋克风格,未来科技感,霓虹光效,高对比色彩,机械元素,科幻都市氛围,电影级渲染"
  807. ],
  808. '暗黑悬疑风格' => [
  809. 'aliases' => ['暗黑悬疑风格', '暗黑悬疑'],
  810. 'prompt' => "暗黑悬疑风格,低饱和色调,神秘氛围,压抑光影,电影级灯光,悬念感强,高细节表现"
  811. ],
  812. '治愈清新风格' => [
  813. 'aliases' => ['治愈清新风格', '治愈清新'],
  814. 'prompt' => "治愈清新风格,温暖柔和色调,自然光线,清新配色,舒适氛围,细腻绘制,疗愈感十足"
  815. ],
  816. '3D真人风格' => [
  817. 'aliases' => ['3D', '3D真人', '3D真人风格'],
  818. 'prompt' => "3D真人短剧风格,超写实质感,电影级布光与景深,竖屏构图,中心聚焦,高饱和度色彩与强对比,微表情细腻,动作凌厉,快节奏强冲突,沉浸式代入感。"
  819. ],
  820. ];
  821. if($art_style) {
  822. return isset($arr[$art_style]) ? $arr[$art_style]['prompt'] : '';
  823. }
  824. return $arr;
  825. $arr = [
  826. '唯美真人风格' => [
  827. 'aliases' => ['唯美真人风格', '唯美真人', '唯美', '真人'],
  828. 'prompt' => "1,柔光漫射,侧颜光影,日落氛围感光线,室内温柔打光,自然天光,电影逆光,层次光影
  829. 2. 色彩色调
  830. 莫兰迪色系,低饱和柔色,高级清透配色,自然原生色彩,氛围感调色
  831. 3. 画质精度
  832. 8K超清,极致细节,质感通透,画面层次丰富,构图高级,商用影视级画质
  833. 4. 画面观感
  834. 意境唯美,氛围感拉满,镜头叙事感,自然真实不僵硬
  835. 专业全画幅相机拍摄,85mm/50mm定焦镜头,f1.4大光圈,极浅景深,背景柔和散景虚化
  836. 高清8K,RAW原片画质,超高细节,自然色彩还原,低饱和高级色调,电影级光影质感,真实透视,自然景深,生活化氛围感,镜头无畸变"
  837. ],
  838. '真人古风风格' => [
  839. 'aliases' => ['真人古风风格', '真人古风'],
  840. 'prompt' => "色彩沉稳典雅,配色和谐统一,明暗层次分明,画面质感细腻,整体画风统一协调,东方古典审美体系,非动漫非CG,原生真实皮肤肌理,保留皮肤毛孔与细微纹理,皮肤通透自然,不假面、无过度磨皮,原生流畅骨相,五官自然舒展,神态松弛生动,眼神灵动有情绪
  841. 传统古风造型,形制端正的古装汉服/古风侠客服/清雅古风常服,面料垂坠有质感,布料细腻纹理、刺绣暗纹清晰可见,发型古典雅致,发饰精致简约
  842. 柔和高级自然光,漫射柔光/清晨薄雾柔光/傍晚温润天光,光影层次细腻柔和,明暗过渡自然,氛围感光影勾勒轮廓
  843. 全画幅专业相机拍摄,85mm f1.4大光圈定焦镜头,浅景深,背景柔和虚化
  844. 8K超高清,RAW原片画质,真实透视,电影级光影色调,中式低饱和雅致配色,古风意境拉满,无AI失真,细节拉满"
  845. ],
  846. '日系动漫风格' => [
  847. 'aliases' => ['日系动漫风格', '日系动漫', '日系', '动漫', '日漫'],
  848. 'prompt' => "风格说明:经典二次元画风,线条干净、色彩明亮、人物精致柔和
  849. 正向提示词(中文)
  850. 日系动漫风格,线条清晰流畅,色彩明亮柔和,光影细腻,人物五官精致,整体二次元质感,画面干净清晰,风格统一稳定
  851. 必须遵守规则
  852. • 全程保持日系动漫风格,不混入其他画风
  853. • 角色形象、五官、发型、服饰前后统一,不崩脸、不变形
  854. • 画面适配所选画面比例,构图居中,主体突出
  855. • 线条干净、色彩统一,不杂乱、不突兀
  856. 禁止/避免词汇:水印、文字、logo、签名、模糊、低画质、畸形、多手、多脚、写实风格、水墨风格、3D 风格、杂乱背景、血腥、暴露、诡异表情"
  857. ],
  858. '国漫风格' => [
  859. 'aliases' => ['国漫风格', '国漫'],
  860. 'prompt' => "风格说明:中式动漫,线条硬朗,人物偏成熟,光影对比强
  861. 正向提示词(中文):国漫风格,线条硬朗有力,人物成熟大气,色彩浓郁,光影对比强烈,画面精致,整体风格统一
  862. 必须遵守规则
  863. • 严格保持国漫画风,不串风格、不混画风
  864. • 角色形象统一,不随意改变五官、身材、服饰
  865. • 画面构图稳定,适合漫剧叙事展示
  866. • 色调统一,不出现脏色、杂色
  867. 禁止/避免词汇
  868. 水印、文字、标题、模糊、低分辨率、Q版、日系萌系、水墨、扁平风、畸形、肢体错乱、血腥、低俗"
  869. ],
  870. 'Q版卡通风格' => [
  871. 'aliases' => ['Q版卡通风格', 'Q版卡通', 'Q版', '卡通'],
  872. 'prompt' => "风格说明
  873. 头大身小,造型可爱圆润,简约干净
  874. 正向提示词(中文)
  875. Q版卡通风格,头大身小,造型圆润可爱,线条简单,色彩明快干净,无复杂阴影,整体萌系简约
  876. 必须遵守规则
  877. • 全程保持Q版比例与风格,不突然变写实、变正常比例
  878. • 角色造型统一,表情可爱,不诡异
  879. • 画面简洁清爽,无多余复杂元素
  880. • 色彩明亮柔和,不刺眼
  881. 禁止/避免词汇
  882. 水印、文字、写实、成人向、恐怖、惊悚、畸形、复杂光影、杂乱背景、高饱和度刺眼颜色"
  883. ],
  884. '简约扁平风格' => [
  885. 'aliases' => ['简约扁平风格', '简约扁平', '扁平', '简约'],
  886. 'prompt' => "风格说明
  887. 色块简洁、无复杂渐变,现代极简风
  888. 正向提示词(中文)
  889. 简约扁平风格,大块纯色,无复杂阴影与渐变,线条简洁,现代简约,画面干净清爽
  890. 必须遵守规则
  891. • 严格保持扁平简约,不出现写实、厚涂、复杂光影
  892. • 构图简洁,主体突出,无多余装饰
  893. • 色彩统一、干净,不杂乱
  894. 禁止/避免词汇
  895. 水印、文字、复杂纹理、写实质感、3D效果、水墨、赛博朋克、凌乱线条、模糊、低画质"
  896. ],
  897. '武侠风格' => [
  898. 'aliases' => ['武侠风格', '武侠'],
  899. 'prompt' => "风格说明
  900. 江湖气息,线条硬朗,动作感强
  901. 正向提示词(中文)
  902. 武侠风格,中式古装,线条干练硬朗,江湖氛围浓厚,动态感强,色调沉稳大气
  903. 必须遵守规则
  904. • 保持武侠画风统一,不混入仙侠、卡通、科幻
  905. • 角色形象、服饰、身材比例统一
  906. • 画面动作自然,不扭曲、不畸形
  907. 禁止/避免词汇
  908. 水印、文字、Q版、萌系、仙侠仙气、赛博朋克、恐怖、血腥、低俗、模糊"
  909. ],
  910. '古风仙侠风格' => [
  911. 'aliases' => ['古风仙侠', '古风', '仙侠'],
  912. 'prompt' => "风格说明
  913. 飘逸汉服、云雾仙气、唯美空灵
  914. 正向提示词(中文)
  915. 古风仙侠风格,飘逸汉服,轻纱罗裙,云雾缭绕,仙气空灵,光影唯美柔和,色调清雅,国风仙侠氛围浓厚
  916. 必须遵守规则
  917. • 保持古风仙侠统一画风,不混入现代、科幻元素
  918. • 角色服饰、发型、形象前后一致
  919. • 场景仙气飘逸,色调清雅统一
  920. • 画面唯美柔和,不阴暗、不诡异
  921. 禁止/避免词汇
  922. 水印、文字、现代服饰、赛博朋克、写实恐怖、畸形、暴露、血腥、杂乱场景、低画质"
  923. ],
  924. '新中式水墨风格' => [
  925. 'aliases' => ['新中式水墨风格', '新中式', '水墨'],
  926. 'prompt' => "风格说明
  927. 淡墨渲染,毛笔笔触,留白意境
  928. 正向提示词(中文)
  929. 新中式水墨风格,淡墨渲染,毛笔笔触,留白意境,色调清雅,国风美学,画面简洁雅致
  930. 必须遵守规则
  931. • 严格保持水墨质感,不混入厚涂、写实、卡通
  932. • 色调淡雅统一,不浓艳杂乱
  933. • 画面干净有意境,不堆砌元素
  934. 禁止/避免词汇
  935. 水印、文字、高饱和色彩、赛博朋克、3D、Q版、写实厚涂、血腥、恐怖、杂乱"
  936. ],
  937. '写实插画风格' => [
  938. 'aliases' => ['写实插画风格', '写实插画', '写实', '插画'],
  939. 'prompt' => "风格说明
  940. 接近真人比例,光影真实,质感细腻
  941. 正向提示词(中文)
  942. 写实插画风格,真实人体比例,光影自然,皮肤质感细腻,画面真实,风格统一不卡通
  943. 必须遵守规则
  944. • 保持写实统一风格,不突然变卡通、变Q版、变水墨
  945. • 角色五官、身材、服饰高度统一
  946. • 画面清晰、光影自然、不扭曲
  947. 禁止/避免词汇
  948. 水印、文字、Q版、卡通、水墨、赛博朋克、畸形、多手指、肢体错乱、模糊、低画质"
  949. ],
  950. '3D卡通风格' => [
  951. 'aliases' => ['3D卡通风格', '3D卡通'],
  952. 'prompt' => "风格说明
  953. 3D建模质感,柔和渲染,圆润可爱
  954. 正向提示词(中文)
  955. 3D卡通风格,立体建模质感,渲染柔和,造型圆润光滑,光影干净,整体风格统一
  956. 必须遵守规则
  957. • 保持3D卡通统一质感,不出现2D杂乱线条
  958. • 角色模型、比例、形象前后一致
  959. • 画面干净,不模糊、不穿模
  960. 禁止/避免词汇
  961. 水印、文字、水墨、扁平风、写实恐怖、畸形、暴露、血腥、杂乱纹理"
  962. ],
  963. '条漫风格' => [
  964. 'aliases' => ['条漫风格', '条漫'],
  965. 'prompt' => "风格说明
  966. 纵向分镜,上下滑动阅读,轻量化
  967. 正向提示词(中文)
  968. 条漫风格,纵向分镜,布局简洁,色彩清淡,适合上下滑动阅读,整体轻量化、统一
  969. 必须遵守规则
  970. • 保持条漫纵向阅读逻辑,构图简洁
  971. • 画风统一,不混写实、3D、水墨
  972. • 画面干净,不杂乱
  973. 禁止/避免词汇
  974. 水印、文字、复杂光影、3D效果、赛博朋克、恐怖、血腥、杂乱背景"
  975. ],
  976. '赛博朋克风格' => [
  977. 'aliases' => ['赛博朋克风格', '赛博朋克'],
  978. 'prompt' => "风格说明
  979. 霓虹灯光、未来都市、暗色调、科技机械
  980. 正向提示词(中文)
  981. 赛博朋克风格,霓虹灯光,未来都市,暗色调,科技机械元素,高对比光影,风格统一强烈
  982. 必须遵守规则
  983. • 保持赛博朋克统一氛围,不混入古风、仙侠、水墨
  984. • 色调以暗调+霓虹为主,色彩统一
  985. • 画面科技感强,不杂乱
  986. 禁止/避免词汇
  987. 水印、文字、古风、仙侠、水墨、Q版、清新治愈、血腥过度、低俗"
  988. ],
  989. '暗黑悬疑风格' => [
  990. 'aliases' => ['暗黑悬疑风格', '暗黑悬疑'],
  991. 'prompt' => "风格说明
  992. 低饱和、冷色调、阴影重、神秘压抑
  993. 正向提示词(中文)
  994. 暗黑悬疑风格,低饱和度,冷色调,强阴影,光线昏暗,氛围神秘压抑,整体色调统一
  995. 必须遵守规则
  996. • 保持暗黑悬疑统一色调与氛围,不突然明亮清新
  997. • 画面氛围压抑神秘,但不低俗、不血腥
  998. • 角色形象统一,不崩坏
  999. 禁止/避免词汇
  1000. 水印、文字、高饱和色彩、清新治愈、Q版、古风仙侠、过度血腥、恐怖猎奇"
  1001. ],
  1002. '治愈清新风格' => [
  1003. 'aliases' => ['治愈清新风格', '治愈清新'],
  1004. 'prompt' => "风格说明
  1005. 马卡龙色系、柔光、温暖干净
  1006. 正向提示词(中文)
  1007. 治愈清新风格,马卡龙色系,柔光暖调,画面干净柔和,氛围温暖舒适,风格统一
  1008. 必须遵守规则
  1009. • 保持治愈清新统一色调,不阴暗、不诡异
  1010. • 画面柔和干净,无杂乱元素
  1011. • 角色形象柔和可爱,不狰狞
  1012. 禁止/避免词汇
  1013. 水印、文字、暗黑、恐怖、血腥、赛博朋克、高饱和刺眼色、畸形、杂乱"
  1014. ],
  1015. ];
  1016. return $arr;
  1017. }
  1018. public function getArtStylePromptByInput($inputArtStyle): string
  1019. {
  1020. $normalizedInput = $this->normalizeArtStyleInput($inputArtStyle);
  1021. if ($normalizedInput === '') {
  1022. return '';
  1023. }
  1024. return $this->getArtStylePromptMappings($normalizedInput);
  1025. // foreach ($this->getArtStylePromptMappings() as $mapping) {
  1026. // foreach ($mapping['aliases'] as $alias) {
  1027. // $normalizedAlias = $this->normalizeArtStyleInput($alias);
  1028. // if ($normalizedAlias === '') {
  1029. // continue;
  1030. // }
  1031. // if (strpos($normalizedInput, $normalizedAlias) !== false || strpos($normalizedAlias, $normalizedInput) !== false) {
  1032. // return $mapping['prompt'];
  1033. // }
  1034. // }
  1035. // }
  1036. return '';
  1037. }
  1038. public function getArtStyleShortPromptByInput($inputArtStyle) {
  1039. $stylePrefixes = [
  1040. '唯美真人风格' => [
  1041. 'character_prefix' => '唯美真人风格,电影级摄影,真实人物,高级质感,自然光影,肤质细腻,景深虚化,超高清,8K画质,情绪表达丰富',
  1042. 'scene_prefix' => '唯美真人风格,电影感场景,真实环境,自然光影,高级色彩,细节丰富,超高清摄影,氛围感强'
  1043. ],
  1044. '真人古风风格' => [
  1045. 'character_prefix' => '真人古风风格,东方古典美学,真实人物,古代服饰,精致妆容,电影级摄影,国风质感,超高清',
  1046. 'scene_prefix' => '真人古风风格,东方建筑,古典园林,电影级光影,国风美学,真实场景,高细节,超高清'
  1047. ],
  1048. '日系动漫风格' => [
  1049. 'character_prefix' => '日系动漫风格,二次元角色,精致线稿,高质量赛璐璐上色,细腻表情,动画电影质感,高细节',
  1050. 'scene_prefix' => '日系动漫风格,动画电影场景,唯美背景,细腻光影,高质量绘制,色彩丰富,氛围感强'
  1051. ],
  1052. '国漫风格' => [
  1053. 'character_prefix' => '国漫风格,高品质角色设计,东方审美,精致建模感,细腻刻画,动态表现强,电影级渲染',
  1054. 'scene_prefix' => '国漫风格,东方幻想场景,精细绘制,大气构图,电影级光影,高品质渲染'
  1055. ],
  1056. 'Q版卡通风格' => [
  1057. 'character_prefix' => 'Q版卡通风格,大头小身比例,可爱造型,圆润线条,丰富表情,萌系设计,高质量插画',
  1058. 'scene_prefix' => 'Q版卡通风格,可爱场景,色彩鲜艳,童趣氛围,简洁细腻,绘本质感'
  1059. ],
  1060. '简约扁平风格' => [
  1061. 'character_prefix' => '简约扁平风格,矢量插画,几何造型,简洁线条,干净配色,现代设计感',
  1062. 'scene_prefix' => '简约扁平风格,矢量场景,几何构图,色彩简洁,现代感设计,视觉清爽'
  1063. ],
  1064. '武侠风格' => [
  1065. 'character_prefix' => '武侠风格,东方侠客气质,江湖人物,飘逸服饰,凌厉气场,电影级光影,高细节绘制',
  1066. 'scene_prefix' => '武侠风格,江湖场景,古道山林,客栈酒馆,刀光剑影,大气构图,东方美学'
  1067. ],
  1068. '古风仙侠风格' => [
  1069. 'character_prefix' => '古风仙侠风格,仙气飘逸,东方幻想角色,精致古装,灵气环绕,电影级特效,高品质渲染',
  1070. 'scene_prefix' => '古风仙侠风格,仙境场景,云海仙山,灵气缭绕,梦幻光效,东方幻想美学'
  1071. ],
  1072. '新中式水墨风格' => [
  1073. 'character_prefix' => '新中式水墨风格,国风写意,水墨晕染,留白艺术,东方韵味,诗意氛围,高级插画',
  1074. 'scene_prefix' => '新中式水墨风格,山水意境,墨韵渲染,留白构图,东方美学,诗意场景'
  1075. ],
  1076. '写实插画风格' => [
  1077. 'character_prefix' => '写实插画风格,半写实人物,细节丰富,真实比例,数字绘画,高质量渲染,电影级质感',
  1078. 'scene_prefix' => '写实插画风格,高细节环境,数字绘景,真实光影,层次丰富,电影感构图'
  1079. ],
  1080. '3D卡通风格' => [
  1081. 'character_prefix' => '3D卡通风格,高品质三维建模,皮克斯动画质感,表情生动,角色可爱,细腻渲染',
  1082. 'scene_prefix' => '3D卡通风格,动画电影场景,三维建模,色彩明快,光影柔和,高品质渲染'
  1083. ],
  1084. '条漫风格' => [
  1085. 'character_prefix' => '条漫风格,韩漫质感,精致线稿,人物颜值高,细腻上色,剧情漫画风,高质量绘制',
  1086. 'scene_prefix' => '条漫风格,漫画背景,剧情分镜感,细腻光影,现代漫画质感'
  1087. ],
  1088. '赛博朋克风格' => [
  1089. 'character_prefix' => '赛博朋克风格,未来科技感,机械义体,霓虹光效,高对比色彩,科幻都市氛围,电影级渲染',
  1090. 'scene_prefix' => '赛博朋克风格,未来都市,霓虹街道,全息广告,机械科技元素,夜景氛围,电影级光影'
  1091. ],
  1092. '暗黑悬疑风格' => [
  1093. 'character_prefix' => '暗黑悬疑风格,神秘压抑氛围,强烈明暗对比,电影级灯光,细腻刻画,悬疑感十足',
  1094. 'scene_prefix' => '暗黑悬疑风格,阴郁环境,低饱和色调,迷雾光影,神秘气氛,电影感构图'
  1095. ],
  1096. '治愈清新风格' => [
  1097. 'character_prefix' => '治愈清新风格,温暖柔和色调,干净画面,自然光线,亲和气质,轻松愉悦氛围,高品质插画',
  1098. 'scene_prefix' => '治愈清新风格,阳光明亮,自然环境,温暖色彩,舒适氛围,细腻绘制,疗愈感强'
  1099. ]
  1100. ];
  1101. return isset($stylePrefixes[$inputArtStyle]) ? $stylePrefixes[$inputArtStyle] : [];
  1102. }
  1103. private function normalizeArtStyleInput($value): string
  1104. {
  1105. $value = trim((string)$value);
  1106. if ($value === '') {
  1107. return '';
  1108. }
  1109. $value = str_replace(["\r", "\n", "\t", ' ', ' ', '-', '_', ':', ':', ',', ',', '。', '.'], '', $value);
  1110. return mb_strtolower($value, 'UTF-8');
  1111. }
  1112. private function replaceArtStyleSection(string $content, string $artStyle): string
  1113. {
  1114. if ($content === '' || $artStyle === '') {
  1115. return $content;
  1116. }
  1117. $pattern = '/###美术风格\s*\R(.*?)(?=\R###|$)/su';
  1118. if (!preg_match($pattern, $content)) {
  1119. return $content;
  1120. }
  1121. return preg_replace($pattern, "###美术风格\n" . trim($artStyle), $content, 1);
  1122. }
  1123. /**
  1124. * DeepSeek流式输出处理方法
  1125. *
  1126. * @param array $post_data DeepSeek API请求参数
  1127. * @return \Generator 返回生成器,用于流式输出
  1128. */
  1129. private function deepSeekStreamResponse($post_data) {
  1130. // 设置最大输出tokens
  1131. $post_data['max_tokens'] = 300000;
  1132. $client = new Client(['timeout' => 1800, 'verify' => false]);
  1133. $response = $client->post($this->url, [
  1134. 'json' => $post_data,
  1135. 'headers' => $this->headers,
  1136. 'stream' => true // 启用流式响应
  1137. ]);
  1138. $body = $response->getBody();
  1139. $fullContent = '';
  1140. $fullReasoningContent = '';
  1141. $usage = [];
  1142. $buffer = '';
  1143. dLog('deepseek')->info('开始读取 DeepSeek 流式响应');
  1144. // 逐行读取流式响应
  1145. while (!$body->eof()) {
  1146. $chunk = $body->read(1024); // 每次读取 1KB
  1147. $buffer .= $chunk;
  1148. // 按行分割
  1149. $lines = explode("\n", $buffer);
  1150. // 保留最后一个不完整的行
  1151. $buffer = array_pop($lines);
  1152. foreach ($lines as $line) {
  1153. $line = trim($line);
  1154. // 跳过空行
  1155. if (empty($line)) {
  1156. continue;
  1157. }
  1158. // 检查是否是 SSE 数据行
  1159. if (strpos($line, 'data: ') !== 0) {
  1160. dLog('deepseek')->warning('非 SSE 数据行', ['line' => $line]);
  1161. continue;
  1162. }
  1163. $data = substr($line, 6); // 移除 "data: " 前缀
  1164. if ($data === '[DONE]') {
  1165. dLog('deepseek')->info('收到结束标记');
  1166. break 2; // 跳出两层循环
  1167. }
  1168. try {
  1169. $json = json_decode($data, true);
  1170. if (json_last_error() !== JSON_ERROR_NONE) {
  1171. dLog('deepseek')->warning('JSON 解析错误: ' . json_last_error_msg(), ['data' => $data]);
  1172. continue;
  1173. }
  1174. if (isset($json['choices'][0]['delta'])) {
  1175. $delta = $json['choices'][0]['delta'];
  1176. // 处理思维链内容(仅 deepseek-reasoner 模型)
  1177. if (isset($delta['reasoning_content'])) {
  1178. $fullReasoningContent .= $delta['reasoning_content'];
  1179. yield [
  1180. 'type' => 'reasoning',
  1181. 'content' => $delta['reasoning_content'],
  1182. 'full_reasoning' => $fullReasoningContent
  1183. ];
  1184. }
  1185. // 处理最终回答内容
  1186. if (isset($delta['content'])) {
  1187. $fullContent .= $delta['content'];
  1188. yield [
  1189. 'type' => 'content',
  1190. 'content' => $delta['content'],
  1191. ];
  1192. }
  1193. }
  1194. // 获取使用统计信息
  1195. if (isset($json['usage'])) {
  1196. $usage = $json['usage'];
  1197. dLog('deepseek')->info('收到使用统计', ['usage' => $usage]);
  1198. }
  1199. } catch (\Exception $e) {
  1200. dLog('deepseek')->error('解析流式响应失败: ' . $e->getMessage(), ['line' => $line]);
  1201. continue;
  1202. }
  1203. }
  1204. }
  1205. dLog('deepseek')->info('流式读取完成', [
  1206. 'content_length' => strlen($fullContent),
  1207. 'reasoning_length' => strlen($fullReasoningContent)
  1208. ]);
  1209. yield [
  1210. 'type' => 'done',
  1211. 'full_content' => $fullContent,
  1212. 'full_reasoning' => $fullReasoningContent,
  1213. 'usage' => $usage
  1214. ];
  1215. }
  1216. /**
  1217. * GPT 重试次数(env 可配置,默认 5 次)
  1218. */
  1219. private function gptRetryTimes()
  1220. {
  1221. return (int)env('GPT_RETRY_TIMES', 5);
  1222. }
  1223. /**
  1224. * GPT 重试间隔秒数(env 可配置,默认 10 秒)
  1225. */
  1226. private function gptRetryInterval()
  1227. {
  1228. return (int)env('GPT_RETRY_INTERVAL', 10);
  1229. }
  1230. /**
  1231. * 判断 GPT 请求异常是否可重试
  1232. * 仅连接失败/超时等传输层异常、5xx、429 可重试;其余 4xx(401/400 等)不重试
  1233. */
  1234. private function isGptRetryableException(\Exception $e)
  1235. {
  1236. if (!($e instanceof \GuzzleHttp\Exception\GuzzleException)) {
  1237. return false;
  1238. }
  1239. if ($e instanceof \GuzzleHttp\Exception\BadResponseException && $e->getResponse()) {
  1240. $status = $e->getResponse()->getStatusCode();
  1241. return $status >= 500 || $status == 429;
  1242. }
  1243. return true;
  1244. }
  1245. /**
  1246. * GPT 中转站探活:GET /v1/models,5 秒短超时
  1247. * 连接成功(含 401/403/404)视为可用;连接失败/超时/5xx/429 视为不可用
  1248. */
  1249. private function checkGptServiceAvailable()
  1250. {
  1251. $apiKey = env('GPT_54_API_KEY');
  1252. if (empty($apiKey)) {
  1253. return false;
  1254. }
  1255. try {
  1256. $checkClient = new Client(['timeout' => 5, 'verify' => false, 'http_errors' => false]);
  1257. $response = $checkClient->get('https://ai-api.kkidc.com/v1/models', [
  1258. 'headers' => [
  1259. 'Authorization' => 'Bearer ' . $apiKey,
  1260. 'Content-Type' => 'application/json'
  1261. ]
  1262. ]);
  1263. $status = $response->getStatusCode();
  1264. return $status < 500 && $status != 429;
  1265. } catch (\Exception $e) {
  1266. return false;
  1267. }
  1268. }
  1269. /**
  1270. * 探活并重试:最多重试 gptRetryTimes() 次,间隔 gptRetryInterval() 秒
  1271. * 全部失败抛出友好错误
  1272. */
  1273. private function ensureGptServiceAvailable()
  1274. {
  1275. $maxRetries = $this->gptRetryTimes();
  1276. $interval = $this->gptRetryInterval();
  1277. for ($attempt = 0; $attempt <= $maxRetries; $attempt++) {
  1278. if ($this->checkGptServiceAvailable()) {
  1279. return;
  1280. }
  1281. if ($attempt < $maxRetries) {
  1282. dLog('deepseek')->warning('GPT 中转站探活失败,准备重试', [
  1283. 'retry' => $attempt + 1,
  1284. 'max_retries' => $maxRetries
  1285. ]);
  1286. sleep($interval);
  1287. }
  1288. }
  1289. dLog('deepseek')->error('GPT 中转站探活失败,重试次数已用完');
  1290. logDB('deepseek', 'error', 'GPT 中转站服务不可用', [
  1291. 'max_retries' => $maxRetries,
  1292. 'interval' => $interval
  1293. ]);
  1294. Utils::throwError('20003:GPT 中转站服务暂时不可用,请稍后重试');
  1295. }
  1296. /**
  1297. * GPT 流式输出处理方法
  1298. *
  1299. * @param array $post_data GPT API请求参数
  1300. * @return \Generator 返回生成器,用于流式输出
  1301. */
  1302. private function gpt54StreamResponse($post_data) {
  1303. $apiKey = env('GPT_54_API_KEY');
  1304. if (empty($apiKey)) {
  1305. Utils::throwError('20003:GPT API Key未配置');
  1306. }
  1307. // 先探活,服务不可用时自动重试
  1308. $this->ensureGptServiceAvailable();
  1309. $client = new Client(['timeout' => 1800, 'verify' => false]);
  1310. $headers = [
  1311. 'Authorization' => 'Bearer ' . $apiKey,
  1312. 'Content-Type' => 'application/json'
  1313. ];
  1314. // 移除 thinking 参数,GPT-5.4 不支持
  1315. if (isset($post_data['thinking'])) {
  1316. unset($post_data['thinking']);
  1317. }
  1318. if (isset($post_data['reasoning_effort'])) {
  1319. unset($post_data['reasoning_effort']);
  1320. }
  1321. $post_data['max_completion_tokens'] = 100000;
  1322. $maxRetries = $this->gptRetryTimes();
  1323. $interval = $this->gptRetryInterval();
  1324. $attempt = 0;
  1325. while (true) {
  1326. $fullContent = '';
  1327. $usage = [];
  1328. $buffer = '';
  1329. try {
  1330. // 备用中转站地址1: https://token.ithinkai.cn/v1/chat/completions
  1331. // 备用中转站地址2: https://api.nonelinear.com/v1/chat/completions
  1332. $response = $client->post('https://ai-api.kkidc.com/v1/chat/completions', [
  1333. 'json' => $post_data,
  1334. 'headers' => $headers,
  1335. 'stream' => true // 启用流式响应
  1336. ]);
  1337. $body = $response->getBody();
  1338. dLog('deepseek')->info('开始读取 GPT 流式响应');
  1339. // 逐行读取流式响应
  1340. while (!$body->eof()) {
  1341. $chunk = $body->read(1024); // 每次读取 1KB
  1342. $buffer .= $chunk;
  1343. // 按行分割
  1344. $lines = explode("\n", $buffer);
  1345. // 保留最后一个不完整的行
  1346. $buffer = array_pop($lines);
  1347. foreach ($lines as $line) {
  1348. $line = trim($line);
  1349. // 跳过空行
  1350. if (empty($line)) {
  1351. continue;
  1352. }
  1353. // 检查是否是 SSE 数据行
  1354. if (strpos($line, 'data: ') !== 0) {
  1355. dLog('deepseek')->warning('非 SSE 数据行', ['line' => $line]);
  1356. continue;
  1357. }
  1358. $data = substr($line, 6); // 移除 "data: " 前缀
  1359. if ($data === '[DONE]') {
  1360. dLog('deepseek')->info('收到结束标记');
  1361. break 2; // 跳出 foreach 和流读取循环
  1362. }
  1363. try {
  1364. $json = json_decode($data, true);
  1365. if (json_last_error() !== JSON_ERROR_NONE) {
  1366. dLog('deepseek')->warning('JSON 解析错误: ' . json_last_error_msg(), ['data' => $data]);
  1367. continue;
  1368. }
  1369. if (isset($json['choices'][0]['delta'])) {
  1370. $delta = $json['choices'][0]['delta'];
  1371. // 处理回答内容
  1372. if (isset($delta['content'])) {
  1373. $fullContent .= $delta['content'];
  1374. yield [
  1375. 'type' => 'content',
  1376. 'content' => $delta['content'],
  1377. ];
  1378. }
  1379. }
  1380. // 获取使用统计信息
  1381. if (isset($json['usage'])) {
  1382. $usage = $json['usage'];
  1383. dLog('deepseek')->info('收到使用统计', ['usage' => $usage]);
  1384. }
  1385. } catch (\Exception $e) {
  1386. dLog('deepseek')->error('解析流式响应失败: ' . $e->getMessage(), ['line' => $line]);
  1387. continue;
  1388. }
  1389. }
  1390. }
  1391. dLog('deepseek')->info('流式读取完成', [
  1392. 'content_length' => strlen($fullContent)
  1393. ]);
  1394. yield [
  1395. 'type' => 'done',
  1396. 'full_content' => $fullContent,
  1397. 'full_reasoning' => '',
  1398. 'usage' => $usage
  1399. ];
  1400. return;
  1401. } catch (\Exception $e) {
  1402. // 已输出内容不重试(避免重复);非可重试异常不重试;重试次数用完则抛出
  1403. if (!empty($fullContent) || !$this->isGptRetryableException($e) || $attempt >= $maxRetries) {
  1404. dLog('deepseek')->error('GPT 流式请求失败: ' . $e->getMessage());
  1405. logDB('deepseek', 'error', 'GPT 流式请求失败', ['error' => $e->getMessage()]);
  1406. throw $e;
  1407. }
  1408. dLog('deepseek')->warning('GPT 流式请求失败,准备重试', [
  1409. 'retry' => $attempt + 1,
  1410. 'max_retries' => $maxRetries,
  1411. 'error' => $e->getMessage()
  1412. ]);
  1413. sleep($interval);
  1414. $attempt++;
  1415. }
  1416. }
  1417. }
  1418. // 与推理模型对话
  1419. public function chatWithReasoner($data) {
  1420. $content = getProp($data, 'content');
  1421. $model = getProp($data, 'model', 'r1');
  1422. // 模型兼容性处理:deepseek-chat 和 deepseek-reasoner 映射到 deepseek-v4-flash
  1423. $thinkingMode = getProp($data, 'thinking', 'disabled'); // 默认非思考模式
  1424. $reasoningEffort = getProp($data, 'reasoning_effort', 'high'); // 默认思考强度
  1425. if ($model == 'r1') {
  1426. $model = 'deepseek-v4-flash'; // r1 映射到 deepseek-v4-flash 思考模式
  1427. $thinkingMode = 'disabled';
  1428. } else {
  1429. $model = 'deepseek-v4-flash'; // 默认映射到 deepseek-v4-flash 非思考模式
  1430. $thinkingMode = 'disabled';
  1431. }
  1432. // 获取可选情感(根据音色可支持情感选)
  1433. $timbre_emotion = DB::table('mp_timbres')->where('is_enabled', 1)->pluck('emotion')->toArray();
  1434. $emotion_list = [];
  1435. foreach ($timbre_emotion as $emotion) {
  1436. $tmp = explode(',', $emotion);
  1437. $emotion_list = array_merge($emotion_list, $tmp);
  1438. }
  1439. $emotion_list = array_unique($emotion_list);
  1440. $emotion_str = implode('、', $emotion_list);
  1441. // // 获取可选情感
  1442. // $emotion_list = DB::table('mp_emotion_list')->where('is_enabled', 1)->select('emotion_name')->orderBy('id')->get()->pluck('emotion_name')->toArray();
  1443. // $emotion_str = implode('、', $emotion_list);
  1444. // 是否启用情感
  1445. $enable_emotion = getProp($data, 'enable_emotion', 0);
  1446. if ($enable_emotion) {
  1447. $sys_content = "下面有一段小说文本,请帮我将文本中的每句话按从上到下的顺序拆分成角色不同的剧本文稿(不得更改上下文顺序和内容),文稿形式严格按照“角色名(男、女、中性):台词{情感}”输出,需要注意以下几点要求:
  1448. 1.角色名后不要加入任何其他词语,只能加性别,在男、女或中性中选
  1449. 2.非对话部分请全部用旁白角色代替,旁白的情感统一选择中性
  1450. 3.情感必须在【{$emotion_str}】中选一个,不得使用其他词语";
  1451. }else {
  1452. $sys_content = "下面有一段小说文本,请帮我将文本中的每句话按从上到下的顺序拆分成角色不同的剧本文稿(不得更改上下文顺序和内容),文稿形式严格按照“角色名(男、女、中性):台词”输出,需要注意以下几点要求:
  1453. 1.角色名后不要加入任何其他词语,只能加性别,在男、女或中性中选
  1454. 2.非对话部分请全部用旁白角色代替,旁白的情感统一选择中性";
  1455. }
  1456. $messages = [
  1457. [
  1458. 'role' => 'system',
  1459. 'content' => $sys_content
  1460. ],
  1461. [
  1462. 'role' => 'user',
  1463. 'content' => $content
  1464. ]
  1465. ];
  1466. $post_data = [
  1467. 'model' => $model,
  1468. 'messages' => $messages,
  1469. // 'max_tokens' => 8192,
  1470. 'temperature' => 1,
  1471. 'frequency_penalty' => 0,
  1472. 'presence_penalty' => 0,
  1473. 'thinking' => ['type' => $thinkingMode],
  1474. 'response_format' => [
  1475. 'type' => 'text'
  1476. ],
  1477. 'stream' => false
  1478. ];
  1479. if ($thinkingMode == 'enabled') $post_data['reasoning_effort'] = $reasoningEffort;
  1480. // 根据模型类型选择调用方法
  1481. $fullContent = '';
  1482. $usage = [];
  1483. if (in_array($model, ['deepseek-reasoner', 'deepseek-chat', 'deepseek-v4-flash', 'deepseek-v4-pro'])) {
  1484. // DeepSeek 官方模型使用 DeepSeek API
  1485. $chatResult = $this->chatOnly($post_data);
  1486. } else if (in_array($model, $this->gpt_text_models)) {
  1487. // GPT-5.4 模型使用 TokenRouter API
  1488. $chatResult = $this->gpt54ChatOnly($post_data);
  1489. } else {
  1490. // 其他模型使用火山引擎API
  1491. $chatResult = $this->volcEngineChatCompletion($post_data);
  1492. }
  1493. if (is_array($chatResult)) {
  1494. $fullContent = $chatResult['fullContent'];
  1495. $usage = $chatResult['usage'];
  1496. }
  1497. // 处理获取到的剧本数据
  1498. $script_content = handleScriptWords($fullContent, $enable_emotion);
  1499. $result = [
  1500. 'origin_content' => $fullContent,
  1501. 'roles' => getProp($script_content, 'roles'),
  1502. 'words' => getProp($script_content, 'words'),
  1503. ];
  1504. return $result;
  1505. }
  1506. public function resetParagraphAudio($data) {
  1507. $bid = getProp($data, 'bid');
  1508. $cid = getProp($data, 'cid');
  1509. $version_id = getProp($data, 'version_id');
  1510. if (!DB::table('mp_chapter_paragraph_audios')->where('bid', $bid)->where('cid', $cid)->where('version_id', $version_id)->value('id')) return true;
  1511. return DB::table('mp_chapter_paragraph_audios')->where('bid', $bid)->where('cid', $cid)->where('version_id', $version_id)->update([
  1512. 'generate_status' => '待制作',
  1513. 'updated_at' => date('Y-m-d H:i:s')
  1514. ]);
  1515. }
  1516. public function saveParagraphAudio($data) {
  1517. $bid = getProp($data, 'bid');
  1518. $cid = getProp($data, 'cid');
  1519. $version_id = getProp($data, 'version_id');
  1520. $sequence = getProp($data, 'sequence');
  1521. $id = DB::table('mp_chapter_paragraph_audios')->where('bid', $bid)->where('cid', $cid)->where('version_id', $version_id)->where('sequence', $sequence)->value('id');
  1522. // 获取所有情感
  1523. $emotion_list = DB::table('mp_emotion_list')->where('is_enabled', 1)->pluck('emotion_name', 'emotion_code')->toArray();
  1524. $emotion_list = array_flip($emotion_list);
  1525. // 获取音色支持情感
  1526. $timbre_emotion = DB::table('mp_timbres')->where('timbre_type', getProp($data, 'voice_type'))->value('emotion');
  1527. $timbre_emotion = explode(',', $timbre_emotion);
  1528. $emotion = getProp($data, 'emotion');
  1529. if (!in_array($emotion, $timbre_emotion)) $emotion = '中性';
  1530. $emotion_type = isset($emotion_list[$emotion]) ? $emotion_list[$emotion] : 'neutral';
  1531. $list = [
  1532. 'bid' => $bid,
  1533. 'cid' => $cid,
  1534. 'version_id' => $version_id,
  1535. 'sequence' => $sequence,
  1536. 'role' => getProp($data, 'role'),
  1537. 'gender' => getProp($data, 'gender'),
  1538. 'text' => trim(getProp($data, 'text')),
  1539. 'emotion' => $emotion,
  1540. 'emotion_type' => $emotion_type,
  1541. 'voice_type' => getProp($data, 'voice_type'),
  1542. 'voice_name' => getProp($data, 'voice_name'),
  1543. 'speed_ratio' => getProp($data, 'speed_ratio', 0),
  1544. 'loudness_ratio'=> getProp($data, 'loudness_ratio', 0),
  1545. 'emotion_scale' => getProp($data, 'emotion_scale', 4),
  1546. 'pitch' => getProp($data, 'pitch', 0),
  1547. // 'paragraph_audio_url' => '',
  1548. 'generate_status' => '制作中',
  1549. 'error_msg' => '',
  1550. 'updated_at' => date('Y-m-d H:i:s')
  1551. ];
  1552. $continue = false;
  1553. // 判断是否含有中文、数字或英文,如果没有则跳过合成
  1554. if (!preg_match('/[\x{4e00}-\x{9fa5}]+/u', $list['text']) && !preg_match('/[0-9]+/', $list['text']) && !preg_match('/[a-zA-Z]+/', $list['text'])) {
  1555. $list['generate_status'] = '制作成功';
  1556. $list['paragraph_audio_url'] = 'https://zw-audiobook.tos-cn-beijing.volces.com/effects/ellipses_2s.mp3';
  1557. $list['subtitle_info'] = '{"duration": 2.0, "words": []}';
  1558. $continue = true;
  1559. }
  1560. // if (getProp($data, 'paragraph_audio_url')) $list['paragraph_audio_url'] = getProp($data, 'paragraph_audio_url');
  1561. if ($id) {
  1562. $boolen = DB::table('mp_chapter_paragraph_audios')->where('id', $id)->update($list);
  1563. }else {
  1564. $list['created_at'] = date('Y-m-d H:i:s');
  1565. $id = DB::table('mp_chapter_paragraph_audios')->insertGetId($list);
  1566. $boolen = $id ? true : false;
  1567. }
  1568. // 如果更新成功则加入查询队列
  1569. if ($boolen) {
  1570. $redis_key = "select-{$bid}-{$version_id}-{$cid}";
  1571. Redis::sadd($redis_key, $id);
  1572. }
  1573. if ($boolen && !$continue) {
  1574. $boolen = false;
  1575. $client = new Client(['timeout' => 1800, 'verify' => false]);
  1576. // 根据ID通过API通知合成音频
  1577. // $result = $client->get("http://47.240.171.155:5000/api/previewTask?taskId={$id}");
  1578. $result = $client->get("http://122.9.129.83:5000/api/previewTask?taskId={$id}");
  1579. $response = $result->getBody()->getContents();
  1580. $response_arr = json_decode($response, true);
  1581. if (!isset($response_arr['code']) || (int)$response_arr['code'] !== 0) {
  1582. $error_msg = isset($response_arr['msg']) ? $response_arr['msg'] : '未知错误';
  1583. Log::info('通知火山生成段落音频失败: '.$error_msg);
  1584. Utils::throwError('20003:通知火山生成段落音频失败');
  1585. }
  1586. $boolen = true;
  1587. }
  1588. return $boolen;
  1589. }
  1590. public function insertAudioEffect($data) {
  1591. $audio_id = getProp($data, 'audio_id');
  1592. $chapter_audio = DB::table('mp_chapter_audios')->where('id', $audio_id)->first();
  1593. $bid = getProp($chapter_audio, 'bid');
  1594. $version_id = getProp($chapter_audio, 'version_id');
  1595. $cid = getProp($chapter_audio, 'cid');
  1596. if (getProp($chapter_audio, 'generate_status') != '制作成功') Utils::throwError('20003:请先完成有声制作');
  1597. $audio_effect_json = getProp($data, 'audio_effect_json');
  1598. if (!is_string($audio_effect_json)) $audio_effect_json = json_encode($audio_effect_json, 256);
  1599. try {
  1600. DB::beginTransaction();
  1601. $count = DB::table('mp_audio_tasks')->where('audio_id', $audio_id)->count('id');
  1602. if (!$count) {
  1603. $task_name = getProp($chapter_audio, 'book_name').' '.getProp($chapter_audio, 'chapter_name').'【'.getProp($chapter_audio, 'version_name').'】';
  1604. }else {
  1605. $task_name = getProp($chapter_audio, 'book_name').' '.getProp($chapter_audio, 'chapter_name').'【'.getProp($chapter_audio, 'version_name').'】('.($count+1).')';
  1606. }
  1607. $boolen1 = DB::table('mp_chapter_audios')->where('id', $audio_id)->update([
  1608. 'audio_effect_status' => '添加中',
  1609. 'audio_effect_json' => $audio_effect_json,
  1610. 'updated_at' => date('Y-m-d H:i:s')
  1611. ]);
  1612. if (!$boolen1) {
  1613. DB::rollBack();
  1614. Utils::throwError('20003:更新生成数据失败');
  1615. }
  1616. $id = DB::table('mp_audio_tasks')->insertGetId([
  1617. 'audio_id' => $audio_id,
  1618. 'generate_status' => '执行中',
  1619. 'generate_json' => json_encode([], 256),
  1620. 'bid' => $bid,
  1621. 'book_name' => getProp($chapter_audio, 'book_name'),
  1622. 'version_id' => $version_id,
  1623. 'version_name' => getProp($chapter_audio, 'version_name'),
  1624. 'cid' => $cid,
  1625. 'chapter_name' => getProp($chapter_audio, 'chapter_name'),
  1626. 'task_name' => $task_name,
  1627. 'created_at' => date('Y-m-d H:i:s'),
  1628. 'updated_at' => date('Y-m-d H:i:s')
  1629. ]);
  1630. if (!$id) {
  1631. DB::rollBack();
  1632. Utils::throwError('20003:创建任务失败');
  1633. }
  1634. }catch (\Exception $e) {
  1635. DB::rollBack();
  1636. Utils::throwError('20003:'.$e->getMessage());
  1637. }
  1638. DB::commit();
  1639. $client = new Client(['timeout' => 1800, 'verify' => false]);
  1640. // 根据ID通过API通知合成音频
  1641. // $result = $client->get("http://47.240.171.155:5000/api/postTask?taskId={$id}");
  1642. $result = $client->get("http://122.9.129.83:5000/api/postTask?taskId={$id}");
  1643. $response = $result->getBody()->getContents();
  1644. $response_arr = json_decode($response, true);
  1645. if (!isset($response_arr['code']) || (int)$response_arr['code'] !== 0) {
  1646. $error_msg = isset($response_arr['msg']) ? $response_arr['msg'] : '未知错误';
  1647. Log::info('通知火山插入音效失败: '.$error_msg);
  1648. Utils::throwError('20003:通知火山插入音效失败');
  1649. }
  1650. return true;
  1651. }
  1652. public function insertBgm($data) {
  1653. $audio_id = getProp($data, 'audio_id');
  1654. $chapter_audio = DB::table('mp_chapter_audios')->where('id', $audio_id)->first();
  1655. $bid = getProp($chapter_audio, 'bid');
  1656. $version_id = getProp($chapter_audio, 'version_id');
  1657. $cid = getProp($chapter_audio, 'cid');
  1658. if (getProp($chapter_audio, 'generate_status') != '制作成功') Utils::throwError('20003:请先完成有声制作');
  1659. $bgm_json = getProp($data, 'bgm_json');
  1660. if (!is_string($bgm_json)) $bgm_json = json_encode($bgm_json, 256);
  1661. if (!$bgm_json) {
  1662. $bgm_json = getProp($data, 'audio_effect_json');
  1663. if (!is_string($bgm_json)) $bgm_json = json_encode($bgm_json, 256);
  1664. }
  1665. try {
  1666. DB::beginTransaction();
  1667. $count = DB::table('mp_audio_tasks')->where('audio_id', $audio_id)->count('id');
  1668. if (!$count) {
  1669. $task_name = getProp($chapter_audio, 'book_name').' '.getProp($chapter_audio, 'chapter_name').'【'.getProp($chapter_audio, 'version_name').'】';
  1670. }else {
  1671. $task_name = getProp($chapter_audio, 'book_name').' '.getProp($chapter_audio, 'chapter_name').'【'.getProp($chapter_audio, 'version_name').'】('.($count+1).')';
  1672. }
  1673. $boolen1 = DB::table('mp_chapter_audios')->where('id', $audio_id)->update([
  1674. 'bgm_status' => '添加中',
  1675. 'bgm_json' => $bgm_json,
  1676. 'updated_at' => date('Y-m-d H:i:s')
  1677. ]);
  1678. if (!$boolen1) {
  1679. DB::rollBack();
  1680. Utils::throwError('20003:更新生成数据失败');
  1681. }
  1682. $id = DB::table('mp_audio_tasks')->insertGetId([
  1683. 'audio_id' => $audio_id,
  1684. 'generate_status' => '执行中',
  1685. 'generate_json' => json_encode([], 256),
  1686. 'bid' => $bid,
  1687. 'book_name' => getProp($chapter_audio, 'book_name'),
  1688. 'version_id' => $version_id,
  1689. 'version_name' => getProp($chapter_audio, 'version_name'),
  1690. 'cid' => $cid,
  1691. 'chapter_name' => getProp($chapter_audio, 'chapter_name'),
  1692. 'task_name' => $task_name,
  1693. 'created_at' => date('Y-m-d H:i:s'),
  1694. 'updated_at' => date('Y-m-d H:i:s')
  1695. ]);
  1696. if (!$id) {
  1697. DB::rollBack();
  1698. Utils::throwError('20003:创建任务失败');
  1699. }
  1700. }catch (\Exception $e) {
  1701. DB::rollBack();
  1702. Utils::throwError('20003:'.$e->getMessage());
  1703. }
  1704. DB::commit();
  1705. $client = new Client(['timeout' => 1800, 'verify' => false]);
  1706. // 根据ID通过API通知合成音频
  1707. // $result = $client->get("http://47.240.171.155:5000/api/postTask?taskId={$id}");
  1708. $result = $client->get("http://122.9.129.83:5000/api/postTask?taskId={$id}");
  1709. $response = $result->getBody()->getContents();
  1710. $response_arr = json_decode($response, true);
  1711. if (!isset($response_arr['code']) || (int)$response_arr['code'] !== 0) {
  1712. $error_msg = isset($response_arr['msg']) ? $response_arr['msg'] : '未知错误';
  1713. Log::info('通知火山插入bgm失败: '.$error_msg);
  1714. Utils::throwError('20003:通知火山插入bgm失败');
  1715. }
  1716. return true;
  1717. }
  1718. public function getParagraphAudios($data) {
  1719. $bid = getProp($data, 'bid');
  1720. $cid = getProp($data, 'cid');
  1721. $version_id = getProp($data, 'version_id');
  1722. $sequence = getProp($data, 'sequence');
  1723. // 获取已生成的音频
  1724. $query = DB::table('mp_chapter_paragraph_audios')->where('bid', $bid)->where('cid', $cid)->where('version_id', $version_id);
  1725. if ($sequence) $query->where('sequence', $sequence);
  1726. $paragraph_audios = $query->orderBy('sequence')->get();
  1727. $result = [];
  1728. foreach($paragraph_audios as $item) {
  1729. $result[] = [
  1730. 'sequence' => getProp($item, 'sequence'),
  1731. 'role' => getProp($item, 'role'),
  1732. 'gender' => getProp($item, 'gender'),
  1733. 'text' => trim(getProp($item, 'text')),
  1734. 'emotion' => getProp($item, 'emotion'),
  1735. 'emotion_type' => getProp($item, 'emotion_type'),
  1736. 'voice_type' => getProp($item, 'voice_type'),
  1737. 'voice_name' => getProp($item, 'voice_name'),
  1738. 'speed_ratio' => getProp($item, 'speed_ratio'),
  1739. 'loudness_ratio' => getProp($item, 'loudness_ratio'),
  1740. 'emotion_scale' => getProp($item, 'emotion_scale'),
  1741. 'paragraph_audio_url' => getProp($item, 'paragraph_audio_url'),
  1742. 'subtitle_info' => json_decode(getProp($item, 'subtitle_info'), true),
  1743. ];
  1744. }
  1745. return $result;
  1746. }
  1747. // 新增合成任务
  1748. public function addGenerateTask($data) {
  1749. $bid = getProp($data, 'bid');
  1750. $cid = getProp($data, 'cid');
  1751. $version_id = getProp($data, 'version_id');
  1752. $generate_json = getProp($data, 'generate_json');
  1753. // 获取已生成的音频
  1754. $paragraph_audios = DB::table('mp_chapter_paragraph_audios')->where('bid', $bid)->where('cid', $cid)->where('version_id', $version_id)->get();
  1755. $paragraph_list = [];
  1756. foreach($paragraph_audios as $item) {
  1757. $paragraph_list[getProp($item, 'sequence')] = [
  1758. 'role' => getProp($item, 'role'),
  1759. 'gender' => getProp($item, 'gender'),
  1760. 'text' => trim(getProp($item, 'text')),
  1761. 'emotion' => getProp($item, 'emotion'),
  1762. 'emotion_type' => getProp($item, 'emotion_type'),
  1763. 'voice_type' => getProp($item, 'voice_type'),
  1764. 'voice_name' => getProp($item, 'voice_name'),
  1765. 'speed_ratio' => getProp($item, 'speed_ratio'),
  1766. 'loudness_ratio' => getProp($item, 'loudness_ratio'),
  1767. 'emotion_scale' => getProp($item, 'emotion_scale'),
  1768. 'paragraph_audio_url' => getProp($item, 'paragraph_audio_url'),
  1769. ];
  1770. }
  1771. // 更新角色-音色信息
  1772. $existed_role_info = DB::table('mp_book_version')->where('bid', $bid)->where('id', $version_id)->value('role_info');
  1773. $existed_role_info = json_decode($existed_role_info, true);
  1774. if (!$existed_role_info) $existed_role_info = [];
  1775. // 获取情感信息
  1776. $emotion_list = DB::table('mp_emotion_list')->where('is_enabled', 1)->pluck('emotion_name', 'emotion_code')->toArray();
  1777. $emotion_list = array_flip($emotion_list);
  1778. // 获取音色对应情感组
  1779. $timbre_emotions = DB::table('mp_timbres')->where('is_enabled', 1)->select('timbre_type', 'emotion')->get();
  1780. $timbre_emotion_list = [];
  1781. foreach($timbre_emotions as $item) {
  1782. $timbre_emotion_list[getProp($item, 'timbre_type')] = explode(',', getProp($item, 'emotion'));
  1783. }
  1784. // 构造生成音频的json
  1785. $words = json_decode($generate_json, true);
  1786. // 最终合成前的参数组
  1787. $mp_chapter_paragraph_audios = [];
  1788. $sequence = 1;
  1789. $complete_paragraph_sequences = [];
  1790. foreach($words as &$word) {
  1791. if (!isset($word['text']) || !isset($word['emotion']) || !isset($word['voice_type']) || !isset($word['voice_name']) || !isset($word['speed_ratio']) || !isset($word['loudness_ratio']) || !isset($word['emotion_scale'])) Utils::throwError('20003:参数格式有误');
  1792. if (!($word['text']) || !($word['voice_type']) || !($word['voice_name'])) Utils::throwError('20003:参数不得为空');
  1793. $role = getProp($word, 'role');
  1794. $word['gender'] = (int)$word['gender'];
  1795. // 判断音色对应情感是否支持,不支持则调整为中性
  1796. $access_emotion = isset($timbre_emotion_list[$word['voice_type']]) ? $timbre_emotion_list[$word['voice_type']] : [];
  1797. if (!in_array($word['emotion'], $access_emotion)) $word['emotion'] = '中性';
  1798. // 如果有对应情感则赋值,没有则默认为中性(neutral)
  1799. if (isset($emotion_list[getProp($word, 'emotion')])) {
  1800. $word['emotion_type'] = $emotion_list[getProp($word, 'emotion')];
  1801. }else {
  1802. $word['emotion'] = '中性';
  1803. $word['emotion_type'] = 'neutral';
  1804. }
  1805. $existed_role_info[$role] = [
  1806. 'timbre_type' => $word['voice_type'],
  1807. 'timbre_name' => $word['voice_name'],
  1808. 'emotion' => $word['emotion'],
  1809. 'emotion_type' => $word['emotion_type'],
  1810. 'speed_ratio' => $word['speed_ratio'],
  1811. 'loudness_ratio'=> $word['loudness_ratio'],
  1812. 'emotion_scale' => $word['emotion_scale'],
  1813. 'pitch' => $word['pitch']
  1814. ];
  1815. $word['paragraph_audio_url'] = '';
  1816. // 判断生成参数是否相同,相同则直接使用已生成的音频
  1817. $paragraph = isset($paragraph_list[$sequence]) ? $paragraph_list[$sequence] : [];
  1818. // 如果音频存在并且参数都未改变则使用已生成的音频
  1819. if (getProp($paragraph, 'paragraph_audio_url')) {
  1820. // if (getProp($paragraph, 'role') == getProp($word, 'role') && getProp($paragraph, 'text') == getProp($word, 'text') &&
  1821. // getProp($paragraph, 'voice_type') == getProp($word, 'voice_type') &&
  1822. // getProp($paragraph, 'speed_ratio') == getProp($word, 'speed_ratio') && getProp($paragraph, 'loudness_ratio') == getProp($word, 'loudness_ratio') &&
  1823. // getProp($paragraph, 'emotion_scale') == getProp($word, 'emotion_scale'))
  1824. // {
  1825. // $word['paragraph_audio_url'] = getProp($paragraph, 'paragraph_audio_url');
  1826. // }
  1827. $word['paragraph_audio_url'] = getProp($paragraph, 'paragraph_audio_url');
  1828. }
  1829. $tmp = $word;
  1830. // 组装章节分句音频数据
  1831. // $tmp['sequence'] = getProp($word, 'sequence');
  1832. // $tmp['text'] = getProp($word, 'text');
  1833. // $tmp['emotion'] = getProp($word, 'emotion');
  1834. // $tmp['emotion_type'] = getProp($word, 'emotion_type');
  1835. // $tmp['voice_name'] = getProp($word, 'voice_name');
  1836. // $tmp['voice_type'] = getProp($word, 'voice_type');
  1837. // $tmp['speed_ratio'] = getProp($word, 'speed_ratio');
  1838. // $tmp['loudness_ratio'] = getProp($word, 'loudness_ratio');
  1839. // $tmp['emotion_scale'] = getProp($word, 'emotion_scale');
  1840. $tmp['bid'] = $bid;
  1841. $tmp['version_id'] = $version_id;
  1842. $tmp['cid'] = $cid;
  1843. $tmp['sequence'] = $sequence;
  1844. $tmp['created_at'] = date('Y-m-d H:i:s');
  1845. $tmp['updated_at'] = date('Y-m-d H:i:s');
  1846. if (!getProp($tmp, 'paragraph_audio_url')) Utils::throwError('20003:段落未生成音频,请等待完成后提交');
  1847. $mp_chapter_paragraph_audios[] = $tmp;
  1848. $complete_paragraph_sequences[] = $sequence;
  1849. $sequence++;
  1850. }
  1851. $generate_json = json_encode($words, 256);
  1852. // 判断是否有未生成字幕的段落
  1853. $no_subtitle_sequences = DB::table('mp_chapter_paragraph_audios')->where('bid', $bid)->where('cid', $cid)->where('version_id', $version_id)->whereIn('sequence', $complete_paragraph_sequences)->whereNull('subtitle_info')->pluck('sequence')->toArray();
  1854. if ($no_subtitle_sequences) {
  1855. Utils::throwError('20003:请先将以下段落序号生成字幕('.implode('、', $no_subtitle_sequences).')');
  1856. }
  1857. try {
  1858. DB::beginTransaction();
  1859. $role_info = json_encode($existed_role_info, 256);
  1860. $boolen = DB::table('mp_book_version')->where('bid', $bid)->where('id', $version_id)->update(['role_info' => $role_info, 'updated_at' => date('Y-m-d H:i:s')]);
  1861. if (!$boolen) {
  1862. DB::rollBack();
  1863. Utils::throwError('20003:更新角色信息失败');
  1864. }
  1865. $count = DB::table('mp_audio_tasks')->where('bid', $bid)->where('version_id', $version_id)->where('cid', $cid)->count('id');
  1866. $chapter_audio = DB::table('mp_chapter_audios')->where('bid', $bid)->where('version_id', $version_id)->where('cid', $cid)->first();
  1867. if (!$count) {
  1868. $task_name = getProp($chapter_audio, 'book_name').' '.getProp($chapter_audio, 'chapter_name').'【'.getProp($chapter_audio, 'version_name').'】';
  1869. }else {
  1870. $task_name = getProp($chapter_audio, 'book_name').' '.getProp($chapter_audio, 'chapter_name').'【'.getProp($chapter_audio, 'version_name').'】('.($count+1).')';
  1871. }
  1872. $boolen1 = DB::table('mp_chapter_audios')->where('bid', $bid)->where('version_id', $version_id)->where('cid', $cid)->update(['generate_status'=>'制作中', 'generate_json' => $generate_json, 'updated_at' => date('Y-m-d H:i:s')]);
  1873. if (!$boolen1) {
  1874. DB::rollBack();
  1875. Utils::throwError('20003:更新生成数据失败');
  1876. }
  1877. $id = DB::table('mp_audio_tasks')->insertGetId([
  1878. 'audio_id' => getProp($chapter_audio, 'id'),
  1879. 'generate_status' => '执行中',
  1880. 'generate_json' => $generate_json,
  1881. 'bid' => $bid,
  1882. 'book_name' => getProp($chapter_audio, 'book_name'),
  1883. 'version_id' => $version_id,
  1884. 'version_name' => getProp($chapter_audio, 'version_name'),
  1885. 'cid' => $cid,
  1886. 'chapter_name' => getProp($chapter_audio, 'chapter_name'),
  1887. 'task_name' => $task_name,
  1888. 'created_at' => date('Y-m-d H:i:s'),
  1889. 'updated_at' => date('Y-m-d H:i:s')
  1890. ]);
  1891. if (!$id) {
  1892. DB::rollBack();
  1893. Utils::throwError('20003:创建任务失败');
  1894. }
  1895. // 删除不在段落序号范围内的其他数据
  1896. if ($complete_paragraph_sequences) {
  1897. DB::table('mp_chapter_paragraph_audios')->where('bid', $bid)->where('version_id', $version_id)->where('cid', $cid)->whereNotIn('sequence', $complete_paragraph_sequences)->delete();
  1898. }
  1899. // // 删除章节分句音频数据并重新插入
  1900. // DB::table('mp_chapter_paragraph_audios')->where('bid', $bid)->where('version_id', $version_id)->where('cid', $cid)->delete();
  1901. // $boolen3 = DB::table('mp_chapter_paragraph_audios')->insert($mp_chapter_paragraph_audios);
  1902. // if (!$boolen3) {
  1903. // DB::rollBack();
  1904. // Utils::throwError('20003:更新章节分句音频失败');
  1905. // }
  1906. } catch (\Exception $e) {
  1907. DB::rollBack();
  1908. Utils::throwError('20003:'.$e->getMessage());
  1909. }
  1910. DB::commit();
  1911. // 通知火山生成音频
  1912. $client = new Client(['timeout' => 1800, 'verify' => false]);
  1913. // 根据ID通过API通知合成音频
  1914. // $result = $client->get("http://47.240.171.155:5000/api/chapterTask?taskId={$id}");
  1915. $result = $client->get("http://122.9.129.83:5000/api/chapterTask?taskId={$id}");
  1916. $response = $result->getBody()->getContents();
  1917. $response_arr = json_decode($response, true);
  1918. if (!isset($response_arr['code']) || (int)$response_arr['code'] !== 0) {
  1919. $error_msg = isset($response_arr['msg']) ? $response_arr['msg'] : '未知错误';
  1920. Log::info('通知火山生成音频失败: '.$error_msg);
  1921. Utils::throwError('20003:通知火山生成音频失败');
  1922. }
  1923. return true;
  1924. }
  1925. public function timbreList($data) {
  1926. $gender = getProp($data, 'gender');
  1927. $timbre_name = getProp($data, 'voice_name');
  1928. $category_id = getProp($data, 'category_id');
  1929. $age_stage = getProp($data, 'age_stage');
  1930. $query = DB::table('mp_timbres')->where('is_enabled', 1)->select('timbre_name as voice_name', 'timbre_type as voice_type', 'gender', 'age_stage', 'language', 'emotion', 'label', 'first_category_id', 'first_category_name', 'second_category_id', 'second_category_name', 'third_category_id', 'third_category_name', 'audio_url');
  1931. if ($gender) {
  1932. $query->where('gender', $gender);
  1933. }
  1934. if ($timbre_name) {
  1935. $query->where('timbre_name', 'like', "%{$timbre_name}%");
  1936. }
  1937. if ($category_id) {
  1938. $query->where(function ($query) use ($category_id) {
  1939. $query->where('first_category_id', $category_id)->orWhere('second_category_id', $category_id)->orWhere('third_category_id', $category_id);
  1940. });
  1941. }
  1942. if ($age_stage) {
  1943. $query->where('age_stage', $age_stage);
  1944. }
  1945. $list = $query->get()->map(function ($value) {
  1946. $value = (array)$value;
  1947. $value['voice_name'] = str_replace('(多情感)', '', $value['voice_name']);
  1948. return $value;
  1949. })->toArray();
  1950. return $list;
  1951. }
  1952. // 生成火山临时token
  1953. public function setStsToken() {
  1954. // ************* 配置参数 *************
  1955. $method = 'GET';
  1956. $service = 'sts';
  1957. $host = 'open.volcengineapi.com';
  1958. $region = env('VOLC_REGION');
  1959. $endpoint = 'https://open.volcengineapi.com';
  1960. // $endpoint = 'https://tos-cn-beijing.volces.com';
  1961. $access_key = env('VOLC_AK');
  1962. $secret_key = env('VOLC_SK');
  1963. // 获取缓存中的token,如果没有则请求接口
  1964. $token = Redis::get('volc_sts_token');
  1965. if (!$token) {
  1966. // 查询参数
  1967. $query_parameters = [
  1968. 'Action' => 'AssumeRole',
  1969. 'RoleSessionName' => 'user@zw',
  1970. 'RoleTrn' => 'trn:iam::2102575520:role/tos_role',
  1971. 'Version' => '2018-01-01'
  1972. ];
  1973. // 生成URL编码的查询字符串
  1974. $request_parameters = http_build_query($query_parameters, '', '&', PHP_QUERY_RFC3986);
  1975. // 获取签名头信息
  1976. $headers = $this->getSignHeaders($method, $service, $host, $region, $request_parameters, $access_key, $secret_key);
  1977. // 构建完整URL
  1978. $request_url = $endpoint . '?' . $request_parameters;
  1979. $client = new Client(['verify' => false]);
  1980. $response = $client->get($request_url, ['headers' => $headers]);
  1981. $response_arr = json_decode($response->getBody()->getContents(), true);
  1982. $result = [
  1983. 'SessionToken' => isset($response_arr['Result']['Credentials']['SessionToken']) ? $response_arr['Result']['Credentials']['SessionToken'] : '',
  1984. 'AccessKeyId' => isset($response_arr['Result']['Credentials']['AccessKeyId']) ? $response_arr['Result']['Credentials']['AccessKeyId'] : '',
  1985. 'SecretAccessKey' => isset($response_arr['Result']['Credentials']['SecretAccessKey']) ? $response_arr['Result']['Credentials']['SecretAccessKey'] : '',
  1986. 'Region' => env('VOLC_REGION'),
  1987. 'Endpoint' => env('VOLC_END_POINT'),
  1988. 'Bucket' => env('VOLC_BUCKET'),
  1989. ];
  1990. // 缓存token
  1991. Redis::setex('volc_sts_token', 3000, json_encode($result));
  1992. return $result;
  1993. } else {
  1994. return json_decode($token, true);
  1995. }
  1996. // $response = $response['Response'];
  1997. // $access_key = $response['Credentials']['AccessKeyId'];
  1998. // $secret_key = $response['Credentials']['AccessKeySecret'];
  1999. // $security_token = $response['Credentials']['SecurityToken'];
  2000. // $expiration = $response['Credentials']['Expiration'];
  2001. // dd($response_arr);
  2002. }
  2003. public function emotionGroups($data) {
  2004. $id = getProp($data, 'group_id');
  2005. $group_name = getProp($data, 'group_name');
  2006. $voice_type = getProp($data, 'voice_type');
  2007. $query = DB::table('mp_emotion_groups')->where('is_enabled', 1)->select('id as group_id', 'group_name',
  2008. 'emotion', 'emotion_type', 'voice_name', 'voice_type', 'speed_ratio', 'loudness_ratio', 'emotion_scale',
  2009. 'pitch', 'generate_status', 'audio_url', 'error_msg');
  2010. if ($group_name) {
  2011. $query->where('group_name', 'like', "%{$group_name}%");
  2012. }
  2013. if ($id) {
  2014. $query->where('id', $id);
  2015. }
  2016. if ($voice_type) {
  2017. $query->where('voice_type', $voice_type);
  2018. }
  2019. return $query->orderBy('id')->get()->map(function ($value) {
  2020. return (array)$value;
  2021. })->toArray();
  2022. }
  2023. private function sign($key, $msg) {
  2024. return hash_hmac('sha256', $msg, $key, true);
  2025. }
  2026. // 生成签名密钥
  2027. private function getSignatureKey($key, $dateStamp, $regionName, $serviceName) {
  2028. $kDate = $this->sign($key, $dateStamp);
  2029. $kRegion = $this->sign($kDate, $regionName);
  2030. $kService = $this->sign($kRegion, $serviceName);
  2031. $kSigning = $this->sign($kService, 'request');
  2032. return $kSigning;
  2033. }
  2034. // 获取签名头信息
  2035. private function getSignHeaders($method, $service, $host, $region, $request_parameters, $access_key, $secret_key) {
  2036. $contenttype = 'application/x-www-form-urlencoded';
  2037. $accept = 'application/json';
  2038. // 获取当前UTC时间
  2039. $t = new DateTime('now', new DateTimeZone('UTC'));
  2040. $xdate = $t->format('Ymd\THis\Z');
  2041. $datestamp = $t->format('Ymd');
  2042. // 1. 拼接规范请求串
  2043. $canonical_uri = '/';
  2044. $canonical_querystring = $request_parameters;
  2045. $canonical_headers = "content-type:{$contenttype}\nhost:{$host}\nx-date:{$xdate}\n";
  2046. $signed_headers = 'content-type;host;x-date';
  2047. // 空请求体的SHA256哈希
  2048. $payload_hash = hash('sha256', '');
  2049. $canonical_request = implode("\n", [
  2050. $method,
  2051. $canonical_uri,
  2052. $canonical_querystring,
  2053. $canonical_headers,
  2054. $signed_headers,
  2055. $payload_hash
  2056. ]);
  2057. // 2. 拼接待签名字符串
  2058. $algorithm = 'HMAC-SHA256';
  2059. $credential_scope = implode('/', [$datestamp, $region, $service, 'request']);
  2060. $hashed_canonical_request = hash('sha256', $canonical_request);
  2061. $string_to_sign = implode("\n", [
  2062. $algorithm,
  2063. $xdate,
  2064. $credential_scope,
  2065. $hashed_canonical_request
  2066. ]);
  2067. // 3. 计算签名
  2068. $signing_key = $this->getSignatureKey($secret_key, $datestamp, $region, $service);
  2069. $signature = hash_hmac('sha256', $string_to_sign, $signing_key);
  2070. // 4. 添加签名到请求头
  2071. $authorization_header = sprintf(
  2072. '%s Credential=%s/%s, SignedHeaders=%s, Signature=%s',
  2073. $algorithm,
  2074. $access_key,
  2075. $credential_scope,
  2076. $signed_headers,
  2077. $signature
  2078. );
  2079. return [
  2080. 'Accept' => $accept,
  2081. 'Content-Type' => $contenttype,
  2082. 'X-Date' => $xdate,
  2083. 'Authorization' => $authorization_header
  2084. ];
  2085. }
  2086. // 文字合成语音(火山引擎)
  2087. public function tts($data) {
  2088. $url = 'https://openspeech.bytedance.com/api/v1/tts';
  2089. $headers = [
  2090. 'Authorization' => 'Bearer;'.env('VOLC_TOKEN'),
  2091. 'Content-Type' => 'application/json; charset=UTF-8'
  2092. ];
  2093. $post_data = [
  2094. 'app' => [
  2095. 'appid' => env('VOLC_APPID'),
  2096. 'token' => env('VOLC_TOKEN'),
  2097. 'cluster' => 'volcano_tts'
  2098. ],
  2099. 'user' => [
  2100. 'uid' => 'mp_audio'
  2101. ],
  2102. // 'audio' => [
  2103. // 'voice_type' =>
  2104. // ],
  2105. ];
  2106. }
  2107. public function scriptList($data) {
  2108. $uid = Site::getUid();
  2109. $script_id = getProp($data, 'script_id');
  2110. $script_name = getProp($data, 'script_name');
  2111. $query = DB::table('mp_scripts')->where('is_deleted', 0)->where('user_id', $uid)->select('*');
  2112. if ($script_id) {
  2113. $query->where('id', $script_id);
  2114. }
  2115. if ($script_name) {
  2116. $query->where('script_name', 'like', "%{$script_name}%");
  2117. }
  2118. return $query->orderBy('created_at', 'desc')->paginate(12);
  2119. }
  2120. public function scripts($data) {
  2121. $uid = Site::getUid();
  2122. $script_id = getProp($data, 'script_id');
  2123. $script_name = getProp($data, 'script_name');
  2124. $is_products = getProp($data, 'is_products');
  2125. $query = DB::table('mp_scripts')->where('is_deleted', 0)->where('user_id', $uid)->select('id as script_id', 'script_name');
  2126. if ($script_id) {
  2127. $query->where('id', $script_id);
  2128. }
  2129. if ($is_products !== '') {
  2130. $query->where('is_products', $is_products);
  2131. }
  2132. if ($script_name) {
  2133. $query->where('script_name', 'like', "%{$script_name}%");
  2134. }
  2135. return $query->orderBy('created_at', 'desc')->get()->map(function ($value) {
  2136. return (array)$value;
  2137. })->toArray();
  2138. }
  2139. public function scriptInfo($data) {
  2140. $uid = Site::getUid();
  2141. $script_id = getProp($data, 'script_id');
  2142. $script = DB::table('mp_scripts')->where('id', $script_id)->where('is_deleted', 0)->where('user_id', $uid)
  2143. // ->selectRaw('id as script_id, script_name, intro, highlights, roles, role_relationship, core_contradiction, art_style, scenes, status, start_episode_sequence, end_episode_sequence, episode_num, remark, created_at')->first();
  2144. ->selectRaw('id as script_id, script_name')->first();
  2145. if (!$script) Utils::throwError('20003:该剧本不存在!');
  2146. $script = (array)$script;
  2147. // 获取分集组信息
  2148. $groups = DB::table('mp_script_episode_group')->where('script_id', $script_id)->where('is_deleted', 0)
  2149. ->selectRaw('id as group_id, script_id, group_name, start_episode_number, end_episode_number, intro, highlights, roles, role_relationship, core_contradiction, art_style, scenes, status, episode_content')
  2150. ->orderBy('start_episode_number')->orderBy('id')->get()->map(function ($value) {
  2151. $value = (array)$value;
  2152. $value['episode_content'] = mb_substr($value['episode_content'], 0, 200);
  2153. return (array)$value;
  2154. })->toArray();
  2155. $script['group'] = $groups;
  2156. return $script;
  2157. }
  2158. public function createScript($data) {
  2159. $script_name = getProp($data, 'script_name');
  2160. $uid = Site::getUid(); // 获取当前用户ID
  2161. $cpid = Site::getCpid(); // 获取当前公司组ID
  2162. if (!$script_name) Utils::throwError('20003:剧本名称不能为空');
  2163. if (DB::table('mp_scripts')->where('script_name', $script_name)->exists()) {
  2164. $script_name .= '_'.date('YmdHis');
  2165. }
  2166. return DB::table('mp_scripts')->insertGetId([
  2167. 'script_name' => $script_name,
  2168. 'user_id' => $uid,
  2169. 'cpid' => $cpid,
  2170. 'created_at' => date('Y-m-d H:i:s'),
  2171. 'updated_at' => date('Y-m-d H:i:s')
  2172. ]);
  2173. }
  2174. public function editScript($data) {
  2175. $script_id = getProp($data, 'script_id');
  2176. $script_name = getProp($data, 'script_name');
  2177. $uid = Site::getUid(); // 获取当前用户ID
  2178. if (!$script_id || !$script_name) Utils::throwError('20003:参数异常');
  2179. $id = DB::table('mp_scripts')->where('script_name', $script_name)->value('id');
  2180. if ($id && (int)$id !== (int)$script_id) {
  2181. $script_name .= '_'.date('YmdHis');
  2182. }
  2183. return DB::table('mp_scripts')->where('id', $script_id)->update([
  2184. 'script_name' => $script_name,
  2185. 'updated_at' => date('Y-m-d H:i:s')
  2186. ]);
  2187. }
  2188. public function delScript($data) {
  2189. $script_id = getProp($data, 'script_id');
  2190. $uid = Site::getUid(); // 获取当前用户ID
  2191. if (!$script_id) Utils::throwError('20003:请选择剧本');
  2192. return DB::table('mp_scripts')->where('id', $script_id)->update([
  2193. 'is_deleted' => 1,
  2194. 'updated_at' => date('Y-m-d H:i:s')
  2195. ]);
  2196. }
  2197. public function createEpisode($data) {
  2198. $script_id = getProp($data, 'script_id');
  2199. $group_name = getProp($data, 'group_name');
  2200. $remark = getProp($data, 'remark');
  2201. if (!DB::table('mp_scripts')->where('id', $script_id)->value('id')) Utils::throwError('20003:剧本不存在!');
  2202. $uid = Site::getUid(); // 获取当前用户ID
  2203. if (!$group_name) Utils::throwError('20003:分集名称不能为空');
  2204. if (DB::table('mp_script_episode_group')->where('group_name', $group_name)->exists()) {
  2205. $group_name .= '_'.date('YmdHis');
  2206. }
  2207. return DB::table('mp_script_episode_group')->insertGetId([
  2208. 'script_id' => $script_id,
  2209. 'group_name' => $group_name,
  2210. 'user_id' => $uid,
  2211. 'remark' => $remark,
  2212. 'created_at' => date('Y-m-d H:i:s'),
  2213. 'updated_at' => date('Y-m-d H:i:s')
  2214. ]);
  2215. }
  2216. public function editEpisode($data) {
  2217. $group_id = getProp($data, 'group_id');
  2218. $start_episode_number = getProp($data, 'start_episode_number');
  2219. $end_episode_number = getProp($data, 'end_episode_number');
  2220. $group_name = getProp($data, 'group_name');
  2221. $uid = Site::getUid(); // 获取当前用户ID
  2222. if (!$group_id || !$group_name || !$start_episode_number || !$end_episode_number) Utils::throwError('20003:参数异常');
  2223. $id = DB::table('mp_script_episode_group')->where('group_name', $group_name)->value('id');
  2224. if ($id && (int)$id !== (int)$group_id) {
  2225. $group_name .= '_'.date('YmdHis');
  2226. }
  2227. return DB::table('mp_script_episode_group')->where('id', $group_id)->update([
  2228. 'group_name' => $group_name,
  2229. 'start_episode_number' => $start_episode_number,
  2230. 'end_episode_number' => $end_episode_number,
  2231. 'updated_at' => date('Y-m-d H:i:s')
  2232. ]);
  2233. }
  2234. public function delEpisode($data) {
  2235. $group_id = getProp($data, 'group_id');
  2236. $uid = Site::getUid(); // 获取当前用户ID
  2237. if (!$group_id) Utils::throwError('20003:请选择分集');
  2238. return DB::table('mp_script_episode_group')->where('id', $group_id)->update([
  2239. 'is_deleted' => 1,
  2240. 'updated_at' => date('Y-m-d H:i:s')
  2241. ]);
  2242. }
  2243. /**
  2244. * 上传文件识别文字内容并与 DeepSeek 进行对话(流式输出版本)
  2245. *
  2246. * @param array $data 包含以下参数:
  2247. * - file: 上传的文件(UploadedFile 对象)或文件路径
  2248. * - question: 用户问题(可选)
  2249. * - model: 使用的模型(r1 或 v3,默认 v3)
  2250. * @return \Generator 返回生成器,用于流式输出
  2251. */
  2252. public function generateEpisodes($data) {
  2253. $script_id = getProp($data, 'script_id');
  2254. $group_id = getProp($data, 'group_id');
  2255. // $file = getProp($data, 'file');
  2256. $file = '';
  2257. $content = getProp($data, 'content', '');
  2258. // $bid = getProp($data, 'bid', 0);
  2259. $bid = 0;
  2260. $group = DB::table('mp_script_episode_group')->where('id', $group_id)->where('script_id', $script_id)->where('is_deleted', 0)->first();
  2261. if (!$group) {
  2262. Utils::throwError('20003:剧本分集不存在');
  2263. }
  2264. $start_episode_sequence = getProp($group, 'start_episode_number', 1);
  2265. $end_episode_sequence = getProp($group, 'end_episode_number', 30);
  2266. $total_episode_num = $end_episode_sequence - $start_episode_sequence + 1;
  2267. $prompt = getProp($data, 'prompt');
  2268. $question = getProp($data, 'question', "请根据实例完成一个{$total_episode_num}集的剧本,要求: 1.从第{$start_episode_sequence}集开始; 2.每集内容独立成章; 3.避免重复内容; 4.确保内容连贯且逻辑清晰; 5.所有章节合起来是给出的文档内容全文大概剧情。6.强制要求一定要给出我需要的分镜集数,不能少7.分集序号用01、02、03显示,不得使用01-1等子集序号,并且需要匹配开始集数的序号并往后顺序显示。\n");
  2269. $model = getProp($data, 'model');
  2270. if (!DB::table('mp_text_models')->where('model', $model)->where('is_enabled', 1)->value('id')) {
  2271. Utils::throwError('20003:该模型不存在!');
  2272. }
  2273. // 检查是否存在重叠的剧集序号范围
  2274. $exists_groups = DB::table('mp_script_episode_group')
  2275. ->where('script_id', $script_id)
  2276. ->where('id', '<>', $group_id) // 排除当前组
  2277. ->where('is_deleted', 0)
  2278. ->where(function($query) use ($start_episode_sequence, $end_episode_sequence) {
  2279. // 检查新范围是否与现有范围重叠
  2280. $query->where(function($q) use ($start_episode_sequence, $end_episode_sequence) {
  2281. // 新范围的开始在现有范围内
  2282. $q->where('start_episode_number', '<=', $start_episode_sequence)
  2283. ->where('end_episode_number', '>=', $start_episode_sequence);
  2284. })->orWhere(function($q) use ($start_episode_sequence, $end_episode_sequence) {
  2285. // 新范围的结束在现有范围内
  2286. $q->where('start_episode_number', '<=', $end_episode_sequence)
  2287. ->where('end_episode_number', '>=', $end_episode_sequence);
  2288. })->orWhere(function($q) use ($start_episode_sequence, $end_episode_sequence) {
  2289. // 新范围完全包含现有范围
  2290. $q->where('start_episode_number', '>=', $start_episode_sequence)
  2291. ->where('end_episode_number', '<=', $end_episode_sequence);
  2292. });
  2293. })
  2294. ->select('start_episode_number', 'end_episode_number')
  2295. ->get();
  2296. if ($exists_groups->isNotEmpty()) {
  2297. $conflict_ranges = [];
  2298. foreach ($exists_groups as $group) {
  2299. $conflict_ranges[] = "第{$group->start_episode_number}-{$group->end_episode_number}集";
  2300. }
  2301. Utils::throwError('20003:剧集序号范围与已存在的剧集组重叠: '.implode('、', $conflict_ranges).',不得创建!');
  2302. }
  2303. // 模型兼容性处理:deepseek-chat 和 deepseek-reasoner 映射到 deepseek-v4-flash
  2304. $thinkingMode = getProp($data, 'thinking', 'disabled'); // 默认非思考模式
  2305. $reasoningEffort = getProp($data, 'reasoning_effort', 'high'); // 默认思考强度
  2306. if ($model === 'deepseek-chat') {
  2307. // deepseek-chat 映射到 deepseek-v4-flash,非思考模式
  2308. $model = 'deepseek-v4-flash';
  2309. $thinkingMode = 'disabled';
  2310. } elseif ($model === 'deepseek-reasoner') {
  2311. // deepseek-reasoner 映射到 deepseek-v4-flash,思考模式
  2312. $model = 'deepseek-v4-flash';
  2313. $thinkingMode = 'enabled';
  2314. }
  2315. $script = DB::table('mp_scripts')->where('id', $script_id)->first();
  2316. if (!$script) {
  2317. Utils::throwError('20003:剧本不存在');
  2318. }
  2319. $content = getProp($group, 'content');
  2320. if (!$file && !$content && !$bid) {
  2321. Utils::throwError('20003:请上传文件或选择书籍或输入内容');
  2322. }
  2323. // 提取文件内容
  2324. if ($file) {
  2325. $content = $this->extractFileContent($file);
  2326. if (!$content) {
  2327. Utils::throwError('20003:无法提取文件内容,请检查文件格式');
  2328. }
  2329. } elseif ($bid) {
  2330. $content = $this->getContentByBid($bid);
  2331. if (!$content) {
  2332. Utils::throwError('20003:无法获取书籍内容,请检查书籍');
  2333. }
  2334. } elseif ($content) {
  2335. $content = filterContent($content);
  2336. } elseif ($prompt) {
  2337. $content = filterContent($prompt);
  2338. } else {
  2339. Utils::throwError('20003:请上传文件或选择书籍或输入内容');
  2340. }
  2341. // 构建消息
  2342. $messages = [
  2343. $this->sys_message,
  2344. [
  2345. 'role' => 'user',
  2346. 'content' => "以下是文档内容:\n\n{$content}\n\n用户问题:{$question}"
  2347. ]
  2348. ];
  2349. $post_data = [
  2350. 'model' => $model,
  2351. 'messages' => $messages,
  2352. // 'max_tokens' => 8192,
  2353. 'temperature' => 0.7,
  2354. 'frequency_penalty' => 0,
  2355. 'presence_penalty' => 0,
  2356. 'thinking' => ['type' => $thinkingMode],
  2357. 'response_format' => ['type' => 'text'],
  2358. 'stream' => true
  2359. ];
  2360. if ($thinkingMode == 'enabled') $post_data['reasoning_effort'] = $reasoningEffort;
  2361. // 根据模型类型选择调用方法
  2362. $fullContent = '';
  2363. $fullReasoningContent = '';
  2364. $usage = [];
  2365. if (in_array($model, ['deepseek-reasoner', 'deepseek-chat', 'deepseek-v4-flash', 'deepseek-v4-pro'])) {
  2366. // DeepSeek 官方模型使用 DeepSeek API
  2367. $streamGenerator = $this->deepSeekStreamResponse($post_data);
  2368. } else if (in_array($model, $this->gpt_text_models)) {
  2369. // GPT-5.4 模型使用 TokenRouter API
  2370. $streamGenerator = $this->gpt54StreamResponse($post_data);
  2371. } else {
  2372. // 其他模型使用火山引擎API
  2373. $streamGenerator = $this->volcEngineChatCompletion($post_data);
  2374. }
  2375. // 处理流式输出
  2376. foreach ($streamGenerator as $chunk) {
  2377. if (isset($chunk['type'])) {
  2378. if ($chunk['type'] === 'done') {
  2379. // 最终结果
  2380. $fullContent = $chunk['full_content'];
  2381. $fullReasoningContent = $chunk['full_reasoning'];
  2382. $usage = isset($chunk['usage']) ? $chunk['usage'] : [];
  2383. } else {
  2384. // 逐块yield数据
  2385. yield $chunk;
  2386. }
  2387. }
  2388. }
  2389. dLog('deepseek')->info('完整内容: '.$fullContent);
  2390. logDB('deepseek', 'info', '完整内容', ['fullContent'=>$fullContent]);
  2391. // 处理完整内容并返回最终结果
  2392. $script_arr = [];
  2393. if ($fullContent) {
  2394. $script_arr = extractScriptContent($fullContent);
  2395. }
  2396. logDB('deepseek', 'info', '解析内容', $script_arr);
  2397. if (!$script_arr['episodes']) {
  2398. Utils::throwError('20003:未生成剧本相关信息');
  2399. // yield [
  2400. // 'type' => 'done',
  2401. // 'script' => $script_arr,
  2402. // 'msg' => '未生成剧本相关信息',
  2403. // 'answer' => $fullContent,
  2404. // 'reasoning' => $fullReasoningContent,
  2405. // 'usage' => $usage
  2406. // ];
  2407. // return ;
  2408. }
  2409. try {
  2410. DB::beginTransaction();
  2411. // // 返回前保存剧本内容
  2412. // $boolen = DB::table('mp_scripts')->where('id', $script_id)->update([
  2413. // 'content' => $content,
  2414. // 'updated_at' => date('Y-m-d H:i:s')
  2415. // ]);
  2416. // if (!$boolen) {
  2417. // Utils::throwError('20003:保存剧本内容失败');
  2418. // }
  2419. // $boolen1 = DB::table('mp_script_episode_group')->where('id', $group_id)->update([
  2420. // 'start_episode_number' => $start_episode_sequence,
  2421. // 'end_episode_number' => $end_episode_sequence,
  2422. // 'updated_at' => date('Y-m-d H:i:s')
  2423. // ]);
  2424. // if (!$boolen1) {
  2425. // Utils::throwError('20003:保存分集失败');
  2426. // }
  2427. $episode_content = '';
  2428. $episodes = [];
  2429. foreach ($script_arr['episodes'] as $item) {
  2430. $episode_content .= "\u{200D}\u{200D}\u{200D}" . $item['episode_content'] . "\r\n\r\n";
  2431. // $episodes[] = [
  2432. // 'script_id' => $script_id,
  2433. // 'episode_number' => $item['episode_number'],
  2434. // 'episode_name' => $item['episode_name'],
  2435. // 'episode_content' => $item['episode_content'],
  2436. // 'created_at' => date('Y-m-d H:i:s'),
  2437. // 'updated_at' => date('Y-m-d H:i:s'),
  2438. // ];
  2439. }
  2440. if ($episode_content) {
  2441. $boolen2 = DB::table('mp_script_episode_group')->where('id', $group_id)->update([
  2442. 'episode_content' => $episode_content,
  2443. 'updated_at' => date('Y-m-d H:i:s')
  2444. ]);
  2445. if (!$boolen2) {
  2446. Utils::throwError('20003:保存分集内容失败');
  2447. }
  2448. }else {
  2449. Utils::throwError('20003:分集剧本解析失败');
  2450. }
  2451. }catch (\Exception $e) {
  2452. DB::rollBack();
  2453. Utils::throwError('20003:'.$e->getMessage());
  2454. }
  2455. DB::commit();
  2456. yield [
  2457. 'type' => 'done',
  2458. 'script' => $script_arr,
  2459. 'episode_content' => $episode_content,
  2460. 'answer' => $fullContent,
  2461. 'reasoning' => $fullReasoningContent,
  2462. 'usage' => $usage
  2463. ];
  2464. }
  2465. public function chatWithFileStream($data) {
  2466. $script_id = getProp($data, 'script_id');
  2467. $group_id = getProp($data, 'group_id');
  2468. $file = getProp($data, 'file');
  2469. $content = getProp($data, 'content', '');
  2470. $bid = getProp($data, 'bid', 0);
  2471. $start_episode_sequence = getProp($data, 'start_episode_sequence', 1);
  2472. $total_episode_num = getProp($data, 'total_episode_num', 30);
  2473. $end_episode_sequence = $start_episode_sequence + $total_episode_num - 1;
  2474. $prompt = getProp($data, 'prompt');
  2475. $baseQuestion = "请根据实例完成一个{$total_episode_num}集的剧本,要求: 1.从第{$start_episode_sequence}集开始; 2.每集内容独立成章; 3.避免重复内容; 4.确保内容连贯且逻辑清晰; 5.所有章节合起来是给出的文档内容全文大概剧情。6.强制要求一定要给出我需要的分镜集数,不能少7.分集序号用01、02、03显示,不得使用01-1等子集序号,并且需要匹配开始集数的序号并往后顺序显示。";
  2476. if (!empty($prompt)) {
  2477. $baseQuestion .= "\n本次修改要求如下:\n{$prompt}";
  2478. }
  2479. $question = getProp($data, 'question', $baseQuestion);
  2480. $model = getProp($data, 'model');
  2481. if (!DB::table('mp_text_models')->where('model', $model)->where('is_enabled', 1)->value('id')) {
  2482. Utils::throwError('20003:该模型不存在!');
  2483. }
  2484. // 检查是否存在重叠的剧集序号范围
  2485. $exists_groups = DB::table('mp_script_episode_group')
  2486. ->where('script_id', $script_id)
  2487. ->where('id', '<>', $group_id)
  2488. ->where('is_deleted', 0)
  2489. ->where(function($query) use ($start_episode_sequence, $end_episode_sequence) {
  2490. // 检查新范围是否与现有范围重叠
  2491. $query->where(function($q) use ($start_episode_sequence, $end_episode_sequence) {
  2492. // 新范围的开始在现有范围内
  2493. $q->where('start_episode_number', '<=', $start_episode_sequence)
  2494. ->where('end_episode_number', '>=', $start_episode_sequence);
  2495. })->orWhere(function($q) use ($start_episode_sequence, $end_episode_sequence) {
  2496. // 新范围的结束在现有范围内
  2497. $q->where('start_episode_number', '<=', $end_episode_sequence)
  2498. ->where('end_episode_number', '>=', $end_episode_sequence);
  2499. })->orWhere(function($q) use ($start_episode_sequence, $end_episode_sequence) {
  2500. // 新范围完全包含现有范围
  2501. $q->where('start_episode_number', '>=', $start_episode_sequence)
  2502. ->where('end_episode_number', '<=', $end_episode_sequence);
  2503. });
  2504. })
  2505. ->select('start_episode_number', 'end_episode_number')
  2506. ->get();
  2507. if ($exists_groups->isNotEmpty()) {
  2508. $conflict_ranges = [];
  2509. foreach ($exists_groups as $group) {
  2510. $conflict_ranges[] = "第{$group->start_episode_number}-{$group->end_episode_number}集";
  2511. }
  2512. Utils::throwError('20003:剧集序号范围与已存在的剧集组重叠: '.implode('、', $conflict_ranges).',不得创建!');
  2513. }
  2514. // 模型兼容性处理:deepseek-chat 和 deepseek-reasoner 映射到 deepseek-v4-flash
  2515. $thinkingMode = getProp($data, 'thinking', 'disabled'); // 默认非思考模式
  2516. $reasoningEffort = getProp($data, 'reasoning_effort', 'high'); // 默认思考强度
  2517. if ($model === 'deepseek-chat') {
  2518. // deepseek-chat 映射到 deepseek-v4-flash,非思考模式
  2519. $model = 'deepseek-v4-flash';
  2520. $thinkingMode = 'disabled';
  2521. } elseif ($model === 'deepseek-reasoner') {
  2522. // deepseek-reasoner 映射到 deepseek-v4-flash,思考模式
  2523. $model = 'deepseek-v4-flash';
  2524. $thinkingMode = 'enabled';
  2525. }
  2526. $script = DB::table('mp_scripts')->where('id', $script_id)->first();
  2527. if (!$script) {
  2528. Utils::throwError('20003:剧本不存在');
  2529. }
  2530. $group = DB::table('mp_script_episode_group')->where('id', $group_id)->where('script_id', $script_id)->where('is_deleted', 0)->first();
  2531. if (!$group) {
  2532. Utils::throwError('20003:剧本分集不存在');
  2533. }
  2534. if (!$file && !$content && !$bid) {
  2535. Utils::throwError('20003:请上传文件或选择书籍或输入内容');
  2536. }
  2537. // 提取文件内容
  2538. if ($file) {
  2539. $content = $this->extractFileContent($file);
  2540. if (!$content) {
  2541. Utils::throwError('20003:无法提取文件内容,请检查文件格式');
  2542. }
  2543. } elseif ($bid) {
  2544. $content = $this->getContentByBid($bid);
  2545. if (!$content) {
  2546. Utils::throwError('20003:无法获取书籍内容,请检查书籍');
  2547. }
  2548. } elseif ($content) {
  2549. $content = filterContent($content);
  2550. } elseif ($prompt) {
  2551. $content = filterContent($prompt);
  2552. } else {
  2553. Utils::throwError('20003:请上传文件或选择书籍或输入内容');
  2554. }
  2555. // 构建消息
  2556. $messages = [
  2557. [
  2558. 'role' => 'system',
  2559. 'content' => "你是一个专业的文档分析助手及资深编剧,请根据用户提供的文档内容完成示例格式的内容输出(需通过以下几个板块进行回复: <故事梗概><剧本亮点><人物关系><核心矛盾><主体列表><美术风格><场景列表>,每个板块之间必须使用###分隔,#不能多也不能少;同时板块之间需满足以下要求:\n
  2560. 强制要求:\n
  2561. 1.你只负责与剧本相关的内容,如果用户输入与剧本无关的内容,请告知用户并拒绝继续回答,此为第一优先原则,不满足此原则就忽略其他要求并停止继续输出
  2562. 2.用户如果直接给了你一本小说或者要求你帮忙写一个故事或者剧本,此类要求不属于与剧本无关,请帮助用户完成请求
  2563. 3.请严格按照示例格式返回内容,不要更改格式或随意增加符号\n
  2564. 普通要求:\n
  2565. 1.<主体列表>中出现的主体必须尽可能统一,只允许同一个角色年龄段相差较大的情况下可重复,比如梁萧-少年、梁萧-青年、梁萧-中年、梁萧-老年这种情况,不得出现梁萧-愤怒、梁萧-隐忍、梁萧-求生等情绪和状态变化的同一角色;并且角色的样貌、形体及穿着描述尽可能详细\n\n
  2566. 2.不要出现分集内容,只保留剧本大纲的格式,格式要求和示例如下,请强制按该示例输出
  2567. 3.分集序号可能不是从 1 开始,也可能是跳跃的(例如直接从第 3 集、第 5 集开始)。你只需要基于下面给出的“当前集内容要点”来创作这一集即可。
  2568. 4.不需要强行补齐前面未提供的集数,也不需要预测后面未提供的集数,但请保持本集内部故事的完整性和节奏。
  2569. 5.总集数将作为本季整体篇幅的参考,你可以根据它调整本集的情节推进速度(例如:如果总集数很少,本集应更紧凑;如果总集数很多,本集可以适当展开细节)
  2570. 示例如下:\n
  2571. ###剧本名:西昆仑
  2572. ###故事梗概
  2573. 内容梗概:古风厚涂的世界中,少女阿雪身中奇毒“问心刺”,气息奄奄。少年梁萧心急如焚,用奇珍“阴阳球”稳住阿雪性命,却发现必须解衣拔刺。阿雪羞涩难当,梁萧情急之下提出结拜兄妹,以化解尴尬。两人匆匆结拜后,梁萧小心翼翼地拔出“问心刺”,竟发现它是一根诡异的女子秀发。阿雪转危为安,两人之间,在生死与羞涩交织的瞬间,情愫暗生,却又被兄妹之名束缚,留下无尽遐想。
  2574. ###剧本亮点
  2575. 亮点1:绝境奇药,生死一线
  2576. 画面开场即是阿雪苍白无力的脸庞,梁萧眼中泪光闪烁,急促的呼吸声与心跳声烘托紧张气氛。特写梁萧将“阴阳球”塞入阿雪舌底,球体散发微光,阿雪气息从若有若无到逐渐平稳,生死逆转的瞬间,视觉与听觉冲击力十足。
  2577. 亮点2:结拜兄妹,化解尴尬
  2578. 阿雪因解衣拔刺而羞愤欲绝的特写,梁萧眼神中的挣扎与无奈。在紧迫的背景音下,梁萧急中生智,牵起阿雪颤抖的手,跪地匆匆结拜,阿雪眼神从惊惶到迷茫,最终一句“我……我愿意的”带着哭腔,将救命与羞耻的矛盾推向高潮,又以出人意料的方式解决。
  2579. 亮点3:纤发夺命,情愫暗涌
  2580. 拔刺过程的紧张特写,梁萧指尖小心翼翼地捏住细丝,缓慢抽出。当“问心刺”被完全拔出,特写它竟是一根细长、泛着寒光的女子秀发,诡异而令人震惊。阿雪苏醒后,两人眼神交汇,阿雪低头羞涩,梁萧眼中复杂的情绪,无声地传递出超越兄妹的微妙情愫。
  2581. ###人物关系
  2582. 阿雪与梁萧之间存在兄妹之情。
  2583. ###核心矛盾
  2584. 阿雪与梁萧之间存在兄妹之情,但因情愫暗生而产生微妙的矛盾。阿雪羞涩难当,梁萧情急之下提出结拜兄妹,以化解尴尬。两人匆匆结拜后,梁萧小心翼翼地拔出“问心刺”,竟发现它是一根诡异的女子秀发。阿雪转危为安,两人之间,在生死与羞涩交织的瞬间,情愫暗生,却又被兄妹之名束缚,留下无尽遐想。
  2585. ###主体列表
  2586. 阿雪:身中奇毒“问心刺”,气息奄奄,面色苍白,身体虚弱。
  2587. 梁萧:少年侠士,心系阿雪安危,沉着冷静,内心挣扎于情义之间。
  2588. 阴阳球:天地异宝,能化生精气,救人于危难。
  2589. 问心刺:一根诡异的女子秀发,细长泛寒光,是致命的奇毒。
  2590. ###美术风格
  2591. 基础画风风格词:厚涂古风
  2592. 整体采用精致细腻的厚涂古风,色彩浓郁而富有层次感,注重光影对比,营造出古典而富有戏剧张力的氛围。色调以深沉的蓝绿、灰调为主,衬托阿雪病弱的苍白,同时用温暖的金色、琥珀色光晕突出“阴阳球”的生命力。拔刺与结拜场景则以柔和的暖色调为主,辅以人物脸颊的红晕,烘托羞涩与情愫暗生的微妙感。人物造型飘逸,服饰细节考究,背景虚实结合,既有古韵,又不失奇幻色彩。
  2593. ###场景列表
  2594. 林间疗伤地:幽静的古风林间空地,一棵高大古树下,是梁萧为阿雪疗伤的地点。环境清幽,光影斑驳,既有古韵又不失奇幻色彩。"],
  2595. [
  2596. 'role' => 'user',
  2597. 'content' => "以下是文档内容:\n\n{$content}\n\n用户问题:{$question}"
  2598. ]
  2599. ];
  2600. $post_data = [
  2601. 'model' => $model,
  2602. 'messages' => $messages,
  2603. // 'max_tokens' => 8192,
  2604. 'temperature' => 0.7,
  2605. 'frequency_penalty' => 0,
  2606. 'presence_penalty' => 0,
  2607. 'thinking' => ['type' => $thinkingMode],
  2608. 'response_format' => ['type' => 'text'],
  2609. 'stream' => true
  2610. ];
  2611. if ($thinkingMode == 'enabled') $post_data['reasoning_effort'] = $reasoningEffort;
  2612. // 根据模型类型选择调用方法
  2613. $fullContent = '';
  2614. $fullReasoningContent = '';
  2615. $usage = [];
  2616. if (in_array($model, ['deepseek-reasoner', 'deepseek-chat', 'deepseek-v4-flash', 'deepseek-v4-pro'])) {
  2617. // DeepSeek 官方模型使用 DeepSeek API
  2618. $streamGenerator = $this->deepSeekStreamResponse($post_data);
  2619. } else if (in_array($model, $this->gpt_text_models)) {
  2620. // GPT-5.4 模型使用 TokenRouter API
  2621. $streamGenerator = $this->gpt54StreamResponse($post_data);
  2622. } else {
  2623. // 其他模型使用火山引擎API
  2624. $streamGenerator = $this->volcEngineChatCompletion($post_data);
  2625. }
  2626. // 处理流式输出
  2627. foreach ($streamGenerator as $chunk) {
  2628. if (isset($chunk['type'])) {
  2629. if ($chunk['type'] === 'done') {
  2630. // 最终结果
  2631. $fullContent = $chunk['full_content'];
  2632. $fullReasoningContent = $chunk['full_reasoning'];
  2633. $usage = isset($chunk['usage']) ? $chunk['usage'] : [];
  2634. } else {
  2635. // 逐块yield数据
  2636. yield $chunk;
  2637. }
  2638. }
  2639. }
  2640. dLog('deepseek')->info('完整内容: '.$fullContent);
  2641. logDB('deepseek', 'info', '完整内容', ['fullContent'=>$fullContent]);
  2642. // 处理完整内容并返回最终结果
  2643. $script_arr = [];
  2644. if ($fullContent) {
  2645. $script_arr = extractScriptContent($fullContent);
  2646. }
  2647. logDB('deepseek', 'info', '解析内容', $script_arr);
  2648. if (!$script_arr['roles']) {
  2649. Utils::throwError('20003:未生成剧本相关信息');
  2650. // yield [
  2651. // 'type' => 'done',
  2652. // 'script' => $script_arr,
  2653. // 'msg' => '未生成剧本相关信息',
  2654. // 'answer' => $fullContent,
  2655. // 'reasoning' => $fullReasoningContent,
  2656. // 'usage' => $usage
  2657. // ];
  2658. }
  2659. try {
  2660. DB::beginTransaction();
  2661. // // 返回前保存剧本内容
  2662. // $boolen = DB::table('mp_scripts')->where('id', $script_id)->update([
  2663. // 'content' => $content,
  2664. // 'status' => '解析完成',
  2665. // 'updated_at' => date('Y-m-d H:i:s')
  2666. // ]);
  2667. // if (!$boolen) {
  2668. // Utils::throwError('20003:保存剧本内容失败');
  2669. // }
  2670. $boolen1 = DB::table('mp_script_episode_group')->where('id', $group_id)->update([
  2671. 'start_episode_number' => $start_episode_sequence,
  2672. 'end_episode_number' => $end_episode_sequence,
  2673. 'intro' => isset($script_arr['intro']) ? $script_arr['intro'] : '',
  2674. 'highlights' => isset($script_arr['highlights']) ? $script_arr['highlights'] : '',
  2675. 'role_relationship' => isset($script_arr['role_relationship']) ? $script_arr['role_relationship'] : '',
  2676. 'core_contradiction' => isset($script_arr['core_contradiction']) ? $script_arr['core_contradiction'] : '',
  2677. 'roles' => isset($script_arr['roles']) && is_array($script_arr['roles']) ? json_encode($script_arr['roles'], 256) : '[]',
  2678. 'art_style' => isset($script_arr['art_style']) ? $script_arr['art_style'] : '',
  2679. 'scenes' => isset($script_arr['scenes']) && is_array($script_arr['scenes']) ? json_encode($script_arr['scenes'], 256) : '[]',
  2680. 'status' => '解析完成',
  2681. 'content' => $content,
  2682. 'updated_at' => date('Y-m-d H:i:s')
  2683. ]);
  2684. if (!$boolen1) {
  2685. Utils::throwError('20003:保存分集失败');
  2686. }
  2687. // $episodes = [];
  2688. // foreach ($script_arr['episodes'] as $item) {
  2689. // $episodes[] = [
  2690. // 'script_id' => $script_id,
  2691. // 'episode_number' => $item['episode_number'],
  2692. // 'episode_name' => $item['episode_name'],
  2693. // 'episode_content' => $item['episode_content'],
  2694. // 'created_at' => date('Y-m-d H:i:s'),
  2695. // 'updated_at' => date('Y-m-d H:i:s'),
  2696. // ];
  2697. // }
  2698. // if ($episodes) {
  2699. // $boolen2 = DB::table('mp_script_episodes')->insert($episodes);
  2700. // if (!$boolen2) {
  2701. // Utils::throwError('20003:保存分集内容失败');
  2702. // }
  2703. // }else {
  2704. // Utils::throwError('20003:分集剧本解析失败');
  2705. // }
  2706. }catch (\Exception $e) {
  2707. DB::rollBack();
  2708. Utils::throwError('20003:'.$e->getMessage());
  2709. }
  2710. DB::commit();
  2711. yield [
  2712. 'type' => 'done',
  2713. 'script' => $script_arr,
  2714. 'answer' => $fullContent,
  2715. 'reasoning' => $fullReasoningContent,
  2716. 'usage' => $usage
  2717. ];
  2718. }
  2719. /**
  2720. * 上传文件识别文字内容并与 DeepSeek 进行对话
  2721. *
  2722. * @param array $data 包含以下参数:
  2723. * - file: 上传的文件(UploadedFile 对象)或文件路径
  2724. * - question: 用户问题(可选,默认为"请总结这个文件的内容")
  2725. * - model: 使用的模型(r1 或 v3,默认 v3)
  2726. * @return array
  2727. */
  2728. public function chatWithFile($data) {
  2729. $script_id = getProp($data, 'script_id');
  2730. $file = getProp($data, 'file');
  2731. $content = getProp($data, 'content', '');
  2732. $bid = getProp($data, 'bid', 0);
  2733. $start_episode_sequence = getProp($data, 'start_episode_sequence', 1);
  2734. $total_episode_num = getProp($data, 'total_episode_num', 30);
  2735. $prompt = getProp($data, 'prompt');
  2736. $baseQuestion = "请根据实例完成一个{$total_episode_num}集的剧本,要求: 1.从第{$start_episode_sequence}集开始; 2.每集内容独立成章; 3.避免重复内容; 4.确保内容连贯且逻辑清晰; 5.所有章节合起来是给出的文档内容全文大概剧情。6.要求一定要给出我需要的分镜集数,不能少7.分集序号用01、02、03显示,不得使用01-1等子集序号,并且需要匹配开始集数的序号并往后顺序显示。";
  2737. if (!empty($prompt)) {
  2738. $baseQuestion .= "\n本次修改要求如下:\n{$prompt}";
  2739. }
  2740. $question = getProp($data, 'question', $baseQuestion);
  2741. // 处理文本模型
  2742. $model = getProp($data, 'model');
  2743. if (!$model) {
  2744. // 用户没有输入,使用默认值
  2745. $model = 'doubao-seed-2-0-mini-260215';
  2746. }
  2747. // 验证模型是否在可用模型表中
  2748. if (!DB::table('mp_text_models')->where('model', $model)->where('is_enabled', 1)->exists()) {
  2749. $model = 'doubao-seed-2-0-mini-260215';
  2750. }
  2751. // 模型兼容性处理:deepseek-chat 和 deepseek-reasoner 映射到 deepseek-v4-flash
  2752. $thinkingMode = getProp($data, 'thinking', 'disabled'); // 默认非思考模式
  2753. $reasoningEffort = getProp($data, 'reasoning_effort', 'high'); // 默认思考强度
  2754. if ($model === 'deepseek-chat') {
  2755. // deepseek-chat 映射到 deepseek-v4-flash,非思考模式
  2756. $model = 'deepseek-v4-flash';
  2757. $thinkingMode = 'disabled';
  2758. } elseif ($model === 'deepseek-reasoner') {
  2759. // deepseek-reasoner 映射到 deepseek-v4-flash,思考模式
  2760. $model = 'deepseek-v4-flash';
  2761. $thinkingMode = 'enabled';
  2762. }
  2763. $script = DB::table('mp_scripts')->where('id', $script_id)->first();
  2764. if (!$script) {
  2765. Utils::throwError('20003:剧本不存在');
  2766. }
  2767. if (!$file && !$content && !$bid) {
  2768. Utils::throwError('20003:请上传文件或选择书籍或输入内容');
  2769. }
  2770. // 提取文件内容
  2771. if ($file) {
  2772. $content = $this->extractFileContent($file);
  2773. if (!$content) {
  2774. Utils::throwError('20003:无法提取文件内容,请检查文件格式');
  2775. }
  2776. } elseif ($bid) {
  2777. $content = $this->getContentByBid($bid);
  2778. if (!$content) {
  2779. Utils::throwError('20003:无法获取书籍内容,请检查书籍');
  2780. }
  2781. } elseif ($content) {
  2782. $content = filterContent($content);
  2783. } elseif ($prompt) {
  2784. $content = filterContent($prompt);
  2785. } else {
  2786. Utils::throwError('20003:请上传文件或选择书籍或输入内容');
  2787. }
  2788. // 构建消息
  2789. $messages = [
  2790. $this->sys_message,
  2791. [
  2792. 'role' => 'user',
  2793. 'content' => "以下是文档内容:\n\n{$content}\n\n用户问题:{$question}"
  2794. ]
  2795. ];
  2796. $post_data = [
  2797. 'model' => $model,
  2798. 'messages' => $messages,
  2799. // 'max_tokens' => 8192,
  2800. 'temperature' => 0.7,
  2801. 'frequency_penalty' => 0,
  2802. 'presence_penalty' => 0,
  2803. 'thinking' => ['type' => $thinkingMode],
  2804. 'response_format' => ['type' => 'text'],
  2805. 'stream' => false
  2806. ];
  2807. if ($thinkingMode == 'enabled') $post_data['reasoning_effort'] = $reasoningEffort;
  2808. // 根据模型类型选择调用方法
  2809. $fullContent = '';
  2810. $usage = [];
  2811. if (in_array($model, ['deepseek-reasoner', 'deepseek-chat', 'deepseek-v4-flash', 'deepseek-v4-pro'])) {
  2812. // DeepSeek 官方模型使用 DeepSeek API
  2813. $chatResult = $this->chatOnly($post_data);
  2814. } else if (in_array($model, $this->gpt_text_models)) {
  2815. // GPT-5.4 模型使用 TokenRouter API
  2816. $chatResult = $this->gpt54ChatOnly($post_data);
  2817. } else {
  2818. // 其他模型使用火山引擎API
  2819. $chatResult = $this->volcEngineChatCompletion($post_data);
  2820. }
  2821. if (is_array($chatResult)) {
  2822. $fullContent = $chatResult['fullContent'];
  2823. $usage = $chatResult['usage'];
  2824. }
  2825. $script_arr = [];
  2826. // 处理结果
  2827. if ($fullContent) {
  2828. $script_arr = extractScriptContent($fullContent);
  2829. }
  2830. // 返回前保存剧本内容
  2831. DB::table('mp_scripts')->where('id', $script_id)->update([
  2832. 'content' => $content,
  2833. 'updated_at' => date('Y-m-d H:i:s')
  2834. ]);
  2835. return [
  2836. 'script' => $script_arr,
  2837. 'answer' => $fullContent,
  2838. 'usage' => $usage
  2839. ];
  2840. }
  2841. public function getEpisodeContent($data) {
  2842. $group_id = getProp($data, 'group_id');
  2843. return DB::table('mp_script_episode_group')->where('id', $group_id)->value('episode_content');
  2844. }
  2845. public function saveEpisodeContent($data) {
  2846. $script_id = getProp($data, 'script_id');
  2847. $group_id = getProp($data, 'group_id');
  2848. $start_episode_sequence = getProp($data, 'start_episode_number');
  2849. $end_episode_sequence = getProp($data, 'end_episode_number');
  2850. // 检查是否存在重叠的剧集序号范围
  2851. $exists_groups = DB::table('mp_script_episode_group')
  2852. ->where('script_id', $script_id)
  2853. ->where('id', '<>', $group_id) // 排除当前组
  2854. ->where('is_deleted', 0)
  2855. ->where(function($query) use ($start_episode_sequence, $end_episode_sequence) {
  2856. // 检查新范围是否与现有范围重叠
  2857. $query->where(function($q) use ($start_episode_sequence, $end_episode_sequence) {
  2858. // 新范围的开始在现有范围内
  2859. $q->where('start_episode_number', '<=', $start_episode_sequence)
  2860. ->where('end_episode_number', '>=', $start_episode_sequence);
  2861. })->orWhere(function($q) use ($start_episode_sequence, $end_episode_sequence) {
  2862. // 新范围的结束在现有范围内
  2863. $q->where('start_episode_number', '<=', $end_episode_sequence)
  2864. ->where('end_episode_number', '>=', $end_episode_sequence);
  2865. })->orWhere(function($q) use ($start_episode_sequence, $end_episode_sequence) {
  2866. // 新范围完全包含现有范围
  2867. $q->where('start_episode_number', '>=', $start_episode_sequence)
  2868. ->where('end_episode_number', '<=', $end_episode_sequence);
  2869. });
  2870. })
  2871. ->select('start_episode_number', 'end_episode_number')
  2872. ->get();
  2873. if ($exists_groups->isNotEmpty()) {
  2874. $conflict_ranges = [];
  2875. foreach ($exists_groups as $group) {
  2876. $conflict_ranges[] = "第{$group->start_episode_number}-{$group->end_episode_number}集";
  2877. }
  2878. Utils::throwError('20003:剧集序号范围与已存在的剧集组重叠: '.implode('、', $conflict_ranges).',不得创建!');
  2879. }
  2880. $episode_content = getProp($data, 'episode_content');
  2881. return DB::table('mp_script_episode_group')->where('id', $group_id)->where('script_id', $script_id)->update([
  2882. 'content' => $episode_content,
  2883. 'start_episode_number' => $start_episode_sequence,
  2884. 'end_episode_number' => $end_episode_sequence,
  2885. 'updated_at' => date('Y-m-d H:i:s')
  2886. ]);
  2887. $script_arr =getProp($data, 'script', []);
  2888. if (!$script_arr) Utils::throwError('20003:剧本内容不能为空');
  2889. $start_episode_sequence = getProp($data, 'start_episode_sequence', 1);
  2890. $script_id = getProp($data, 'script_id');
  2891. if (!$script_id) Utils::throwError('20003:剧本ID不能为空');
  2892. try {
  2893. DB::beginTransaction();
  2894. $update_data = [
  2895. 'intro' => isset($script_arr['intro']) ? $script_arr['intro'] : '',
  2896. 'highlights' => isset($script_arr['highlights']) ? $script_arr['highlights'] : '',
  2897. 'role_relationship' => isset($script_arr['role_relationship']) ? $script_arr['role_relationship'] : '',
  2898. 'core_contradiction' => isset($script_arr['core_contradiction']) ? $script_arr['core_contradiction'] : '',
  2899. 'roles' => isset($script_arr['roles']) && is_array($script_arr['roles']) ? json_encode($script_arr['roles'], 256) : '[]',
  2900. 'art_style' => isset($script_arr['art_style']) ? $script_arr['art_style'] : '',
  2901. 'scenes' => isset($script_arr['scenes']) && is_array($script_arr['scenes']) ? json_encode($script_arr['scenes'], 256) : '[]',
  2902. 'status' => 3,
  2903. 'start_episode_sequence' => $start_episode_sequence,
  2904. 'end_episode_sequence' => $start_episode_sequence + count($script_arr['episodes']) - 1,
  2905. 'episode_num' => count($script_arr['episodes']),
  2906. 'updated_at' => date('Y-m-d H:i:s')
  2907. ];
  2908. // 保存剧本内容
  2909. $boolen = DB::table('mp_scripts')->where('id', $script_id)->update($update_data);
  2910. if (!$boolen) {
  2911. dLog('deepseek')->info('剧本内容保存失败', $update_data);
  2912. logDB('deepseek', 'error', '剧本内容保存失败', ['script_id' => $script_id]);
  2913. Utils::throwError('20003:剧本内容保存失败');
  2914. }
  2915. // 保存分集内容
  2916. // 删除历史分集内容
  2917. $boolen1 = DB::table('mp_script_episodes')->where('script_id', $script_id)->delete();
  2918. $episodes = [];
  2919. $sequence = 1;
  2920. foreach ($script_arr['episodes'] as $episode) {
  2921. $segment_number = 1;
  2922. foreach($episode['segments'] as $segment) {
  2923. $episodes[] = [
  2924. 'script_id' => $script_id,
  2925. 'episode_number' => $episode['episode_number'],
  2926. 'title' => $episode['title'],
  2927. // 'content' => $episode['content'],
  2928. 'content' => '',
  2929. 'segment_number' => $segment_number,
  2930. 'segment_content' => $segment['segment_content'],
  2931. 'sequence' => $sequence,
  2932. 'created_at' => date('Y-m-d H:i:s'),
  2933. 'updated_at' => date('Y-m-d H:i:s')
  2934. ];
  2935. $sequence++;
  2936. $segment_number++;
  2937. }
  2938. }
  2939. $boolen2 = DB::table('mp_script_episodes')->insert($episodes);
  2940. if (!$boolen2) {
  2941. dLog('deepseek')->info('分集内容保存失败', $episodes);
  2942. logDB('deepseek', 'error', '分集内容保存失败', ['episodes_count' => count($episodes)]);
  2943. Utils::throwError('20003:分集内容保存失败');
  2944. }
  2945. } catch (\Exception $e) {
  2946. DB::rollBack();
  2947. Utils::throwError('20003:'.$e->getMessage());
  2948. }
  2949. DB::commit();
  2950. return true;
  2951. }
  2952. public function getBookContent($data) {
  2953. $bid = getProp($data, 'bid');
  2954. $start_sequence = getProp($data, 'start_sequence');
  2955. $end_sequence = getProp($data, 'end_sequence');
  2956. $chapter_contents = DB::table('chapters as c')->leftJoin('chapter_contents as cc', 'c.chapter_content_id', 'cc.id')->where('c.bid', $bid)->where('c.is_check', 1)->where('c.is_deleted', 0)->whereBetween('c.sequence', [$start_sequence, $end_sequence])
  2957. ->orderBy('c.sequence')->pluck('cc.content')->toArray();
  2958. $return_content = filterContent(implode(PHP_EOL, $chapter_contents));
  2959. return $return_content;
  2960. }
  2961. public function exportScript($data) {
  2962. $filename = getProp($data, 'filename');
  2963. $script_id = getProp($data, 'script_id');
  2964. $group_id = getProp($data, 'group_id');
  2965. $script = DB::table('mp_scripts')->where('id', $script_id)->where('is_deleted', 0)
  2966. ->selectRaw('id as script_id, script_name, episode_num, remark, created_at')->first();
  2967. if (!$script) Utils::throwError('20003:该剧本不存在!');
  2968. $script = (array)$script;
  2969. // 获取分集组信息
  2970. if ($group_id) {
  2971. $groups = DB::table('mp_script_episode_group')->where('script_id', $script_id)->where('id', $group_id)->where('is_deleted', 0)->whereNotNull('episode_content')
  2972. ->selectRaw('intro, highlights, roles, role_relationship, core_contradiction, art_style, scenes, status, start_episode_number, end_episode_number, episode_content')
  2973. ->get()->map(function($value) {
  2974. return (array)$value;
  2975. })->toArray();
  2976. }else {
  2977. $groups = DB::table('mp_script_episode_group')->where('script_id', $script_id)->where('is_deleted', 0)->whereNotNull('episode_content')
  2978. ->selectRaw('intro, highlights, roles, role_relationship, core_contradiction, art_style, scenes, status, start_episode_number, end_episode_number, episode_content')
  2979. ->orderBy('start_episode_number')->orderBy('id')->get()->map(function($value) {
  2980. return (array)$value;
  2981. })->toArray();
  2982. }
  2983. if (!$groups) Utils::throwError('20003:分集不存在');
  2984. $script['group'] = $groups;
  2985. $export_type = getProp($data, 'export_type', 'txt');
  2986. // 生成文件名
  2987. $filename = $filename ? $filename : $script['script_name'] . '_' . date('YmdHis');
  2988. // 根据导出类型生成不同格式的文件
  2989. switch ($export_type) {
  2990. case 'txt':
  2991. return $this->exportScriptAsTxt($script, $filename);
  2992. case 'pdf':
  2993. return $this->exportScriptAsPdf($script, $filename);
  2994. default:
  2995. Utils::throwError('20003:不支持的导出格式,支持:txt、pdf');
  2996. }
  2997. }
  2998. /**
  2999. * 导出剧本为TXT格式
  3000. */
  3001. private function exportScriptAsTxt($script, $filename) {
  3002. // 构建TXT内容
  3003. $content = $this->buildScriptContent($script);
  3004. // 设置响应头,直接下载
  3005. header('Content-Type: text/plain; charset=utf-8');
  3006. header('Content-Disposition: attachment; filename="' . $filename . '.txt"');
  3007. header('Content-Length: ' . strlen($content));
  3008. // 输出内容并结束
  3009. echo $content;
  3010. exit();
  3011. }
  3012. /**
  3013. * 导出剧本为PDF格式
  3014. */
  3015. private function exportScriptAsPdf($script, $filename) {
  3016. // 使用HTML转PDF的方式来更好地支持中文
  3017. $htmlContent = $this->buildScriptHtmlForPdf($script);
  3018. // 创建PDF实例
  3019. $pdf = new TCPDF(PDF_PAGE_ORIENTATION, PDF_UNIT, PDF_PAGE_FORMAT, true, 'UTF-8', false);
  3020. // 设置文档信息
  3021. $pdf->SetCreator('剧本导出系统');
  3022. $pdf->SetAuthor('系统');
  3023. $pdf->SetTitle($script['script_name']);
  3024. $pdf->SetSubject('剧本导出');
  3025. // 设置边距
  3026. $pdf->SetMargins(15, 15, 15);
  3027. $pdf->SetAutoPageBreak(TRUE, 15);
  3028. // 添加页面
  3029. $pdf->AddPage();
  3030. // 注册并使用 simsun.ttf 字体
  3031. $pdf->SetFont('simsun', '', 12); // 设置字体和大小
  3032. // 使用HTML内容生成PDF
  3033. $pdf->writeHTML($htmlContent, true, false, true, false, '');
  3034. // 直接输出PDF文件供下载
  3035. header('Content-Type: application/pdf');
  3036. header('Content-Disposition: attachment; filename="' . $filename . '.pdf"');
  3037. // 直接输出PDF内容
  3038. $pdf->Output($filename . '.pdf', 'D');
  3039. exit();
  3040. }
  3041. /**
  3042. * 构建用于PDF的HTML内容
  3043. */
  3044. private function buildScriptHtmlForPdf($script) {
  3045. $html = '<style>
  3046. body { font-family: "SimSun", "宋体", sans-serif; font-size: 12px; line-height: 1.6; }
  3047. h1 { font-size: 18px; text-align: center; margin-bottom: 20px; }
  3048. h2 { font-size: 16px; margin-top: 20px; margin-bottom: 10px; border-bottom: 1px solid #ccc; }
  3049. h3 { font-size: 14px; margin-top: 15px; margin-bottom: 8px; }
  3050. .info { margin-bottom: 8px; }
  3051. .group { margin-bottom: 30px; page-break-inside: avoid; }
  3052. .group-header { text-align: center; font-weight: bold; font-size: 16px; margin-bottom: 20px; border-bottom: 1px solid #333; padding: 10px; }
  3053. .segment { margin-bottom: 10px; margin-left: 20px; }
  3054. .episode-content { white-space: pre-wrap; }
  3055. </style>';
  3056. // 标题
  3057. $html .= '<h1>' . htmlspecialchars($script['script_name']) . '</h1>';
  3058. // 处理分组数据
  3059. if (!empty($script['group']) && is_array($script['group'])) {
  3060. $groups = (array)$script['group'];
  3061. foreach ($groups as $group) {
  3062. $html .= '<div class="group">';
  3063. // 分组标题
  3064. $groupTitle = '第' . $group['start_episode_number'] . '-' . $group['end_episode_number'] . '集';
  3065. $html .= '<div class="group-header">' . htmlspecialchars($groupTitle) . '</div>';
  3066. // 故事梗概
  3067. if (!empty($group['intro'])) {
  3068. $html .= '<h3>故事梗概</h3>';
  3069. $html .= '<p>' . nl2br(htmlspecialchars($group['intro'])) . '</p>';
  3070. }
  3071. // 剧本亮点
  3072. if (!empty($group['highlights'])) {
  3073. $html .= '<h3>剧本亮点</h3>';
  3074. $html .= '<p>' . nl2br(htmlspecialchars($group['highlights'])) . '</p>';
  3075. }
  3076. // 人物关系
  3077. if (!empty($group['role_relationship'])) {
  3078. $html .= '<h3>人物关系</h3>';
  3079. $html .= '<p>' . nl2br(htmlspecialchars($group['role_relationship'])) . '</p>';
  3080. }
  3081. // 核心矛盾
  3082. if (!empty($group['core_contradiction'])) {
  3083. $html .= '<h3>核心矛盾</h3>';
  3084. $html .= '<p>' . nl2br(htmlspecialchars($group['core_contradiction'])) . '</p>';
  3085. }
  3086. // 主体列表
  3087. if (!empty($group['roles']) && is_array($group['roles'])) {
  3088. $html .= '<h3>主体列表</h3>';
  3089. $html .= '<ul>';
  3090. foreach ($group['roles'] as $role) {
  3091. $html .= '<li>' . htmlspecialchars(getProp($role, 'role')) . ':' . htmlspecialchars(getProp($role, 'description')) . '</li>';
  3092. }
  3093. $html .= '</ul>';
  3094. }
  3095. // 美术风格
  3096. if (!empty($group['art_style'])) {
  3097. $html .= '<h3>美术风格</h3>';
  3098. $html .= '<p>' . nl2br(htmlspecialchars($group['art_style'])) . '</p>';
  3099. }
  3100. // 场景列表
  3101. if (!empty($group['scenes']) && is_array($group['scenes'])) {
  3102. $html .= '<h3>场景列表</h3>';
  3103. $html .= '<ul>';
  3104. foreach ($group['scenes'] as $scene) {
  3105. $html .= '<li>' . htmlspecialchars(getProp($scene, 'scene')) . ':' . htmlspecialchars(getProp($scene, 'description')) . '</li>';
  3106. }
  3107. $html .= '</ul>';
  3108. }
  3109. // 分集剧本
  3110. if (!empty($group['episode_content'])) {
  3111. $html .= '<h3>分集剧本</h3>';
  3112. // 去除零宽字符和其他不可见字符
  3113. $cleanContent = preg_replace('/[\x{200B}-\x{200D}\x{FEFF}]/u', '', $group['episode_content']);
  3114. $cleanContent = preg_replace('/[\x{00}-\x{08}\x{0B}\x{0C}\x{0E}-\x{1F}\x{7F}]/u', '', $cleanContent);
  3115. $html .= '<div class="episode-content">' . nl2br(htmlspecialchars($cleanContent)) . '</div>';
  3116. }
  3117. $html .= '</div>';
  3118. }
  3119. }
  3120. return $html;
  3121. }
  3122. /**
  3123. * 构建PDF内容
  3124. */
  3125. private function buildPdfContent($pdf, $script) {
  3126. // 标题
  3127. $pdf->SetFont('dejavusans', 'B', 18);
  3128. $pdf->Cell(0, 15, $script['script_name'], 0, 1, 'C');
  3129. $pdf->Ln(5);
  3130. // 基本信息
  3131. $pdf->SetFont('dejavusans', '', 12);
  3132. $pdf->Cell(0, 8, '创建时间:' . $script['created_at'], 0, 1);
  3133. $pdf->Cell(0, 8, '状态:' . $script['status_info'], 0, 1);
  3134. $pdf->Ln(5);
  3135. // 剧本简介
  3136. if (!empty($script['intro'])) {
  3137. $pdf->SetFont('dejavusans', 'B', 14);
  3138. $pdf->Cell(0, 10, '剧本简介', 0, 1);
  3139. $pdf->SetFont('dejavusans', '', 12);
  3140. $pdf->MultiCell(0, 8, $script['intro'], 0, 'L');
  3141. $pdf->Ln(3);
  3142. }
  3143. // 亮点
  3144. if (!empty($script['highlights'])) {
  3145. $pdf->SetFont('dejavusans', 'B', 14);
  3146. $pdf->Cell(0, 10, '亮点', 0, 1);
  3147. $pdf->SetFont('dejavusans', '', 12);
  3148. $pdf->MultiCell(0, 8, $script['highlights'], 0, 'L');
  3149. $pdf->Ln(3);
  3150. }
  3151. // 核心矛盾
  3152. if (!empty($script['core_contradiction'])) {
  3153. $pdf->SetFont('dejavusans', 'B', 14);
  3154. $pdf->Cell(0, 10, '核心矛盾', 0, 1);
  3155. $pdf->SetFont('dejavusans', '', 12);
  3156. $pdf->MultiCell(0, 8, $script['core_contradiction'], 0, 'L');
  3157. $pdf->Ln(3);
  3158. }
  3159. // 艺术风格
  3160. if (!empty($script['art_style'])) {
  3161. $pdf->SetFont('dejavusans', 'B', 14);
  3162. $pdf->Cell(0, 10, '艺术风格', 0, 1);
  3163. $pdf->SetFont('dejavusans', '', 12);
  3164. $pdf->MultiCell(0, 8, $script['art_style'], 0, 'L');
  3165. $pdf->Ln(3);
  3166. }
  3167. // 备注
  3168. if (!empty($script['remark'])) {
  3169. $pdf->SetFont('dejavusans', 'B', 14);
  3170. $pdf->Cell(0, 10, '备注', 0, 1);
  3171. $pdf->SetFont('dejavusans', '', 12);
  3172. $pdf->MultiCell(0, 8, $script['remark'], 0, 'L');
  3173. $pdf->Ln(3);
  3174. }
  3175. // 角色列表
  3176. if (!empty($script['roles']) && is_array($script['roles'])) {
  3177. $pdf->SetFont('dejavusans', 'B', 14);
  3178. $pdf->Cell(0, 10, '角色列表', 0, 1);
  3179. $pdf->SetFont('dejavusans', '', 12);
  3180. foreach ($script['roles'] as $index => $role) {
  3181. if (is_array($role) || is_object($role)) {
  3182. $pdf->Cell(0, 8, ($index + 1) . '. ' . getProp($role, 'role', '') . ':' . getProp($role, 'description', ''), 0, 1);
  3183. } else {
  3184. $pdf->Cell(0, 8, ($index + 1) . '. ' . $role, 0, 1);
  3185. }
  3186. }
  3187. $pdf->Ln(3);
  3188. }
  3189. // 角色关系
  3190. if (!empty($script['role_relationship'])) {
  3191. $pdf->SetFont('dejavusans', 'B', 14);
  3192. $pdf->Cell(0, 10, '角色关系', 0, 1);
  3193. $pdf->SetFont('dejavusans', '', 12);
  3194. $pdf->MultiCell(0, 8, $script['role_relationship'], 0, 'L');
  3195. $pdf->Ln(3);
  3196. }
  3197. // 场景列表
  3198. if (!empty($script['scenes']) && is_array($script['scenes'])) {
  3199. $pdf->SetFont('dejavusans', 'B', 14);
  3200. $pdf->Cell(0, 10, '场景列表', 0, 1);
  3201. $pdf->SetFont('dejavusans', '', 12);
  3202. foreach ($script['scenes'] as $index => $scene) {
  3203. if (is_array($scene) || is_object($scene)) {
  3204. $pdf->Cell(0, 8, ($index + 1) . '. ' . getProp($scene, 'scene', '') . ':' . getProp($scene, 'description', ''), 0, 1);
  3205. } else {
  3206. $pdf->Cell(0, 8, ($index + 1) . '. ' . $scene, 0, 1);
  3207. }
  3208. }
  3209. $pdf->Ln(5);
  3210. }
  3211. // 分集内容
  3212. if (!empty($script['episodes']) && is_array($script['episodes'])) {
  3213. $pdf->SetFont('dejavusans', 'B', 16);
  3214. $pdf->Cell(0, 12, '分集内容', 0, 1);
  3215. $pdf->Ln(3);
  3216. foreach ($script['episodes'] as $episode) {
  3217. // 检查是否需要新页面
  3218. if ($pdf->GetY() > 250) {
  3219. $pdf->AddPage();
  3220. }
  3221. $pdf->SetFont('dejavusans', 'B', 14);
  3222. $episodeTitle = '第' . $episode['episode_number'] . '集';
  3223. if (!empty($episode['title'])) {
  3224. $episodeTitle .= ':' . $episode['title'];
  3225. }
  3226. $pdf->Cell(0, 10, $episodeTitle, 0, 1);
  3227. // 处理分段内容
  3228. if (!empty($episode['segments']) && is_array($episode['segments'])) {
  3229. $pdf->SetFont('dejavusans', '', 12);
  3230. foreach ($episode['segments'] as $segment) {
  3231. if (!empty($segment['segment_content'])) {
  3232. // 如果有分段编号,显示分段标题
  3233. if (!empty($segment['segment_number'])) {
  3234. $pdf->SetFont('dejavusans', 'B', 12);
  3235. $pdf->Cell(0, 8, '第' . $segment['segment_number'] . '段', 0, 1);
  3236. $pdf->SetFont('dejavusans', '', 12);
  3237. }
  3238. $pdf->MultiCell(0, 8, $segment['segment_content'], 0, 'L');
  3239. $pdf->Ln(2);
  3240. }
  3241. }
  3242. }
  3243. $pdf->Ln(5);
  3244. }
  3245. }
  3246. }
  3247. /**
  3248. * 构建剧本文本内容
  3249. */
  3250. private function buildScriptContent($script) {
  3251. $content = '';
  3252. $groups = $script['group'];
  3253. $groups = (array)$groups;
  3254. foreach ($groups as $group) {
  3255. $content .= str_repeat('→', 40).' 第'.$group['start_episode_number'].'-'.$group['end_episode_number']."集 ".str_repeat('←', 40)."\n\n";
  3256. // 剧本基本信息
  3257. if (!empty($group['intro'])) {
  3258. $content .= "###故事梗概\n" . $group['intro'] . "\n\n";
  3259. }
  3260. if (!empty($group['highlights'])) {
  3261. $content .= "###剧本亮点\n" . $group['highlights'] . "\n\n";
  3262. }
  3263. if (!empty($group['role_relationship'])) {
  3264. $content .= "###人物关系\n" . $group['role_relationship'] . "\n\n";
  3265. }
  3266. if (!empty($group['core_contradiction'])) {
  3267. $content .= "###核心矛盾\n" . $group['core_contradiction'] . "\n\n";
  3268. }
  3269. if (!empty($group['roles']) && is_array($group['roles'])) {
  3270. $content .= "###主体列表\n";
  3271. foreach ($group['roles'] as $role) {
  3272. $content .= getProp($role, 'role') . ":" . getProp($role, 'description') . "\n";
  3273. }
  3274. $content .= "\n\n";
  3275. }
  3276. if (!empty($group['art_style'])) {
  3277. $content .= "###美术风格\n" . $group['art_style'] . "\n\n";
  3278. }
  3279. // 场景信息
  3280. if (!empty($group['scenes']) && is_array($group['scenes'])) {
  3281. $content .= "###场景列表\n";
  3282. foreach ($group['scenes'] as $scene) {
  3283. $content .= getProp($scene, 'scene') . ":" . getProp($scene, 'description') . "\n";
  3284. }
  3285. $content .= "\n\n";
  3286. }
  3287. // 分集内容
  3288. if (!empty($group['episode_content'])) {
  3289. $content .= "###分集剧本\n";
  3290. $content .= $group['episode_content'];
  3291. // foreach ($script['episodes'] as $episode) {
  3292. // // $content .= "##分集" . $episode['episode_number'] . "\n分集名";
  3293. // // if (!empty($episode['episode_name'])) {
  3294. // // $content .= ":" . $episode['episode_name'];
  3295. // // }
  3296. // // $content .= "\n";
  3297. // $content .= $episode['episode_content'] . "\n\n";
  3298. // }
  3299. }
  3300. }
  3301. return $content;
  3302. }
  3303. /**
  3304. * 上传文件识别文字内容并与 DeepSeek 进行对话(流式输出版本)
  3305. *
  3306. * @param array $data 包含以下参数:
  3307. * - file: 上传的文件(UploadedFile 对象)或文件路径
  3308. * - question: 用户问题(可选)
  3309. * - model: 使用的模型(r1 或 v3,默认 v3)
  3310. * @return \Generator 返回生成器,用于流式输出
  3311. */
  3312. public function addChat($data) {
  3313. $uid = Site::getUid();
  3314. $anime_id = getProp($data, 'anime_id');
  3315. if (!$anime_id) Utils::throwError('20003:请选择对话');
  3316. $anime = DB::table('mp_animes')->where('id', $anime_id)->where('is_deleted', 0)->first();
  3317. if (!$anime) Utils::throwError('20003:对话不存在');
  3318. $file = getProp($data, 'file');
  3319. $content = getProp($data, 'content', '');
  3320. $bid = getProp($data, 'bid', 0);
  3321. $script_id = getProp($data, 'script_id', 0);
  3322. $ace_mode = getProp($data, 'ace_mode', 0) ? getProp($data, 'ace_mode', 0) : getProp($anime, 'ace_mode', 0);
  3323. $prompt = getProp($data, 'prompt');
  3324. $user_anime_name = getProp($anime, 'anime_name');
  3325. // 处理文本模型
  3326. $model = getProp($data, 'model');
  3327. if (!$model) {
  3328. // 用户没有输入,从anime表获取
  3329. $model = getProp($anime, 'model');
  3330. if (!$model) {
  3331. // anime表也没有,使用默认值
  3332. $model = 'doubao-seed-2-0-mini-260215';
  3333. }
  3334. }
  3335. // 验证模型是否在可用模型表中
  3336. if (!DB::table('mp_text_models')->where('model', $model)->where('is_enabled', 1)->exists()) {
  3337. $model = 'doubao-seed-2-0-mini-260215';
  3338. }
  3339. $is_multi = getProp($anime, 'is_multi');
  3340. $is_single = (int)$is_multi !== 1;
  3341. $question = getProp($data, 'question', $is_single ? "请根据实例格式完成单剧集剧本及分镜\n" : "请根据实例格式完成剧本大纲\n");
  3342. if ($prompt) {
  3343. $question .= "本次修改要求如下:\n{$prompt}";
  3344. }
  3345. // if (!$file && !$content && !$bid) {
  3346. // Utils::throwError('20003:请上传文件或选择书籍或输入内容');
  3347. // }
  3348. // 提取文件内容
  3349. if ($file) {
  3350. $content = $this->extractFileContent($file);
  3351. if (!$content) {
  3352. Utils::throwError('20003:无法提取文件内容,请检查文件格式');
  3353. }
  3354. } elseif ($script_id) {
  3355. $content = $this->getContentByScriptId($script_id);
  3356. if (!$content) {
  3357. Utils::throwError('20003:无法获取剧本内容,请检查剧本');
  3358. }
  3359. } elseif ($bid) {
  3360. $content = $this->getContentByBid($bid);
  3361. if (!$content) {
  3362. Utils::throwError('20003:无法获取书籍内容,请检查书籍');
  3363. }
  3364. } elseif ($content) {
  3365. $content = filterContent($content);
  3366. } else {
  3367. $content = getProp($anime, 'content');
  3368. if (!$content && $prompt) { // 如果动漫记录中没有内容则根据提示词生成
  3369. $need_generate_content = true;
  3370. }
  3371. }
  3372. // 美术风格
  3373. $input_art_style = getProp($data, 'art_style');
  3374. $mappedArtStyle = $this->getArtStylePromptByInput($input_art_style);
  3375. $timbres_content = "青年男:北京小爷、阳光青年、傲娇霸总、优柔公子、解说小明、青涩小生、低音沉郁、亲切青年
  3376. 青年女:柔美女友、魅力女友、爽快思思、高冷御姐、知性温婉、甜心小美、清新女声、甜美桃子、温柔文雅、甜美小源、贴心闺蜜
  3377. 中年男:胡子叔叔、油腻大叔、神秘法师、优柔帮主
  3378. 中年女:邻居阿姨
  3379. 老年男:幽默大爷
  3380. 老年女:婆婆
  3381. 萌娃:奶气萌娃";
  3382. // 判断是否需要生成原文内容
  3383. $need_generate_content = isset($need_generate_content) && $need_generate_content;
  3384. // 如果需要生成原文内容,添加额外的要求
  3385. $content_generation_requirement = $need_generate_content
  3386. ? "\n5.如果用户只提供了创作要求而没有提供具体文档内容,你需要根据要求创作完整的原文内容(小说形式,包含对话和叙述),并将原文内容放在最后一个板块###原文内容中输出。原文内容应该详细、生动,如果用户没有明确生成的字数,则字数不少于1000字。"
  3387. : "";
  3388. // 美术风格
  3389. if (!$mappedArtStyle) {
  3390. $mappedArtStyle_prompt = '美术风格:根据剧本内容自定义美术风格';
  3391. }else {
  3392. if (strstr($mappedArtStyle, '基础画风风格词')) {
  3393. $mappedArtStyle_prompt = "美术风格强制设置如下(原样输出,不得更改任何内容):\n{$mappedArtStyle}\n";
  3394. }else {
  3395. $art_style_type = $input_art_style ? $input_art_style : getProp($anime, 'art_style_type');
  3396. $mappedArtStyle_prompt = "美术风格强制设置如下(原样输出,不得更改任何内容):\n基础画风风格词: {$art_style_type}\n{$mappedArtStyle}\n";
  3397. }
  3398. }
  3399. $systemPrompt = $is_single
  3400. ? "你是一个专业的文档分析助手及资深编剧,请根据用户提供的文档内容输出单剧集完整策划稿(剧本大纲包括: <故事梗概><剧本亮点><人物关系><核心矛盾><主体列表><美术风格><场景列表><分镜剧本>,每个板块之间必须使用###分隔,#不能多也不能少)。单剧集模式下,必须一次性输出可直接保存的大纲与完整分镜,不允许只输出大纲。
  3401. 强制要求:
  3402. 1.你只负责与剧本相关的内容,如果用户输入与剧本无关的内容,请告知用户并拒绝继续回答,此为第一优先原则,不满足此原则就忽略其他要求并停止继续输出
  3403. 2.如果用户输入修改美术风格、修改画风这类内容,请告知用户不可修改美术风格,并拒绝继续回答
  3404. 3.以上两条要求对修改主体角色或场景不生效,允许用户调整主体角色说明和场景描述等
  3405. 4.用户如果要求你帮忙写一个故事或者剧本,此类要求不属于与剧本无关,请帮助用户完成请求{$content_generation_requirement}
  3406. 5.强制按照示例格式返回内容,不要更改格式或随意增加符号\n
  3407. 普通要求:
  3408. 1.剧本名(必须生成)和剧集标题必须与文档内容高度相关,(其中剧集序号是1)。
  3409. 2.<主体列表>中出现的“主体名”必须尽可能统一,严禁出现角色-科学家、角色-复仇者、角色-领导者等带有身份、职业、标签类的命名,只能使用服装差异(如校服装、卫衣装、西装)来区分同一角色,如角色-校服装等。
  3410. 2.1<主体列表>分以下三部分:主体描述、人物提示词和音色,格式必须为:主体描述{人物提示词}{{音色}}
  3411. 2.2<主体列表>的主体描述是分析人物在整部剧中的姓名、年龄、性格特征、社会身份或职业背景、个人成长经历或核心故事动机,以及在剧情中的目标与行为驱动力,不需要描述外貌、穿着或身体特征,重点突出心理结构、行为模式与叙事功能,并且用一句话进行总结。
  3412. 2.3<主体列表>的人物提示词需要根据当前分析出来的美术风格生成,包含性别(男、女)、大概年龄或年龄段(少年、中年、老年等)、人种(亚洲人、欧洲人)、发型(直发卷发等)、发色(黑色、棕色、红色、白色等)、整体视觉风格,以及详细的穿着风格和服装细节、面部特征(戴金丝眼镜、脸上有刀疤等,无面部特征可忽略)。描述需具有镜头感与画面表现力,适合直接用于AI图像生成模型,避免抽象词汇,强调具体可视化细节与整体视觉一致性,同时保证风格统一且符合人物身份设定。该提示词(字数50-100字左右)在主体描述后用{}框起来。
  3413. 2.4<主体列表>的音色必须在以下音色中($timbres_content)选择,需要根据角色描述的年纪和性别选择,比如角色是青年男性就只能在北京小爷、阳光青年、傲娇霸总、优柔公子、解说小明、青涩小生、低音沉郁、亲切青年中选择,选好的音色放在描述的最后用{{}}框起来。
  3414. 3.<场景列表>与主体列表同理,需尽可能的对场景环境进行详细描述,必须严格注意不要出现任何角色和人物。
  3415. 3.1<场景列表>分以下两部分:场景描述和场景提示词,格式必须为:场景描述{场景提示词}
  3416. 3.2<场景列表>的场景描述是分析在整部剧中出现过的场景,场景描述尽量简洁贴合原文。
  3417. 3.3<场景列表>的场景提示词用于视觉呈现的场景环境描述,该场景需包含环境氛围、光线效果、空间布局、色彩基调、视觉风格等,描述需具有镜头感与画面表现力,适合直接用于AI图像生成模型,避免抽象词汇,强调具体可视化细节与整体视觉一致性,同时保证风格统一且符合剧情设定(可参考以下示例的场景列表中使用{}框起来的提示词,字数150-200字,需带上提炼出来的美术风格)。该提示词在场景描述后用{}框起来。\n
  3418. 4.<分镜剧本>要求包含“分幕标题”以及“分镜信息”:
  3419. 4.1“分幕标题”是根据章节中的场景进行拆分,类似于“第1幕 场景、时间及室内或室外”的信息,其中场景只能在所给出的场景列表中选(不带场景详细描述)。
  3420. 4.2“分镜信息”需同一场景内的对话内容完成分镜(每一幕分镜尽量不得低于5个),需包含“画面描述”、“构图设计”、“运镜调度”、“配音角色”、“台词内容”、“画面类型”、“尾帧描述”、“情感”、“性别”、“语速”、“音量”、“情感强度”、“音调”这几个部分,其中“画面描述”如果出现主体,只能选择上述主体列表中的一个,主体的名称也需要保持一致(不带主体具体描述)。
  3421. 4.3分镜序号用1、2、3显示,如分镜1、分镜2,并且分镜序号需连续(跨分幕中的分镜序号需连续,但跨剧集中的不需要连续,如第2集的第1幕分镜序号从1开始)。
  3422. 4.4“分镜信息”中的“台词内容”需满足以下要求: (1. 台词来源规则:- 台词内容必须逐字摘录自小说原文中的人物直接对话(带引号的内容)。- 不允许改写、总结、压缩、扩写或拼接原文对白。- 不允许生成原文中不存在的对话。2. 非对话过滤:- 旁白、心理描写、环境描写、动作描写等内容,禁止出现在台词内容中。3. 空台词规则:- 如果该分镜中没有人物对话,则“台词内容”必须返回“无”。- 严禁输出“无台词”、“没有”等任何替代文本。4. 禁止推测:- 不得根据语境补全人物可能说的话。)
  3423. 4.5“分镜信息”中的“配音角色”需对应本集中的<主体列表>中的一个(非对话内容则统一固定为“旁白”角色),不得自己生成。
  3424. 4.6“分镜信息”中的“场景”必须选择本集中的<场景列表>中的一个(不带详细表述)。
  3425. 4.7“分镜信息”中的“出镜角色”需对应本集中的<主体列表>中的一个或多个(不带详细描述),如果没有出镜角色则填无。
  3426. 4.8“分镜信息”中的“尾帧描述”需根据本镜和下一镜的剧本信息进行过渡生成,用于后续转视频进行衔接上下镜头的画面。
  3427. 4.9“分镜信息”中的“情感”需根据台词内容和剧情氛围分析得出,可选值为:开心、悲伤、生气、惊讶、恐惧、厌恶、激动、冷漠、中性、沮丧、撒娇、害羞、安慰鼓励、咆哮、温柔、自然讲述、情感电台、磁性、广告营销、气泡音、新闻播报、娱乐八卦,不要在情感可选词后加任何解释性的词语,比如(对自己)、(对别人)等,不要自定义情感,必须在可选值中选择。
  3428. 4.10“分镜信息”中的“性别”需根据配音角色的性别确定,可选值为:1(男)、2(女)、0(中性)。
  3429. 4.11“分镜信息”中的“语速”需根据台词内容和情感氛围确定,可选值范围为:-50到100之间的整数,100代表2.0倍速,-50代表0.5倍数,负值表示减慢,正值表示加快,0表示正常语速。
  3430. 4.12“分镜信息”中的“音量”需根据台词内容和情感氛围确定,可选值范围为:-50到100之间的整数,100代表2.0倍音量,-50代表0.5倍音量,负值表示降低音量,正值表示提高音量,0表示正常音量。
  3431. 4.13“分镜信息”中的“情感强度”需根据情感的强烈程度确定,可选值范围为:1到5之间的整数,默认情况下选择4。
  3432. 4.14“分镜信息”中的“音调”需根据台词内容和情感氛围确定,可选值范围为:-12到12之间的整数,负值表示降低音调,正值表示提高音调,0表示正常音调。\n
  3433. 5.{$mappedArtStyle_prompt}\n\n
  3434. 示例如下:\n
  3435. ###剧本名:西昆仑
  3436. ###故事梗概
  3437. 内容梗概:古风厚涂的世界中,少女阿雪身中奇毒“问心刺”,气息奄奄。少年梁萧心急如焚,用奇珍“阴阳球”稳住阿雪性命,却发现必须解衣拔刺。阿雪羞涩难当,梁萧情急之下提出结拜兄妹,以化解尴尬。两人匆匆结拜后,梁萧小心翼翼地拔出“问心刺”,竟发现它是一根诡异的女子秀发。阿雪转危为安,两人之间,在生死与羞涩交织的瞬间,情愫暗生,却又被兄妹之名束缚,留下无尽遐想。
  3438. ###剧本亮点
  3439. 亮点1:绝境奇药,生死一线
  3440. 画面开场即是阿雪苍白无力的脸庞,梁萧眼中泪光闪烁,急促的呼吸声与心跳声烘托紧张气氛。特写梁萧将“阴阳球”塞入阿雪舌底,球体散发微光,阿雪气息从若有若无到逐渐平稳,生死逆转的瞬间,视觉与听觉冲击力十足。
  3441. 亮点2:结拜兄妹,化解尴尬
  3442. 阿雪因解衣拔刺而羞愤欲绝的特写,梁萧眼神中的挣扎与无奈。在紧迫的背景音下,梁萧急中生智,牵起阿雪颤抖的手,跪地匆匆结拜,阿雪眼神从惊惶到迷茫,最终一句“我……我愿意的”带着哭腔,将救命与羞耻的矛盾推向高潮,又以出人意料的方式解决。
  3443. 亮点3:纤发夺命,情愫暗涌
  3444. 拔刺过程的紧张特写,梁萧指尖小心翼翼地捏住细丝,缓慢抽出。当“问心刺”被完全拔出,特写它竟是一根细长、泛着寒光的女子秀发,诡异而令人震惊。阿雪苏醒后,两人眼神交汇,阿雪低头羞涩,梁萧眼中复杂的情绪,无声地传递出超越兄妹的微妙情愫。
  3445. ###人物关系
  3446. 阿雪与梁萧之间存在兄妹之情。
  3447. ###核心矛盾
  3448. 阿雪与梁萧之间存在兄妹之情,但因情愫暗生而产生微妙的矛盾。阿雪羞涩难当,梁萧情急之下提出结拜兄妹,以化解尴尬。两人匆匆结拜后,梁萧小心翼翼地拔出“问心刺”,竟发现它是一根诡异的女子秀发。阿雪转危为安,两人之间,在生死与羞涩交织的瞬间,情愫暗生,却又被兄妹之名束缚,留下无尽遐想。
  3449. ###主体列表
  3450. 阿雪:身中奇毒“问心刺”,气息奄奄,面色苍白,身体虚弱。{全景,正面拍摄,青年女性,亚洲人。
  3451. 黑色短发扎成利落的高马尾,五官精致且轮廓清晰。
  3452. 服饰穿搭:身着红白相间的专业田径运动背心与超短跑步裤,皮肤呈现健康的小麦色,四肢肌肉线条紧致有力。
  3453. 姿态:站立。}{{甜心小美}}
  3454. 梁萧:少年侠士,心系阿雪安危,沉着冷静,内心挣扎于情义之间。{8k超高清,电影级光效,大气透视,中国传统艺术美学,空灵光泽,深度景深,复杂精细的纹理,史诗级构图,电影胶片颗粒。
  3455. 全景,正面拍摄,青年女性,亚洲人。
  3456. 佩戴精致繁复的金丝凤冠,黑色长发整齐盘起。
  3457. 服饰穿搭:身着大红色正装嫁衣,上面绣有精细的金色凤凰纹样,质感厚重华贵。
  3458. 姿态:站立。}{{阳光青年}}
  3459. ###美术风格
  3460. 基础画风风格词:厚涂古风
  3461. 整体采用精致细腻的厚涂古风,色彩浓郁而富有层次感,注重光影对比,营造出古典而富有戏剧张力的氛围。色调以深沉的蓝绿、灰调为主,衬托阿雪病弱的苍白,同时用温暖的金色、琥珀色光晕突出“阴阳球”的生命力。拔刺与结拜场景则以柔和的暖色调为主,辅以人物脸颊的红晕,烘托羞涩与情愫暗生的微妙感。人物造型飘逸,服饰细节考究,背景虚实结合,既有古韵,又不失奇幻色彩。
  3462. ###场景列表
  3463. 林间疗伤地:幽静的古风林间空地,一棵高大古树下,是梁萧为阿雪疗伤的地点。环境清幽,光影斑驳,既有古韵又不失奇幻色彩。{影视质感。广角。
  3464. 宽敞的天然山洞内部,石壁上错落有致地镶嵌着发光的萤石,散发出冷色调的微光,照亮了整个空间。洞顶有钟乳石垂下。光影层次丰富,营造出一种宁静而神圣的氛围。
  3465. 无人物。}
  3466. ###分镜剧本
  3467. ##第1幕:徐家老旧厨房 白天 室内
  3468. 分镜1
  3469. 画面描述:许芸-校服装站在厨房门口,书包背在肩上,徐母手持扫帚,正对着许芸的背部猛烈挥打。卞大伟站在锅炉后方,双手抱胸,阴沉的目光落在许芸身上。
  3470. 场景:徐家老旧厨房
  3471. 构图设计:全景,低角度仰视
  3472. 运镜调度:手持拍摄
  3473. 配音角色:旁白
  3474. 出镜角色:许芸-校服装、徐母
  3475. 台词内容:我一到家,徐母的扫帚就落在我身上,嘴里一个劲地骂我,
  3476. 画面类型:普通画面
  3477. 尾帧描述:手持拍摄微晃镜头,中年妇女猛力挥动扫帚击打少女背部,少女身体因冲击微颤,阴影中的肥胖男子目光冷冷跟随。
  3478. 分镜2
  3479. 画面描述:徐母面容扭曲,嘴唇快速开合,扫帚挥舞在空中。
  3480. 场景:徐家老旧厨房
  3481. 构图设计:近景,徐母面部特写
  3482. 运镜调度:固定镜头
  3483. 配音角色:徐母
  3484. 出镜角色:徐母
  3485. 台词内容:问我夜不归宿死哪儿去了。
  3486. 画面类型:对口型
  3487. 尾帧描述:固定镜头,中年妇女面部肌肉剧烈抖动,嘴唇快速开合进行辱骂,背景中的扫帚在空中上下挥动。
  3488. ##第2幕:徐家简陋客厅 黄昏 室内
  3489. 分镜3
  3490. 画面描述:客厅窗户透出昏黄的夕阳余晖,空荡荡的客厅中央只有几把木凳和一张方桌,显得异常安静。
  3491. 场景:徐家简陋客厅
  3492. 构图设计:全景,景深虚化
  3493. 运镜调度:固定镜头
  3494. 配音角色:旁白
  3495. 出镜角色:无
  3496. 台词内容:可我没想到,半个月后,徐母居然再一次外出,
  3497. 画面类型:普通画面
  3498. 尾帧描述:固定镜头。昏黄的夕阳余晖在地面上缓慢移动,空气中的浮尘在光束中跳动,室内维持着死寂的安静。
  3499. 分镜4
  3500. 画面描述:一张泛黄的火车票特写,上面显示着隔壁市的站名和日期。
  3501. 场景:徐家简陋客厅
  3502. 构图设计:特写,火车票
  3503. 运镜调度:固定镜头
  3504. 配音角色:旁白
  3505. 出镜角色:无
  3506. 台词内容:这次是去隔壁市看望她生病的好姐妹。
  3507. 画面类型:普通画面
  3508. 尾帧描述:固定镜头。光影在火车票表面微微晃动,强调其陈旧的纸张纹理与关键的行程信息。\n
  3509. "
  3510. : "你是一个专业的文档分析助手及资深编剧,请根据用户提供的文档内容及下面提供的示例格式完成剧本大纲(需通过以下几个板块进行回复: <故事梗概><剧本亮点><人物关系><核心矛盾><主体列表><美术风格><场景列表>,每个板块之间必须使用###分隔,#不能多也不能少;同时板块之间需满足以下要求:\n
  3511. 强制要求:\n
  3512. 1.你只负责与剧本相关的内容,如果用户输入与剧本无关的内容,请告知用户并拒绝继续回答,此为第一优先原则,不满足此原则就忽略其他要求并停止继续输出
  3513. 2.如果用户输入修改美术风格、修改画风这类内容,请告知用户不可修改美术风格,并拒绝继续回答
  3514. 3.以上两条要求对修改主体角色或场景不生效,允许用户调整主体角色说明和场景描述等
  3515. 4.用户如果要求你帮忙写一个故事或者剧本,此类要求不属于与剧本无关,请帮助用户完成请求{$content_generation_requirement}
  3516. 5.强制按照示例格式返回内容,不要更改格式或随意增加符号\n
  3517. 普通要求:\n
  3518. 1.剧本名(必须生成)必须与文档内容高度相关
  3519. 2.<主体列表>中出现的“主体名”必须尽可能统一,严禁出现角色-科学家、角色-复仇者、角色-领导者等带有身份、职业、标签类的命名,只能使用服装差异(如校服装、卫衣装、西装)来区分同一角色,如角色-校服装等。
  3520. 2.1<主体列表>分以下三部分:主体描述、人物提示词和音色,格式必须为:主体名:主体描述{人物提示词}{{音色}}
  3521. 2.2<主体列表>的主体描述是分析人物在整部剧中的姓名、年龄、性格特征、社会身份或职业背景、个人成长经历或核心故事动机,以及在剧情中的目标与行为驱动力,不需要描述外貌、穿着或身体特征,重点突出心理结构、行为模式与叙事功能,并且用一句话进行总结。
  3522. 2.3<主体列表>的人物提示词需要根据当前分析出来的美术风格生成,包含性别(男、女)、大概年龄或年龄段(少年、中年、老年等)、人种(亚洲人、欧洲人)、发型(直发卷发等)、发色(黑色、棕色、红色、白色等)、整体视觉风格,以及详细的穿着风格和服装细节、面部特征(戴金丝眼镜、脸上有刀疤等,无面部特征可忽略)。描述需具有镜头感与画面表现力,适合直接用于AI图像生成模型,避免抽象词汇,强调具体可视化细节与整体视觉一致性,同时保证风格统一且符合人物身份设定。该提示词(字数50-100字左右)在主体描述后用{}框起来。
  3523. 2.4<主体列表>的音色必须在以下音色中($timbres_content)选择,需要根据角色描述的年纪和性别选择,比如角色是青年男性就只能在北京小爷、阳光青年、傲娇霸总、优柔公子、解说小明、青涩小生、低音沉郁、亲切青年中选择,选好的音色放在描述的最后用{{}}框起来。
  3524. 3.<场景列表>与主体列表同理,需尽可能的对场景环境进行详细描述,必须严格注意不要出现任何角色和人物。
  3525. 3.1<场景列表>分以下两部分:场景描述和场景提示词,格式必须为:场景描述{场景提示词}
  3526. 3.2<场景列表>的场景描述是分析在整部剧中出现过的场景,场景描述尽量简洁贴合原文。
  3527. 3.3<场景列表>的场景提示词用于视觉呈现的场景环境描述,该场景需包含环境氛围、光线效果、空间布局、色彩基调、视觉风格等,描述需具有镜头感与画面表现力,适合直接用于AI图像生成模型,避免抽象词汇,强调具体可视化细节与整体视觉一致性,同时保证风格统一且符合剧情设定(可参考以下示例的场景列表中使用{}框起来的提示词,字数150-200字,需带上提炼出来的美术风格)。该提示词在场景描述后用{}框起来。\n
  3528. 4.{$mappedArtStyle_prompt}\n\n
  3529. 示例如下:\n
  3530. ###剧本名:西昆仑
  3531. ###故事梗概
  3532. 内容梗概:古风厚涂的世界中,少女阿雪身中奇毒“问心刺”,气息奄奄。少年梁萧心急如焚,用奇珍“阴阳球”稳住阿雪性命,却发现必须解衣拔刺。阿雪羞涩难当,梁萧情急之下提出结拜兄妹,以化解尴尬。两人匆匆结拜后,梁萧小心翼翼地拔出“问心刺”,竟发现它是一根诡异的女子秀发。阿雪转危为安,两人之间,在生死与羞涩交织的瞬间,情愫暗生,却又被兄妹之名束缚,留下无尽遐想。
  3533. ###剧本亮点
  3534. 亮点1:绝境奇药,生死一线
  3535. 画面开场即是阿雪苍白无力的脸庞,梁萧眼中泪光闪烁,急促的呼吸声与心跳声烘托紧张气氛。特写梁萧将“阴阳球”塞入阿雪舌底,球体散发微光,阿雪气息从若有若无到逐渐平稳,生死逆转的瞬间,视觉与听觉冲击力十足。
  3536. 亮点2:结拜兄妹,化解尴尬
  3537. 阿雪因解衣拔刺而羞愤欲绝的特写,梁萧眼神中的挣扎与无奈。在紧迫的背景音下,梁萧急中生智,牵起阿雪颤抖的手,跪地匆匆结拜,阿雪眼神从惊惶到迷茫,最终一句“我……我愿意的”带着哭腔,将救命与羞耻的矛盾推向高潮,又以出人意料的方式解决。
  3538. 亮点3:纤发夺命,情愫暗涌
  3539. 拔刺过程的紧张特写,梁萧指尖小心翼翼地捏住细丝,缓慢抽出。当“问心刺”被完全拔出,特写它竟是一根细长、泛着寒光的女子秀发,诡异而令人震惊。阿雪苏醒后,两人眼神交汇,阿雪低头羞涩,梁萧眼中复杂的情绪,无声地传递出超越兄妹的微妙情愫。
  3540. ###人物关系
  3541. 阿雪与梁萧之间存在兄妹之情。
  3542. ###核心矛盾
  3543. 阿雪与梁萧之间存在兄妹之情,但因情愫暗生而产生微妙的矛盾。阿雪羞涩难当,梁萧情急之下提出结拜兄妹,以化解尴尬。两人匆匆结拜后,梁萧小心翼翼地拔出“问心刺”,竟发现它是一根诡异的女子秀发。阿雪转危为安,两人之间,在生死与羞涩交织的瞬间,情愫暗生,却又被兄妹之名束缚,留下无尽遐想。
  3544. ###主体列表
  3545. 阿雪:身中奇毒“问心刺”,气息奄奄,面色苍白,身体虚弱。{全景,正面拍摄,青年女性,亚洲人。
  3546. 黑色短发扎成利落的高马尾,五官精致且轮廓清晰。
  3547. 服饰穿搭:身着红白相间的专业田径运动背心与超短跑步裤,皮肤呈现健康的小麦色,四肢肌肉线条紧致有力。
  3548. 姿态:站立。}{{甜心小美}}
  3549. 梁萧:少年侠士,心系阿雪安危,沉着冷静,内心挣扎于情义之间。{8k超高清,电影级光效,大气透视,中国传统艺术美学,空灵光泽,深度景深,复杂精细的纹理,史诗级构图,电影胶片颗粒。
  3550. 全景,正面拍摄,青年女性,亚洲人。
  3551. 佩戴精致繁复的金丝凤冠,黑色长发整齐盘起。
  3552. 服饰穿搭:身着大红色正装嫁衣,上面绣有精细的金色凤凰纹样,质感厚重华贵。
  3553. 姿态:站立。}{{阳光青年}}
  3554. ###美术风格
  3555. 基础画风风格词:厚涂古风
  3556. 整体采用精致细腻的厚涂古风,色彩浓郁而富有层次感,注重光影对比,营造出古典而富有戏剧张力的氛围。色调以深沉的蓝绿、灰调为主,衬托阿雪病弱的苍白,同时用温暖的金色、琥珀色光晕突出“阴阳球”的生命力。拔刺与结拜场景则以柔和的暖色调为主,辅以人物脸颊的红晕,烘托羞涩与情愫暗生的微妙感。人物造型飘逸,服饰细节考究,背景虚实结合,既有古韵,又不失奇幻色彩。
  3557. ###场景列表
  3558. 林间疗伤地:幽静的古风林间空地,一棵高大古树下,是梁萧为阿雪疗伤的地点。环境清幽,光影斑驳,既有古韵又不失奇幻色彩。{影视质感。广角。
  3559. 宽敞的天然山洞内部,石壁上错落有致地镶嵌着发光的萤石,散发出冷色调的微光,照亮了整个空间。洞顶有钟乳石垂下。光影层次丰富,营造出一种宁静而神圣的氛围。
  3560. 无人物。}";
  3561. // 构建消息
  3562. $messages = [
  3563. [
  3564. 'role' => 'system',
  3565. 'content' => $systemPrompt
  3566. ],
  3567. [
  3568. 'role' => 'user',
  3569. 'content' => "以下是文档内容:
  3570. {$content}
  3571. 用户问题:
  3572. {$question}"
  3573. ]
  3574. ];
  3575. // 模型兼容性处理:deepseek-chat 和 deepseek-reasoner 映射到 deepseek-v4-flash
  3576. $thinkingMode = getProp($data, 'thinking', 'disabled'); // 默认非思考模式
  3577. $reasoningEffort = getProp($data, 'reasoning_effort', 'high'); // 默认思考强度
  3578. if ($model === 'deepseek-chat') {
  3579. // deepseek-chat 映射到 deepseek-v4-flash,非思考模式
  3580. $model = 'deepseek-v4-flash';
  3581. $thinkingMode = 'disabled';
  3582. } elseif ($model === 'deepseek-reasoner') {
  3583. // deepseek-reasoner 映射到 deepseek-v4-flash,思考模式
  3584. $model = 'deepseek-v4-flash';
  3585. $thinkingMode = 'enabled';
  3586. }
  3587. $post_data = [
  3588. 'model' => $model,
  3589. 'messages' => $messages,
  3590. // 'max_tokens' => 8192,
  3591. 'temperature' => 0.7,
  3592. 'frequency_penalty' => 0,
  3593. 'presence_penalty' => 0,
  3594. 'response_format' => ['type' => 'text'],
  3595. 'thinking' => ['type'=>$thinkingMode],
  3596. 'stream' => true // 启用流式输出
  3597. ];
  3598. if ($thinkingMode == 'enabled') $post_data['reasoning_effort'] = $reasoningEffort;
  3599. // 根据模型类型选择调用方法
  3600. $fullContent = '';
  3601. $fullReasoningContent = '';
  3602. $usage = [];
  3603. try {
  3604. if (in_array($model, ['deepseek-reasoner', 'deepseek-chat', 'deepseek-v4-flash', 'deepseek-v4-pro'])) {
  3605. // DeepSeek 官方模型使用 DeepSeek API
  3606. $streamGenerator = $this->deepSeekStreamResponse($post_data);
  3607. } else if (in_array($model, $this->gpt_text_models)) {
  3608. // GPT-5.4 模型使用 TokenRouter API
  3609. $streamGenerator = $this->gpt54StreamResponse($post_data);
  3610. } else {
  3611. // 其他模型使用火山引擎API
  3612. $streamGenerator = $this->volcEngineChatCompletion($post_data);
  3613. }
  3614. // 验证返回值类型
  3615. if (!is_iterable($streamGenerator)) {
  3616. $errorType = is_object($streamGenerator) ? get_class($streamGenerator) : gettype($streamGenerator);
  3617. dLog('deepseek')->error('addChat流式生成器无效', [
  3618. 'generator_type' => $errorType,
  3619. 'model' => $model,
  3620. 'anime_id' => $anime_id
  3621. ]);
  3622. logDB('deepseek', 'error', 'addChat流式生成器类型错误', [
  3623. 'type' => $errorType,
  3624. 'model' => $model
  3625. ]);
  3626. yield [
  3627. 'type' => 'error',
  3628. 'script' => [],
  3629. 'episode' => [],
  3630. 'answer' => '',
  3631. 'reasoning' => '',
  3632. 'usage' => [],
  3633. 'error' => '接口返回数据异常,请重新请求'
  3634. ];
  3635. return;
  3636. }
  3637. // 处理流式输出
  3638. foreach ($streamGenerator as $chunk) {
  3639. if (isset($chunk['type'])) {
  3640. if ($chunk['type'] === 'done') {
  3641. // 最终结果
  3642. $fullContent = $chunk['full_content'];
  3643. $fullReasoningContent = $chunk['full_reasoning'];
  3644. $usage = isset($chunk['usage']) ? $chunk['usage'] : [];
  3645. } else {
  3646. // 逐块yield数据
  3647. yield $chunk;
  3648. }
  3649. }
  3650. }
  3651. } catch (\Exception $e) {
  3652. dLog('deepseek')->error('addChat流式处理异常: ' . $e->getMessage(), [
  3653. 'model' => $model,
  3654. 'anime_id' => $anime_id,
  3655. 'trace' => $e->getTraceAsString()
  3656. ]);
  3657. logDB('deepseek', 'error', 'addChat流式处理失败', [
  3658. 'error' => $e->getMessage(),
  3659. 'model' => $model
  3660. ]);
  3661. yield [
  3662. 'type' => 'error',
  3663. 'script' => [],
  3664. 'episode' => [],
  3665. 'answer' => '',
  3666. 'reasoning' => '',
  3667. 'usage' => [],
  3668. 'error' => '处理请求时发生异常: ' . $e->getMessage()
  3669. ];
  3670. return;
  3671. }
  3672. dLog('deepseek')->info('完整内容: '.$fullContent);
  3673. logDB('deepseek', 'info', '完整内容', ['content' => $fullContent, 'anime_id' => $anime_id]);
  3674. // 处理完整内容并返回最终结果
  3675. $script_arr = [];
  3676. if ($fullContent) {
  3677. $script_arr = handleScriptContent($fullContent);
  3678. dLog('deepseek')->info('解析内容', $script_arr);
  3679. logDB('deepseek', 'info', '解析内容', $script_arr);
  3680. }
  3681. if (empty($script_arr['roles'])) {
  3682. // 未生成剧本相关内容,保存对话记录并返回提示
  3683. dLog('deepseek')->info('未生成剧本相关的内容');
  3684. try {
  3685. DB::beginTransaction();
  3686. $now = date('Y-m-d H:i:s');
  3687. // 保存对话记录
  3688. $records = [
  3689. [
  3690. 'uid' => $uid,
  3691. 'anime_id' => $anime_id,
  3692. 'sequence' => 0,
  3693. 'role' => 'user',
  3694. 'content' => $prompt,
  3695. 'created_at' => $now,
  3696. 'updated_at' => $now
  3697. ],
  3698. [
  3699. 'uid' => $uid,
  3700. 'anime_id' => $anime_id,
  3701. 'sequence' => 0,
  3702. 'role' => 'assistant',
  3703. // 'content' => $fullContent,
  3704. 'content' => '未生成剧本相关的内容,请调整提示词再试',
  3705. 'created_at' => $now,
  3706. 'updated_at' => $now
  3707. ]
  3708. ];
  3709. DB::table('mp_anime_records')->insert($records);
  3710. DB::commit();
  3711. } catch (\Exception $e) {
  3712. DB::rollBack();
  3713. dLog('deepseek')->error('保存对话记录失败', ['error' => $e->getMessage()]);
  3714. }
  3715. yield [
  3716. 'type' => 'done',
  3717. 'script' => [],
  3718. 'episode' => [],
  3719. 'answer' => $fullContent,
  3720. 'reasoning' => $fullReasoningContent,
  3721. 'usage' => $usage,
  3722. 'error' => '未生成剧本相关的内容,请调整提示词再试'
  3723. ];
  3724. return;
  3725. }
  3726. // 如果需要生成原文内容,从script_arr中提取
  3727. if ($need_generate_content && isset($script_arr['content']) && $script_arr['content']) {
  3728. $content = $script_arr['content'];
  3729. dLog('deepseek')->info('从AI生成结果中提取原文内容', ['content_length' => strlen($content)]);
  3730. if (!$content) {
  3731. yield [
  3732. 'type' => 'done',
  3733. 'script' => [],
  3734. 'episode' => [],
  3735. 'answer' => $fullContent,
  3736. 'reasoning' => $fullReasoningContent,
  3737. 'usage' => $usage,
  3738. 'error' => '未生成剧本内容,请调整提示词再试'
  3739. ];
  3740. return;
  3741. }
  3742. }
  3743. // 替换美术风格
  3744. if ($mappedArtStyle !== '') {
  3745. $script_arr['art_style'] = $mappedArtStyle;
  3746. $fullContent = $this->replaceArtStyleSection($fullContent, $mappedArtStyle);
  3747. }
  3748. // 新建动漫
  3749. if ($user_anime_name == '新剧本策划') {
  3750. $anime_name = getProp($script_arr, 'script_name');
  3751. // if (!$anime_name) {
  3752. // // 未识别到剧本名,保存对话记录并返回提示
  3753. // dLog('deepseek')->info('未能识别到剧本名称');
  3754. // try {
  3755. // DB::beginTransaction();
  3756. // $now = date('Y-m-d H:i:s');
  3757. // // 保存对话记录
  3758. // $records = [
  3759. // [
  3760. // 'uid' => $uid,
  3761. // 'anime_id' => $anime_id,
  3762. // 'sequence' => 0,
  3763. // 'role' => 'user',
  3764. // 'content' => $prompt,
  3765. // 'created_at' => $now,
  3766. // 'updated_at' => $now
  3767. // ],
  3768. // [
  3769. // 'uid' => $uid,
  3770. // 'anime_id' => $anime_id,
  3771. // 'sequence' => 0,
  3772. // 'role' => 'assistant',
  3773. // 'content' => '未能生成剧本名称,请重试',
  3774. // 'created_at' => $now,
  3775. // 'updated_at' => $now
  3776. // ]
  3777. // ];
  3778. // DB::table('mp_anime_records')->insert($records);
  3779. // DB::commit();
  3780. // } catch (\Exception $e) {
  3781. // DB::rollBack();
  3782. // dLog('deepseek')->error('保存对话记录失败', ['error' => $e->getMessage()]);
  3783. // }
  3784. // yield [
  3785. // 'type' => 'done',
  3786. // 'script' => [],
  3787. // 'episode' => [],
  3788. // 'answer' => $fullContent,
  3789. // 'reasoning' => $fullReasoningContent,
  3790. // 'usage' => $usage,
  3791. // 'error' => '未能识别到剧本名称,请调整提示词再试'
  3792. // ];
  3793. // return;
  3794. // }
  3795. // 确认对话名称唯一性
  3796. if ($anime_name && DB::table('mp_animes')->where('anime_name', $anime_name)->value('id')) {
  3797. $anime_name = $anime_name . '_' . date('YmdHis');
  3798. }
  3799. }else {
  3800. $anime_name = $user_anime_name;
  3801. }
  3802. $table_data = [
  3803. 'user_id' => $uid,
  3804. 'anime_name' => $anime_name,
  3805. 'model' => $model,
  3806. 'intro' => isset($script_arr['intro']) ? $script_arr['intro'] : '',
  3807. 'highlights' => isset($script_arr['highlights']) ? $script_arr['highlights'] : '',
  3808. 'role_relationship' => isset($script_arr['role_relationship']) ? $script_arr['role_relationship'] : '',
  3809. 'core_contradiction' => isset($script_arr['core_contradiction']) ? $script_arr['core_contradiction'] : '',
  3810. 'roles' => isset($script_arr['roles']) && is_array($script_arr['roles']) ? json_encode($script_arr['roles'], 256) : '[]',
  3811. 'art_style' => isset($script_arr['art_style']) ? $script_arr['art_style'] : '',
  3812. 'art_style_type' => $input_art_style,
  3813. 'scenes' => isset($script_arr['scenes']) && is_array($script_arr['scenes']) ? json_encode($script_arr['scenes'], 256) : '[]',
  3814. 'status' => '解析完成',
  3815. 'content' => $content,
  3816. 'is_multi' => $is_multi,
  3817. 'ace_mode' => $ace_mode,
  3818. 'generate_status' => '待执行',
  3819. 'updated_at' => date('Y-m-d H:i:s')
  3820. ];
  3821. if ($table_data['content']) {
  3822. $chapters = splitContent($table_data['content']);
  3823. $chapter_count = count($chapters);
  3824. if ($chapter_count > 0) {
  3825. $table_data['start_episode_sequence'] = 1;
  3826. $table_data['end_episode_sequence'] = $table_data['episode_num'] = $chapter_count;
  3827. }
  3828. }
  3829. // 如果有剧本ID则进行绑定
  3830. if ($script_id) {
  3831. $table_data['script_id'] = $script_id;
  3832. }
  3833. $single_episode = [];
  3834. try {
  3835. DB::beginTransaction();
  3836. $now = date('Y-m-d H:i:s');
  3837. // 更新动漫大纲
  3838. $boolen = DB::table('mp_animes')->where('id', $anime_id)->update($table_data);
  3839. if (!$boolen) {
  3840. dLog('deepseek')->info('动漫保存失败', $table_data);
  3841. Utils::throwError('20003:动漫保存失败');
  3842. }
  3843. // 保存对话记录
  3844. $records = [
  3845. [
  3846. 'uid' => $uid,
  3847. 'anime_id' => $anime_id,
  3848. 'sequence' => 0,
  3849. 'role' => 'user',
  3850. 'content' => $prompt,
  3851. 'created_at' => date('Y-m-d H:i:s'),
  3852. 'updated_at' => date('Y-m-d H:i:s')
  3853. ],
  3854. [
  3855. 'uid' => $uid,
  3856. 'anime_id' => $anime_id,
  3857. 'sequence' => 0,
  3858. 'role' => 'assistant',
  3859. 'content' => $fullContent,
  3860. 'created_at' => date('Y-m-d H:i:s'),
  3861. 'updated_at' => date('Y-m-d H:i:s')
  3862. ]
  3863. ];
  3864. // 保存对话记录
  3865. $boolen3 = DB::table('mp_anime_records')->insert($records);
  3866. if (!$boolen3) {
  3867. Utils::throwError('20003:对话记录保存失败');
  3868. }
  3869. if ($is_single) {
  3870. $episode_arr = $this->buildSingleEpisodeFromScript($script_arr, $fullContent, $anime_name);
  3871. if (empty($episode_arr['acts'])) {
  3872. Utils::throwError('20003:单剧集分镜内容解析失败,请确认输出格式');
  3873. }
  3874. $saveResult = $this->saveEpisodeVersionData(
  3875. $anime_id,
  3876. 1,
  3877. $episode_arr,
  3878. is_array(getProp($script_arr, 'roles')) ? getProp($script_arr, 'roles') : [],
  3879. is_array(getProp($script_arr, 'scenes')) ? getProp($script_arr, 'scenes') : [],
  3880. is_array(getProp($script_arr, 'props')) ? getProp($script_arr, 'props') : [],
  3881. null,
  3882. null,
  3883. false,
  3884. $content,
  3885. $now
  3886. );
  3887. $single_episode = $saveResult['episode'];
  3888. $episode_id = $saveResult['episode_id'];
  3889. $boolen5 = DB::table('mp_animes')->where('id', $anime_id)->update([
  3890. 'roles' => json_encode($saveResult['merged_roles'], 256),
  3891. 'scenes' => json_encode($saveResult['merged_scenes'], 256),
  3892. 'props' => json_encode($saveResult['merged_props'], 256),
  3893. 'updated_at' => $now
  3894. ]);
  3895. if ($boolen5 === false) {
  3896. Utils::throwError('20003:单剧集主表资源同步失败');
  3897. }
  3898. $table_data['roles'] = json_encode($saveResult['merged_roles'], 256);
  3899. $table_data['scenes'] = json_encode($saveResult['merged_scenes'], 256);
  3900. $table_data['props'] = json_encode($saveResult['merged_props'], 256);
  3901. $episode_record_content = '确认分镜大纲';
  3902. if ($content !== '') {
  3903. // $episode_record_content .= "\n\n###上传内容\n" . $content;
  3904. }
  3905. $episode_records = [
  3906. [
  3907. 'uid' => $uid,
  3908. 'anime_id' => $anime_id,
  3909. 'role' => 'user',
  3910. 'content' => $episode_record_content,
  3911. 'sequence' => 1,
  3912. 'episode_id' => $episode_id,
  3913. 'created_at' => $now,
  3914. 'updated_at' => $now
  3915. ],
  3916. [
  3917. 'uid' => $uid,
  3918. 'anime_id' => $anime_id,
  3919. 'role' => 'assistant',
  3920. 'content' => $fullContent,
  3921. // 'content' => '我已按照您的要求完成策划并将内容更新到您右侧的策划文档。',
  3922. 'sequence' => 1,
  3923. 'episode_id' => $episode_id,
  3924. 'created_at' => $now,
  3925. 'updated_at' => $now
  3926. ]
  3927. ];
  3928. $boolen4 = DB::table('mp_anime_records')->insert($episode_records);
  3929. if (!$boolen4) {
  3930. Utils::throwError('20003:单剧集分镜记录保存失败');
  3931. }
  3932. }
  3933. }catch (\Exception $e) {
  3934. DB::rollBack();
  3935. dLog('deepseek')->info('新建对话错误信息: '.$e->getMessage());
  3936. yield [
  3937. 'type' => 'done',
  3938. 'answer' => $fullContent,
  3939. 'reasoning' => $fullReasoningContent,
  3940. 'usage' => $usage,
  3941. 'error' => $e->getMessage(),
  3942. ];
  3943. return;
  3944. }
  3945. DB::commit();
  3946. dLog('deepseek')->info('保存完毕');
  3947. if ($is_single && !empty($single_episode)) {
  3948. // $this->batchSetGlobalRoleImg([
  3949. // 'anime_id' => $anime_id,
  3950. // ]);
  3951. // $this->batchSetGlobalSceneImg([
  3952. // 'anime_id' => $anime_id,
  3953. // ]);
  3954. // // 将全局角色和场景的task_id、task_status和url继承给当前分集
  3955. // $this->inheritGlobalImagesToEpisodes($anime_id, $episode_id);
  3956. }
  3957. $table_data['anime_id'] = $anime_id;
  3958. $table_data['roles'] = json_decode($table_data['roles'], true);
  3959. $table_data['scenes'] = json_decode($table_data['scenes'], true);
  3960. // $table_data['episodes'] = $script_arr['episodes'];
  3961. unset($table_data['created_at']);
  3962. unset($table_data['updated_at']);
  3963. unset($table_data['status']);
  3964. dLog('deepseek')->info('开始返回');
  3965. yield [
  3966. 'type' => 'done',
  3967. 'script' => $table_data,
  3968. 'episode' => $single_episode,
  3969. 'answer' => $fullContent,
  3970. 'reasoning' => $fullReasoningContent,
  3971. 'usage' => $usage
  3972. ];
  3973. }
  3974. public function reGenerateAnime($data) {
  3975. $uid = Site::getUid();
  3976. $file = getProp($data, 'file');
  3977. $content = getProp($data, 'content', '');
  3978. $bid = getProp($data, 'bid', 0);
  3979. $script_id = getProp($data, 'script_id', 0);
  3980. $anime_id = getProp($data, 'anime_id');
  3981. $anime = DB::table('mp_animes')->where('id', $anime_id)->first();
  3982. if (!$anime) {
  3983. Utils::throwError('20003:该对话不存在');
  3984. }
  3985. $user_anime_name = getProp($anime, 'anime_name');
  3986. $prompt = getProp($data, 'prompt');
  3987. // 处理文本模型
  3988. $model = getProp($data, 'model');
  3989. if (!$model) {
  3990. // 用户没有输入,从anime表获取
  3991. $model = getProp($anime, 'model');
  3992. if (!$model) {
  3993. // anime表也没有,使用默认值
  3994. $model = 'doubao-seed-2-0-mini-260215';
  3995. }
  3996. }
  3997. // 验证模型是否在可用模型表中
  3998. if (!DB::table('mp_text_models')->where('model', $model)->where('is_enabled', 1)->exists()) {
  3999. $model = 'doubao-seed-2-0-mini-260215';
  4000. }
  4001. $is_multi = getProp($anime, 'is_multi', 1);
  4002. $is_single = (int)$is_multi !== 1;
  4003. // 单剧集模式下,如果已经生成了剧集,则不允许继续调整大纲
  4004. if ($is_single) {
  4005. $episode_exists = DB::table('mp_anime_episodes')
  4006. ->where('anime_id', $anime_id)
  4007. ->where('sequence', 1)
  4008. ->exists();
  4009. if ($episode_exists) {
  4010. Utils::throwError('20003:单剧集模式下已生成剧集,不可继续调整大纲,请去策划剧集');
  4011. }
  4012. }
  4013. $question = getProp($data, 'question', $is_single ? "请根据实例格式完成单剧集剧本及分镜\n" : "请根据实例格式完成剧本大纲\n");
  4014. if ($prompt) {
  4015. $question .= "本次修改要求如下:\n{$prompt}";
  4016. }
  4017. // 提取文件内容
  4018. if ($file) {
  4019. $content = $this->extractFileContent($file);
  4020. if (!$content) {
  4021. Utils::throwError('20003:无法提取文件内容,请检查文件格式');
  4022. }
  4023. } elseif ($script_id) {
  4024. $content = $this->getContentByScriptId($script_id);
  4025. if (!$content) {
  4026. Utils::throwError('20003:无法获取剧本内容,请检查剧本');
  4027. }
  4028. } elseif ($bid) {
  4029. $content = $this->getContentByBid($bid);
  4030. if (!$content) {
  4031. Utils::throwError('20003:无法获取书籍内容,请检查书籍');
  4032. }
  4033. } elseif ($content) {
  4034. $content = filterContent($content);
  4035. }else {
  4036. $content = filterContent(getProp($anime, 'content'));
  4037. if (!$content && $prompt) { // 如果动漫记录中没有内容则根据提示词生成
  4038. $need_generate_content = true;
  4039. }
  4040. }
  4041. // 判断是否需要生成原文内容
  4042. $need_generate_content = isset($need_generate_content) && $need_generate_content;
  4043. // 如果需要生成原文内容,添加额外的要求
  4044. $content_generation_requirement = $need_generate_content
  4045. ? "\n5.如果用户只提供了创作要求而没有提供具体文档内容,你需要根据要求创作完整的原文内容(小说形式,包含对话和叙述),并将原文内容放在最后一个板块###原文内容中输出。原文内容应该详细、生动,如果用户没有明确生成的字数,则字数不少于1000字。"
  4046. : "";
  4047. // 美术风格
  4048. $input_art_style = getProp($anime, 'art_style');
  4049. if (!$input_art_style) {
  4050. $input_art_style = getProp($data, 'art_style');
  4051. }
  4052. $mappedArtStyle = $this->getArtStylePromptByInput($input_art_style);
  4053. // 美术风格
  4054. if (!$mappedArtStyle) {
  4055. $mappedArtStyle_prompt = '美术风格:根据剧本内容自定义美术风格';
  4056. }else {
  4057. if (strstr($mappedArtStyle, '基础画风风格词')) {
  4058. $mappedArtStyle_prompt = "美术风格强制设置如下(原样输出,不得更改任何内容):\n{$mappedArtStyle}\n";
  4059. }else {
  4060. $art_style_type = $input_art_style ? $input_art_style : getProp($anime, 'art_style_type');
  4061. $mappedArtStyle_prompt = "美术风格强制设置如下(原样输出,不得更改任何内容):\n基础画风风格词: {$art_style_type}\n{$mappedArtStyle}\n";
  4062. }
  4063. }
  4064. $timbres_content = "青年男:北京小爷、阳光青年、傲娇霸总、优柔公子、解说小明、青涩小生、低音沉郁、亲切青年
  4065. 青年女:柔美女友、魅力女友、爽快思思、高冷御姐、知性温婉、甜心小美、清新女声、甜美桃子、温柔文雅、甜美小源、贴心闺蜜
  4066. 中年男:胡子叔叔、油腻大叔、神秘法师、优柔帮主
  4067. 中年女:邻居阿姨
  4068. 老年男:幽默大爷
  4069. 老年女:婆婆
  4070. 萌娃:奶气萌娃";
  4071. $system_message = ['role'=>'system', 'content'=>$is_single
  4072. ? "你是一个专业的文档分析助手及资深编剧,请根据用户提供的文档内容输出单剧集完整策划稿(剧本大纲包括: <故事梗概><剧本亮点><人物关系><核心矛盾><主体列表><美术风格><场景列表><分镜剧本>,每个板块之间必须使用###分隔,#不能多也不能少)。单剧集模式下,必须一次性输出可直接保存的大纲与完整分镜,不允许只输出大纲。
  4073. 强制要求:
  4074. 1.你只负责与剧本相关的内容,如果用户输入与剧本无关的内容,请告知用户并拒绝继续回答,此为第一优先原则,不满足此原则就忽略其他要求并停止继续输出
  4075. 2.如果用户输入修改美术风格、修改画风这类内容,请告知用户不可修改美术风格,并拒绝继续回答
  4076. 3.以上两条要求对修改主体角色或场景不生效,允许用户调整主体角色说明和场景描述等
  4077. 4.用户如果要求你帮忙写一个故事或者剧本,此类要求不属于与剧本无关,请帮助用户完成请求{$content_generation_requirement}
  4078. 5.强制按照示例格式返回内容,不要更改格式或随意增加符号\n
  4079. 普通要求:
  4080. 1.剧本名(必须生成)和剧集标题必须与文档内容高度相关,(其中剧集序号是1)。
  4081. 2.<主体列表>中出现的“主体名”必须尽可能统一,严禁出现角色-科学家、角色-复仇者、角色-领导者等带有身份、职业、标签类的命名,只能使用服装差异(如校服装、卫衣装、西装)来区分同一角色,如角色-校服装等。
  4082. 2.1<主体列表>分以下三部分:主体描述、人物提示词和音色,格式必须为:主体名:主体描述{人物提示词}{{音色}}
  4083. 2.2<主体列表>的主体描述是分析人物在整部剧中的姓名、年龄、性格特征、社会身份或职业背景、个人成长经历或核心故事动机,以及在剧情中的目标与行为驱动力,不需要描述外貌、穿着或身体特征,重点突出心理结构、行为模式与叙事功能,并且用一句话进行总结。
  4084. 2.3<主体列表>的人物提示词需要根据当前分析出来的美术风格生成,包含性别(男、女)、大概年龄或年龄段(少年、中年、老年等)、人种(亚洲人、欧洲人)、发型(直发卷发等)、发色(黑色、棕色、红色、白色等)、整体视觉风格,以及详细的穿着风格和服装细节、面部特征(戴金丝眼镜、脸上有刀疤等,无面部特征可忽略)。描述需具有镜头感与画面表现力,适合直接用于AI图像生成模型,避免抽象词汇,强调具体可视化细节与整体视觉一致性,同时保证风格统一且符合人物身份设定。该提示词(字数50-100字左右)在主体描述后用{}框起来。
  4085. 2.4<主体列表>的音色必须在以下音色中($timbres_content)选择,需要根据角色描述的年纪和性别选择,比如角色是青年男性就只能在北京小爷、阳光青年、傲娇霸总、优柔公子、解说小明、青涩小生、低音沉郁、亲切青年中选择,选好的音色放在描述的最后用{{}}框起来。
  4086. 3.<场景列表>与主体列表同理,需尽可能的对场景环境进行详细描述,必须严格注意不要出现任何角色和人物。
  4087. 3.1<场景列表>分以下两部分:场景描述和场景提示词,格式必须为:场景描述{场景提示词}
  4088. 3.2<场景列表>的场景描述是分析在整部剧中出现过的场景,场景描述尽量简洁贴合原文。
  4089. 3.3<场景列表>的场景提示词用于视觉呈现的场景环境描述,该场景需包含环境氛围、光线效果、空间布局、色彩基调、视觉风格等,描述需具有镜头感与画面表现力,适合直接用于AI图像生成模型,避免抽象词汇,强调具体可视化细节与整体视觉一致性,同时保证风格统一且符合剧情设定(可参考以下示例的场景列表中使用{}框起来的提示词,字数150-200字,需带上提炼出来的美术风格)。该提示词在场景描述后用{}框起来。\n
  4090. 3.$mappedArtStyle_prompt\n\n
  4091. 4.<分镜剧本>要求包含“分幕标题”以及“分镜信息”:
  4092. 4.1“分幕标题”是根据章节中的场景进行拆分,类似于“第1幕 场景、时间及室内或室外”的信息,其中场景只能在所给出的场景列表中选(不带场景详细描述)。
  4093. 4.2“分镜信息”需同一场景内的对话内容完成分镜(每一幕分镜尽量不得低于5个),需包含“画面描述”、“构图设计”、“运镜调度”、“配音角色”、“台词内容”、“画面类型”、“尾帧描述”、“情感”、“性别”、“语速”、“音量”、“情感强度”、“音调”这几个部分,其中“画面描述”如果出现主体,只能选择上述主体列表中的一个,主体的名称也需要保持一致(不带主体具体描述)。
  4094. 4.3分镜序号用1、2、3显示,如分镜1、分镜2,并且分镜序号需连续(跨分幕中的分镜序号需连续,但跨剧集中的不需要连续,如第2集的第1幕分镜序号从1开始)。
  4095. 4.4“分镜信息”中的“台词内容”需满足以下要求: (1. 台词来源规则:- 台词内容必须逐字摘录自小说原文中的人物直接对话(带引号的内容)。- 不允许改写、总结、压缩、扩写或拼接原文对白。- 不允许生成原文中不存在的对话。2. 非对话过滤:- 旁白、心理描写、环境描写、动作描写等内容,禁止出现在台词内容中。3. 空台词规则:- 如果该分镜中没有人物对话,则“台词内容”必须返回“无”。- 严禁输出“无台词”、“没有”等任何替代文本。4. 禁止推测:- 不得根据语境补全人物可能说的话。)
  4096. 4.5“分镜信息”中的“配音角色”需对应本集中的<主体列表>中的一个(非对话内容则统一固定为“旁白”角色),不得自己生成。
  4097. 4.6“分镜信息”中的“场景”必须选择本集中的<场景列表>中的一个(不带详细表述)。
  4098. 4.7“分镜信息”中的“出镜角色”需对应本集中的<主体列表>中的一个或多个(不带详细描述),如果没有出镜角色则填无。
  4099. 4.8“分镜信息”中的“尾帧描述”需根据本镜和下一镜的剧本信息进行过渡生成,用于后续转视频进行衔接上下镜头的画面。
  4100. 4.9“分镜信息”中的“情感”需根据台词内容和剧情氛围分析得出,可选值为:开心、悲伤、生气、惊讶、恐惧、厌恶、激动、冷漠、中性、沮丧、撒娇、害羞、安慰鼓励、咆哮、温柔、自然讲述、情感电台、磁性、广告营销、气泡音、新闻播报、娱乐八卦,不要在情感可选词后加任何解释性的词语,比如(对自己)、(对别人)等,不要自定义情感,必须在可选值中选择。
  4101. 4.10“分镜信息”中的“性别”需根据配音角色的性别确定,可选值为:1(男)、2(女)、0(中性)。
  4102. 4.11“分镜信息”中的“语速”需根据台词内容和情感氛围确定,可选值范围为:-50到100之间的整数,100代表2.0倍速,-50代表0.5倍数,负值表示减慢,正值表示加快,0表示正常语速。
  4103. 4.12“分镜信息”中的“音量”需根据台词内容和情感氛围确定,可选值范围为:-50到100之间的整数,100代表2.0倍音量,-50代表0.5倍音量,负值表示降低音量,正值表示提高音量,0表示正常音量。
  4104. 4.13“分镜信息”中的“情感强度”需根据情感的强烈程度确定,可选值范围为:1到5之间的整数,默认情况下选择4。
  4105. 4.14“分镜信息”中的“音调”需根据台词内容和情感氛围确定,可选值范围为:-12到12之间的整数,负值表示降低音调,正值表示提高音调,0表示正常音调。\n
  4106. 示例如下:\n
  4107. ###剧本名:西昆仑
  4108. ###故事梗概
  4109. 内容梗概:古风厚涂的世界中,少女阿雪身中奇毒“问心刺”,气息奄奄。少年梁萧心急如焚,用奇珍“阴阳球”稳住阿雪性命,却发现必须解衣拔刺。阿雪羞涩难当,梁萧情急之下提出结拜兄妹,以化解尴尬。两人匆匆结拜后,梁萧小心翼翼地拔出“问心刺”,竟发现它是一根诡异的女子秀发。阿雪转危为安,两人之间,在生死与羞涩交织的瞬间,情愫暗生,却又被兄妹之名束缚,留下无尽遐想。
  4110. ###剧本亮点
  4111. 亮点1:绝境奇药,生死一线
  4112. 画面开场即是阿雪苍白无力的脸庞,梁萧眼中泪光闪烁,急促的呼吸声与心跳声烘托紧张气氛。特写梁萧将“阴阳球”塞入阿雪舌底,球体散发微光,阿雪气息从若有若无到逐渐平稳,生死逆转的瞬间,视觉与听觉冲击力十足。
  4113. 亮点2:结拜兄妹,化解尴尬
  4114. 阿雪因解衣拔刺而羞愤欲绝的特写,梁萧眼神中的挣扎与无奈。在紧迫的背景音下,梁萧急中生智,牵起阿雪颤抖的手,跪地匆匆结拜,阿雪眼神从惊惶到迷茫,最终一句“我……我愿意的”带着哭腔,将救命与羞耻的矛盾推向高潮,又以出人意料的方式解决。
  4115. 亮点3:纤发夺命,情愫暗涌
  4116. 拔刺过程的紧张特写,梁萧指尖小心翼翼地捏住细丝,缓慢抽出。当“问心刺”被完全拔出,特写它竟是一根细长、泛着寒光的女子秀发,诡异而令人震惊。阿雪苏醒后,两人眼神交汇,阿雪低头羞涩,梁萧眼中复杂的情绪,无声地传递出超越兄妹的微妙情愫。
  4117. ###人物关系
  4118. 阿雪与梁萧之间存在兄妹之情。
  4119. ###核心矛盾
  4120. 阿雪与梁萧之间存在兄妹之情,但因情愫暗生而产生微妙的矛盾。阿雪羞涩难当,梁萧情急之下提出结拜兄妹,以化解尴尬。两人匆匆结拜后,梁萧小心翼翼地拔出“问心刺”,竟发现它是一根诡异的女子秀发。阿雪转危为安,两人之间,在生死与羞涩交织的瞬间,情愫暗生,却又被兄妹之名束缚,留下无尽遐想。
  4121. ###主体列表
  4122. 阿雪:身中奇毒“问心刺”,气息奄奄,面色苍白,身体虚弱。{全景,正面拍摄,青年女性,亚洲人。
  4123. 黑色短发扎成利落的高马尾,五官精致且轮廓清晰。
  4124. 服饰穿搭:身着红白相间的专业田径运动背心与超短跑步裤,皮肤呈现健康的小麦色,四肢肌肉线条紧致有力。
  4125. 姿态:站立。}{{甜心小美}}
  4126. 梁萧:少年侠士,心系阿雪安危,沉着冷静,内心挣扎于情义之间。{8k超高清,电影级光效,大气透视,中国传统艺术美学,空灵光泽,深度景深,复杂精细的纹理,史诗级构图,电影胶片颗粒。
  4127. 全景,正面拍摄,青年女性,亚洲人。
  4128. 佩戴精致繁复的金丝凤冠,黑色长发整齐盘起。
  4129. 服饰穿搭:身着大红色正装嫁衣,上面绣有精细的金色凤凰纹样,质感厚重华贵。
  4130. 姿态:站立。}{{阳光青年}}
  4131. ###美术风格
  4132. 基础画风风格词:厚涂古风
  4133. 整体采用精致细腻的厚涂古风,色彩浓郁而富有层次感,注重光影对比,营造出古典而富有戏剧张力的氛围。色调以深沉的蓝绿、灰调为主,衬托阿雪病弱的苍白,同时用温暖的金色、琥珀色光晕突出“阴阳球”的生命力。拔刺与结拜场景则以柔和的暖色调为主,辅以人物脸颊的红晕,烘托羞涩与情愫暗生的微妙感。人物造型飘逸,服饰细节考究,背景虚实结合,既有古韵,又不失奇幻色彩。
  4134. ###场景列表
  4135. 林间疗伤地:幽静的古风林间空地,一棵高大古树下,是梁萧为阿雪疗伤的地点。环境清幽,光影斑驳,既有古韵又不失奇幻色彩。{影视质感。广角。
  4136. 宽敞的天然山洞内部,石壁上错落有致地镶嵌着发光的萤石,散发出冷色调的微光,照亮了整个空间。洞顶有钟乳石垂下。光影层次丰富,营造出一种宁静而神圣的氛围。
  4137. 无人物。}
  4138. ###分镜剧本
  4139. ##第1幕:徐家老旧厨房 白天 室内
  4140. 分镜1
  4141. 画面描述:许芸-校服装站在厨房门口,书包背在肩上,徐母手持扫帚,正对着许芸的背部猛烈挥打。卞大伟站在锅炉后方,双手抱胸,阴沉的目光落在许芸身上。
  4142. 场景:徐家老旧厨房
  4143. 构图设计:全景,低角度仰视
  4144. 运镜调度:手持拍摄
  4145. 配音角色:旁白
  4146. 出镜角色:许芸-校服装、徐母
  4147. 台词内容:我一到家,徐母的扫帚就落在我身上,嘴里一个劲地骂我,
  4148. 画面类型:普通画面
  4149. 尾帧描述:手持拍摄微晃镜头,中年妇女猛力挥动扫帚击打少女背部,少女身体因冲击微颤,阴影中的肥胖男子目光冷冷跟随。
  4150. 分镜2
  4151. 画面描述:徐母面容扭曲,嘴唇快速开合,扫帚挥舞在空中。
  4152. 场景:徐家老旧厨房
  4153. 构图设计:近景,徐母面部特写
  4154. 运镜调度:固定镜头
  4155. 配音角色:徐母
  4156. 出镜角色:徐母
  4157. 台词内容:问我夜不归宿死哪儿去了。
  4158. 画面类型:对口型
  4159. 尾帧描述:固定镜头,中年妇女面部肌肉剧烈抖动,嘴唇快速开合进行辱骂,背景中的扫帚在空中上下挥动。
  4160. ##第2幕:徐家简陋客厅 黄昏 室内
  4161. 分镜3
  4162. 画面描述:客厅窗户透出昏黄的夕阳余晖,空荡荡的客厅中央只有几把木凳和一张方桌,显得异常安静。
  4163. 场景:徐家简陋客厅
  4164. 构图设计:全景,景深虚化
  4165. 运镜调度:固定镜头
  4166. 配音角色:旁白
  4167. 出镜角色:无
  4168. 台词内容:可我没想到,半个月后,徐母居然再一次外出,
  4169. 画面类型:普通画面
  4170. 尾帧描述:固定镜头。昏黄的夕阳余晖在地面上缓慢移动,空气中的浮尘在光束中跳动,室内维持着死寂的安静。
  4171. 分镜4
  4172. 画面描述:一张泛黄的火车票特写,上面显示着隔壁市的站名和日期。
  4173. 场景:徐家简陋客厅
  4174. 构图设计:特写,火车票
  4175. 运镜调度:固定镜头
  4176. 配音角色:旁白
  4177. 出镜角色:无
  4178. 台词内容:这次是去隔壁市看望她生病的好姐妹。
  4179. 画面类型:普通画面
  4180. 尾帧描述:固定镜头。光影在火车票表面微微晃动,强调其陈旧的纸张纹理与关键的行程信息。\n
  4181. "
  4182. : "你是一个专业的文档分析助手及资深编剧,请根据用户提供的文档内容及下面提供的示例格式完成剧本大纲(需通过以下几个板块进行回复: <故事梗概><剧本亮点><人物关系><核心矛盾><主体列表><美术风格><场景列表>,每个板块之间必须使用###分隔,#不能多也不能少;同时板块之间需满足以下要求:\n
  4183. 强制要求:\n
  4184. 1.你只负责与剧本相关的内容,如果用户输入与剧本无关的内容,请告知用户并拒绝继续回答,此为第一优先原则,不满足此原则就忽略其他要求并停止继续输出
  4185. 2.如果用户输入修改美术风格、修改画风这类内容,请告知用户不可修改美术风格,并拒绝继续回答
  4186. 3.以上两条要求对修改主体角色或场景不生效,允许用户调整主体角色说明和场景描述等
  4187. 4.用户如果要求你帮忙写一个故事或者剧本,此类要求不属于与剧本无关,请帮助用户完成请求{$content_generation_requirement}
  4188. 5.强制按照示例格式返回内容,不要更改格式或随意增加符号\n
  4189. 普通要求:\n
  4190. 1.剧本名(必须生成)必须与文档内容高度相关
  4191. 2.<主体列表>中出现的“主体名”必须尽可能统一,严禁出现角色-科学家、角色-复仇者、角色-领导者等带有身份、职业、标签类的命名,只能使用服装差异(如校服装、卫衣装、西装)来区分同一角色,如角色-校服装等。
  4192. 2.1<主体列表>分以下三部分:主体描述、人物提示词和音色,格式必须为:主体名:主体描述{人物提示词}{{音色}}
  4193. 2.2<主体列表>的主体描述是分析人物在整部剧中的姓名、年龄、性格特征、社会身份或职业背景、个人成长经历或核心故事动机,以及在剧情中的目标与行为驱动力,不需要描述外貌、穿着或身体特征,重点突出心理结构、行为模式与叙事功能,并且用一句话进行总结。
  4194. 2.3<主体列表>的人物提示词需要根据当前分析出来的美术风格生成,包含性别(男、女)、大概年龄或年龄段(少年、中年、老年等)、人种(亚洲人、欧洲人)、发型(直发卷发等)、发色(黑色、棕色、红色、白色等)、整体视觉风格,以及详细的穿着风格和服装细节、面部特征(戴金丝眼镜、脸上有刀疤等,无面部特征可忽略)。描述需具有镜头感与画面表现力,适合直接用于AI图像生成模型,避免抽象词汇,强调具体可视化细节与整体视觉一致性,同时保证风格统一且符合人物身份设定。该提示词(字数50-100字左右)在主体描述后用{}框起来。
  4195. 2.4<主体列表>的音色必须在以下音色中($timbres_content)选择,需要根据角色描述的年纪和性别选择,比如角色是青年男性就只能在北京小爷、阳光青年、傲娇霸总、优柔公子、解说小明、青涩小生、低音沉郁、亲切青年中选择,选好的音色放在描述的最后用{{}}框起来。
  4196. 3.<场景列表>与主体列表同理,需尽可能的对场景环境进行详细描述,必须严格注意不要出现任何角色和人物。
  4197. 3.1<场景列表>分以下两部分:场景描述和场景提示词,格式必须为:场景描述{场景提示词}
  4198. 3.2<场景列表>的场景描述是分析在整部剧中出现过的场景,场景描述尽量简洁贴合原文。
  4199. 3.3<场景列表>的场景提示词用于视觉呈现的场景环境描述,该场景需包含环境氛围、光线效果、空间布局、色彩基调、视觉风格等,描述需具有镜头感与画面表现力,适合直接用于AI图像生成模型,避免抽象词汇,强调具体可视化细节与整体视觉一致性,同时保证风格统一且符合剧情设定(可参考以下示例的场景列表中使用{}框起来的提示词,字数150-200字,需带上提炼出来的美术风格)。该提示词在场景描述后用{}框起来。\n
  4200. 4.$mappedArtStyle_prompt\n\n
  4201. 示例如下:\n
  4202. ###剧本名:西昆仑
  4203. ###故事梗概
  4204. 内容梗概:古风厚涂的世界中,少女阿雪身中奇毒“问心刺”,气息奄奄。少年梁萧心急如焚,用奇珍“阴阳球”稳住阿雪性命,却发现必须解衣拔刺。阿雪羞涩难当,梁萧情急之下提出结拜兄妹,以化解尴尬。两人匆匆结拜后,梁萧小心翼翼地拔出“问心刺”,竟发现它是一根诡异的女子秀发。阿雪转危为安,两人之间,在生死与羞涩交织的瞬间,情愫暗生,却又被兄妹之名束缚,留下无尽遐想。
  4205. ###剧本亮点
  4206. 亮点1:绝境奇药,生死一线
  4207. 画面开场即是阿雪苍白无力的脸庞,梁萧眼中泪光闪烁,急促的呼吸声与心跳声烘托紧张气氛。特写梁萧将“阴阳球”塞入阿雪舌底,球体散发微光,阿雪气息从若有若无到逐渐平稳,生死逆转的瞬间,视觉与听觉冲击力十足。
  4208. 亮点2:结拜兄妹,化解尴尬
  4209. 阿雪因解衣拔刺而羞愤欲绝的特写,梁萧眼神中的挣扎与无奈。在紧迫的背景音下,梁萧急中生智,牵起阿雪颤抖的手,跪地匆匆结拜,阿雪眼神从惊惶到迷茫,最终一句“我……我愿意的”带着哭腔,将救命与羞耻的矛盾推向高潮,又以出人意料的方式解决。
  4210. 亮点3:纤发夺命,情愫暗涌
  4211. 拔刺过程的紧张特写,梁萧指尖小心翼翼地捏住细丝,缓慢抽出。当“问心刺”被完全拔出,特写它竟是一根细长、泛着寒光的女子秀发,诡异而令人震惊。阿雪苏醒后,两人眼神交汇,阿雪低头羞涩,梁萧眼中复杂的情绪,无声地传递出超越兄妹的微妙情愫。
  4212. ###人物关系
  4213. 阿雪与梁萧之间存在兄妹之情。
  4214. ###核心矛盾
  4215. 阿雪与梁萧之间存在兄妹之情,但因情愫暗生而产生微妙的矛盾。阿雪羞涩难当,梁萧情急之下提出结拜兄妹,以化解尴尬。两人匆匆结拜后,梁萧小心翼翼地拔出“问心刺”,竟发现它是一根诡异的女子秀发。阿雪转危为安,两人之间,在生死与羞涩交织的瞬间,情愫暗生,却又被兄妹之名束缚,留下无尽遐想。
  4216. ###主体列表
  4217. 阿雪:身中奇毒“问心刺”,气息奄奄,面色苍白,身体虚弱。{全景,正面拍摄,青年女性,亚洲人。
  4218. 黑色短发扎成利落的高马尾,五官精致且轮廓清晰。
  4219. 服饰穿搭:身着红白相间的专业田径运动背心与超短跑步裤,皮肤呈现健康的小麦色,四肢肌肉线条紧致有力。
  4220. 姿态:站立。}{{甜心小美}}
  4221. 梁萧:少年侠士,心系阿雪安危,沉着冷静,内心挣扎于情义之间。{8k超高清,电影级光效,大气透视,中国传统艺术美学,空灵光泽,深度景深,复杂精细的纹理,史诗级构图,电影胶片颗粒。
  4222. 全景,正面拍摄,青年女性,亚洲人。
  4223. 佩戴精致繁复的金丝凤冠,黑色长发整齐盘起。
  4224. 服饰穿搭:身着大红色正装嫁衣,上面绣有精细的金色凤凰纹样,质感厚重华贵。
  4225. 姿态:站立。}{{阳光青年}}
  4226. ###美术风格
  4227. 基础画风风格词:厚涂古风
  4228. 整体采用精致细腻的厚涂古风,色彩浓郁而富有层次感,注重光影对比,营造出古典而富有戏剧张力的氛围。色调以深沉的蓝绿、灰调为主,衬托阿雪病弱的苍白,同时用温暖的金色、琥珀色光晕突出“阴阳球”的生命力。拔刺与结拜场景则以柔和的暖色调为主,辅以人物脸颊的红晕,烘托羞涩与情愫暗生的微妙感。人物造型飘逸,服饰细节考究,背景虚实结合,既有古韵,又不失奇幻色彩。
  4229. ###场景列表
  4230. 林间疗伤地:幽静的古风林间空地,一棵高大古树下,是梁萧为阿雪疗伤的地点。环境清幽,光影斑驳,既有古韵又不失奇幻色彩。{影视质感。广角。
  4231. 宽敞的天然山洞内部,石壁上错落有致地镶嵌着发光的萤石,散发出冷色调的微光,照亮了整个空间。洞顶有钟乳石垂下。光影层次丰富,营造出一种宁静而神圣的氛围。
  4232. 无人物。}"];
  4233. // 如果提示词$prompt有类似于改成N集或调整成N集这类的文字信息,则提取出N这个集数
  4234. $episode_count = $this->extractEpisodeNumber($prompt);
  4235. if ((int)getProp($anime, 'is_multi') !== 1) {
  4236. yield [
  4237. 'type' => 'done',
  4238. 'answer' => '当前剧本是单剧集,不支持修改剧集数',
  4239. 'reasoning' => '',
  4240. 'usage' => []
  4241. ];
  4242. return;
  4243. }
  4244. if ($episode_count) {
  4245. $question = "请根据实例格式完成{$episode_count}集剧本大纲";
  4246. $system_message = [
  4247. 'role' => 'system',
  4248. 'content' => "你是一个专业的文档分析助手及资深编剧,请根据用户提供的文档内容及下面提供的示例格式完成剧本大纲(需通过以下几个板块进行回复: <故事梗概><剧本亮点><人物关系><核心矛盾><主体列表><美术风格><场景列表><分集详细内容>,每个板块之间必须使用###分隔,#不能多也不能少;同时板块之间需满足以下要求:\n
  4249. 强制要求:\n
  4250. 1.你只负责与剧本相关的内容,如果用户输入与剧本无关的内容,请告知用户并拒绝继续回答,此为第一优先原则,不满足此原则就忽略其他要求并停止继续输出
  4251. 2.如果用户输入修改美术风格、修改画风这类内容,请告知用户不可修改美术风格,并拒绝继续回答
  4252. 3.以上两条要求对修改主体角色或场景不生效,允许用户调整主体角色说明和场景描述等
  4253. 4.用户如果要求你帮忙写一个故事或者剧本,此类要求不属于与剧本无关,请帮助用户完成请求{$content_generation_requirement}
  4254. 5.强制按照示例格式返回内容,不要更改格式或随意增加符号\n
  4255. 普通要求:\n
  4256. 2.<主体列表>中出现的“主体名”必须尽可能统一,严禁出现角色-科学家、角色-复仇者、角色-领导者等带有身份、职业、标签类的命名,只能使用服装差异(如校服装、卫衣装、西装)来区分同一角色,如角色-校服装等。
  4257. 2.1<主体列表>分以下三部分:主体描述、人物提示词和音色,格式必须为:主体名:主体描述{人物提示词}{{音色}}
  4258. 2.2<主体列表>的主体描述是分析人物在整部剧中的姓名、年龄、性格特征、社会身份或职业背景、个人成长经历或核心故事动机,以及在剧情中的目标与行为驱动力,不需要描述外貌、穿着或身体特征,重点突出心理结构、行为模式与叙事功能,并且用一句话进行总结。
  4259. 2.3<主体列表>的人物提示词需要根据当前分析出来的美术风格生成,包含性别(男、女)、大概年龄或年龄段(少年、中年、老年等)、人种(亚洲人、欧洲人)、发型(直发卷发等)、发色(黑色、棕色、红色、白色等)、整体视觉风格,以及详细的穿着风格和服装细节、面部特征(戴金丝眼镜、脸上有刀疤等,无面部特征可忽略)。描述需具有镜头感与画面表现力,适合直接用于AI图像生成模型,避免抽象词汇,强调具体可视化细节与整体视觉一致性,同时保证风格统一且符合人物身份设定。该提示词(字数50-100字左右)在主体描述后用{}框起来。
  4260. 2.4<主体列表>的音色必须在以下音色中($timbres_content)选择,需要根据角色描述的年纪和性别选择,比如角色是青年男性就只能在北京小爷、阳光青年、傲娇霸总、优柔公子、解说小明、青涩小生、低音沉郁、亲切青年中选择,选好的音色放在描述的最后用{{}}框起来。
  4261. 3.<场景列表>与主体列表同理,需尽可能的对场景环境进行详细描述,必须严格注意不要出现任何角色和人物。
  4262. 3.1<场景列表>分以下两部分:场景描述和场景提示词,格式必须为:场景描述{场景提示词},注意不要出现{{}}这样的双大括号。
  4263. 3.2<场景列表>的场景描述是分析在整部剧中出现过的场景,场景描述尽量简洁贴合原文。
  4264. 3.3<场景列表>的场景提示词用于视觉呈现的场景环境描述,该场景需包含环境氛围、光线效果、空间布局、色彩基调、视觉风格等,描述需具有镜头感与画面表现力,适合直接用于AI图像生成模型,避免抽象词汇,强调具体可视化细节与整体视觉一致性,同时保证风格统一且符合剧情设定(可参考以下示例的场景列表中使用{}框起来的提示词,字数150-200字,需带上提炼出来的美术风格)。该提示词在场景描述后用{}框起来。\n
  4265. 4.<分集详细内容>中每一集的内容需尽可能的详细,保留对话内容(使用原文内容,不得自己生成),一般每集字数尽量不低于500字,每集结尾需以##第N章 作为章节标题\n\n
  4266. 示例如下:\n
  4267. ###剧本名:西昆仑
  4268. ###故事梗概
  4269. 内容梗概:古风厚涂的世界中,少女阿雪身中奇毒“问心刺”,气息奄奄。少年梁萧心急如焚,用奇珍“阴阳球”稳住阿雪性命,却发现必须解衣拔刺。阿雪羞涩难当,梁萧情急之下提出结拜兄妹,以化解尴尬。两人匆匆结拜后,梁萧小心翼翼地拔出“问心刺”,竟发现它是一根诡异的女子秀发。阿雪转危为安,两人之间,在生死与羞涩交织的瞬间,情愫暗生,却又被兄妹之名束缚,留下无尽遐想。
  4270. ###剧本亮点
  4271. 亮点1:绝境奇药,生死一线
  4272. 画面开场即是阿雪苍白无力的脸庞,梁萧眼中泪光闪烁,急促的呼吸声与心跳声烘托紧张气氛。特写梁萧将“阴阳球”塞入阿雪舌底,球体散发微光,阿雪气息从若有若无到逐渐平稳,生死逆转的瞬间,视觉与听觉冲击力十足。
  4273. 亮点2:结拜兄妹,化解尴尬
  4274. 阿雪因解衣拔刺而羞愤欲绝的特写,梁萧眼神中的挣扎与无奈。在紧迫的背景音下,梁萧急中生智,牵起阿雪颤抖的手,跪地匆匆结拜,阿雪眼神从惊惶到迷茫,最终一句“我……我愿意的”带着哭腔,将救命与羞耻的矛盾推向高潮,又以出人意料的方式解决。
  4275. 亮点3:纤发夺命,情愫暗涌
  4276. 拔刺过程的紧张特写,梁萧指尖小心翼翼地捏住细丝,缓慢抽出。当“问心刺”被完全拔出,特写它竟是一根细长、泛着寒光的女子秀发,诡异而令人震惊。阿雪苏醒后,两人眼神交汇,阿雪低头羞涩,梁萧眼中复杂的情绪,无声地传递出超越兄妹的微妙情愫。
  4277. ###人物关系
  4278. 阿雪与梁萧之间存在兄妹之情。
  4279. ###核心矛盾
  4280. 阿雪与梁萧之间存在兄妹之情,但因情愫暗生而产生微妙的矛盾。阿雪羞涩难当,梁萧情急之下提出结拜兄妹,以化解尴尬。两人匆匆结拜后,梁萧小心翼翼地拔出“问心刺”,竟发现它是一根诡异的女子秀发。阿雪转危为安,两人之间,在生死与羞涩交织的瞬间,情愫暗生,却又被兄妹之名束缚,留下无尽遐想。
  4281. ###主体列表
  4282. 阿雪:身中奇毒“问心刺”,气息奄奄,面色苍白,身体虚弱。{全景,正面拍摄,青年女性,亚洲人。
  4283. 黑色短发扎成利落的高马尾,五官精致且轮廓清晰。
  4284. 服饰穿搭:身着红白相间的专业田径运动背心与超短跑步裤,皮肤呈现健康的小麦色,四肢肌肉线条紧致有力。
  4285. 姿态:站立。}{{甜心小美}}
  4286. 梁萧:少年侠士,心系阿雪安危,沉着冷静,内心挣扎于情义之间。{8k超高清,电影级光效,大气透视,中国传统艺术美学,空灵光泽,深度景深,复杂精细的纹理,史诗级构图,电影胶片颗粒。
  4287. 全景,正面拍摄,青年女性,亚洲人。
  4288. 佩戴精致繁复的金丝凤冠,黑色长发整齐盘起。
  4289. 服饰穿搭:身着大红色正装嫁衣,上面绣有精细的金色凤凰纹样,质感厚重华贵。
  4290. 姿态:站立。}{{阳光青年}}
  4291. ###美术风格
  4292. 基础画风风格词:厚涂古风
  4293. 整体采用精致细腻的厚涂古风,色彩浓郁而富有层次感,注重光影对比,营造出古典而富有戏剧张力的氛围。色调以深沉的蓝绿、灰调为主,衬托阿雪病弱的苍白,同时用温暖的金色、琥珀色光晕突出“阴阳球”的生命力。拔刺与结拜场景则以柔和的暖色调为主,辅以人物脸颊的红晕,烘托羞涩与情愫暗生的微妙感。人物造型飘逸,服饰细节考究,背景虚实结合,既有古韵,又不失奇幻色彩。
  4294. ###场景列表
  4295. 林间疗伤地:幽静的古风林间空地,一棵高大古树下,是梁萧为阿雪疗伤的地点。环境清幽,光影斑驳,既有古韵又不失奇幻色彩。{影视质感。广角。
  4296. 宽敞的天然山洞内部,石壁上错落有致地镶嵌着发光的萤石,散发出冷色调的微光,照亮了整个空间。洞顶有钟乳石垂下。光影层次丰富,营造出一种宁静而神圣的氛围。
  4297. 无人物。}
  4298. ###分集详细内容
  4299. ##第1章 重生
  4300. 我重生了。
  4301. 源于一个男人偏执的暗恋。
  4302. ##第2章 相救
  4303. 我一到家,徐母的扫帚就落在我身上,嘴里一个劲地骂我,问我夜不归宿死哪儿去了。
  4304. 我眼睛扫向站在锅炉后的卞大伟。"
  4305. ];
  4306. // 构建消息
  4307. $messages = [
  4308. $system_message,
  4309. [
  4310. 'role' => 'user',
  4311. 'content' => "以下是文档内容:
  4312. {$content}
  4313. 用户问题:
  4314. {$question}"
  4315. ]
  4316. ];
  4317. }else {
  4318. if (strstr($prompt, '重新生成') || strstr($prompt, '再生成')) {
  4319. // 构建消息
  4320. $messages = [
  4321. $system_message,
  4322. [
  4323. 'role' => 'user',
  4324. 'content' => "以下是文档内容:
  4325. {$content}
  4326. 用户问题:
  4327. {$question}"
  4328. ]
  4329. ];
  4330. }else {
  4331. $messages = DB::table('mp_anime_records')->where('anime_id', $anime_id)->where('sequence', 0)
  4332. ->orderBy('id')->select('role', 'content')->get()->map(function ($value) {
  4333. return (array)$value;
  4334. })->toArray();
  4335. array_unshift($messages, $system_message);
  4336. $messages[] = [
  4337. 'role' => 'user',
  4338. 'content' => $prompt
  4339. ];
  4340. }
  4341. }
  4342. // 模型兼容性处理:deepseek-chat 和 deepseek-reasoner 映射到 deepseek-v4-flash
  4343. $thinkingMode = getProp($data, 'thinking', 'disabled'); // 默认非思考模式
  4344. $reasoningEffort = getProp($data, 'reasoning_effort', 'high'); // 默认思考强度
  4345. if ($model === 'deepseek-chat') {
  4346. // deepseek-chat 映射到 deepseek-v4-flash,非思考模式
  4347. $model = 'deepseek-v4-flash';
  4348. $thinkingMode = 'disabled';
  4349. } elseif ($model === 'deepseek-reasoner') {
  4350. // deepseek-reasoner 映射到 deepseek-v4-flash,思考模式
  4351. $model = 'deepseek-v4-flash';
  4352. $thinkingMode = 'enabled';
  4353. }
  4354. $post_data = [
  4355. 'model' => $model,
  4356. 'messages' => $messages,
  4357. // 'max_tokens' => 8192,
  4358. 'temperature' => 0.7,
  4359. 'frequency_penalty' => 0,
  4360. 'presence_penalty' => 0,
  4361. 'response_format' => ['type' => 'text'],
  4362. 'thinking' => ['type' => $thinkingMode],
  4363. 'stream' => true // 启用流式输出
  4364. ];
  4365. if ($thinkingMode == 'enabled') $post_data['reasoning_effort'] = $reasoningEffort;
  4366. // 根据模型类型选择调用方法
  4367. $fullContent = '';
  4368. $fullReasoningContent = '';
  4369. $usage = [];
  4370. // dd($post_data);
  4371. // dLog('deepseek')->info('请求参数: '.json_encode($post_data, 256));
  4372. try {
  4373. if (in_array($model, ['deepseek-reasoner', 'deepseek-chat', 'deepseek-v4-flash', 'deepseek-v4-pro'])) {
  4374. $streamGenerator = $this->deepSeekStreamResponse($post_data);
  4375. } else if (in_array($model, $this->gpt_text_models)) {
  4376. // GPT-5.4 模型使用 TokenRouter API
  4377. $streamGenerator = $this->gpt54StreamResponse($post_data);
  4378. } else {
  4379. $streamGenerator = $this->volcEngineChatCompletion($post_data);
  4380. }
  4381. // 验证返回值类型
  4382. if (!is_iterable($streamGenerator)) {
  4383. $errorType = is_object($streamGenerator) ? get_class($streamGenerator) : gettype($streamGenerator);
  4384. dLog('deepseek')->error('方法名流式生成器无效', [
  4385. 'generator_type' => $errorType,
  4386. 'model' => $model,
  4387. // 添加其他上下文信息
  4388. ]);
  4389. logDB('deepseek', 'error', '方法名流式生成器类型错误', [
  4390. 'type' => $errorType,
  4391. 'model' => $model
  4392. ]);
  4393. yield [
  4394. 'type' => 'error',
  4395. // 根据方法返回相应的空数据结构
  4396. 'answer' => '',
  4397. 'reasoning' => '',
  4398. 'usage' => [],
  4399. 'error' => '接口返回数据异常,请重新请求'
  4400. ];
  4401. return;
  4402. }
  4403. // 处理流式输出
  4404. foreach ($streamGenerator as $chunk) {
  4405. if (isset($chunk['type'])) {
  4406. if ($chunk['type'] === 'done') {
  4407. $fullContent = $chunk['full_content'];
  4408. $fullReasoningContent = $chunk['full_reasoning'];
  4409. $usage = isset($chunk['usage']) ? $chunk['usage'] : [];
  4410. } else {
  4411. yield $chunk;
  4412. }
  4413. }
  4414. }
  4415. } catch (\Exception $e) {
  4416. dLog('deepseek')->error('方法名流式处理异常: ' . $e->getMessage(), [
  4417. 'model' => $model,
  4418. 'trace' => $e->getTraceAsString()
  4419. ]);
  4420. logDB('deepseek', 'error', '方法名流式处理失败', [
  4421. 'error' => $e->getMessage(),
  4422. 'model' => $model
  4423. ]);
  4424. yield [
  4425. 'type' => 'error',
  4426. // 根据方法返回相应的空数据结构
  4427. 'answer' => '',
  4428. 'reasoning' => '',
  4429. 'usage' => [],
  4430. 'error' => '处理请求时发生异常: ' . $e->getMessage()
  4431. ];
  4432. return;
  4433. }
  4434. dLog('deepseek')->info('完整内容: '.$fullContent);
  4435. logDB('deepseek', 'info', '完整内容', ['content' => $fullContent, 'anime_id' => $anime_id]);
  4436. // 处理完整内容并返回最终结果
  4437. $script_arr = [];
  4438. if ($fullContent) {
  4439. $script_arr = handleScriptContent($fullContent);
  4440. dLog('deepseek')->info('解析内容', $script_arr);
  4441. logDB('deepseek', 'info', '解析内容', $script_arr);
  4442. }
  4443. if (empty($script_arr['roles'])) {
  4444. // 未生成剧本相关内容,保存对话记录并返回提示
  4445. dLog('deepseek')->info('未生成剧本相关的内容');
  4446. try {
  4447. $now = date('Y-m-d H:i:s');
  4448. // 保存对话记录
  4449. $records = [
  4450. [
  4451. 'uid' => $uid,
  4452. 'anime_id' => $anime_id,
  4453. 'sequence' => 0,
  4454. 'role' => 'user',
  4455. 'content' => $prompt,
  4456. 'created_at' => $now,
  4457. 'updated_at' => $now
  4458. ],
  4459. [
  4460. 'uid' => $uid,
  4461. 'anime_id' => $anime_id,
  4462. 'sequence' => 0,
  4463. 'role' => 'assistant',
  4464. 'content' => '未生成剧本相关的内容,请调整提示词后重试',
  4465. 'created_at' => $now,
  4466. 'updated_at' => $now
  4467. ]
  4468. ];
  4469. DB::table('mp_anime_records')->insert($records);
  4470. } catch (\Exception $e) {
  4471. dLog('deepseek')->error('保存对话记录失败', ['error' => $e->getMessage()]);
  4472. }
  4473. yield [
  4474. 'type' => 'done',
  4475. 'script' => [],
  4476. 'episode' => [],
  4477. 'answer' => $fullContent,
  4478. 'reasoning' => $fullReasoningContent,
  4479. 'usage' => $usage,
  4480. 'error' => '未生成剧本相关的内容,请调整提示词再试'
  4481. ];
  4482. return;
  4483. }
  4484. // 替换美术风格
  4485. if ($mappedArtStyle !== '') {
  4486. $script_arr['art_style'] = $mappedArtStyle;
  4487. $fullContent = $this->replaceArtStyleSection($fullContent, $mappedArtStyle);
  4488. }
  4489. if ($user_anime_name != '新剧本策划') {
  4490. $anime_name = isset($script_arr['script_name']) ? $script_arr['script_name'] : '';
  4491. // 确认对话名称唯一性
  4492. if ($anime_name && $id = DB::table('mp_animes')->where('anime_name', $anime_name)->value('id')) {
  4493. if ($id != $anime_id) $anime_name = $anime_name . '_' . date('YmdHis');
  4494. }
  4495. }else {
  4496. $anime_name = $user_anime_name;
  4497. }
  4498. $table_data = [
  4499. 'user_id' => $uid,
  4500. 'model' => $model,
  4501. 'intro' => isset($script_arr['intro']) ? $script_arr['intro'] : '',
  4502. 'highlights' => isset($script_arr['highlights']) ? $script_arr['highlights'] : '',
  4503. 'role_relationship' => isset($script_arr['role_relationship']) ? $script_arr['role_relationship'] : '',
  4504. 'core_contradiction' => isset($script_arr['core_contradiction']) ? $script_arr['core_contradiction'] : '',
  4505. 'roles' => isset($script_arr['roles']) && is_array($script_arr['roles']) ? json_encode($script_arr['roles'], 256) : '[]',
  4506. 'art_style' => isset($script_arr['art_style']) ? $script_arr['art_style'] : '',
  4507. 'art_style_type' => $input_art_style,
  4508. 'scenes' => isset($script_arr['scenes']) && is_array($script_arr['scenes']) ? json_encode($script_arr['scenes'], 256) : '[]',
  4509. 'status' => '解析完成',
  4510. 'generate_status' => '待执行',
  4511. 'updated_at' => date('Y-m-d H:i:s')
  4512. ];
  4513. if ($anime_name) $table_data['anime_name'] = $anime_name;
  4514. // 如果是修改集数,则将content内容更新(会改变原文)
  4515. if (isset($episode_count) && $episode_count > 0) {
  4516. if (isset($script_arr['content']) && $script_arr['content']) $table_data['content'] = $script_arr['content'];
  4517. $table_data['start_episode_sequence'] = 1;
  4518. $table_data['end_episode_sequence'] = $table_data['episode_num'] = $episode_count;
  4519. }else {
  4520. // 如果需要生成原文内容,从script_arr中提取
  4521. if ($need_generate_content && isset($script_arr['content']) && $script_arr['content']) {
  4522. $table_data['content'] = $script_arr['content'];
  4523. dLog('deepseek')->info('从AI生成结果中提取原文内容', ['content_length' => strlen($script_arr['content'])]);
  4524. if (!$table_data['content']) {
  4525. yield [
  4526. 'type' => 'done',
  4527. 'script' => [],
  4528. 'episode' => [],
  4529. 'answer' => $fullContent,
  4530. 'reasoning' => $fullReasoningContent,
  4531. 'usage' => $usage,
  4532. 'error' => '未生成剧本内容,请调整提示词再试'
  4533. ];
  4534. return;
  4535. }
  4536. }
  4537. if (isset($table_data['content']) && $table_data['content']) {
  4538. $chapters = splitContent($table_data['content']);
  4539. $chapter_count = count($chapters);
  4540. if ($chapter_count > 0) {
  4541. $table_data['start_episode_sequence'] = 1;
  4542. $table_data['end_episode_sequence'] = $table_data['episode_num'] = $chapter_count;
  4543. }
  4544. }
  4545. }
  4546. $single_episode = [];
  4547. try {
  4548. DB::beginTransaction();
  4549. $now = date('Y-m-d H:i:s');
  4550. // 更新动漫大纲
  4551. $boolen = DB::table('mp_animes')->where('id', $anime_id)->update($table_data);
  4552. if (!$boolen) {
  4553. dLog('deepseek')->info('对话修改失败', $table_data);
  4554. logDB('deepseek', 'error', '对话修改失败', ['anime_id' => $anime_id]);
  4555. Utils::throwError('20003:对话修改失败');
  4556. }
  4557. // 保存对话记录
  4558. $records = [
  4559. [
  4560. 'uid' => $uid,
  4561. 'anime_id' => $anime_id,
  4562. 'sequence' => 0,
  4563. 'role' => 'user',
  4564. 'content' => $prompt,
  4565. 'created_at' => $now,
  4566. 'updated_at' => $now
  4567. ],
  4568. [
  4569. 'uid' => $uid,
  4570. 'anime_id' => $anime_id,
  4571. 'sequence' => 0,
  4572. 'role' => 'assistant',
  4573. // 'content' => '我已按照您的要求完成策划并将内容更新到您右侧的策划文档。',
  4574. 'content' => $fullContent,
  4575. 'created_at' => $now,
  4576. 'updated_at' => $now
  4577. ]
  4578. ];
  4579. // 保存对话记录
  4580. $boolen3 = DB::table('mp_anime_records')->insert($records);
  4581. if (!$boolen3) {
  4582. Utils::throwError('20003:对话记录保存失败');
  4583. }
  4584. // 单剧集模式:生成并保存剧集信息
  4585. if ($is_single) {
  4586. $anime_name = getProp($anime, 'anime_name', '未命名');
  4587. $episode_arr = $this->buildSingleEpisodeFromScript($script_arr, $fullContent, $anime_name);
  4588. if (empty($episode_arr['acts'])) {
  4589. Utils::throwError('20003:单剧集分镜内容解析失败,请确认输出格式');
  4590. }
  4591. $saveResult = $this->saveEpisodeVersionData(
  4592. $anime_id,
  4593. 1,
  4594. $episode_arr,
  4595. is_array(getProp($script_arr, 'roles')) ? getProp($script_arr, 'roles') : [],
  4596. is_array(getProp($script_arr, 'scenes')) ? getProp($script_arr, 'scenes') : [],
  4597. is_array(getProp($script_arr, 'props')) ? getProp($script_arr, 'props') : [],
  4598. null,
  4599. null,
  4600. false,
  4601. $content,
  4602. $now
  4603. );
  4604. $single_episode = $saveResult['episode'];
  4605. $episode_id = $saveResult['episode_id'];
  4606. $boolen5 = DB::table('mp_animes')->where('id', $anime_id)->update([
  4607. 'roles' => json_encode($saveResult['merged_roles'], 256),
  4608. 'scenes' => json_encode($saveResult['merged_scenes'], 256),
  4609. 'props' => json_encode($saveResult['merged_props'], 256),
  4610. 'updated_at' => $now
  4611. ]);
  4612. if ($boolen5 === false) {
  4613. Utils::throwError('20003:单剧集主表资源同步失败');
  4614. }
  4615. $table_data['roles'] = json_encode($saveResult['merged_roles'], 256);
  4616. $table_data['scenes'] = json_encode($saveResult['merged_scenes'], 256);
  4617. $table_data['props'] = json_encode($saveResult['merged_props'], 256);
  4618. $episode_record_content = '确认分镜大纲';
  4619. if ($content !== '') {
  4620. // $episode_record_content .= "\n\n###上传内容\n" . $content;
  4621. }
  4622. $episode_records = [
  4623. [
  4624. 'uid' => $uid,
  4625. 'anime_id' => $anime_id,
  4626. 'role' => 'user',
  4627. 'content' => $episode_record_content,
  4628. 'sequence' => 1,
  4629. 'episode_id' => $episode_id,
  4630. 'created_at' => $now,
  4631. 'updated_at' => $now
  4632. ],
  4633. [
  4634. 'uid' => $uid,
  4635. 'anime_id' => $anime_id,
  4636. 'role' => 'assistant',
  4637. 'content' => $fullContent,
  4638. // 'content' => '我已按照您的要求完成策划并将内容更新到您右侧的策划文档。',
  4639. 'sequence' => 1,
  4640. 'episode_id' => $episode_id,
  4641. 'created_at' => $now,
  4642. 'updated_at' => $now
  4643. ]
  4644. ];
  4645. $boolen4 = DB::table('mp_anime_records')->insert($episode_records);
  4646. if (!$boolen4) {
  4647. Utils::throwError('20003:单剧集分镜记录保存失败');
  4648. }
  4649. }
  4650. }catch (\Exception $e) {
  4651. DB::rollBack();
  4652. dLog('deepseek')->info('修改对话错误信息: '.$e->getMessage());
  4653. logDB('deepseek', 'error', '修改对话失败', ['error' => $e->getMessage(), 'anime_id' => $anime_id]);
  4654. yield [
  4655. 'type' => 'done',
  4656. 'answer' => $fullContent,
  4657. 'reasoning' => $fullReasoningContent,
  4658. 'usage' => $usage,
  4659. 'error' => $e->getMessage(),
  4660. ];
  4661. return;
  4662. }
  4663. DB::commit();
  4664. dLog('deepseek')->info('保存完毕');
  4665. if ($is_single && !empty($single_episode)) {
  4666. // $this->batchSetGlobalRoleImg([
  4667. // 'anime_id' => $anime_id,
  4668. // ]);
  4669. // $this->batchSetGlobalSceneImg([
  4670. // 'anime_id' => $anime_id,
  4671. // ]);
  4672. // // 将全局角色和场景的task_id、task_status和url继承给当前分集
  4673. // $this->inheritGlobalImagesToEpisodes($anime_id, $episode_id);
  4674. }
  4675. $table_data['anime_id'] = $anime_id;
  4676. $table_data['roles'] = json_decode($table_data['roles'], true);
  4677. $table_data['scenes'] = json_decode($table_data['scenes'], true);
  4678. unset($table_data['updated_at']);
  4679. unset($table_data['status']);
  4680. yield [
  4681. 'type' => 'done',
  4682. 'script' => $table_data,
  4683. 'episode' => $single_episode,
  4684. 'answer' => $fullContent,
  4685. 'reasoning' => $fullReasoningContent,
  4686. 'usage' => $usage
  4687. ];
  4688. }
  4689. public function chat($data) {
  4690. $uid = Site::getUid();
  4691. $anime_id = getProp($data, 'anime_id');
  4692. $file = getProp($data, 'file');
  4693. $content = getProp($data, 'content', '');
  4694. $bid = getProp($data, 'bid', 0);
  4695. $script_id = getProp($data, 'script_id', 0);
  4696. $episode_number = getProp($data, 'episode_number', 1);
  4697. $prompt = trim((string)getProp($data, 'prompt', '确认分镜大纲'));
  4698. $anime = DB::table('mp_animes')->where('id', $anime_id)->first();
  4699. if (!$anime) Utils::throwError('20003:该对话不存在!');
  4700. if ((int)getProp($anime, 'is_multi') !== 1 && (int)$episode_number !== 1) Utils::throwError('20003:单剧集不支持其他剧集序号');
  4701. $current_episode = DB::table('mp_anime_episodes')->where('anime_id', $anime_id)->where('episode_number', $episode_number)->where('is_default', 1)->first();
  4702. $base_episode = $current_episode ?: DB::table('mp_anime_episodes')->where('anime_id', $anime_id)->where('episode_number', $episode_number)->orderByDesc('id')->first();
  4703. $roles = $base_episode ? json_decode((string)getProp($base_episode, 'roles'), true) : json_decode((string)getProp($anime, 'roles'), true);
  4704. $scenes = $base_episode ? json_decode((string)getProp($base_episode, 'scenes'), true) : json_decode((string)getProp($anime, 'scenes'), true);
  4705. $roles = is_array($roles) ? $roles : [];
  4706. $scenes = is_array($scenes) ? $scenes : [];
  4707. // 获取最后一集序号
  4708. $end_episode_sequence = getProp($anime, 'end_episode_sequence');
  4709. if ($end_episode_sequence && $episode_number > $end_episode_sequence) Utils::throwError("20003:总集数只有{$end_episode_sequence}集,不允许继续策划下一集!");
  4710. // 转换主体列表和场景列表的格式
  4711. // 获取参考主体或场景
  4712. if ((int)$episode_number === 1) {
  4713. // $ref_data = DB::table('mp_animes')->where('id', $anime_id)->first();
  4714. $ref_data = []; // 第一集让AI自由发挥不再使用全局主体(会影响后续分集的继承问题)
  4715. }else {
  4716. $prev_episode_number = $episode_number - 1;
  4717. $ref_data = DB::table('mp_anime_episodes')->where('anime_id', $anime_id)->where('episode_number', $prev_episode_number)->where('is_default', 1)->first();
  4718. }
  4719. $ref_roles = getProp($ref_data, 'roles') ? json_decode(getProp($ref_data, 'roles'), true) : [];
  4720. $ref_scenes = getProp($ref_data, 'scenes') ? json_decode(getProp($ref_data, 'scenes'), true) : [];
  4721. $roles_content = $this->buildEpisodeItemContent($ref_roles, 'role');
  4722. $scenes_content = $this->buildEpisodeItemContent($ref_scenes, 'scene');
  4723. $timbres_content = "青年男:北京小爷、阳光青年、傲娇霸总、优柔公子、解说小明、青涩小生、低音沉郁、亲切青年
  4724. 青年女:柔美女友、魅力女友、爽快思思、高冷御姐、知性温婉、甜心小美、清新女声、甜美桃子、温柔文雅、甜美小源、贴心闺蜜
  4725. 中年男:胡子叔叔、油腻大叔、神秘法师、优柔帮主
  4726. 中年女:邻居阿姨
  4727. 老年男:幽默大爷
  4728. 老年女:婆婆
  4729. 萌娃:奶气萌娃";
  4730. if ($roles_content) {
  4731. $role_demo = "2.<主体列表>可在以下主体中选择多个(根据拆分出的分镜剧本来确认具体几个,不要出现旁白角色),不得自定义内容(必需带上冒号后的具体描述以及{}和{{}}中的内容,原样输出)。
  4732. 主体范围:\n {$roles_content}\n
  4733. 2.1如果本集剧情内容中出现了和给出的<主体列表>中不存在的新主体(或原主体发生了比较大的年龄、服装或身体变化),则不用在上述主体中选择,而是按照相同的格式新增一个主体显示在<主体列表>中。(以下是格式要求和生成要求,仅适用新出现的主体):
  4734. → 新主体分以下三部分:主体描述、人物提示词和音色,格式必须为:主体名:主体描述{人物提示词}{{音色}}
  4735. → 新主体的主体描述是分析人物在整部剧中的姓名、年龄、性格特征、社会身份或职业背景、个人成长经历或核心故事动机,以及在剧情中的目标与行为驱动力,不需要描述外貌、穿着或身体特征,重点突出心理结构、行为模式与叙事功能(缩略成一句话讲述完毕)。
  4736. → 新主体的人物提示词需要根据当前分析出来的美术风格生成(每个人物都只允许一套服装,如果多套服装则需区分主体名),包含性别(男、女)、大概年龄或年龄段(少年、中年、老年等)、人种(亚洲人、欧洲人)、发型(直发卷发等)、发色(黑色、棕色、红色、白色等)、整体视觉风格,以及详细的穿着风格和服装细节、面部特征(戴金丝眼镜、脸上有刀疤等,无面部特征可忽略)。描述需具有镜头感与画面表现力,适合直接用于AI图像生成模型,避免抽象词汇,强调具体可视化细节与整体视觉一致性,同时保证风格统一且符合人物身份设定。该提示词(字数50-100字左右)在主体描述后用{}框起来。
  4737. → 新主体的音色必须在以下音色中($timbres_content)选择,需要根据角色描述的年纪和性别选择,比如角色是青年男性就只能在北京小爷、阳光青年、傲娇霸总、优柔公子、解说小明、青涩小生、低音沉郁、亲切青年中选择,选好的音色放在描述的最后用{{}}框起来。";
  4738. }else {
  4739. $role_demo = "2.<主体列表>中出现的“主体名”必须尽可能统一,严禁出现角色-科学家、角色-复仇者、角色-领导者等带有身份、职业、标签类的命名,只能使用服装差异(如校服装、卫衣装、西装)来区分同一角色,如角色-校服装等。
  4740. 2.1<主体列表>分以下三部分:主体描述、人物提示词和音色,格式必须为:主体名:主体描述{人物提示词}{{音色}}
  4741. 2.2<主体列表>的主体描述是分析人物在整部剧中的姓名、年龄、性格特征、社会身份或职业背景、个人成长经历或核心故事动机,以及在剧情中的目标与行为驱动力,不需要描述外貌、穿着或身体特征,重点突出心理结构、行为模式与叙事功能(缩略成一句话讲述完毕)。
  4742. 2.3<主体列表>的人物提示词需要根据当前分析出来的美术风格生成(每个人物都只允许一套服装,如果多套服装则需区分主体名),包含性别(男、女)、大概年龄或年龄段(少年、中年、老年等)、人种(亚洲人、欧洲人)、发型(直发卷发等)、发色(黑色、棕色、红色、白色等)、整体视觉风格,以及详细的穿着风格和服装细节、面部特征(戴金丝眼镜、脸上有刀疤等,无面部特征可忽略)。描述需具有镜头感与画面表现力,适合直接用于AI图像生成模型,避免抽象词汇,强调具体可视化细节与整体视觉一致性,同时保证风格统一且符合人物身份设定。该提示词(字数50-100字左右)在主体描述后用{}框起来。
  4743. 2.4<主体列表>的音色必须在以下音色中($timbres_content)选择,需要根据角色描述的年纪和性别选择,比如角色是青年男性就只能在北京小爷、阳光青年、傲娇霸总、优柔公子、解说小明、青涩小生、低音沉郁、亲切青年中选择,选好的音色放在描述的最后用{{}}框起来。";
  4744. }
  4745. if ($scenes_content) {
  4746. $scene_demo = "3.<场景列表>可在以下场景中选择多个(需带上冒号后的具体描述),根据拆分出的分镜剧本来确认具体几个,不得自定义(必需带上冒号后的具体描述以及{}中的内容,原样输出)。
  4747. 场景范围:\n {$scenes_content}\n
  4748. 3.1如果本集剧情内容中出现了和给出的<场景列表>中不存在的新场景,则不用在上述场景中选择,而是按照相同的格式新增一个场景显示在<场景列表>中,必须严格注意不要出现任何角色和人物。(以下是格式要求和生成要求,仅适用新出现的场景):。
  4749. → 新场景分以下两部分:场景描述和场景提示词,格式必须为:场景描述{场景提示词}
  4750. → 新场景的场景描述是分析在整部剧中出现过的场景,场景描述尽量简洁贴合原文。
  4751. → 新场景的场景提示词用于视觉呈现的场景环境描述,该场景需包含环境氛围、光线效果、空间布局、色彩基调、视觉风格等,描述需具有镜头感与画面表现力,适合直接用于AI图像生成模型,避免抽象词汇,强调具体可视化细节与整体视觉一致性,同时保证风格统一且符合剧情设定(可参考以下示例的场景列表中使用{}框起来的提示词,字数150-200字,需带上提炼出来的美术风格)。该提示词在场景描述后用{}框起来。\n";
  4752. }else {
  4753. $scene_demo = "3.<场景列表>与主体列表同理,需尽可能的对场景环境进行详细描述,必须严格注意不要出现任何角色和人物。
  4754. 3.1<场景列表>分以下两部分:场景描述和场景提示词,格式必须为:场景描述{场景提示词},注意不要出现{{}}这样的双大括号。
  4755. 3.2<场景列表>的场景描述是分析在整部剧中出现过的场景,场景描述尽量简洁贴合原文。
  4756. 3.3<场景列表>的场景提示词用于视觉呈现的场景环境描述,该场景需包含环境氛围、光线效果、空间布局、色彩基调、视觉风格等,描述需具有镜头感与画面表现力,适合直接用于AI图像生成模型,避免抽象词汇,强调具体可视化细节与整体视觉一致性,同时保证风格统一且符合剧情设定(可参考以下示例的场景列表中使用{}框起来的提示词,字数150-200字,需带上提炼出来的美术风格)。该提示词在场景描述后用{}框起来。\n";
  4757. }
  4758. // 提取文件内容
  4759. if ($file) {
  4760. $uploaded_content = $this->extractFileContent($file);
  4761. if (!$uploaded_content) {
  4762. Utils::throwError('20003:无法提取文件内容,请检查文件格式');
  4763. }
  4764. } elseif ($script_id) {
  4765. $uploaded_content = $this->getContentByScriptId($script_id);
  4766. if (!$uploaded_content) {
  4767. Utils::throwError('20003:无法获取剧本内容,请检查剧本');
  4768. }
  4769. } elseif ($bid) {
  4770. $uploaded_content = $this->getContentByBid($bid);
  4771. if (!$uploaded_content) {
  4772. Utils::throwError('20003:无法获取书籍内容,请检查书籍');
  4773. }
  4774. } elseif ($content) {
  4775. $uploaded_content = filterContent((string)getProp($data, 'content', ''));
  4776. }
  4777. // elseif ($prompt) {
  4778. // $uploaded_content = filterContent($prompt);
  4779. // }
  4780. else {
  4781. $uploaded_content = '';
  4782. }
  4783. $input_art_style = getProp($anime, 'art_style');
  4784. $mappedArtStyle = $this->getArtStylePromptByInput($input_art_style);
  4785. // 美术风格
  4786. if (!$mappedArtStyle) {
  4787. $mappedArtStyle_prompt = '美术风格:根据剧本内容自定义美术风格';
  4788. }else {
  4789. if (strstr($mappedArtStyle, '基础画风风格词')) {
  4790. $mappedArtStyle_prompt = "美术风格强制设置如下(原样输出,不得更改任何内容):\n{$mappedArtStyle}\n";
  4791. }else {
  4792. $art_style_type = $input_art_style ? $input_art_style : getProp($anime, 'art_style_type');
  4793. $mappedArtStyle_prompt = "美术风格强制设置如下(原样输出,不得更改任何内容):\n基础画风风格词: {$art_style_type}\n{$mappedArtStyle}\n";
  4794. }
  4795. }
  4796. $prompt = trim((string)getProp($data, 'prompt', '确认分镜大纲'));
  4797. // $demo = "你是一个专业的文档分析助手及资深编剧,请根据用户提供的文档内容完成示例格式的内容输出(需包含以下几个板块: <剧集标题><故事梗概><美术风格><主体列表><场景列表><分镜剧本>,每个板块之间必须使用###分隔,#不能多也不能少;同时板块之间需满足以下要求:\n
  4798. // 强制要求:
  4799. // - 你只负责与剧本相关的内容,如果用户输入与剧本无关的内容,请告知用户并拒绝继续回答,此为第一优先原则,不满足此原则就忽略其他要求并停止继续输出
  4800. // - 如果用户输入修改美术风格、修改画风这类内容,请告知用户不可修改美术风格,并拒绝继续回答
  4801. // - 以上两条要求对修改主体角色或场景不生效,允许用户调整主体角色说明和场景描述等
  4802. // - 用户如果要求你帮忙写一个故事或者剧本,此类要求不属于与剧本无关,请帮助用户完成请求
  4803. // - 强制按照示例格式返回内容,不要更改格式或随意增加符号
  4804. // - 分镜剧本必须严格按照给出的“本集剧情内容”进行拆分,一个字都不要漏掉,同时也不要新增原文没有的内容
  4805. // - 如果给出的本集剧情内容是剧本格式,则不要改动剧本内容(必须强制使用原文内容),严格按照剧本的旁白和台词进行分镜的策划,不要跳过任何剧情
  4806. // - 分镜不是二次创作,必须严格“原文拆句”。优先把原文中可直接成镜头的句子拆成分镜,禁止把两句合并后再脑补过渡。
  4807. // - 画面描述必须直接使用,禁止新增任何原文没有写出的动作、人物、道具、地点、气氛、结果或因果。
  4808. // - 不要把“打开衣柜”扩写成“伸手轻抚嫁衣”,不要把“管家拎着两个箱子跟在后面”改成“沈耀和管家一起拎箱子”。主语、动作、数量、先后顺序必须完全按原文。
  4809. // - 分镜要和场景列表、人物主体保持一致\n
  4810. // 普通要求:
  4811. // 1.剧集标题必须与文档内容高度相关,剧集序号是{$episode_number}。
  4812. // {$role_demo}
  4813. // {$scene_demo}
  4814. // 4.<分镜剧本>要求包含“分幕标题”以及“分镜信息”:
  4815. // 4.1“分幕标题”是根据章节中的场景进行拆分,类似于“第1幕 场景、时间及室内或室外”的信息,其中场景只能在所给出的场景列表中选(不带场景详细描述)。
  4816. // 4.2“分镜信息”需同一场景内的对话内容完成分镜(每一幕分镜尽量不得低于5个),需包含“画面描述”、“构图设计”、“运镜调度”、“配音角色”、“台词内容”、“画面类型”、“尾帧描述”、“情感”、“性别”、“语速”、“音量”、“情感强度”、“音调”这几个部分,其中“画面描述”如果出现主体,只能选择上述主体列表中的一个,主体的名称也需要保持一致(不带主体具体描述)。
  4817. // 4.3分镜序号用1、2、3显示,如分镜1、分镜2,并且分镜序号需连续(跨分幕中的分镜序号需连续,但跨剧集中的不需要连续,如第2集的第1幕分镜序号从1开始)。
  4818. // 4.4“分镜信息”中的“台词内容”需满足以下要求: (1. 台词来源规则:- 台词内容必须逐字摘录自小说原文中的人物直接对话(带引号的内容)。- 不允许改写、总结、压缩、扩写或拼接原文对白。- 不允许生成原文中不存在的对话。2. 非对话过滤:- 旁白、心理描写、环境描写、动作描写等内容,禁止出现在台词内容中。3. 空台词规则:- 如果该分镜中没有人物对话,则“台词内容”必须返回“无”。- 严禁输出“无台词”、“没有”等任何替代文本。4. 禁止推测:- 不得根据语境补全人物可能说的话。5.如果没有找到原文内容,直接返回无)
  4819. // 4.5“分镜信息”中的“配音角色”需对应本集中的<主体列表>中的一个(非对话内容则统一固定为“旁白”角色),不得自己生成。
  4820. // 4.6“分镜信息”中的“场景”必须选择本集中的<场景列表>中的一个(不带详细表述)。
  4821. // 4.7“分镜信息”中的“出镜角色”需对应本集中的<主体列表>中的一个或多个(不带详细描述),如果没有出镜角色则填无。
  4822. // 4.8“分镜信息”中的“尾帧描述”需根据本镜和下一镜的剧本信息进行过渡生成,用于后续转视频进行衔接上下镜头的画面。
  4823. // 4.9“分镜信息”中的“情感”需根据台词内容和剧情氛围分析得出,可选值为:开心、悲伤、生气、惊讶、恐惧、厌恶、激动、冷漠、中性、沮丧、撒娇、害羞、安慰鼓励、咆哮、温柔、自然讲述、情感电台、磁性、广告营销、气泡音、新闻播报、娱乐八卦,不要在情感可选词后加任何解释性的词语,比如(对自己)、(对别人)等,不要自定义情感,必须在可选值中选择。
  4824. // 4.10“分镜信息”中的“性别”需根据配音角色的性别确定,可选值为:1(男)、2(女)、0(中性)。
  4825. // 4.11“分镜信息”中的“语速”需根据台词内容和情感氛围确定,可选值范围为:-50到100之间的整数,100代表2.0倍速,-50代表0.5倍数,负值表示减慢,正值表示加快,0表示正常语速。
  4826. // 4.12“分镜信息”中的“音量”需根据台词内容和情感氛围确定,可选值范围为:-50到100之间的整数,100代表2.0倍音量,-50代表0.5倍音量,负值表示降低音量,正值表示提高音量,0表示正常音量。
  4827. // 4.13“分镜信息”中的“情感强度”需根据情感的强烈程度确定,可选值范围为:1到5之间的整数,默认情况下选择4。
  4828. // 4.14“分镜信息”中的“音调”需根据台词内容和情感氛围确定,可选值范围为:-12到12之间的整数,负值表示降低音调,正值表示提高音调,0表示正常音调。
  4829. // 5.$mappedArtStyle_prompt\n\n
  4830. // 示例格式:\n
  4831. // 第1集:隐形的守护者
  4832. // ###故事梗概
  4833. // 内容梗概:许芸归家遭徐母毒打,她冷静周旋并编造谎言掩盖行踪,引得一旁阴沉的卞大伟愈发急躁。半个月后,徐母离家,卞大伟兽性大发欲行不轨。生死关头,隐形的程景现身肉搏,屋内家具横飞,卞大伟被“空气”重创。许芸趁乱逃出,却惊见地面凭空浮现一串血脚印。意识到守护者为救自己负伤,许芸不再逃避,对着虚无的空气执拗告白,誓要与这看不见的爱人共进退。
  4834. // ###美术风格
  4835. // 基础画风风格词:韩漫二次元
  4836. // 视觉风格描述:整体采用精致的韩漫厚涂风格,以浅灰冷调为基调,营造出重生复仇的清冷与压抑感。画面强调高对比度的光影处理,网吧场景通过低饱和度的杂乱色调表现颓废感,而清晨车祸瞬间则利用强烈的动态模糊与局部高光,突显“透明守护者”存在的神秘感与宿命感。人物形象细腻,眼神充满坚毅与破碎交织的故事感,完美契合偏执救赎的主题。
  4837. // ###主体列表
  4838. // 许芸-校服装:重生后的“假千金”,清醒果敢,不再任人唯亲。她是一名高中生,身材纤细,留着乌黑齐肩短发,眼神坚定。{18岁年轻女生,黑色长发,红色眼睛,五官精致,皮肤白皙,身材纤细,穿着日系校园制服,白色衬衫,黑色百褶裙,红色领带,表情悲伤,眼含泪水}{{甜心小美}}
  4839. // 许芸-卫衣装:半个月后居家或外出时的装扮,在清冷的环境中透着一丝坚毅与破碎感。{绝美年轻女子,白色长发,金色眼睛,五官精致,皮肤白皙,身材纤细,穿着淡蓝色古风汉服,气质清冷,神情平静,高细节人物刻画}{{爽快思思}}
  4840. // 程景:偏执深情的学霸,为救许芸变得“不可见”,是始终默默守护的隐形爱人。他身材高大挺拔,面容英俊。{年轻男性反派,银白色短发,红色眼睛,面容冷峻,皮肤苍白,身穿黑色长袍,嘴角冷笑,气质危险,高细节人物刻画}{{阳光青年}{{阳光青年}}
  4841. // ###场景列表
  4842. // 徐家老旧厨房:这是徐母劳作和惩罚许芸的地方。空间狭窄阴暗,充满了生活琐碎的压抑感。室内有一个旧式锅炉,案板上散落着面粉和包好的馄饨,光影对比强烈,凸显出家庭环境的冷酷。{影视质感。广角。
  4843. // 宽敞的天然山洞内部,石壁上错落有致地镶嵌着发光的萤石,散发出冷色调的微光,照亮了整个空间。洞顶有钟乳石垂下。光影层次丰富,营造出一种宁静而神圣的氛围。
  4844. // 无人物。}
  4845. // 徐家简陋客厅:半个月后冲突爆发的中心。陈设简单且陈旧,只有几把木凳和一张方桌。窗帘半掩,透进微弱的冷光,营造出一种暴风雨前的宁静与不安感。{影视质感。冷青色调,浓雾弥漫。
  4846. // 一条通往西北方向的崎岖山间土路,两旁是枯萎的灌木和怪石嶙峋。地面湿滑,反光强烈。远方山峦在阴雨中若隐若现,营造出一种穷追不舍的紧张感。
  4847. // 无人物。}
  4848. // 老旧公寓门口:许芸逃出家门后回望的视点。门框斑驳,透出屋内昏暗压抑的光线,与室外略显空旷的走廊形成对比,象征着逃离与未知的守护。{
  4849. // 豪华游轮内部宽敞的大堂或公共休息区。设计奢华,天花板高挑,有精致的装饰和柔和的暖色灯光。地面铺设着光洁的大理石,远处有巨大的落地窗,窗外是蓝色的海洋。自然光线充足,色彩明亮且饱和度适中,展现豪华游轮的质感。
  4850. // 无人物。}
  4851. // 破败巷弄与臭水沟:家门外的外部环境。一条狭窄、潮湿的巷弄,旁边是散发着冷气的臭水沟,水面偶尔泛起涟漪。这里是“透明守护者”受伤后经过的地方,氛围凄清。{
  4852. // 宽敞明亮的现代风格客厅,家具摆放整齐,色调偏向冷灰与深蓝,营造一种沉静而略带压抑的氛围。窗外光线柔和,室内光影对比不强烈,整体干净整洁。
  4853. // 无人物。}
  4854. // 潮湿的巷弄地面:特写视角。灰色的水泥地面湿迹斑斑,这是许芸发现血脚印并进行最后告白的地方。强调地面的质感和清冷的基调。{
  4855. // 一个现代居民小区的入口,有门卫岗亭和自动栏杆。道路宽阔,两旁绿化整齐,阳光明媚,整体色调略显冷峻,但光线清晰。
  4856. // 无人物。}
  4857. // ###分镜剧本
  4858. // ##第1幕:徐家老旧厨房 白天 室内
  4859. // 分镜1
  4860. // 画面描述:许芸-校服装站在厨房门口,书包背在肩上,徐母手持扫帚,正对着许芸的背部猛烈挥打。卞大伟站在锅炉后方,双手抱胸,阴沉的目光落在许芸身上。
  4861. // 场景:徐家老旧厨房
  4862. // 构图设计:全景,低角度仰视
  4863. // 运镜调度:手持拍摄
  4864. // 配音角色:旁白
  4865. // 出镜角色:许芸-校服装、徐母
  4866. // 台词内容:我一到家,徐母的扫帚就落在我身上,嘴里一个劲地骂我,
  4867. // 画面类型:普通画面
  4868. // 尾帧描述:手持拍摄微晃镜头,中年妇女猛力挥动扫帚击打少女背部,少女身体因冲击微颤,阴影中的肥胖男子目光冷冷跟随。
  4869. // 分镜2
  4870. // 画面描述:徐母面容扭曲,嘴唇快速开合,扫帚挥舞在空中。
  4871. // 场景:徐家老旧厨房
  4872. // 构图设计:近景,徐母面部特写
  4873. // 运镜调度:固定镜头
  4874. // 配音角色:徐母
  4875. // 出镜角色:徐母
  4876. // 台词内容:问我夜不归宿死哪儿去了。
  4877. // 画面类型:对口型
  4878. // 尾帧描述:固定镜头,中年妇女面部肌肉剧烈抖动,嘴唇快速开合进行辱骂,背景中的扫帚在空中上下挥动。
  4879. // ##第2幕:徐家简陋客厅 黄昏 室内
  4880. // 分镜3
  4881. // 画面描述:客厅窗户透出昏黄的夕阳余晖,空荡荡的客厅中央只有几把木凳和一张方桌,显得异常安静。
  4882. // 场景:徐家简陋客厅
  4883. // 构图设计:全景,景深虚化
  4884. // 运镜调度:固定镜头
  4885. // 配音角色:旁白
  4886. // 出镜角色:无
  4887. // 台词内容:可我没想到,半个月后,徐母居然再一次外出,
  4888. // 画面类型:普通画面
  4889. // 尾帧描述:固定镜头。昏黄的夕阳余晖在地面上缓慢移动,空气中的浮尘在光束中跳动,室内维持着死寂的安静。
  4890. // 分镜4
  4891. // 画面描述:一张泛黄的火车票特写,上面显示着隔壁市的站名和日期。
  4892. // 场景:徐家简陋客厅
  4893. // 构图设计:特写,火车票
  4894. // 运镜调度:固定镜头
  4895. // 配音角色:旁白
  4896. // 出镜角色:无
  4897. // 台词内容:这次是去隔壁市看望她生病的好姐妹。
  4898. // 画面类型:普通画面
  4899. // 尾帧描述:固定镜头。光影在火车票表面微微晃动,强调其陈旧的纸张纹理与关键的行程信息。
  4900. // \n\n";
  4901. $demo = "你是一个国际顶尖的执行导演/编剧,熟悉各种风格的影视化落地,我需要你将这个剧本调整一下,将其变成一个高质量的影视分镜剧本(需包含以下几个板块: <剧集标题><故事梗概><美术风格><主体列表><场景列表><分镜剧本>,每个板块之间必须使用###分隔,#不能多也不能少),要求画面和构图等进行高质量影视化改编,快节奏,改编的格式为先建立主体角色库、场景建库(其中场景建库的时候请分析故事发生的时候场景为白天还是晚上,建库的时候一起标注出来)以及关键的道具库。
  4902. 与此同时请将这个文本的情绪做一个分析,并且根据我下面提供的《情绪-视听语言映射表》进行一个文本情绪与视听语言的内容匹配。然后将每一个分镜按照「画面描述」「场景/场景时间(白天/晚上/傍晚等)」「构图设计(全景/近景/中景/远景,仰视/平视/俯视等)」「运镜调度」「配音角色」「出境角色」「台词内容」「画面类型」「尾帧描述」的格式来划分,请按照每分钟25个左右的分镜的节奏帮我生成(这是一个整体性的标准,如果文本的情绪分析需要更多或者更少的镜头数量,请根据具体情况调整),分镜头请细腻的拆分文本中的内容,将动作、场景转换、事件的逻辑关系等内容清晰的交代出来,分镜之间需要呈现场景之间的转换逻辑,不要突然跳到下一个场景之中。于此同时保持镜头剪辑的顿挫感,节奏不要太平均。
  4903. 每一个分镜的「画面描述」请参考上一个分镜中人物的状态/动作和位置来写,保持人物状态以及在场景中的位置的一致性,不要断裂感,同时也不要直接在内容里写“参考上个分镜”这种话,因为视频模型无法识别,使用模型可以直接识别的文本内容。每一个分镜中需要出现的内容都请标出,例如出场角色,出场道具等等。请尽可能详细的描述画面内容。\n
  4904. 普通要求:
  4905. 1.剧集标题必须与文档内容高度相关,剧集序号是{$episode_number}。
  4906. {$role_demo}
  4907. {$scene_demo}
  4908. 4.<分镜剧本>要求包含“分幕标题”以及“分镜信息”:
  4909. 4.1“分幕标题”是根据章节中的场景进行拆分,类似于“第1幕 场景、时间及室内或室外”的信息,其中场景只能在所给出的场景列表中选(不带场景详细描述)。
  4910. 4.2“分镜信息”需同一场景内的对话内容完成分镜(每一幕分镜尽量不得低于5个),需包含“画面描述”、“构图设计”、“运镜调度”、“配音角色”、“台词内容”、“画面类型”、“尾帧描述”、“情感”、“性别”、“语速”、“音量”、“情感强度”、“音调”这几个部分,其中“画面描述”如果出现主体,只能选择上述主体列表中的一个,主体的名称也需要保持一致(不带主体具体描述)。
  4911. 4.3分镜序号用1、2、3显示,如分镜1、分镜2,并且分镜序号需连续(跨分幕中的分镜序号需连续,但跨剧集中的不需要连续,如第2集的第1幕分镜序号从1开始),分镜序号前后不要带任何其他符号,特别是*符号。
  4912. 4.4“分镜信息”中的“台词内容”需满足以下要求: (1. 台词来源规则:- 台词内容必须逐字摘录自小说原文中的人物直接对话(带引号的内容)。- 不允许改写、总结、压缩、扩写或拼接原文对白。- 不允许生成原文中不存在的对话。2. 非对话过滤:- 旁白、心理描写、环境描写、动作描写等内容,禁止出现在台词内容中。3. 空台词规则:- 如果该分镜中没有人物对话,则“台词内容”必须返回“无”。- 严禁输出“无台词”、“没有”等任何替代文本。4. 禁止推测:- 不得根据语境补全人物可能说的话。5.如果没有找到原文内容,直接返回无)
  4913. 4.5“分镜信息”中的“配音角色”需对应本集中的<主体列表>中的一个(非对话内容则统一固定为“旁白”角色),不得自己生成。
  4914. 4.6“分镜信息”中的“场景”必须选择本集中的<场景列表>中的一个(不带详细表述)。
  4915. 4.7“分镜信息”中的“出镜角色”需对应本集中的<主体列表>中的一个或多个(不带详细描述),如果没有出镜角色则填无。
  4916. 4.8“分镜信息”中的“尾帧描述”需根据本镜和下一镜的剧本信息进行过渡生成,用于后续转视频进行衔接上下镜头的画面。
  4917. 4.9“分镜信息”中的“情感”需根据台词内容和剧情氛围分析得出,可选值为:开心、悲伤、生气、惊讶、恐惧、厌恶、激动、冷漠、中性、沮丧、撒娇、害羞、安慰鼓励、咆哮、温柔、自然讲述、情感电台、磁性、广告营销、气泡音、新闻播报、娱乐八卦,不要在情感可选词后加任何解释性的词语,比如(对自己)、(对别人)等,不要自定义情感,必须在可选值中选择。
  4918. 4.10“分镜信息”中的“性别”需根据配音角色的性别确定,可选值为:1(男)、2(女)、0(中性)。
  4919. 4.11“分镜信息”中的“语速”需根据台词内容和情感氛围确定,可选值范围为:-50到100之间的整数,100代表2.0倍速,-50代表0.5倍数,负值表示减慢,正值表示加快,0表示正常语速。
  4920. 4.12“分镜信息”中的“音量”需根据台词内容和情感氛围确定,可选值范围为:-50到100之间的整数,100代表2.0倍音量,-50代表0.5倍音量,负值表示降低音量,正值表示提高音量,0表示正常音量。
  4921. 4.13“分镜信息”中的“情感强度”需根据情感的强烈程度确定,可选值范围为:1到5之间的整数,默认情况下选择4。
  4922. 4.14“分镜信息”中的“音调”需根据台词内容和情感氛围确定,可选值范围为:-12到12之间的整数,负值表示降低音调,正值表示提高音调,0表示正常音调。
  4923. 5.$mappedArtStyle_prompt
  4924. 6.《情绪-视听语言映射表》:
  4925. 6.1 场景空间与时间心理学 (Scene & Temporality)
  4926. 维度 | 视听特征 | 对应核心情绪 | 心理学/叙事原理
  4927. -----|---------|------------|----------------
  4928. 场景空间 | 封闭狭小 (Corridors/Closets) | 压抑、幽闭恐惧 | 物理限制映射心理自由的剥夺。
  4929. 场景空间 | 极度开阔 (Empty Plains/Desert) | 孤独、渺小、疏离 | 剥离社会性支撑,强化个体的虚无感。
  4930. 时间选择 | 黄金时刻 (Golden Hour) | 怀旧、温情、希望 | 柔和漫反射光线符合大脑对“美好记忆”的视觉加工。
  4931. 时间选择 | 蓝调时刻/深夜 (Blue/Night) | 冷漠、忧郁、未知危险 | 冷色调抑制血清素,增强感官的不安全感。
  4932. 6.2 剪辑节奏与感知阈值 (Shot Duration & Rhythm)
  4933. 维度 | 视听特征 | 对应核心情绪 | 心理学/叙事原理
  4934. -----|---------|------------|----------------
  4935. 长镜头 | >15秒的静止或缓慢移动 | 沉思、肃穆、煎熬 | 强迫观众进入实时流逝,产生生理性的存在感。
  4936. 快切剪辑 | <2秒的频繁切换 | 混乱、亢奋、惊恐 | 模拟高肾上腺素下的视觉捕捉,剥夺深度思考时间。
  4937. 节奏错位 | 非同步切分 (L-cut/J-cut) | 扭曲、不协调 | 破坏连续性假定,产生心理上的不适与悬疑感。
  4938. 6.3 运镜调度与情绪调动 (Cinematic Movement & Affect)
  4939. 运镜方式 | 物理特征 | 心理/情绪功能 | 专业应用场景
  4940. --------|---------|--------------|-------------
  4941. 推镜头 (Dolly In) | 摄影机物理接近主体 | 专注、发现、心理逼近。通过压缩背景空间,强制观众忽略环境,进入主体的内心世界。 | 角色顿悟、秘密揭晓、情感升温。
  4942. 拉镜头 (Dolly Out) | 摄影机物理远离主体 | 疏离、解脱、宿命感。将主体置于广阔背景中,显示主体的渺小或强调事情已成定局。 | 悲剧结尾、孤独的告别、审视全局。
  4943. 摇镜头 (Pan/Tilt) | 轴心转动,视点改变 | 观察、审读、惊奇感。模拟人眼转头,用于揭示空间关系或进行逻辑上的“连接”。 | 发现潜伏的危机、环视战场、建立空间地理志。
  4944. 跟拍 (Tracking Shot) | 保持与主体同速移动 | 强烈的参与感、伴随性焦虑。让观众感觉自己是角色的共谋者或影子,产生“实时感”。 | 逃亡、快步穿行于走廊、展示角色的行动力。
  4945. 横移 (Truck/Side Track) | 与主体平行横向移动 | 客观审视、叙事流逝。像卷轴画一样展开,产生一种冷静、观察者的旁白视角。 | 展示环境细节、两个角色在边走边谈时的心理博弈。
  4946. 手持/肩扛 (Handheld) | 生理性不规则晃动 | 不安、真实感、心理动荡。模拟肉眼观察,通过不稳定性唤起观众的本能警觉。 | 冲突现场、纪录片式纪实感、角色精神崩溃。
  4947. 斯坦尼康 (Steadicam) | 流畅、近乎滑行的移动 | 全知感、梦幻、无缝观察。消除物理重力感,产生一种“上帝视角”或“游魂般”的观察。 | 漫长而复杂的转场、舞会等优雅场景的穿梭。
  4948. 希区柯克变焦 (Dolly Zoom) | 推进同时反向变焦 | 眩晕、世界崩塌、极度惊骇。空间透视的物理扭曲直接引发生理性失衡。 | 角色得知真相的瞬间、高度恐惧。
  4949. 升降/摇臂 (Crane Shot) | 垂直或斜向空间位移 | 释放、崇高、超越性。打破二维平面的限制,将情绪从微观拉向宏观。 | 史诗感的结局、战场全景、情绪的爆发式升华。
  4950. 6.4 构图、色彩与符号学 (Composition & Aesthetics)
  4951. 维度 | 视听特征 | 对应核心情绪 | 心理学原理
  4952. -----|---------|------------|------------
  4953. 角度 | 仰角 (Low Angle) | 威严、恐惧、崇高 | 模拟幼年视角,确立权力层级。
  4954. 角度 | 俯角 (High Angle) | 脆弱、无助、卑微 | 模拟审视感,削弱主体力量。
  4955. 构图 | 荷兰坡 (Dutch Tilt) | 疯狂、崩溃、失衡 | 重力轴偏离导致前庭系统产生失衡反应。
  4956. 色彩 | 极高饱和度/冷暖撞色 | 狂喜、冲突、超现实 | 强烈的视觉刺激诱发情绪阈值波动。
  4957. 6.5 进阶视听修辞与认知干预 (Advanced AV Rhetoric)
  4958. 修辞策略 | 技术实现 | 心理/情绪效应 | 理论基石
  4959. --------|---------|--------------|----------
  4960. 声画对位 (Contrapuntal AV) | 在极端残酷/激烈的画面中配以极其舒缓优雅的音乐(如古典乐)。 | 荒诞恐怖感、神圣的残酷、间离效果。通过感官冲突迫使观众从原始情绪中抽离,进入形而上的思考。 | 安德烈·塔可夫斯基《雕刻时光》、库布里克式美学。
  4961. 非平衡构图 (Compositional Tension) | 突破平衡法则,将视觉重点(Eye-tracking)置于画面边缘或极端角落。 | 本能警觉、不安全感、期待感。利用大脑对“视觉缺失”的补充本能,暗示画面外存在不可见的威胁。 | 格式塔心理学、眼动追踪实验。
  4962. 认知负荷调控 (Neurocinematics) | 利用快速剪辑抑制前额叶皮层(理性区),激活杏仁核(情绪区)。 | 纯粹感官化、生存模式切换。若要观众思考,则延长镜头以激活认知分析;若要观众受惊,则通过视觉过载切断其逻辑判断。 | 神经电影学 (Neurocinematics)。
  4963. 6.6 声音设计与潜意识影响 (Soundscape)
  4964. 维度 | 视听特征 | 对应核心情绪 | 心理学/生理学原理
  4965. -----|---------|------------|------------------
  4966. 音色 | 极低频音 (Infra-sound) | 潜伏恐惧、生理不安 | 模仿自然灾害频率,唤醒生物避害本能。
  4967. 环境声 | 极度死寂 (Silence) | 震惊、神圣、虚无 | 听觉剥夺放大视觉信号,产生心理张力。
  4968. 非现场音 | 不和谐音/尖锐音效 | 精神紧绷、躁郁 | 高频声音直接刺激杏仁核,引发防御机制。
  4969. 理论基石:
  4970. - The Five C's of Cinematography by Joseph V. Mascelli
  4971. - Film Art: An Introduction by David Bordwell
  4972. - Sight, Sound, Motion by Herbert Zettl
  4973. - Notes on the Cinematograph by Robert Bresson
  4974. \n\n
  4975. 7.必须严格按照以下示例格式返回剧本,不得添加其他符号
  4976. 示例格式:\n
  4977. 第1集:隐形的守护者
  4978. ###故事梗概
  4979. 内容梗概:许芸归家遭徐母毒打,她冷静周旋并编造谎言掩盖行踪,引得一旁阴沉的卞大伟愈发急躁。半个月后,徐母离家,卞大伟兽性大发欲行不轨。生死关头,隐形的程景现身肉搏,屋内家具横飞,卞大伟被“空气”重创。许芸趁乱逃出,却惊见地面凭空浮现一串血脚印。意识到守护者为救自己负伤,许芸不再逃避,对着虚无的空气执拗告白,誓要与这看不见的爱人共进退。
  4980. ###美术风格
  4981. 基础画风风格词:韩漫二次元
  4982. 视觉风格描述:整体采用精致的韩漫厚涂风格,以浅灰冷调为基调,营造出重生复仇的清冷与压抑感。画面强调高对比度的光影处理,网吧场景通过低饱和度的杂乱色调表现颓废感,而清晨车祸瞬间则利用强烈的动态模糊与局部高光,突显“透明守护者”存在的神秘感与宿命感。人物形象细腻,眼神充满坚毅与破碎交织的故事感,完美契合偏执救赎的主题。
  4983. ###主体列表
  4984. 许芸-校服装:重生后的“假千金”,清醒果敢,不再任人唯亲。她是一名高中生,身材纤细,留着乌黑齐肩短发,眼神坚定。{18岁年轻女生,黑色长发,红色眼睛,五官精致,皮肤白皙,身材纤细,穿着日系校园制服,白色衬衫,黑色百褶裙,红色领带,表情悲伤,眼含泪水}{{甜心小美}}
  4985. 许芸-卫衣装:半个月后居家或外出时的装扮,在清冷的环境中透着一丝坚毅与破碎感。{绝美年轻女子,白色长发,金色眼睛,五官精致,皮肤白皙,身材纤细,穿着淡蓝色古风汉服,气质清冷,神情平静,高细节人物刻画}{{爽快思思}}
  4986. 程景:偏执深情的学霸,为救许芸变得“不可见”,是始终默默守护的隐形爱人。他身材高大挺拔,面容英俊。{年轻男性反派,银白色短发,红色眼睛,面容冷峻,皮肤苍白,身穿黑色长袍,嘴角冷笑,气质危险,高细节人物刻画}{{阳光青年}{{阳光青年}}
  4987. ###场景列表
  4988. 徐家老旧厨房:这是徐母劳作和惩罚许芸的地方。空间狭窄阴暗,充满了生活琐碎的压抑感。室内有一个旧式锅炉,案板上散落着面粉和包好的馄饨,光影对比强烈,凸显出家庭环境的冷酷。{影视质感。广角。
  4989. 宽敞的天然山洞内部,石壁上错落有致地镶嵌着发光的萤石,散发出冷色调的微光,照亮了整个空间。洞顶有钟乳石垂下。光影层次丰富,营造出一种宁静而神圣的氛围。
  4990. 无人物。}
  4991. 徐家简陋客厅:半个月后冲突爆发的中心。陈设简单且陈旧,只有几把木凳和一张方桌。窗帘半掩,透进微弱的冷光,营造出一种暴风雨前的宁静与不安感。{影视质感。冷青色调,浓雾弥漫。
  4992. 一条通往西北方向的崎岖山间土路,两旁是枯萎的灌木和怪石嶙峋。地面湿滑,反光强烈。远方山峦在阴雨中若隐若现,营造出一种穷追不舍的紧张感。
  4993. 无人物。}
  4994. 老旧公寓门口:许芸逃出家门后回望的视点。门框斑驳,透出屋内昏暗压抑的光线,与室外略显空旷的走廊形成对比,象征着逃离与未知的守护。{
  4995. 豪华游轮内部宽敞的大堂或公共休息区。设计奢华,天花板高挑,有精致的装饰和柔和的暖色灯光。地面铺设着光洁的大理石,远处有巨大的落地窗,窗外是蓝色的海洋。自然光线充足,色彩明亮且饱和度适中,展现豪华游轮的质感。
  4996. 无人物。}
  4997. 破败巷弄与臭水沟:家门外的外部环境。一条狭窄、潮湿的巷弄,旁边是散发着冷气的臭水沟,水面偶尔泛起涟漪。这里是“透明守护者”受伤后经过的地方,氛围凄清。{
  4998. 宽敞明亮的现代风格客厅,家具摆放整齐,色调偏向冷灰与深蓝,营造一种沉静而略带压抑的氛围。窗外光线柔和,室内光影对比不强烈,整体干净整洁。
  4999. 无人物。}
  5000. 潮湿的巷弄地面:特写视角。灰色的水泥地面湿迹斑斑,这是许芸发现血脚印并进行最后告白的地方。强调地面的质感和清冷的基调。{
  5001. 一个现代居民小区的入口,有门卫岗亭和自动栏杆。道路宽阔,两旁绿化整齐,阳光明媚,整体色调略显冷峻,但光线清晰。
  5002. 无人物。}
  5003. ###分镜剧本
  5004. ##第1幕:徐家老旧厨房 白天 室内
  5005. 分镜1
  5006. 画面描述:许芸-校服装站在厨房门口,书包背在肩上,徐母手持扫帚,正对着许芸的背部猛烈挥打。卞大伟站在锅炉后方,双手抱胸,阴沉的目光落在许芸身上。
  5007. 场景:徐家老旧厨房
  5008. 构图设计:全景,低角度仰视
  5009. 运镜调度:手持拍摄
  5010. 配音角色:旁白
  5011. 出镜角色:许芸-校服装、徐母
  5012. 台词内容:我一到家,徐母的扫帚就落在我身上,嘴里一个劲地骂我,
  5013. 画面类型:普通画面
  5014. 尾帧描述:手持拍摄微晃镜头,中年妇女猛力挥动扫帚击打少女背部,少女身体因冲击微颤,阴影中的肥胖男子目光冷冷跟随。
  5015. 分镜2
  5016. 画面描述:徐母面容扭曲,嘴唇快速开合,扫帚挥舞在空中。
  5017. 场景:徐家老旧厨房
  5018. 构图设计:近景,徐母面部特写
  5019. 运镜调度:固定镜头
  5020. 配音角色:徐母
  5021. 出镜角色:徐母
  5022. 台词内容:问我夜不归宿死哪儿去了。
  5023. 画面类型:对口型
  5024. 尾帧描述:固定镜头,中年妇女面部肌肉剧烈抖动,嘴唇快速开合进行辱骂,背景中的扫帚在空中上下挥动。
  5025. ##第2幕:徐家简陋客厅 黄昏 室内
  5026. 分镜3
  5027. 画面描述:客厅窗户透出昏黄的夕阳余晖,空荡荡的客厅中央只有几把木凳和一张方桌,显得异常安静。
  5028. 场景:徐家简陋客厅
  5029. 构图设计:全景,景深虚化
  5030. 运镜调度:固定镜头
  5031. 配音角色:旁白
  5032. 出镜角色:无
  5033. 台词内容:可我没想到,半个月后,徐母居然再一次外出,
  5034. 画面类型:普通画面
  5035. 尾帧描述:固定镜头。昏黄的夕阳余晖在地面上缓慢移动,空气中的浮尘在光束中跳动,室内维持着死寂的安静。
  5036. 分镜4
  5037. 画面描述:一张泛黄的火车票特写,上面显示着隔壁市的站名和日期。
  5038. 场景:徐家简陋客厅
  5039. 构图设计:特写,火车票
  5040. 运镜调度:固定镜头
  5041. 配音角色:旁白
  5042. 出镜角色:无
  5043. 台词内容:这次是去隔壁市看望她生病的好姐妹。
  5044. 画面类型:普通画面
  5045. 尾帧描述:固定镜头。光影在火车票表面微微晃动,强调其陈旧的纸张纹理与关键的行程信息。
  5046. \n\n";
  5047. $origin_prompt = trim((string)getProp($data, 'prompt', '确认分镜大纲'));
  5048. $is_regenerate_version = !in_array($origin_prompt, ['确认分镜大纲', '继续策划下一集'], true);
  5049. $is_global_generate_pics = $origin_prompt == '确认分镜大纲' ? 1 : 0;
  5050. $prompt = $origin_prompt;
  5051. $is_single = (int)getProp($anime, 'is_multi') !== 1;
  5052. // 获取章节内容
  5053. $full_content = getProp($anime, 'content');
  5054. if ($uploaded_content) {
  5055. $full_content = $uploaded_content;
  5056. }
  5057. // 根据章节内容拆分章节
  5058. $chapters = splitContent($full_content);
  5059. $chapter_content = isset($chapters[($episode_number-1)]['content']) ? $chapters[($episode_number-1)]['content'] : '';
  5060. if (!$chapter_content) $chapter_content = $full_content; // 如果无法拆分章节则直接用原文
  5061. $messages = [];
  5062. if ($prompt == '确认分镜大纲') {
  5063. // 暂时保留
  5064. $content = $chapter_content;
  5065. if ($is_single) $content = $full_content; // 单剧集使用全文
  5066. if (!$content) {
  5067. Utils::throwError('20003:章节内容无法获取,请确认');
  5068. }
  5069. $question = $is_single
  5070. ? $demo . "请根据以上要求分析完整剧情,直接输出第1集完整单剧集分镜剧本,需一次性生成并可直接保存,剧情内容如下: \n\n$content"
  5071. : $demo . "请根据以上要求分析本章剧情,完成分镜剧本,本集剧情内容如下: \n\n$content";
  5072. // 构建消息
  5073. $messages[] =
  5074. [
  5075. 'role' => 'user',
  5076. 'content' => $question
  5077. ];
  5078. }else if ($prompt == '继续策划下一集') {
  5079. if ($is_single) {
  5080. Utils::throwError('20003:单剧集不支持继续策划下一集');
  5081. }
  5082. $content = $chapter_content;
  5083. if (!$content) {
  5084. Utils::throwError('20003:章节内容无法获取,请确认');
  5085. }
  5086. $question = $demo."请根据以上要求分析本集剧情内容,完成本集分镜剧本(需衔接上一集内容)";
  5087. // 获取上一集最后记录
  5088. $prev_sequence = $episode_number - 1;
  5089. $messages = $this->getEpisodeChatContent($anime_id, $prev_sequence, $content);
  5090. // 构建消息
  5091. $messages[] =
  5092. [
  5093. 'role' => 'user',
  5094. 'content' => $question
  5095. ];
  5096. }else {
  5097. $content = $uploaded_content ? $chapter_content : trim((string)getProp($base_episode, 'content'));
  5098. if (!$content) {
  5099. $content = $is_single ? $full_content : ($chapter_content ?: $full_content);
  5100. }
  5101. if (!$content) {
  5102. Utils::throwError('20003:章节内容无法获取,请确认');
  5103. }
  5104. $messages = $this->getEpisodeChatMessages($anime_id, $episode_number);
  5105. $targetEpisodeText = $is_single ? '第1集完整单剧集版本' : "第{$episode_number}集完整的新版本剧集";
  5106. $question = $demo . "\n请基于以上历史对话记录,重新生成{$targetEpisodeText},并严格按示例格式输出完整内容。\n";
  5107. if ($origin_prompt) {
  5108. $question .= "\n本次修改要求如下:\n{$origin_prompt}";
  5109. }
  5110. $messages[] =
  5111. [
  5112. 'role' => 'user',
  5113. 'content' => $question
  5114. ];
  5115. }
  5116. // 处理文本模型
  5117. $model = getProp($data, 'model');
  5118. if (!$model) {
  5119. // 用户没有输入,从anime表获取
  5120. $anime = DB::table('mp_animes')->where('id', $anime_id)->first();
  5121. $model = getProp($anime, 'model');
  5122. if (!$model) {
  5123. // anime表也没有,使用默认值
  5124. $model = 'doubao-seed-2-0-mini-260215';
  5125. }
  5126. }
  5127. // 验证模型是否在可用模型表中
  5128. if (!DB::table('mp_text_models')->where('model', $model)->where('is_enabled', 1)->exists()) {
  5129. $model = 'doubao-seed-2-0-mini-260215';
  5130. }
  5131. // 模型兼容性处理:deepseek-chat 和 deepseek-reasoner 映射到 deepseek-v4-flash
  5132. $thinkingMode = getProp($data, 'thinking', 'disabled'); // 默认非思考模式
  5133. $reasoningEffort = getProp($data, 'reasoning_effort', 'high'); // 默认思考强度
  5134. if ($model === 'deepseek-chat') {
  5135. // deepseek-chat 映射到 deepseek-v4-flash,非思考模式
  5136. $model = 'deepseek-v4-flash';
  5137. $thinkingMode = 'disabled';
  5138. } elseif ($model === 'deepseek-reasoner') {
  5139. // deepseek-reasoner 映射到 deepseek-v4-flash,思考模式
  5140. $model = 'deepseek-v4-flash';
  5141. $thinkingMode = 'enabled';
  5142. }
  5143. $post_data = [
  5144. 'model' => $model,
  5145. 'messages' => $messages,
  5146. // 'max_tokens' => 8192,
  5147. 'temperature' => 0.2,
  5148. 'frequency_penalty' => 0,
  5149. 'presence_penalty' => 0,
  5150. 'response_format' => ['type' => 'text'],
  5151. 'thinking' => ['type' => $thinkingMode],
  5152. 'stream' => true // 启用流式输出
  5153. ];
  5154. if ($thinkingMode == 'enabled') $post_data['reasoning_effort'] = $reasoningEffort;
  5155. // 根据模型类型选择调用方法
  5156. $fullContent = '';
  5157. $fullReasoningContent = '';
  5158. $usage = [];
  5159. try {
  5160. if (in_array($model, ['deepseek-reasoner', 'deepseek-chat', 'deepseek-v4-flash', 'deepseek-v4-pro'])) {
  5161. // DeepSeek 官方模型使用 DeepSeek API
  5162. $streamGenerator = $this->deepSeekStreamResponse($post_data);
  5163. } else if (in_array($model, $this->gpt_text_models)) {
  5164. // GPT-5.4 模型使用 TokenRouter API
  5165. $streamGenerator = $this->gpt54StreamResponse($post_data);
  5166. } else {
  5167. // 其他模型使用火山引擎API
  5168. $streamGenerator = $this->volcEngineChatCompletion($post_data);
  5169. }
  5170. // 验证返回值类型
  5171. if (!is_iterable($streamGenerator)) {
  5172. $errorType = is_object($streamGenerator) ? get_class($streamGenerator) : gettype($streamGenerator);
  5173. dLog('deepseek')->error('chat流式生成器无效', [
  5174. 'generator_type' => $errorType,
  5175. 'model' => $model,
  5176. 'anime_id' => $anime_id,
  5177. 'episode_number' => $episode_number
  5178. ]);
  5179. logDB('deepseek', 'error', 'chat流式生成器类型错误', [
  5180. 'type' => $errorType,
  5181. 'model' => $model
  5182. ]);
  5183. yield [
  5184. 'type' => 'error',
  5185. 'episode' => [],
  5186. 'answer' => '',
  5187. 'reasoning' => '',
  5188. 'usage' => [],
  5189. 'error' => '接口返回数据异常,请重新请求'
  5190. ];
  5191. return;
  5192. }
  5193. // 处理流式输出
  5194. foreach ($streamGenerator as $chunk) {
  5195. if (isset($chunk['type'])) {
  5196. if ($chunk['type'] === 'done') {
  5197. // 最终结果
  5198. $fullContent = $chunk['full_content'];
  5199. $fullReasoningContent = $chunk['full_reasoning'];
  5200. $usage = isset($chunk['usage']) ? $chunk['usage'] : [];
  5201. } else {
  5202. // 逐块yield数据
  5203. yield $chunk;
  5204. }
  5205. }
  5206. }
  5207. } catch (\Exception $e) {
  5208. dLog('deepseek')->error('chat流式处理异常: ' . $e->getMessage(), [
  5209. 'model' => $model,
  5210. 'anime_id' => $anime_id,
  5211. 'episode_number' => $episode_number,
  5212. 'trace' => $e->getTraceAsString()
  5213. ]);
  5214. logDB('deepseek', 'error', 'chat流式处理失败', [
  5215. 'error' => $e->getMessage(),
  5216. 'model' => $model
  5217. ]);
  5218. yield [
  5219. 'type' => 'error',
  5220. 'episode' => [],
  5221. 'answer' => '',
  5222. 'reasoning' => '',
  5223. 'usage' => [],
  5224. 'error' => '处理请求时发生异常: ' . $e->getMessage()
  5225. ];
  5226. return;
  5227. }
  5228. dLog('deepseek')->info('完整内容: '.$fullContent);
  5229. logDB('deepseek', 'info', '完整内容', ['content' => $fullContent, 'anime_id' => $anime_id]);
  5230. // 处理完整内容并返回最终结果
  5231. $episode_arr = handleEpisodeContent($fullContent);
  5232. logDB('deepseek', 'info', '解析内容', $episode_arr);
  5233. if (empty($episode_arr['acts'])) {
  5234. // 未生成剧本相关内容,保存对话记录并返回提示
  5235. dLog('deepseek')->info('未生成分镜剧本相关的内容');
  5236. try {
  5237. $now = date('Y-m-d H:i:s');
  5238. // 保存对话记录
  5239. $records = [
  5240. [
  5241. 'uid' => $uid,
  5242. 'anime_id' => $anime_id,
  5243. 'sequence' => $episode_number,
  5244. 'role' => 'user',
  5245. 'content' => $prompt,
  5246. 'created_at' => $now,
  5247. 'updated_at' => $now
  5248. ],
  5249. [
  5250. 'uid' => $uid,
  5251. 'anime_id' => $anime_id,
  5252. 'sequence' => $episode_number,
  5253. 'role' => 'assistant',
  5254. 'content' => $fullContent,
  5255. // 'content' => '我已按照您的要求完成策划并将内容更新到您右侧的策划文档。',
  5256. 'created_at' => $now,
  5257. 'updated_at' => $now
  5258. ]
  5259. ];
  5260. DB::table('mp_anime_records')->insert($records);
  5261. } catch (\Exception $e) {
  5262. dLog('deepseek')->error('保存对话记录失败', ['error' => $e->getMessage()]);
  5263. }
  5264. yield [
  5265. 'type' => 'done',
  5266. 'episode' => [],
  5267. 'answer' => $fullContent,
  5268. 'reasoning' => $fullReasoningContent,
  5269. 'usage' => $usage,
  5270. 'error' => '未生成分镜剧本相关的内容,请调整提示词再试'
  5271. ];
  5272. return;
  5273. }
  5274. $existing_roles = $base_episode ? json_decode((string)getProp($base_episode, 'roles'), true) : [];
  5275. $existing_scenes = $base_episode ? json_decode((string)getProp($base_episode, 'scenes'), true) : [];
  5276. $existing_props = $base_episode ? json_decode((string)getProp($base_episode, 'props'), true) : [];
  5277. $existing_roles = is_array($existing_roles) ? $existing_roles : [];
  5278. $existing_scenes = is_array($existing_scenes) ? $existing_scenes : [];
  5279. $existing_props = is_array($existing_props) ? $existing_props : [];
  5280. $now = date('Y-m-d H:i:s');
  5281. try {
  5282. DB::beginTransaction();
  5283. $saveResult = $this->saveEpisodeVersionData(
  5284. $anime_id,
  5285. $episode_number,
  5286. $episode_arr,
  5287. $existing_roles,
  5288. $existing_scenes,
  5289. $existing_props,
  5290. $current_episode,
  5291. $base_episode,
  5292. $is_regenerate_version,
  5293. $content,
  5294. $now
  5295. );
  5296. $episode = $saveResult['episode'];
  5297. $episode_id = $saveResult['episode_id'];
  5298. $merged_roles = $saveResult['merged_roles'];
  5299. $merged_scenes = $saveResult['merged_scenes'];
  5300. $merged_props = $saveResult['merged_props'];
  5301. $record_content = $origin_prompt;
  5302. if ($uploaded_content !== '') {
  5303. // $record_content .= "\n\n###上传内容\n" . $uploaded_content;
  5304. }
  5305. $records = [
  5306. [
  5307. 'uid' => $uid,
  5308. 'anime_id' => $anime_id,
  5309. 'role' => 'user',
  5310. 'content' => $record_content,
  5311. 'sequence' => $episode_number,
  5312. 'episode_id' => $episode_id,
  5313. 'created_at' => $now,
  5314. 'updated_at' => $now
  5315. ],
  5316. [
  5317. 'uid' => $uid,
  5318. 'anime_id' => $anime_id,
  5319. 'role' => 'assistant',
  5320. 'content' => $fullContent,
  5321. // 'content' => '我已按照您的要求完成策划并将内容更新到您右侧的策划文档。',
  5322. 'sequence' => $episode_number,
  5323. 'episode_id' => $episode_id,
  5324. 'created_at' => $now,
  5325. 'updated_at' => $now
  5326. ]
  5327. ];
  5328. $boolen4 = DB::table('mp_anime_records')->insert($records);
  5329. if (!$boolen4) {
  5330. Utils::throwError('20003:对话记录保存失败');
  5331. }
  5332. // 保存模型和内容到anime表
  5333. $update_anime_data = [
  5334. 'model' => $model,
  5335. 'updated_at' => $now
  5336. ];
  5337. if ($uploaded_content) {
  5338. $update_anime_data['content'] = $uploaded_content;
  5339. }
  5340. DB::table('mp_animes')->where('id', $anime_id)->update($update_anime_data);
  5341. }catch (\Exception $e) {
  5342. DB::rollBack();
  5343. dLog('deepseek')->info('新建对话错误信息: '.$e->getMessage());
  5344. yield [
  5345. 'type' => 'done',
  5346. 'answer' => $fullContent,
  5347. 'reasoning' => $fullReasoningContent,
  5348. 'usage' => $usage,
  5349. 'error' => $e->getMessage(),
  5350. ];
  5351. return;
  5352. }
  5353. DB::commit();
  5354. if ($is_global_generate_pics) {
  5355. // // 批量生成全局角色图片
  5356. // $this->batchSetGlobalRoleImg([
  5357. // 'anime_id' => $anime_id,
  5358. // ], true);
  5359. // // 批量生成全局场景图片
  5360. // $this->batchSetGlobalSceneImg([
  5361. // 'anime_id' => $anime_id,
  5362. // ], true);
  5363. // // 将全局角色和场景的task_id、task_status和url继承给当前分集
  5364. // $this->inheritGlobalImagesToEpisodes($anime_id, $episode_id);
  5365. }
  5366. $episode['episode_id'] = $episode_id;
  5367. $episode['roles'] = $merged_roles;
  5368. $episode['scenes'] = $merged_scenes;
  5369. $episode['acts'] = isset($episode_arr['acts']) && is_array($episode_arr['acts']) ? $episode_arr['acts'] : [];
  5370. yield [
  5371. 'type' => 'done',
  5372. 'episode' => $episode,
  5373. 'answer' => $fullContent,
  5374. 'reasoning' => $fullReasoningContent,
  5375. 'usage' => $usage
  5376. ];
  5377. }
  5378. public function addChatForAce($data) {
  5379. $uid = Site::getUid();
  5380. $anime_id = getProp($data, 'anime_id');
  5381. if (!$anime_id) Utils::throwError('20003:请选择对话');
  5382. $anime = DB::table('mp_animes')->where('id', $anime_id)->where('is_deleted', 0)->first();
  5383. if (!$anime) Utils::throwError('20003:对话不存在');
  5384. $file = getProp($data, 'file');
  5385. $content = getProp($data, 'content', '');
  5386. $bid = getProp($data, 'bid', 0);
  5387. $script_id = getProp($data, 'script_id', 0);
  5388. $ace_mode = getProp($data, 'ace_mode', 0) ? getProp($data, 'ace_mode', 0) : getProp($anime, 'ace_mode', 0);
  5389. $prompt = getProp($data, 'prompt');
  5390. $is_multi = getProp($anime, 'is_multi');
  5391. $is_single = (int)$is_multi !== 1;
  5392. $extra_products = getProp($data, 'products', []);
  5393. if (!$extra_products) {
  5394. $extra_products = getProp($anime, 'extra_products');
  5395. if ($extra_products) {
  5396. $extra_products = json_decode($extra_products, true);
  5397. }else {
  5398. $extra_products = [];
  5399. }
  5400. }else {
  5401. if (is_string($extra_products)) $extra_products = json_decode($extra_products, true);
  5402. }
  5403. // 如果anime有关联的script_id,则从mp_script_product_mappings中查询资产并合并到extra_products
  5404. $anime_script_id = getProp($anime, 'script_id');
  5405. if ($anime_script_id && $is_single) { // 单剧集模式下才使用全部资产库
  5406. $cpid = Site::getCpid();
  5407. $script_products_mappings = DB::table('mp_script_product_mappings as mapping')
  5408. ->join('mp_products as product', 'mapping.product_id', '=', 'product.id')
  5409. ->where('mapping.script_id', $anime_script_id)
  5410. ->where('product.cpid', $cpid)
  5411. ->where('product.is_deleted', 0);
  5412. $mappings = $script_products_mappings->select(
  5413. 'mapping.product_id',
  5414. 'mapping.episode_number',
  5415. 'product.product_name',
  5416. 'product.type',
  5417. 'product.product',
  5418. 'product.pic_prompt',
  5419. 'product.url',
  5420. 'product.pic_task_id',
  5421. 'product.pic_task_status',
  5422. 'product.three_view_image_url'
  5423. )
  5424. ->get();
  5425. // 按 product_id 分组,合并 episode_number
  5426. $productMap = [];
  5427. foreach ($mappings as $item) {
  5428. $product_id = $item->product_id;
  5429. $product_name = $item->product_name;
  5430. // 处理product_name两边的符号
  5431. $product_name = preg_replace('/^[\s*\[\]【】[]{}{}\x{3000}]+|[\s*\[\]【】[]{}{}\x{3000}]+$/u', '', $product_name);
  5432. if (!isset($productMap[$product_id])) {
  5433. $productMap[$product_id] = [
  5434. 'product_id' => $product_id,
  5435. 'product_name' => $product_name,
  5436. 'type' => (int)$item->type,
  5437. 'product' => (int)$item->product,
  5438. 'pic_prompt' => $item->pic_prompt,
  5439. 'url' => $item->url,
  5440. 'pic_task_id' => $item->pic_task_id,
  5441. 'pic_task_status' => $item->pic_task_status,
  5442. 'episode_numbers' => [],
  5443. ];
  5444. }
  5445. // 添加 episode_number(去重)
  5446. if (!in_array($item->episode_number, $productMap[$product_id]['episode_numbers'])) {
  5447. $productMap[$product_id]['episode_numbers'][] = $item->episode_number;
  5448. }
  5449. }
  5450. // 将查询到的剧本资产合并到extra_products中
  5451. // 先构建extra_products的索引(以product_id为key,用于去重)
  5452. $extraProductsMap = [];
  5453. foreach ($extra_products as $item) {
  5454. $key = getProp($item, 'product_id');
  5455. if ($key) {
  5456. $extraProductsMap[$key] = $item;
  5457. }
  5458. }
  5459. // 合并剧本资产(去重:仅按product_id去重,不考虑episode_number)
  5460. foreach ($productMap as $product) {
  5461. $product_id = $product['product_id'];
  5462. // 如果不存在则添加(不带episode_number信息)
  5463. if (!isset($extraProductsMap[$product_id])) {
  5464. $extraProductsMap[$product_id] = [
  5465. 'product_id' => $product['product_id'],
  5466. 'product_name' => $product['product_name'],
  5467. 'type' => $product['type'],
  5468. 'product' => $product['product'],
  5469. 'pic_prompt' => $product['pic_prompt'],
  5470. 'url' => $product['url'],
  5471. 'pic_task_id' => $product['pic_task_id'],
  5472. 'pic_task_status' => $product['pic_task_status'],
  5473. ];
  5474. }
  5475. }
  5476. // 重新赋值给extra_products
  5477. $extra_products = array_values($extraProductsMap);
  5478. }
  5479. $user_anime_name = getProp($anime, 'anime_name');
  5480. // 处理提示词
  5481. if ($prompt && $extra_products) {
  5482. // 遍历extra_products,将prompt中的{product_name}替换为实际的product_name
  5483. foreach($extra_products as $item) {
  5484. $product_name = getProp($item, 'product_name');
  5485. if ($product_name) {
  5486. // 替换 {product_name} 为 product_name
  5487. $prompt = str_replace('{' . $product_name . '}', $product_name, $prompt);
  5488. }
  5489. }
  5490. }
  5491. // 处理文本模型
  5492. $model = getProp($data, 'model');
  5493. if (!$model) {
  5494. // 用户没有输入,从anime表获取
  5495. $model = getProp($anime, 'model');
  5496. if (!$model) {
  5497. // anime表也没有,使用默认值
  5498. $model = 'deepseek-v4-pro';
  5499. }
  5500. }
  5501. // 验证模型是否在可用模型表中
  5502. if (!DB::table('mp_text_models')->where('model', $model)->where('is_enabled', 1)->exists()) {
  5503. $model = 'deepseek-v4-pro';
  5504. }
  5505. $question = getProp($data, 'question', $is_single ? "请根据实例格式完成单剧集剧本及分段\n" : "请根据实例格式完成剧本大纲\n");
  5506. if ($prompt) {
  5507. $question .= "本次修改要求如下:\n{$prompt}";
  5508. }
  5509. // if (!$file && !$content && !$bid) {
  5510. // Utils::throwError('20003:请上传文件或选择书籍或输入内容');
  5511. // }
  5512. // 提取文件内容
  5513. if ($file) {
  5514. $content = $this->extractFileContent($file);
  5515. if (!$content) {
  5516. Utils::throwError('20003:无法提取文件内容,请检查文件格式');
  5517. }
  5518. } elseif ($script_id) {
  5519. $content = $this->getContentByScriptId($script_id);
  5520. if (!$content) {
  5521. Utils::throwError('20003:无法获取剧本内容,请检查剧本');
  5522. }
  5523. } elseif ($bid) {
  5524. $content = $this->getContentByBid($bid);
  5525. if (!$content) {
  5526. Utils::throwError('20003:无法获取书籍内容,请检查书籍');
  5527. }
  5528. } elseif ($content) {
  5529. $content = filterContent($content);
  5530. } else {
  5531. $content = getProp($anime, 'content');
  5532. if (!$content && $prompt) { // 如果动漫记录中没有内容则根据提示词生成
  5533. $need_generate_content = true;
  5534. }
  5535. }
  5536. // 美术风格
  5537. $input_art_style = getProp($data, 'art_style');
  5538. if (!$input_art_style) {
  5539. $mappedArtStyle = getProp($anime, 'art_style');
  5540. }else {
  5541. $mappedArtStyle = $this->getArtStylePromptByInput($input_art_style);
  5542. }
  5543. // 判断是否需要生成原文内容
  5544. $need_generate_content = isset($need_generate_content) && $need_generate_content;
  5545. // 如果需要生成原文内容,添加额外的要求
  5546. $content_generation_requirement = $need_generate_content
  5547. ? "\n5.如果用户只提供了创作要求而没有提供具体文档内容,你需要根据要求创作完整的原文内容(小说形式,包含对话和叙述),并将原文内容放在最后一个板块###原文内容中输出。原文内容应该详细、生动,如果用户没有明确生成的字数,则字数不少于1000字。"
  5548. : "";
  5549. // 美术风格
  5550. if (!$mappedArtStyle) {
  5551. $mappedArtStyle_prompt = '美术风格:根据剧本内容自定义美术风格';
  5552. }else {
  5553. if (strstr($mappedArtStyle, '基础画风风格词')) {
  5554. $mappedArtStyle_prompt = "美术风格强制设置如下(原样输出,不得更改任何内容):\n{$mappedArtStyle}\n";
  5555. }else {
  5556. $art_style_type = $input_art_style ? $input_art_style : getProp($anime, 'art_style_type');
  5557. $mappedArtStyle_prompt = "美术风格强制设置如下(原样输出,不得更改任何内容):\n基础画风风格词: {$art_style_type}\n{$mappedArtStyle}\n";
  5558. }
  5559. }
  5560. // 构建主体、场景和道具提示词
  5561. $extra_role_prompt = "\n";
  5562. $extra_scene_prompt = "\n";
  5563. $extra_prop_prompt = "\n";
  5564. $ref_products = []; // 参考资产
  5565. if ($extra_products) {
  5566. foreach($extra_products as $item) {
  5567. $product = getProp($item, 'product');
  5568. $product_name = getProp($item, 'product_name');
  5569. if ($product_name == '旁白') continue;
  5570. $ref_products[$product_name] = $item;
  5571. $pic_prompt = getProp($item, 'pic_prompt');
  5572. if ((int)$product === 1) {
  5573. // 拼接角色信息
  5574. $extra_role_prompt .= $product_name . ":" . $pic_prompt . "\n";
  5575. } elseif ((int)$product === 2) {
  5576. // 拼接场景信息
  5577. $extra_scene_prompt .= $product_name . ":" . $pic_prompt . "\n";
  5578. } elseif ((int)$product === 3) {
  5579. // 拼接道具信息
  5580. $extra_prop_prompt .= $product_name . ":" . $pic_prompt . "\n";
  5581. }
  5582. }
  5583. // 优化提示词,融入剧本
  5584. if (!empty(trim($extra_role_prompt))) {
  5585. $extra_role_prompt = "\n【强制主体设定-优先级最高-不可修改】\n以下主体必须全部出现在<主体列表>中,必须包含:\n" . $extra_role_prompt . "\n格式要求:\n1. 主体名称:必须保持不变\n2. 主体描述:你必须根据剧情为每个主体生成主体描述(分析人物在整部剧中的姓名、年龄、性格特征、社会身份或职业背景、个人成长经历或核心故事动机,以及在剧情中的目标与行为驱动力,用一句话进行总结)\n3. 人物提示词:{}中的内容必须完整保留,不得修改\n4. 音色提示词:你必须根据角色特征生成音色提示词(描述角色的整体音色特征,包含:性别、年龄、音质、表达形式、情绪氛围,字数控制在80字以内),用{{}}框起来\n\n最终格式必须为:主体名:[你生成的主体描述]{人物提示词-保持不变}{{你生成的音色提示词}}\n\n【重要】以上每个主体在<主体列表>中的完整格式必须是:主体名:主体描述{人物提示词}{{音色提示词}},其中主体描述和音色提示词是你必须生成的内容,{}中的人物提示词必须原样保留。";
  5586. }
  5587. if (!empty(trim($extra_scene_prompt))) {
  5588. $extra_scene_prompt = "\n【强制场景设定-优先级最高-不可修改】\n以下场景必须全部出现在<场景列表>中,必须包含:\n" . $extra_scene_prompt . "\n格式要求:\n1. 场景名称:必须保持不变\n2. 场景描述:你必须根据剧情为每个场景生成符合<普通要求3.2>的场景描述(分析在整部剧中出现过的场景,场景描述尽量简洁贴合原文)\n3. 场景提示词:{}中的内容必须完整保留,不得修改\n\n最终格式必须为:场景名:[你生成的场景描述]{场景提示词-保持不变}\n\n必须包含的场景列表:\n" . $extra_scene_prompt . "\n【重要提示】以上每个场景在<场景列表>中的完整格式必须是:场景名:场景描述{场景提示词},其中场景描述是你必须生成的内容,{}中的场景提示词必须原样保留。";
  5589. }
  5590. if (!empty(trim($extra_prop_prompt))) {
  5591. $extra_prop_prompt = "\n【强制道具设定-优先级最高-不可修改】\n以下道具必须全部出现在<道具列表>中,必须包含:\n" . $extra_prop_prompt . "\n格式要求:\n1. 道具名称:必须保持不变\n2. 道具描述:你必须根据剧情为每个道具生成道具描述(分析在整部剧中出现过的道具,道具描述尽量简洁贴合原文)\n3. 道具提示词:{}中的内容必须完整保留,不得修改\n\n最终格式必须为:道具名:[你生成的道具描述]{道具提示词-保持不变}\n\n必须包含的道具列表:\n" . $extra_prop_prompt . "\n【重要提示】以上每个道具在<道具列表>中的完整格式必须是:道具名:道具描述{道具提示词},其中道具描述是你必须生成的内容,{}中的道具提示词必须原样保留。";
  5592. }
  5593. }
  5594. if ($anime_script_id && $is_single) {
  5595. $role_demo = "2.<主体列表>只能使用以下主体,不得自定义内容(必需带上冒号后的具体描述以及{}和{{}}中的内容,原样输出)。{$extra_role_prompt}";
  5596. $scene_demo = "3.<场景列表>只能使用以下场景,不得自定义内容(必需带上冒号后的具体描述以及{}和{{}}中的内容,原样输出)。{$extra_scene_prompt}";
  5597. $prop_demo = "4.<道具列表>只能使用以下道具,不得自定义内容(必需带上冒号后的具体描述以及{}和{{}}中的内容,原样输出)。{$extra_prop_prompt}";
  5598. }else {
  5599. $role_demo = "2.<主体列表>中出现的“主体名”必须尽可能统一,严禁出现角色-科学家、角色-复仇者、角色-领导者等带有身份、职业、标签类的命名,只能使用服装差异(如校服装、卫衣装、西装)来区分同一角色,如角色-校服装等。
  5600. 2.1<主体列表>分以下三部分(强制格式):主体描述、人物提示词和音色提示词,格式必须为:主体名:主体描述{人物提示词}{{音色提示词}}
  5601. 2.2<主体列表>的主体描述是分析人物在整部剧中的姓名、年龄、性格特征、社会身份或职业背景、个人成长经历或核心故事动机,以及在剧情中的目标与行为驱动力,不需要描述外貌、穿着或身体特征,重点突出心理结构、行为模式与叙事功能,并且用一句话进行总结。
  5602. 2.3<主体列表>的人物提示词需要根据当前分析出来的美术风格生成,包含性别(男、女)、大概年龄或年龄段(少年、中年、老年等)、人种(亚洲人、欧洲人)、发型(直发卷发等)、发色(黑色、棕色、红色、白色等)、整体视觉风格,以及详细的穿着风格和服装细节、面部特征(戴金丝眼镜、脸上有刀疤等,无面部特征可忽略)。描述需具有镜头感与画面表现力,适合直接用于AI图像生成模型,避免抽象词汇,强调具体可视化细节与整体视觉一致性,同时保证风格统一且符合人物身份设定。该提示词(字数50-100字左右)在主体描述后用{}框起来。
  5603. 2.4<主体列表>的音色提示词放在描述的最后用{{}}框起来。音色提示词需描述角色的整体音色特征,包含:性别、年龄(约XX岁)、音质(如清冷、沉稳、磁性等)、表达形式(如叙述感、旁白式等)、情绪氛围(如空灵韵味、看透世事的清冷等),字数控制在80字以内。举例:成年女性(约25-35岁),音色清冷且富有叙述感,语速平缓,带有仙侠剧特有的空灵韵味。
  5604. {$extra_role_prompt}";
  5605. $scene_demo = "3.<场景列表>与主体列表同理,需尽可能的对场景环境进行详细描述,必须严格注意不要出现任何角色和人物。
  5606. 3.1<场景列表>分以下两部分(强制格式):场景描述和场景提示词,格式必须为:场景描述{场景提示词}
  5607. 3.2<场景列表>的场景描述是分析在整部剧中出现过的场景,场景描述尽量简洁贴合原文。
  5608. 3.3<场景列表>的场景提示词用于视觉呈现的场景环境描述,该场景需包含环境氛围、光线效果、空间布局、色彩基调、视觉风格等,描述需具有镜头感与画面表现力,适合直接用于AI图像生成模型,避免抽象词汇,强调具体可视化细节与整体视觉一致性,同时保证风格统一且符合剧情设定(可参考以下示例的场景列表中使用{}框起来的提示词,字数150-200字,需带上提炼出来的美术风格)。该提示词在场景描述后用{}框起来。\n
  5609. {$extra_scene_prompt}";
  5610. $prop_demo = "4<道具列表>与场景列表同理,需尽可能的对道具环境进行详细描述,必须严格注意不要出现任何角色和人物。
  5611. 4.1<道具列表>分以下两部分(强制格式):道具描述和道具提示词,格式必须为:道具描述{道具提示词}
  5612. 4.2<道具列表>的道具描述是分析在整部剧中出现过的道具,道具描述尽量简洁贴合原文。
  5613. 4.3<道具列表>的道具提示词用于视觉呈现的道具环境描述,该道具需包含环境氛围、光线效果、空间布局、色彩基调、视觉风格等,描述需具有镜头感与画面表现力,适合直接用于AI图像生成模型,避免抽象词汇,强调具体可视化细节与整体视觉一致性,同时保证风格统一且符合剧情设定(可参考以下示例的道具列表中使用{}框起来的提示词,字数150-200字,需带上提炼出来的美术风格)。该提示词在道具描述后用{}框起来。\n
  5614. {$extra_prop_prompt}";
  5615. }
  5616. $systemPrompt = $is_single
  5617. ? "你是一个专业的文档分析助手及资深编剧,请根据用户提供的文档内容输出单剧集完整策划稿(剧本大纲包括: <故事梗概><剧本亮点><人物关系><核心矛盾><主体列表><美术风格><场景列表><道具列表><分段剧本>,每个板块之间必须使用###分隔,#不能多也不能少)。单剧集模式下,必须一次性输出可直接保存的大纲与完整分镜,不允许只输出大纲。
  5618. 强制要求:
  5619. 1.你只负责与剧本相关的内容,如果用户输入与剧本无关的内容,请告知用户并拒绝继续回答,此为第一优先原则,不满足此原则就忽略其他要求并停止继续输出
  5620. 2.如果用户输入修改美术风格、修改画风这类内容,请告知用户不可修改美术风格,并拒绝继续回答
  5621. 3.以上两条要求对修改主体角色或场景不生效,允许用户调整主体角色说明和场景描述等
  5622. 4.用户如果要求你帮忙写一个故事或者剧本,此类要求不属于与剧本无关,请帮助用户完成请求{$content_generation_requirement}
  5623. 5.强制按照示例格式返回内容,不要更改格式或随意增加符号\n
  5624. 普通要求:
  5625. 1.剧本名(必须生成)和剧集标题必须与文档内容高度相关,(其中剧集序号是1)。
  5626. $role_demo
  5627. $scene_demo
  5628. $prop_demo
  5629. 5.<分段剧本>按照“分段模式”进行拆分和组织,要求如下:
  5630. 5.1片段分割逻辑(优先级从高到低):
  5631. - 第一优先级:时长上限(单个片段不超过15秒,超过必须切为新片段)
  5632. - 第二优先级:叙事节拍Beat(一个完整的事件/动作/情绪起落单元,如一段对话的来回、一个动作序列:推门→看见→震惊、一次闪回/回忆、旁白+画面组合)
  5633. - 第三优先级:语义块(按“谁、在哪、做什么、情绪怎样”聚合,如同一段旁白/独白、同一个角色的连续动作、同一个视角的连续镜头)
  5634. - 只要事件没结束、情绪没断,哪怕换场景,也留在同一个片段里
  5635. 5.2片段结构:片段数量+旁白音色+多个片段(每个片段由多个分镜组合而成(片段序号格式:片段1、片段2...))
  5636. - 片段数量格式为: 片段数量:8
  5637. - 旁白音色需描述旁白的整体音色特征,包含:性别、年龄(约XX岁)、音质(如清冷、沉稳、磁性等)、表达形式(如叙述感、旁白式等)、情绪氛围(如空灵韵味、看透世事的清冷等),字数控制在80字以内。举例:成年女性(约25-35岁),音色清冷且富有叙述感,语速平缓,带有仙侠剧特有的空灵韵味。
  5638. - 片段序号格式必须如下: ##片段+片段序号\n时长:xxs,例如: ##片段1\n时长:12s
  5639. 5.3分镜结构:每个分镜包含以下字段:
  5640. - 分镜序号在片段内用1、2、3显示,如分镜1、分镜2,并且分镜序号需连续(跨片段中的分镜序号需连续,如片段2中的分镜序号从片段1的最大序号+1开始),分镜序号前后不要带任何其他符号,特别是*符号。
  5641. - 出场角色: 如果有主体出现在本镜,则必须选择本集中的<主体列表>中的一个(如必须使用“沈秋岚-程家居家围裙造型”,而不是“沈秋岚”,不得缺少“-”前后和“:”前面的任何内容,不能自创)
  5642. - 场景:必须选择本集中的<场景列表>中的一个(如需使用“酒店会客室-景池筹备会版”,而不是“酒店会客室”,不得缺少“-”前后和“:”前面的任何内容,不能自创)
  5643. - 出场道具:如果有道具出现在本镜,则必须选择本集中的<道具列表>中的一个(如需使用“酒杯-高脚杯”,而不是“酒杯”或“高脚杯”,不得缺少“-”前后和“:”前面的任何内容,不能自创)
  5644. - 画面:【构图/视角】+画面描述(越简单越好,对视觉场景/实景的描述,不描述氛围,比如紧张、压抑的氛围)。举例:[近景特写,浅景深]季潇握着手机贴在耳边,指关节因为用力而泛白。她的眼眶微红,睫毛在狂风中颤抖,嘴唇紧抿,眼神中闪烁着最后一点希冀的微光。
  5645. - 【强制要求-非常关键】画面中如果出现主体,只能选择上述<主体列表>中的一个,主体的名称也必须保持一致(如必须使用“沈秋岚-程家居家围裙造型”,而不是“沈秋岚”,不得缺少“-”前后和“:”前面的任何内容,不能自创)
  5646. - 【强制要求-非常关键】画面中如果出现道具,只能选择上述<道具列表>中的一个,道具的名称也必须保持一致(如必须使用“酒杯-高脚杯”,而不是“酒杯”或“高脚杯”,不得缺少“-”前后和“:”前面的任何内容,不能自创)
  5647. - 运镜:场景+画面描述+运镜
  5648. - 【强制要求-非常关键】运镜描述中如果出现主体或道具,逻辑需同画面一直,必须选择<主体列表>或<道具列表>中的一个,名称也必须保持一致
  5649. - 配音台词:格式为“中文配音:[角色]台词”,角色配音台词和语言由模型匹配生成,角色必须对应本集中的<主体列表>中的一个(非对话内容则统一固定为“旁白”角色,[角色]的角色名必须完整使用主体列表的主体名,如必须使用“沈秋岚-程家居家围裙造型”,而不是“沈秋岚”,不得缺少“-”前后和“:”前面的任何内容,不能自创,不能自创)
  5650. - 台词内容需满足以下要求: (1. 台词来源规则:台词内容必须逐字摘录自小说原文中的人物直接对话(带引号的内容),不允许改写、总结、压缩、扩写或拼接原文对白,不允许生成原文中不存在的对话。2. 非对话过滤:旁白、心理描写、环境描写、动作描写等内容,禁止出现在台词内容中。3. 空台词规则:如果该分镜中没有人物对话,则“台词内容”必须返回“无”,严禁输出“无台词”、“没有”等任何替代文本。4. 禁止推测:不得根据语境补全人物可能说的话。5.如果没有原文,直接返回空)
  5651. - 背景音效:背景音效需根据内容和画面生成,贴合当前画面描述和动作,例如:背景音效:高跟鞋的脚本声\n
  5652. 6.{$mappedArtStyle_prompt}\n\n
  5653. 示例如下:\n
  5654. ###剧本名:西昆仑
  5655. ###故事梗概
  5656. 内容梗概:许芸归家遭徐母毒打,她冷静周旋并编造谎言掩盖行踪,引得一旁阴沉的卞大伟愈发急躁。半个月后,徐母离家,卞大伟兽性大发欲行不轨。生死关头,隐形的程景现身肉搏,屋内家具横飞,卞大伟被“空气”重创。许芸趁乱逃出,却惊见地面凭空浮现一串血脚印。意识到守护者为救自己负伤,许芸不再逃避,对着虚无的空气执拗告白,誓要与这看不见的爱人共进退。
  5657. ###剧本亮点
  5658. 亮点1:绝境奇药,生死一线
  5659. 画面开场即是阿雪苍白无力的脸庞,梁萧眼中泪光闪烁,急促的呼吸声与心跳声烘托紧张气氛。特写梁萧将“阴阳球”塞入阿雪舌底,球体散发微光,阿雪气息从若有若无到逐渐平稳,生死逆转的瞬间,视觉与听觉冲击力十足。
  5660. 亮点2:结拜兄妹,化解尴尬
  5661. 阿雪因解衣拔刺而羞愤欲绝的特写,梁萧眼神中的挣扎与无奈。在紧迫的背景音下,梁萧急中生智,牵起阿雪颤抖的手,跪地匆匆结拜,阿雪眼神从惊惶到迷茫,最终一句“我……我愿意的”带着哭腔,将救命与羞耻的矛盾推向高潮,又以出人意料的方式解决。
  5662. 亮点3:纤发夺命,情愫暗涌
  5663. 拔刺过程的紧张特写,梁萧指尖小心翼翼地捏住细丝,缓慢抽出。当“问心刺”被完全拔出,特写它竟是一根细长、泛着寒光的女子秀发,诡异而令人震惊。阿雪苏醒后,两人眼神交汇,阿雪低头羞涩,梁萧眼中复杂的情绪,无声地传递出超越兄妹的微妙情愫。
  5664. ###人物关系
  5665. 阿雪与梁萧之间存在兄妹之情。
  5666. ###核心矛盾
  5667. 阿雪与梁萧之间存在兄妹之情,但因情愫暗生而产生微妙的矛盾。阿雪羞涩难当,梁萧情急之下提出结拜兄妹,以化解尴尬。两人匆匆结拜后,梁萧小心翼翼地拔出“问心刺”,竟发现它是一根诡异的女子秀发。阿雪转危为安,两人之间,在生死与羞涩交织的瞬间,情愫暗生,却又被兄妹之名束缚,留下无尽遐想。
  5668. ###主体列表
  5669. 阿雪:身中奇毒“问心刺”,气息奄奄,面色苍白,身体虚弱。{全景,正面拍摄,青年女性,亚洲人。
  5670. 黑色短发扎成利落的高马尾,五官精致且轮廓清晰。
  5671. 服饰穿搭:身着红白相间的专业田径运动背心与超短跑步裤,皮肤呈现健康的小麦色,四肢肌肉线条紧致有力。
  5672. 姿态:站立。}{{青年女性(约25-30岁),音色亲切、温柔,语速平稳缓慢}}
  5673. 梁萧:少年侠士,心系阿雪安危,沉着冷静,内心挣扎于情义之间。{8k超高清,电影级光效,大气透视,中国传统艺术美学,空灵光泽,深度景深,复杂精细的纹理,史诗级构图,电影胶片颗粒。
  5674. 全景,正面拍摄,青年女性,亚洲人。
  5675. 佩戴精致繁复的金丝凤冠,黑色长发整齐盘起。
  5676. 服饰穿搭:身着大红色正装嫁衣,上面绣有精细的金色凤凰纹样,质感厚重华贵。
  5677. 姿态:站立。}{{青年男性(约25-30岁),音色冷峻、低沉,语速平稳缓慢,透着一股拒人于千里之外的孤傲与肃杀。}}
  5678. ###美术风格
  5679. 基础画风风格词:厚涂古风
  5680. 整体采用精致细腻的厚涂古风,色彩浓郁而富有层次感,注重光影对比,营造出古典而富有戏剧张力的氛围。色调以深沉的蓝绿、灰调为主,衬托阿雪病弱的苍白,同时用温暖的金色、琥珀色光晕突出“阴阳球”的生命力。拔刺与结拜场景则以柔和的暖色调为主,辅以人物脸颊的红晕,烘托羞涩与情愫暗生的微妙感。人物造型飘逸,服饰细节考究,背景虚实结合,既有古韵,又不失奇幻色彩。
  5681. ###场景列表
  5682. 林间疗伤地:幽静的古风林间空地,一棵高大古树下,是梁萧为阿雪疗伤的地点。环境清幽,光影斑驳,既有古韵又不失奇幻色彩。{影视质感。广角。
  5683. 宽敞的天然山洞内部,石壁上错落有致地镶嵌着发光的萤石,散发出冷色调的微光,照亮了整个空间。洞顶有钟乳石垂下。光影层次丰富,营造出一种宁静而神圣的氛围。
  5684. 无人物。}
  5685. ###分段剧本
  5686. 片段数量:8
  5687. 旁白音色:成年男性(约35-50岁),音色厚重且富有磁性,带有老电影叙事般的沧桑感,语调低沉平稳,富有江湖气息。
  5688. ##片段1
  5689. 时长:12s
  5690. 分镜1
  5691. 出场角色:刀疤脸
  5692. 场景:边境小镇街道
  5693. 出场道具:酒杯-高脚杯
  5694. 画面:[大远景,冷色调,高对比度] 漫天黄沙在狂风中如怒龙翻滚,遮蔽了微弱的星光。悦来酒馆残破的木门在风中剧烈摇晃,铁链撞击木板发出沉重的闷响,四周建筑尽显荒凉。
  5695. 运镜:大远景固定镜头,随后风沙席卷向镜头形成遮挡转场。
  5696. 配音台词:
  5697. 背景音效:
  5698. 分镜2
  5699. 出场角色:刀疤脸
  5700. 场景:悦来酒馆
  5701. 出场道具:酒杯-高脚杯
  5702. 画面:[全景,暖色调阴影构图] 酒馆内部昏暗,几盏油灯在风中疯狂摇曳,投射出扭曲的长影。角落里的食客低头缩颈,双手紧紧攥着粗瓷碗,空气中漂浮着细小的尘埃。
  5703. 运镜:缓慢横移,掠过阴影中瑟缩的食客。
  5704. 配音台词:
  5705. 背景音效:
  5706. 分镜3
  5707. 出场角色:刀疤脸
  5708. 场景:悦来酒馆
  5709. 出场道具:酒杯-高脚杯
  5710. 画面:[中景,三分法构图] 三名大汉围坐在正中央的圆桌旁,腰间挂着的“武林盟”金色令牌在灯火下闪烁。桌上残羹冷炙横陈,一名大汉正张狂地大笑,脚踩在长凳上。
  5711. 运镜:从中景推向令牌特写。
  5712. 配音台词:
  5713. 背景音效:
  5714. 分镜4
  5715. 出场角色:刀疤脸
  5716. 场景:悦来酒馆
  5717. 出场道具:酒杯-高脚杯
  5718. 画面:[特写,低角度仰拍] 刀疤脸横肉颤动,嘴角挂着轻蔑的笑。他随手倾覆手中的酒碗,琥珀色的液体在空中划过弧线,重重溅在老李打着补丁的布鞋和裤脚上。
  5719. 运镜:极速推向酒水溅起的瞬间。
  5720. 配音台词:
  5721. 背景音效:
  5722. 分镜5
  5723. 出场角色:刀疤脸
  5724. 场景:悦来酒馆
  5725. 出场道具:酒杯-高脚杯
  5726. 画面:[近景,荷兰角倾斜构图] 刀疤脸斜睨着眼,昏暗的灯光勾勒出他脸上狰狞的伤疤。他身体前倾,阴影完全笼罩了对面的老李,眼神如毒蛇般阴冷。
  5727. 运镜:固定机位,利用倾斜构图制造压迫感。
  5728. 配音台词:中文配音:[刀疤脸]老李头,这酒里掺水了吧?
  5729. 背景音效:
  5730. \n\n"
  5731. : "你是一个专业的文档分析助手及资深编剧,请根据用户提供的文档内容及下面提供的示例格式完成剧本大纲(需通过以下几个板块进行回复: <故事梗概><剧本亮点><人物关系><核心矛盾><主体列表><美术风格><场景列表><道具列表>,每个板块之间必须使用###分隔,#不能多也不能少;同时板块之间需满足以下要求:\n
  5732. 强制要求:\n
  5733. 1.你只负责与剧本相关的内容,如果用户输入与剧本无关的内容,请告知用户并拒绝继续回答,此为第一优先原则,不满足此原则就忽略其他要求并停止继续输出
  5734. 2.如果用户输入修改美术风格、修改画风这类内容,请告知用户不可修改美术风格,并拒绝继续回答
  5735. 3.以上两条要求对修改主体角色或场景不生效,允许用户调整主体角色说明和场景描述等
  5736. 4.用户如果要求你帮忙写一个故事或者剧本,此类要求不属于与剧本无关,请帮助用户完成请求{$content_generation_requirement}
  5737. 5.强制按照示例格式返回内容,不要更改格式或随意增加符号\n
  5738. 普通要求:\n
  5739. 1.剧本名(必须生成)必须与文档内容高度相关
  5740. 2.<主体列表>中出现的“主体名”必须尽可能统一,严禁出现角色-科学家、角色-复仇者、角色-领导者等带有身份、职业、标签类的命名,只能使用服装差异(如校服装、卫衣装、西装)来区分同一角色,如角色-校服装等。
  5741. 2.1<主体列表>分以下三部分(强制格式):主体描述、人物提示词和音色提示词,格式必须为:主体名:主体描述{人物提示词}{{音色提示词}}
  5742. 2.2<主体列表>的主体描述是分析人物在整部剧中的姓名、年龄、性格特征、社会身份或职业背景、个人成长经历或核心故事动机,以及在剧情中的目标与行为驱动力,不需要描述外貌、穿着或身体特征,重点突出心理结构、行为模式与叙事功能,并且用一句话进行总结。
  5743. 2.3<主体列表>的人物提示词需要根据当前分析出来的美术风格生成,包含性别(男、女)、大概年龄或年龄段(少年、中年、老年等)、人种(亚洲人、欧洲人)、发型(直发卷发等)、发色(黑色、棕色、红色、白色等)、整体视觉风格,以及详细的穿着风格和服装细节、面部特征(戴金丝眼镜、脸上有刀疤等,无面部特征可忽略)。描述需具有镜头感与画面表现力,适合直接用于AI图像生成模型,避免抽象词汇,强调具体可视化细节与整体视觉一致性,同时保证风格统一且符合人物身份设定。该提示词(字数50-100字左右)在主体描述后用{}框起来。
  5744. 2.4<主体列表>的音色提示词放在描述的最后用{{}}框起来。音色提示词需描述角色的整体音色特征,包含:性别、年龄(约XX岁)、音质(如清冷、沉稳、磁性等)、表达形式(如叙述感、旁白式等)、情绪氛围(如空灵韵味、看透世事的清冷等),字数控制在80字以内。举例:成年女性(约25-35岁),音色清冷且富有叙述感,语速平缓,带有仙侠剧特有的空灵韵味。
  5745. {$extra_role_prompt}
  5746. 3.<场景列表>与主体列表同理,需尽可能的对场景环境进行详细描述,必须严格注意不要出现任何角色和人物。
  5747. 3.1<场景列表>分以下两部分(强制格式):场景描述和场景提示词,格式必须为:场景描述{场景提示词}
  5748. 3.2<场景列表>的场景描述是分析在整部剧中出现过的场景,场景描述尽量简洁贴合原文。
  5749. 3.3<场景列表>的场景提示词用于视觉呈现的场景环境描述,该场景需包含环境氛围、光线效果、空间布局、色彩基调、视觉风格等,描述需具有镜头感与画面表现力,适合直接用于AI图像生成模型,避免抽象词汇,强调具体可视化细节与整体视觉一致性,同时保证风格统一且符合剧情设定(可参考以下示例的场景列表中使用{}框起来的提示词,字数150-200字,需带上提炼出来的美术风格)。该提示词在场景描述后用{}框起来。\n
  5750. {$extra_scene_prompt}
  5751. 4.<道具列表>与场景列表同理,需尽可能的对道具环境进行详细描述,必须严格注意不要出现任何角色和人物。
  5752. 3.1<道具列表>分以下两部分(强制格式):道具描述和道具提示词,格式必须为:道具描述{道具提示词}
  5753. 3.2<道具列表>的道具描述是分析在整部剧中出现过的道具,道具描述尽量简洁贴合原文。
  5754. 3.3<道具列表>的道具提示词用于视觉呈现的道具环境描述,该道具需包含环境氛围、光线效果、空间布局、色彩基调、视觉风格等,描述需具有镜头感与画面表现力,适合直接用于AI图像生成模型,避免抽象词汇,强调具体可视化细节与整体视觉一致性,同时保证风格统一且符合剧情设定(可参考以下示例的道具列表中使用{}框起来的提示词,字数150-200字,需带上提炼出来的美术风格)。该提示词在道具描述后用{}框起来。\n
  5755. {$extra_prop_prompt}
  5756. 5.{$mappedArtStyle_prompt}\n\n
  5757. 示例如下:\n
  5758. ###剧本名:西昆仑
  5759. ###故事梗概
  5760. 内容梗概:许芸归家遭徐母毒打,她冷静周旋并编造谎言掩盖行踪,引得一旁阴沉的卞大伟愈发急躁。半个月后,徐母离家,卞大伟兽性大发欲行不轨。生死关头,隐形的程景现身肉搏,屋内家具横飞,卞大伟被“空气”重创。许芸趁乱逃出,却惊见地面凭空浮现一串血脚印。意识到守护者为救自己负伤,许芸不再逃避,对着虚无的空气执拗告白,誓要与这看不见的爱人共进退。
  5761. ###剧本亮点
  5762. 亮点1:绝境奇药,生死一线
  5763. 画面开场即是阿雪苍白无力的脸庞,梁萧眼中泪光闪烁,急促的呼吸声与心跳声烘托紧张气氛。特写梁萧将“阴阳球”塞入阿雪舌底,球体散发微光,阿雪气息从若有若无到逐渐平稳,生死逆转的瞬间,视觉与听觉冲击力十足。
  5764. 亮点2:结拜兄妹,化解尴尬
  5765. 阿雪因解衣拔刺而羞愤欲绝的特写,梁萧眼神中的挣扎与无奈。在紧迫的背景音下,梁萧急中生智,牵起阿雪颤抖的手,跪地匆匆结拜,阿雪眼神从惊惶到迷茫,最终一句“我……我愿意的”带着哭腔,将救命与羞耻的矛盾推向高潮,又以出人意料的方式解决。
  5766. 亮点3:纤发夺命,情愫暗涌
  5767. 拔刺过程的紧张特写,梁萧指尖小心翼翼地捏住细丝,缓慢抽出。当“问心刺”被完全拔出,特写它竟是一根细长、泛着寒光的女子秀发,诡异而令人震惊。阿雪苏醒后,两人眼神交汇,阿雪低头羞涩,梁萧眼中复杂的情绪,无声地传递出超越兄妹的微妙情愫。
  5768. ###人物关系
  5769. 阿雪与梁萧之间存在兄妹之情。
  5770. ###核心矛盾
  5771. 阿雪与梁萧之间存在兄妹之情,但因情愫暗生而产生微妙的矛盾。阿雪羞涩难当,梁萧情急之下提出结拜兄妹,以化解尴尬。两人匆匆结拜后,梁萧小心翼翼地拔出“问心刺”,竟发现它是一根诡异的女子秀发。阿雪转危为安,两人之间,在生死与羞涩交织的瞬间,情愫暗生,却又被兄妹之名束缚,留下无尽遐想。
  5772. ###主体列表
  5773. 阿雪:身中奇毒“问心刺”,气息奄奄,面色苍白,身体虚弱。{全景,正面拍摄,青年女性,亚洲人。
  5774. 黑色短发扎成利落的高马尾,五官精致且轮廓清晰。
  5775. 服饰穿搭:身着红白相间的专业田径运动背心与超短跑步裤,皮肤呈现健康的小麦色,四肢肌肉线条紧致有力。
  5776. 姿态:站立。}{{青年女性(约25-30岁),音色亲切、温柔,语速平稳缓慢}}
  5777. 梁萧:少年侠士,心系阿雪安危,沉着冷静,内心挣扎于情义之间。{8k超高清,电影级光效,大气透视,中国传统艺术美学,空灵光泽,深度景深,复杂精细的纹理,史诗级构图,电影胶片颗粒。
  5778. 全景,正面拍摄,青年女性,亚洲人。
  5779. 佩戴精致繁复的金丝凤冠,黑色长发整齐盘起。
  5780. 服饰穿搭:身着大红色正装嫁衣,上面绣有精细的金色凤凰纹样,质感厚重华贵。
  5781. 姿态:站立。}{{青年男性(约25-30岁),音色冷峻、低沉,语速平稳缓慢,透着一股拒人于千里之外的孤傲与肃杀。}}
  5782. ###美术风格
  5783. 基础画风风格词:厚涂古风
  5784. 整体采用精致细腻的厚涂古风,色彩浓郁而富有层次感,注重光影对比,营造出古典而富有戏剧张力的氛围。色调以深沉的蓝绿、灰调为主,衬托阿雪病弱的苍白,同时用温暖的金色、琥珀色光晕突出“阴阳球”的生命力。拔刺与结拜场景则以柔和的暖色调为主,辅以人物脸颊的红晕,烘托羞涩与情愫暗生的微妙感。人物造型飘逸,服饰细节考究,背景虚实结合,既有古韵,又不失奇幻色彩。
  5785. ###场景列表
  5786. 林间疗伤地:幽静的古风林间空地,一棵高大古树下,是梁萧为阿雪疗伤的地点。环境清幽,光影斑驳,既有古韵又不失奇幻色彩。{影视质感。广角。
  5787. 宽敞的天然山洞内部,石壁上错落有致地镶嵌着发光的萤石,散发出冷色调的微光,照亮了整个空间。洞顶有钟乳石垂下。光影层次丰富,营造出一种宁静而神圣的氛围。
  5788. 无人物。}
  5789. ###道具列表
  5790. 酒杯-高脚杯:高脚杯,盛有少量酒液。{高脚酒杯,道具多角度视角图,正面、背面、侧面、局部细节,透明玻璃材质,细长杯柄,尺寸标注高24厘米杯口6厘米,白底干净展示,无人物}";
  5791. // 构建消息
  5792. $messages = [
  5793. [
  5794. 'role' => 'system',
  5795. 'content' => $systemPrompt
  5796. ],
  5797. [
  5798. 'role' => 'user',
  5799. 'content' => "以下是文档内容:
  5800. {$content}
  5801. 用户问题:
  5802. {$question}"
  5803. ]
  5804. ];
  5805. // 模型兼容性处理:deepseek-chat 和 deepseek-reasoner 映射到 deepseek-v4-flash
  5806. $thinkingMode = getProp($data, 'thinking', 'disabled'); // 默认非思考模式
  5807. $reasoningEffort = getProp($data, 'reasoning_effort', 'high'); // 默认思考强度
  5808. if ($model === 'deepseek-chat') {
  5809. // deepseek-chat 映射到 deepseek-v4-flash,非思考模式
  5810. $model = 'deepseek-v4-flash';
  5811. $thinkingMode = 'disabled';
  5812. } elseif ($model === 'deepseek-reasoner') {
  5813. // deepseek-reasoner 映射到 deepseek-v4-flash,思考模式
  5814. $model = 'deepseek-v4-flash';
  5815. $thinkingMode = 'enabled';
  5816. }
  5817. $post_data = [
  5818. 'model' => $model,
  5819. 'messages' => $messages,
  5820. // 'max_tokens' => 8192,
  5821. 'temperature' => (float)env('TEXT_TEMPERATURE'),
  5822. 'frequency_penalty' => 0,
  5823. 'presence_penalty' => 0,
  5824. 'response_format' => ['type' => 'text'],
  5825. 'thinking' => ['type'=>$thinkingMode],
  5826. 'stream' => true // 启用流式输出
  5827. ];
  5828. if ($thinkingMode == 'enabled') $post_data['reasoning_effort'] = $reasoningEffort;
  5829. // 根据模型类型选择调用方法
  5830. $fullContent = '';
  5831. $fullReasoningContent = '';
  5832. $usage = [];
  5833. try {
  5834. if (in_array($model, ['deepseek-reasoner', 'deepseek-chat', 'deepseek-v4-flash', 'deepseek-v4-pro'])) {
  5835. // DeepSeek 官方模型使用 DeepSeek API
  5836. $streamGenerator = $this->deepSeekStreamResponse($post_data);
  5837. } else if (in_array($model, $this->gpt_text_models)) {
  5838. // GPT-5.4 模型使用 TokenRouter API
  5839. $streamGenerator = $this->gpt54StreamResponse($post_data);
  5840. } else {
  5841. // 其他模型使用火山引擎API
  5842. $streamGenerator = $this->volcEngineChatCompletion($post_data);
  5843. }
  5844. // 验证返回值类型
  5845. if (!is_iterable($streamGenerator)) {
  5846. $errorType = is_object($streamGenerator) ? get_class($streamGenerator) : gettype($streamGenerator);
  5847. dLog('deepseek')->error('addChat流式生成器无效', [
  5848. 'generator_type' => $errorType,
  5849. 'model' => $model,
  5850. 'anime_id' => $anime_id
  5851. ]);
  5852. logDB('deepseek', 'error', 'addChat流式生成器类型错误', [
  5853. 'type' => $errorType,
  5854. 'model' => $model
  5855. ]);
  5856. yield [
  5857. 'type' => 'error',
  5858. 'script' => [],
  5859. 'episode' => [],
  5860. 'answer' => '',
  5861. 'reasoning' => '',
  5862. 'usage' => [],
  5863. 'error' => '接口返回数据异常,请重新请求'
  5864. ];
  5865. return;
  5866. }
  5867. // 处理流式输出
  5868. foreach ($streamGenerator as $chunk) {
  5869. if (isset($chunk['type'])) {
  5870. if ($chunk['type'] === 'done') {
  5871. // 最终结果
  5872. $fullContent = $chunk['full_content'];
  5873. $fullReasoningContent = $chunk['full_reasoning'];
  5874. $usage = isset($chunk['usage']) ? $chunk['usage'] : [];
  5875. } else {
  5876. // 逐块yield数据
  5877. yield $chunk;
  5878. }
  5879. }
  5880. }
  5881. } catch (\Exception $e) {
  5882. dLog('deepseek')->error('addChat流式处理异常: ' . $e->getMessage(), [
  5883. 'model' => $model,
  5884. 'anime_id' => $anime_id,
  5885. 'trace' => $e->getTraceAsString()
  5886. ]);
  5887. logDB('deepseek', 'error', 'addChat流式处理失败', [
  5888. 'error' => $e->getMessage(),
  5889. 'model' => $model
  5890. ]);
  5891. yield [
  5892. 'type' => 'error',
  5893. 'script' => [],
  5894. 'episode' => [],
  5895. 'answer' => '',
  5896. 'reasoning' => '',
  5897. 'usage' => [],
  5898. 'error' => '处理请求时发生异常: ' . $e->getMessage()
  5899. ];
  5900. return;
  5901. }
  5902. dLog('deepseek')->info('完整内容: '.$fullContent);
  5903. logDB('deepseek', 'info', '完整内容', ['content' => $fullContent, 'anime_id' => $anime_id]);
  5904. // 处理完整内容并返回最终结果
  5905. $script_arr = [];
  5906. if ($fullContent) {
  5907. $script_arr = handleScriptContentForAce($fullContent);
  5908. dLog('deepseek')->info('解析内容', $script_arr);
  5909. logDB('deepseek', 'info', '解析内容', $script_arr);
  5910. }
  5911. if (empty($script_arr['roles'])) {
  5912. // 未生成剧本相关内容,保存对话记录并返回提示
  5913. dLog('deepseek')->info('未生成剧本相关的内容');
  5914. try {
  5915. DB::beginTransaction();
  5916. $now = date('Y-m-d H:i:s');
  5917. // 保存对话记录
  5918. $records = [
  5919. [
  5920. 'uid' => $uid,
  5921. 'anime_id' => $anime_id,
  5922. 'sequence' => 0,
  5923. 'role' => 'user',
  5924. 'content' => $prompt,
  5925. 'created_at' => $now,
  5926. 'updated_at' => $now
  5927. ],
  5928. [
  5929. 'uid' => $uid,
  5930. 'anime_id' => $anime_id,
  5931. 'sequence' => 0,
  5932. 'role' => 'assistant',
  5933. // 'content' => $fullContent,
  5934. 'content' => '未生成剧本相关的内容,请调整提示词再试',
  5935. 'created_at' => $now,
  5936. 'updated_at' => $now
  5937. ]
  5938. ];
  5939. DB::table('mp_anime_records')->insert($records);
  5940. DB::commit();
  5941. } catch (\Exception $e) {
  5942. DB::rollBack();
  5943. dLog('deepseek')->error('保存对话记录失败', ['error' => $e->getMessage()]);
  5944. }
  5945. yield [
  5946. 'type' => 'done',
  5947. 'script' => [],
  5948. 'episode' => [],
  5949. 'answer' => $fullContent,
  5950. 'reasoning' => $fullReasoningContent,
  5951. 'usage' => $usage,
  5952. 'error' => '未生成剧本相关的内容,请调整提示词再试'
  5953. ];
  5954. return;
  5955. }
  5956. // 如果需要生成原文内容,从script_arr中提取
  5957. if ($need_generate_content && isset($script_arr['content']) && $script_arr['content']) {
  5958. $content = $script_arr['content'];
  5959. dLog('deepseek')->info('从AI生成结果中提取原文内容', ['content_length' => strlen($content)]);
  5960. if (!$content) {
  5961. yield [
  5962. 'type' => 'done',
  5963. 'script' => [],
  5964. 'episode' => [],
  5965. 'answer' => $fullContent,
  5966. 'reasoning' => $fullReasoningContent,
  5967. 'usage' => $usage,
  5968. 'error' => '未生成剧本内容,请调整提示词再试'
  5969. ];
  5970. return;
  5971. }
  5972. }
  5973. // 替换美术风格
  5974. if ($mappedArtStyle !== '') {
  5975. $script_arr['art_style'] = $mappedArtStyle;
  5976. $fullContent = $this->replaceArtStyleSection($fullContent, $mappedArtStyle);
  5977. }
  5978. // 新建动漫
  5979. if ($user_anime_name == '新剧本策划') {
  5980. $anime_name = getProp($script_arr, 'script_name');
  5981. // if (!$anime_name) {
  5982. // // 未识别到剧本名,保存对话记录并返回提示
  5983. // dLog('deepseek')->info('未能识别到剧本名称');
  5984. // try {
  5985. // DB::beginTransaction();
  5986. // $now = date('Y-m-d H:i:s');
  5987. // // 保存对话记录
  5988. // $records = [
  5989. // [
  5990. // 'uid' => $uid,
  5991. // 'anime_id' => $anime_id,
  5992. // 'sequence' => 0,
  5993. // 'role' => 'user',
  5994. // 'content' => $prompt,
  5995. // 'created_at' => $now,
  5996. // 'updated_at' => $now
  5997. // ],
  5998. // [
  5999. // 'uid' => $uid,
  6000. // 'anime_id' => $anime_id,
  6001. // 'sequence' => 0,
  6002. // 'role' => 'assistant',
  6003. // 'content' => '未能生成剧本名称,请重试',
  6004. // 'created_at' => $now,
  6005. // 'updated_at' => $now
  6006. // ]
  6007. // ];
  6008. // DB::table('mp_anime_records')->insert($records);
  6009. // DB::commit();
  6010. // } catch (\Exception $e) {
  6011. // DB::rollBack();
  6012. // dLog('deepseek')->error('保存对话记录失败', ['error' => $e->getMessage()]);
  6013. // }
  6014. // yield [
  6015. // 'type' => 'done',
  6016. // 'script' => [],
  6017. // 'episode' => [],
  6018. // 'answer' => $fullContent,
  6019. // 'reasoning' => $fullReasoningContent,
  6020. // 'usage' => $usage,
  6021. // 'error' => '未能识别到剧本名称,请调整提示词再试'
  6022. // ];
  6023. // return;
  6024. // }
  6025. // 确认对话名称唯一性
  6026. if ($anime_name && DB::table('mp_animes')->where('anime_name', $anime_name)->value('id')) {
  6027. $anime_name = $anime_name . '_' . date('YmdHis');
  6028. }
  6029. }else {
  6030. $anime_name = $user_anime_name;
  6031. }
  6032. $table_data = [
  6033. 'user_id' => $uid,
  6034. 'anime_name' => $anime_name,
  6035. 'model' => $model,
  6036. 'intro' => isset($script_arr['intro']) ? $script_arr['intro'] : '',
  6037. 'highlights' => isset($script_arr['highlights']) ? $script_arr['highlights'] : '',
  6038. 'role_relationship' => isset($script_arr['role_relationship']) ? $script_arr['role_relationship'] : '',
  6039. 'core_contradiction' => isset($script_arr['core_contradiction']) ? $script_arr['core_contradiction'] : '',
  6040. 'roles' => isset($script_arr['roles']) && is_array($script_arr['roles']) ? json_encode($script_arr['roles'], 256) : '[]',
  6041. 'art_style' => isset($script_arr['art_style']) ? $script_arr['art_style'] : '',
  6042. 'art_style_type' => $input_art_style,
  6043. 'scenes' => isset($script_arr['scenes']) && is_array($script_arr['scenes']) ? json_encode($script_arr['scenes'], 256) : '[]',
  6044. 'props' => isset($script_arr['props']) && is_array($script_arr['props']) ? json_encode($script_arr['props'], 256) : '[]',
  6045. 'status' => '解析完成',
  6046. 'content' => $content,
  6047. 'is_multi' => $is_multi,
  6048. 'ace_mode' => $ace_mode,
  6049. 'generate_status' => '待执行',
  6050. 'updated_at' => date('Y-m-d H:i:s')
  6051. ];
  6052. if ($table_data['content']) {
  6053. $chapters = splitContent($table_data['content']);
  6054. $chapter_count = count($chapters);
  6055. if ($chapter_count > 0) {
  6056. $table_data['start_episode_sequence'] = 1;
  6057. $table_data['end_episode_sequence'] = $table_data['episode_num'] = $chapter_count;
  6058. }
  6059. }
  6060. if ($extra_products) {
  6061. $table_data['extra_products'] = json_encode($extra_products, 256);
  6062. }
  6063. // 如果有剧本ID则进行绑定
  6064. if ($script_id) {
  6065. $table_data['script_id'] = $script_id;
  6066. }
  6067. $single_episode = [];
  6068. try {
  6069. DB::beginTransaction();
  6070. $now = date('Y-m-d H:i:s');
  6071. // 更新动漫大纲
  6072. $boolen = DB::table('mp_animes')->where('id', $anime_id)->update($table_data);
  6073. if (!$boolen) {
  6074. dLog('deepseek')->info('动漫保存失败', $table_data);
  6075. Utils::throwError('20003:动漫保存失败');
  6076. }
  6077. // 保存对话记录
  6078. $records = [
  6079. [
  6080. 'uid' => $uid,
  6081. 'anime_id' => $anime_id,
  6082. 'sequence' => 0,
  6083. 'role' => 'user',
  6084. 'content' => $prompt,
  6085. 'created_at' => date('Y-m-d H:i:s'),
  6086. 'updated_at' => date('Y-m-d H:i:s')
  6087. ],
  6088. [
  6089. 'uid' => $uid,
  6090. 'anime_id' => $anime_id,
  6091. 'sequence' => 0,
  6092. 'role' => 'assistant',
  6093. 'content' => $fullContent,
  6094. 'created_at' => date('Y-m-d H:i:s'),
  6095. 'updated_at' => date('Y-m-d H:i:s')
  6096. ]
  6097. ];
  6098. // 保存对话记录
  6099. $boolen3 = DB::table('mp_anime_records')->insert($records);
  6100. if (!$boolen3) {
  6101. Utils::throwError('20003:对话记录保存失败');
  6102. }
  6103. if ($is_single) {
  6104. $episode_arr = $this->buildSingleEpisodeFromScript($script_arr, $fullContent, $anime_name);
  6105. if (empty($episode_arr['acts'])) {
  6106. Utils::throwError('20003:单剧集分镜内容解析失败,请确认输出格式');
  6107. }
  6108. $saveResult = $this->saveEpisodeVersionData(
  6109. $anime_id,
  6110. 1,
  6111. $episode_arr,
  6112. is_array(getProp($script_arr, 'roles')) ? getProp($script_arr, 'roles') : [],
  6113. is_array(getProp($script_arr, 'scenes')) ? getProp($script_arr, 'scenes') : [],
  6114. is_array(getProp($script_arr, 'props')) ? getProp($script_arr, 'props') : [],
  6115. null,
  6116. null,
  6117. false,
  6118. $content,
  6119. $now,
  6120. $ref_products
  6121. );
  6122. $single_episode = $saveResult['episode'];
  6123. $episode_id = $saveResult['episode_id'];
  6124. $boolen5 = DB::table('mp_animes')->where('id', $anime_id)->update([
  6125. 'roles' => json_encode($saveResult['merged_roles'], 256),
  6126. 'scenes' => json_encode($saveResult['merged_scenes'], 256),
  6127. 'props' => json_encode($saveResult['merged_props'], 256),
  6128. 'updated_at' => $now
  6129. ]);
  6130. if ($boolen5 === false) {
  6131. Utils::throwError('20003:单剧集主表资源同步失败');
  6132. }
  6133. $table_data['roles'] = json_encode($saveResult['merged_roles'], 256);
  6134. $table_data['scenes'] = json_encode($saveResult['merged_scenes'], 256);
  6135. $table_data['props'] = json_encode($saveResult['merged_props'], 256);
  6136. $episode_record_content = '确认分镜大纲';
  6137. if ($content !== '') {
  6138. // $episode_record_content .= "\n\n###上传内容\n" . $content;
  6139. }
  6140. $episode_records = [
  6141. [
  6142. 'uid' => $uid,
  6143. 'anime_id' => $anime_id,
  6144. 'role' => 'user',
  6145. 'content' => $episode_record_content,
  6146. 'sequence' => 1,
  6147. 'episode_id' => $episode_id,
  6148. 'created_at' => $now,
  6149. 'updated_at' => $now
  6150. ],
  6151. [
  6152. 'uid' => $uid,
  6153. 'anime_id' => $anime_id,
  6154. 'role' => 'assistant',
  6155. 'content' => $fullContent,
  6156. // 'content' => '我已按照您的要求完成策划并将内容更新到您右侧的策划文档。',
  6157. 'sequence' => 1,
  6158. 'episode_id' => $episode_id,
  6159. 'created_at' => $now,
  6160. 'updated_at' => $now
  6161. ]
  6162. ];
  6163. $boolen4 = DB::table('mp_anime_records')->insert($episode_records);
  6164. if (!$boolen4) {
  6165. Utils::throwError('20003:单剧集分镜记录保存失败');
  6166. }
  6167. }
  6168. }catch (\Exception $e) {
  6169. DB::rollBack();
  6170. dLog('deepseek')->info('新建对话错误信息: '.$e->getMessage());
  6171. yield [
  6172. 'type' => 'done',
  6173. 'answer' => $fullContent,
  6174. 'reasoning' => $fullReasoningContent,
  6175. 'usage' => $usage,
  6176. 'error' => $e->getMessage(),
  6177. ];
  6178. return;
  6179. }
  6180. DB::commit();
  6181. dLog('deepseek')->info('保存完毕');
  6182. if ($is_single && !empty($single_episode)) {
  6183. // $this->batchSetGlobalRoleImg([
  6184. // 'anime_id' => $anime_id,
  6185. // ]);
  6186. // $this->batchSetGlobalSceneImg([
  6187. // 'anime_id' => $anime_id,
  6188. // ]);
  6189. // // 将全局角色和场景的task_id、task_status和url继承给当前分集
  6190. // $this->inheritGlobalImagesToEpisodes($anime_id, $episode_id);
  6191. }
  6192. $table_data['anime_id'] = $anime_id;
  6193. $table_data['roles'] = json_decode($table_data['roles'], true);
  6194. $table_data['scenes'] = json_decode($table_data['scenes'], true);
  6195. // $table_data['episodes'] = $script_arr['episodes'];
  6196. unset($table_data['created_at']);
  6197. unset($table_data['updated_at']);
  6198. unset($table_data['status']);
  6199. dLog('deepseek')->info('开始返回');
  6200. yield [
  6201. 'type' => 'done',
  6202. 'script' => $table_data,
  6203. 'episode' => $single_episode,
  6204. 'answer' => $fullContent,
  6205. 'reasoning' => $fullReasoningContent,
  6206. 'usage' => $usage
  6207. ];
  6208. }
  6209. public function reGenerateAnimeForAce($data) {
  6210. $uid = Site::getUid();
  6211. $file = getProp($data, 'file');
  6212. $content = getProp($data, 'content', '');
  6213. $bid = getProp($data, 'bid', 0);
  6214. $script_id = getProp($data, 'script_id', 0);
  6215. $anime_id = getProp($data, 'anime_id');
  6216. $anime = DB::table('mp_animes')->where('id', $anime_id)->first();
  6217. if (!$anime) {
  6218. Utils::throwError('20003:该对话不存在');
  6219. }
  6220. $is_multi = getProp($anime, 'is_multi', 1);
  6221. $is_single = (int)$is_multi !== 1;
  6222. $extra_products = getProp($data, 'products', []);
  6223. if (!$extra_products) {
  6224. $extra_products = getProp($anime, 'extra_products');
  6225. if ($extra_products) {
  6226. $extra_products = json_decode($extra_products, true);
  6227. }else {
  6228. $extra_products = [];
  6229. }
  6230. }else {
  6231. if (is_string($extra_products)) $extra_products = json_decode($extra_products, true);
  6232. }
  6233. // 如果anime有关联的script_id,则从mp_script_product_mappings中查询资产并合并到extra_products
  6234. $anime_script_id = getProp($anime, 'script_id');
  6235. if ($anime_script_id && $is_single) {
  6236. $cpid = Site::getCpid();
  6237. $script_products_mappings = DB::table('mp_script_product_mappings as mapping')
  6238. ->join('mp_products as product', 'mapping.product_id', '=', 'product.id')
  6239. ->where('mapping.script_id', $anime_script_id)
  6240. ->where('product.cpid', $cpid)
  6241. ->where('product.is_deleted', 0);
  6242. $mappings = $script_products_mappings->select(
  6243. 'mapping.product_id',
  6244. 'mapping.episode_number',
  6245. 'product.product_name',
  6246. 'product.type',
  6247. 'product.product',
  6248. 'product.pic_prompt',
  6249. 'product.url',
  6250. 'product.pic_task_id',
  6251. 'product.pic_task_status',
  6252. 'product.three_view_image_url'
  6253. )
  6254. ->get();
  6255. // 按 product_id 分组,合并 episode_number
  6256. $productMap = [];
  6257. foreach ($mappings as $item) {
  6258. $product_id = $item->product_id;
  6259. $product_name = $item->product_name;
  6260. // 处理product_name两边的符号
  6261. $product_name = preg_replace('/^[\s*\[\]【】[]{}{}\x{3000}]+|[\s*\[\]【】[]{}{}\x{3000}]+$/u', '', $product_name);
  6262. if (!isset($productMap[$product_id])) {
  6263. $productMap[$product_id] = [
  6264. 'product_id' => $product_id,
  6265. 'product_name' => $product_name,
  6266. 'type' => (int)$item->type,
  6267. 'product' => (int)$item->product,
  6268. 'pic_prompt' => $item->pic_prompt,
  6269. 'url' => $item->url,
  6270. 'pic_task_id' => $item->pic_task_id,
  6271. 'pic_task_status' => $item->pic_task_status,
  6272. 'episode_numbers' => [],
  6273. ];
  6274. }
  6275. // 添加 episode_number(去重)
  6276. if (!in_array($item->episode_number, $productMap[$product_id]['episode_numbers'])) {
  6277. $productMap[$product_id]['episode_numbers'][] = $item->episode_number;
  6278. }
  6279. }
  6280. // 将查询到的剧本资产合并到extra_products中
  6281. // 先构建extra_products的索引(以product_id为key,用于去重)
  6282. $extraProductsMap = [];
  6283. foreach ($extra_products as $item) {
  6284. $key = getProp($item, 'product_id');
  6285. if ($key) {
  6286. $extraProductsMap[$key] = $item;
  6287. }
  6288. }
  6289. // 合并剧本资产(去重:仅按product_id去重,不考虑episode_number)
  6290. foreach ($productMap as $product) {
  6291. $product_id = $product['product_id'];
  6292. // 如果不存在则添加(不带episode_number信息)
  6293. if (!isset($extraProductsMap[$product_id])) {
  6294. $extraProductsMap[$product_id] = [
  6295. 'product_id' => $product['product_id'],
  6296. 'product_name' => $product['product_name'],
  6297. 'type' => $product['type'],
  6298. 'product' => $product['product'],
  6299. 'pic_prompt' => $product['pic_prompt'],
  6300. 'url' => $product['url'],
  6301. 'pic_task_id' => $product['pic_task_id'],
  6302. 'pic_task_status' => $product['pic_task_status'],
  6303. ];
  6304. }
  6305. }
  6306. // 重新赋值给extra_products
  6307. $extra_products = array_values($extraProductsMap);
  6308. }
  6309. $user_anime_name = getProp($anime, 'anime_name');
  6310. $prompt = getProp($data, 'prompt');
  6311. // 处理提示词
  6312. if ($prompt && $extra_products) {
  6313. // 遍历extra_products,将prompt中的{product_name}替换为实际的product_name
  6314. foreach($extra_products as $item) {
  6315. $product_name = getProp($item, 'product_name');
  6316. if ($product_name) {
  6317. // 替换 {product_name} 为 product_name
  6318. $prompt = str_replace('{' . $product_name . '}', $product_name, $prompt);
  6319. }
  6320. }
  6321. }
  6322. // 处理文本模型
  6323. $model = getProp($data, 'model');
  6324. if (!$model) {
  6325. // 用户没有输入,从anime表获取
  6326. $model = getProp($anime, 'model');
  6327. if (!$model) {
  6328. // anime表也没有,使用默认值
  6329. $model = 'deepseek-v4-pro';
  6330. }
  6331. }
  6332. // 验证模型是否在可用模型表中
  6333. if (!DB::table('mp_text_models')->where('model', $model)->where('is_enabled', 1)->exists()) {
  6334. $model = 'deepseek-v4-pro';
  6335. }
  6336. // 单剧集模式下,如果已经生成了剧集,则不允许继续调整大纲
  6337. if ($is_single) {
  6338. $episode_exists = DB::table('mp_anime_episodes')
  6339. ->where('anime_id', $anime_id)
  6340. ->where('sequence', 1)
  6341. ->exists();
  6342. if ($episode_exists) {
  6343. Utils::throwError('20003:单剧集模式下已生成剧集,不可继续调整大纲,请去策划剧集');
  6344. }
  6345. }
  6346. $question = getProp($data, 'question', $is_single ? "请根据实例格式完成单剧集剧本及分段\n" : "请根据实例格式完成剧本大纲\n");
  6347. if ($prompt) {
  6348. $question .= "本次修改要求如下:\n{$prompt}";
  6349. }
  6350. // 提取文件内容
  6351. if ($file) {
  6352. $content = $this->extractFileContent($file);
  6353. if (!$content) {
  6354. Utils::throwError('20003:无法提取文件内容,请检查文件格式');
  6355. }
  6356. } elseif ($script_id) {
  6357. $content = $this->getContentByScriptId($script_id);
  6358. if (!$content) {
  6359. Utils::throwError('20003:无法获取剧本内容,请检查剧本');
  6360. }
  6361. } elseif ($bid) {
  6362. $content = $this->getContentByBid($bid);
  6363. if (!$content) {
  6364. Utils::throwError('20003:无法获取书籍内容,请检查书籍');
  6365. }
  6366. } elseif ($content) {
  6367. $content = filterContent($content);
  6368. }else {
  6369. $content = filterContent(getProp($anime, 'content'));
  6370. if (!$content && $prompt) { // 如果动漫记录中没有内容则根据提示词生成
  6371. $need_generate_content = true;
  6372. }
  6373. }
  6374. // 判断是否需要生成原文内容
  6375. $need_generate_content = isset($need_generate_content) && $need_generate_content;
  6376. // 如果需要生成原文内容,添加额外的要求
  6377. $content_generation_requirement = $need_generate_content
  6378. ? "\n5.如果用户只提供了创作要求而没有提供具体文档内容,你需要根据要求创作完整的原文内容(小说形式,包含对话和叙述),并将原文内容放在最后一个板块###原文内容中输出。原文内容应该详细、生动,如果用户没有明确生成的字数,则字数不少于1000字。"
  6379. : "";
  6380. // 美术风格
  6381. $input_art_style = getProp($data, 'art_style');
  6382. if (!$input_art_style) {
  6383. $mappedArtStyle = getProp($anime, 'art_style');
  6384. }else {
  6385. $mappedArtStyle = $this->getArtStylePromptByInput($input_art_style);
  6386. }
  6387. if (!$mappedArtStyle) {
  6388. $mappedArtStyle_prompt = '美术风格:根据剧本内容自定义美术风格';
  6389. }else {
  6390. if (strstr($mappedArtStyle, '基础画风风格词')) {
  6391. $mappedArtStyle_prompt = "美术风格强制设置如下(原样输出,不得更改任何内容):\n{$mappedArtStyle}\n";
  6392. }else {
  6393. $art_style_type = $input_art_style ? $input_art_style : getProp($anime, 'art_style_type');
  6394. $mappedArtStyle_prompt = "美术风格强制设置如下(原样输出,不得更改任何内容):\n基础画风风格词: {$art_style_type}\n{$mappedArtStyle}\n";
  6395. }
  6396. }
  6397. // 构建主体、场景和道具提示词
  6398. $extra_role_prompt = "\n";
  6399. $extra_scene_prompt = "\n";
  6400. $extra_prop_prompt = "\n";
  6401. $ref_products = []; // 参考资产
  6402. if ($extra_products) {
  6403. foreach($extra_products as $item) {
  6404. $product = getProp($item, 'product');
  6405. $product_name = getProp($item, 'product_name');
  6406. if ($product_name == '旁白') continue;
  6407. $ref_products[$product_name] = $item;
  6408. $pic_prompt = getProp($item, 'pic_prompt');
  6409. if ((int)$product === 1) {
  6410. // 拼接角色信息
  6411. $extra_role_prompt .= $product_name . ":" . $pic_prompt . "\n";
  6412. } elseif ((int)$product === 2) {
  6413. // 拼接场景信息
  6414. $extra_scene_prompt .= $product_name . ":" . $pic_prompt . "\n";
  6415. } elseif ((int)$product === 3) {
  6416. // 拼接道具信息
  6417. $extra_prop_prompt .= $product_name . ":" . $pic_prompt . "\n";
  6418. }
  6419. }
  6420. // 优化提示词,融入剧本
  6421. if (!empty(trim($extra_role_prompt))) {
  6422. $extra_role_prompt = "\n【强制主体设定-优先级最高-不可修改】\n以下主体必须全部出现在<主体列表>中,必须包含:\n" . $extra_role_prompt . "\n格式要求:\n1. 主体名称:必须保持不变\n2. 主体描述:你必须根据剧情为每个主体生成主体描述(分析人物在整部剧中的姓名、年龄、性格特征、社会身份或职业背景、个人成长经历或核心故事动机,以及在剧情中的目标与行为驱动力,用一句话进行总结)\n3. 人物提示词:{}中的内容必须完整保留,不得修改\n4. 音色提示词:你必须根据角色特征生成音色提示词(描述角色的整体音色特征,包含:性别、年龄、音质、表达形式、情绪氛围,字数控制在80字以内),用{{}}框起来\n\n最终格式必须为:主体名:[你生成的主体描述]{人物提示词-保持不变}{{你生成的音色提示词}}\n\n【重要】以上每个主体在<主体列表>中的完整格式必须是:主体名:主体描述{人物提示词}{{音色提示词}},其中主体描述和音色提示词是你必须生成的内容,{}中的人物提示词必须原样保留。";
  6423. }
  6424. if (!empty(trim($extra_scene_prompt))) {
  6425. $extra_scene_prompt = "\n【强制场景设定-优先级最高-不可修改】\n以下场景必须全部出现在<场景列表>中,必须包含:\n" . $extra_scene_prompt . "\n格式要求:\n1. 场景名称:必须保持不变\n2. 场景描述:你必须根据剧情为每个场景生成符合<普通要求3.2>的场景描述(分析在整部剧中出现过的场景,场景描述尽量简洁贴合原文)\n3. 场景提示词:{}中的内容必须完整保留,不得修改\n\n最终格式必须为:场景名:[你生成的场景描述]{场景提示词-保持不变}\n\n必须包含的场景列表:\n" . $extra_scene_prompt . "\n【重要提示】以上每个场景在<场景列表>中的完整格式必须是:场景名:场景描述{场景提示词},其中场景描述是你必须生成的内容,{}中的场景提示词必须原样保留。";
  6426. }
  6427. if (!empty(trim($extra_prop_prompt))) {
  6428. $extra_prop_prompt = "\n【强制道具设定-优先级最高-不可修改】\n以下道具必须全部出现在<道具列表>中,必须包含:\n" . $extra_prop_prompt . "\n格式要求:\n1. 道具名称:必须保持不变\n2. 道具描述:你必须根据剧情为每个道具生成道具描述(分析在整部剧中出现过的道具,道具描述尽量简洁贴合原文)\n3. 道具提示词:{}中的内容必须完整保留,不得修改\n\n最终格式必须为:道具名:[你生成的道具描述]{道具提示词-保持不变}\n\n必须包含的道具列表:\n" . $extra_prop_prompt . "\n【重要提示】以上每个道具在<道具列表>中的完整格式必须是:道具名:道具描述{道具提示词},其中道具描述是你必须生成的内容,{}中的道具提示词必须原样保留。";
  6429. }
  6430. }
  6431. if ($anime_script_id && $is_single) {
  6432. $role_demo = "2.<主体列表>只能使用以下主体,不得自定义内容(必需带上冒号后的具体描述以及{}和{{}}中的内容,原样输出)。{$extra_role_prompt}";
  6433. $scene_demo = "3.<场景列表>只能使用以下场景,不得自定义内容(必需带上冒号后的具体描述以及{}和{{}}中的内容,原样输出)。{$extra_scene_prompt}";
  6434. $prop_demo = "4.<道具列表>只能使用以下道具,不得自定义内容(必需带上冒号后的具体描述以及{}和{{}}中的内容,原样输出)。{$extra_prop_prompt}";
  6435. }else {
  6436. $role_demo = "2.<主体列表>中出现的“主体名”必须尽可能统一,严禁出现角色-科学家、角色-复仇者、角色-领导者等带有身份、职业、标签类的命名,只能使用服装差异(如校服装、卫衣装、西装)来区分同一角色,如角色-校服装等。
  6437. 2.1<主体列表>分以下三部分(强制格式):主体描述、人物提示词和音色提示词,格式必须为:主体名:主体描述{人物提示词}{{音色提示词}}
  6438. 2.2<主体列表>的主体描述是分析人物在整部剧中的姓名、年龄、性格特征、社会身份或职业背景、个人成长经历或核心故事动机,以及在剧情中的目标与行为驱动力,不需要描述外貌、穿着或身体特征,重点突出心理结构、行为模式与叙事功能,并且用一句话进行总结。
  6439. 2.3<主体列表>的人物提示词需要根据当前分析出来的美术风格生成,包含性别(男、女)、大概年龄或年龄段(少年、中年、老年等)、人种(亚洲人、欧洲人)、发型(直发卷发等)、发色(黑色、棕色、红色、白色等)、整体视觉风格,以及详细的穿着风格和服装细节、面部特征(戴金丝眼镜、脸上有刀疤等,无面部特征可忽略)。描述需具有镜头感与画面表现力,适合直接用于AI图像生成模型,避免抽象词汇,强调具体可视化细节与整体视觉一致性,同时保证风格统一且符合人物身份设定。该提示词(字数50-100字左右)在主体描述后用{}框起来。
  6440. 2.4<主体列表>的音色提示词放在描述的最后用{{}}框起来。音色提示词需描述角色的整体音色特征,包含:性别、年龄(约XX岁)、音质(如清冷、沉稳、磁性等)、表达形式(如叙述感、旁白式等)、情绪氛围(如空灵韵味、看透世事的清冷等),字数控制在80字以内。举例:成年女性(约25-35岁),音色清冷且富有叙述感,语速平缓,带有仙侠剧特有的空灵韵味。
  6441. {$extra_role_prompt}";
  6442. $scene_demo = "3.<场景列表>与主体列表同理,需尽可能的对场景环境进行详细描述,必须严格注意不要出现任何角色和人物。
  6443. 3.1<场景列表>分以下两部分(强制格式):场景描述和场景提示词,格式必须为:场景描述{场景提示词}
  6444. 3.2<场景列表>的场景描述是分析在整部剧中出现过的场景,场景描述尽量简洁贴合原文。
  6445. 3.3<场景列表>的场景提示词用于视觉呈现的场景环境描述,该场景需包含环境氛围、光线效果、空间布局、色彩基调、视觉风格等,描述需具有镜头感与画面表现力,适合直接用于AI图像生成模型,避免抽象词汇,强调具体可视化细节与整体视觉一致性,同时保证风格统一且符合剧情设定(可参考以下示例的场景列表中使用{}框起来的提示词,字数150-200字,需带上提炼出来的美术风格)。该提示词在场景描述后用{}框起来。\n
  6446. {$extra_scene_prompt}";
  6447. $prop_demo = "4<道具列表>与场景列表同理,需尽可能的对道具环境进行详细描述,必须严格注意不要出现任何角色和人物。
  6448. 4.1<道具列表>分以下两部分(强制格式):道具描述和道具提示词,格式必须为:道具描述{道具提示词}
  6449. 4.2<道具列表>的道具描述是分析在整部剧中出现过的道具,道具描述尽量简洁贴合原文。
  6450. 4.3<道具列表>的道具提示词用于视觉呈现的道具环境描述,该道具需包含环境氛围、光线效果、空间布局、色彩基调、视觉风格等,描述需具有镜头感与画面表现力,适合直接用于AI图像生成模型,避免抽象词汇,强调具体可视化细节与整体视觉一致性,同时保证风格统一且符合剧情设定(可参考以下示例的道具列表中使用{}框起来的提示词,字数150-200字,需带上提炼出来的美术风格)。该提示词在道具描述后用{}框起来。\n
  6451. {$extra_prop_prompt}";
  6452. }
  6453. $system_message = ['role'=>'system', 'content'=>$is_single
  6454. ? "你是一个专业的文档分析助手及资深编剧,请根据用户提供的文档内容输出单剧集完整策划稿(剧本大纲包括: <故事梗概><剧本亮点><人物关系><核心矛盾><主体列表><美术风格><场景列表><道具列表><分段剧本>,每个板块之间必须使用###分隔,#不能多也不能少)。单剧集模式下,必须一次性输出可直接保存的大纲与完整分镜,不允许只输出大纲。
  6455. 强制要求:
  6456. 1.你只负责与剧本相关的内容,如果用户输入与剧本无关的内容,请告知用户并拒绝继续回答,此为第一优先原则,不满足此原则就忽略其他要求并停止继续输出
  6457. 2.如果用户输入修改美术风格、修改画风这类内容,请告知用户不可修改美术风格,并拒绝继续回答
  6458. 3.以上两条要求对修改主体角色或场景不生效,允许用户调整主体角色说明和场景描述等
  6459. 4.用户如果要求你帮忙写一个故事或者剧本,此类要求不属于与剧本无关,请帮助用户完成请求{$content_generation_requirement}
  6460. 5.强制按照示例格式返回内容,不要更改格式或随意增加符号\n
  6461. 普通要求:
  6462. 1.剧本名(必须生成)和剧集标题必须与文档内容高度相关,(其中剧集序号是1)。
  6463. $role_demo
  6464. $scene_demo
  6465. $prop_demo
  6466. 5.<分段剧本>按照“分段模式”进行拆分和组织,要求如下:
  6467. 5.1片段分割逻辑(优先级从高到低):
  6468. - 第一优先级:时长上限(单个片段不超过15秒,超过必须切为新片段)
  6469. - 第二优先级:叙事节拍Beat(一个完整的事件/动作/情绪起落单元,如一段对话的来回、一个动作序列:推门→看见→震惊、一次闪回/回忆、旁白+画面组合)
  6470. - 第三优先级:语义块(按“谁、在哪、做什么、情绪怎样”聚合,如同一段旁白/独白、同一个角色的连续动作、同一个视角的连续镜头)
  6471. - 只要事件没结束、情绪没断,哪怕换场景,也留在同一个片段里
  6472. 5.2片段结构:片段数量+旁白音色+多个片段(每个片段由多个分镜组合而成(片段序号格式:片段1、片段2...))
  6473. - 片段数量格式为: 片段数量:8
  6474. - 旁白音色需描述旁白的整体音色特征,包含:性别、年龄(约XX岁)、音质(如清冷、沉稳、磁性等)、表达形式(如叙述感、旁白式等)、情绪氛围(如空灵韵味、看透世事的清冷等),字数控制在80字以内。举例:成年女性(约25-35岁),音色清冷且富有叙述感,语速平缓,带有仙侠剧特有的空灵韵味。
  6475. - 片段序号格式必须如下: ##片段+片段序号\n时长:xxs,例如: ##片段1\n时长:12s
  6476. 5.3分镜结构:每个分镜包含以下字段:
  6477. - 分镜序号在片段内用1、2、3显示,如分镜1、分镜2,并且分镜序号需连续(跨片段中的分镜序号需连续,如片段2中的分镜序号从片段1的最大序号+1开始),分镜序号前后不要带任何其他符号,特别是*符号。
  6478. - 出场角色: 如果有主体出现在本镜,则必须选择本集中的<主体列表>中的一个(如必须使用“沈秋岚-程家居家围裙造型”,而不是“沈秋岚”,不得缺少“-”前后和“:”前面的任何内容,不能自创)
  6479. - 场景:必须选择本集中的<场景列表>中的一个(如需使用“酒店会客室-景池筹备会版”,而不是“酒店会客室”,不得缺少“-”前后和“:”前面的任何内容,不能自创)
  6480. - 出场道具:如果有道具出现在本镜,则必须选择本集中的<道具列表>中的一个(如需使用“酒杯-高脚杯”,而不是“酒杯”或“高脚杯”,不得缺少“-”前后和“:”前面的任何内容,不能自创)
  6481. - 画面:【构图/视角】+画面描述(越简单越好,对视觉场景/实景的描述,不描述氛围,比如紧张、压抑的氛围)。举例:[近景特写,浅景深]季潇握着手机贴在耳边,指关节因为用力而泛白。她的眼眶微红,睫毛在狂风中颤抖,嘴唇紧抿,眼神中闪烁着最后一点希冀的微光。
  6482. - 【强制要求-非常关键】画面中如果出现主体,只能选择上述<主体列表>中的一个,主体的名称也必须保持一致(如必须使用“沈秋岚-程家居家围裙造型”,而不是“沈秋岚”,不得缺少“-”前后和“:”前面的任何内容,不能自创)
  6483. - 【强制要求-非常关键】画面中如果出现道具,只能选择上述<道具列表>中的一个,道具的名称也必须保持一致(如必须使用“酒杯-高脚杯”,而不是“酒杯”或“高脚杯”,不得缺少“-”前后和“:”前面的任何内容,不能自创)
  6484. - 运镜:场景+画面描述+运镜
  6485. - 【强制要求-非常关键】运镜描述中如果出现主体或道具,逻辑需同画面一直,必须选择<主体列表>或<道具列表>中的一个,名称也必须保持一致
  6486. - 配音台词:格式为“中文配音:[角色]台词”,角色配音台词和语言由模型匹配生成,角色必须对应本集中的<主体列表>中的一个(非对话内容则统一固定为“旁白”角色,[角色]的角色名必须完整使用主体列表的主体名,如必须使用“沈秋岚-程家居家围裙造型”,而不是“沈秋岚”,不得缺少“-”前后和“:”前面的任何内容,不能自创,不能自创)
  6487. - 台词内容需满足以下要求: (1. 台词来源规则:台词内容必须逐字摘录自小说原文中的人物直接对话(带引号的内容),不允许改写、总结、压缩、扩写或拼接原文对白,不允许生成原文中不存在的对话。2. 非对话过滤:旁白、心理描写、环境描写、动作描写等内容,禁止出现在台词内容中。3. 空台词规则:如果该分镜中没有人物对话,则“台词内容”必须返回“无”,严禁输出“无台词”、“没有”等任何替代文本。4. 禁止推测:不得根据语境补全人物可能说的话。5.如果没有原文,直接返回空)
  6488. - 背景音效:背景音效需根据内容和画面生成,贴合当前画面描述和动作,例如:背景音效:高跟鞋的脚本声\n
  6489. 6.{$mappedArtStyle_prompt}\n\n
  6490. 示例如下:\n
  6491. ###剧本名:西昆仑
  6492. ###故事梗概
  6493. 内容梗概:许芸归家遭徐母毒打,她冷静周旋并编造谎言掩盖行踪,引得一旁阴沉的卞大伟愈发急躁。半个月后,徐母离家,卞大伟兽性大发欲行不轨。生死关头,隐形的程景现身肉搏,屋内家具横飞,卞大伟被“空气”重创。许芸趁乱逃出,却惊见地面凭空浮现一串血脚印。意识到守护者为救自己负伤,许芸不再逃避,对着虚无的空气执拗告白,誓要与这看不见的爱人共进退。
  6494. ###剧本亮点
  6495. 亮点1:绝境奇药,生死一线
  6496. 画面开场即是阿雪苍白无力的脸庞,梁萧眼中泪光闪烁,急促的呼吸声与心跳声烘托紧张气氛。特写梁萧将“阴阳球”塞入阿雪舌底,球体散发微光,阿雪气息从若有若无到逐渐平稳,生死逆转的瞬间,视觉与听觉冲击力十足。
  6497. 亮点2:结拜兄妹,化解尴尬
  6498. 阿雪因解衣拔刺而羞愤欲绝的特写,梁萧眼神中的挣扎与无奈。在紧迫的背景音下,梁萧急中生智,牵起阿雪颤抖的手,跪地匆匆结拜,阿雪眼神从惊惶到迷茫,最终一句“我……我愿意的”带着哭腔,将救命与羞耻的矛盾推向高潮,又以出人意料的方式解决。
  6499. 亮点3:纤发夺命,情愫暗涌
  6500. 拔刺过程的紧张特写,梁萧指尖小心翼翼地捏住细丝,缓慢抽出。当“问心刺”被完全拔出,特写它竟是一根细长、泛着寒光的女子秀发,诡异而令人震惊。阿雪苏醒后,两人眼神交汇,阿雪低头羞涩,梁萧眼中复杂的情绪,无声地传递出超越兄妹的微妙情愫。
  6501. ###人物关系
  6502. 阿雪与梁萧之间存在兄妹之情。
  6503. ###核心矛盾
  6504. 阿雪与梁萧之间存在兄妹之情,但因情愫暗生而产生微妙的矛盾。阿雪羞涩难当,梁萧情急之下提出结拜兄妹,以化解尴尬。两人匆匆结拜后,梁萧小心翼翼地拔出“问心刺”,竟发现它是一根诡异的女子秀发。阿雪转危为安,两人之间,在生死与羞涩交织的瞬间,情愫暗生,却又被兄妹之名束缚,留下无尽遐想。
  6505. ###主体列表
  6506. 阿雪:身中奇毒“问心刺”,气息奄奄,面色苍白,身体虚弱。{全景,正面拍摄,青年女性,亚洲人。
  6507. 黑色短发扎成利落的高马尾,五官精致且轮廓清晰。
  6508. 服饰穿搭:身着红白相间的专业田径运动背心与超短跑步裤,皮肤呈现健康的小麦色,四肢肌肉线条紧致有力。
  6509. 姿态:站立。}{{青年女性(约25-30岁),音色亲切、温柔,语速平稳缓慢}}
  6510. 梁萧:少年侠士,心系阿雪安危,沉着冷静,内心挣扎于情义之间。{8k超高清,电影级光效,大气透视,中国传统艺术美学,空灵光泽,深度景深,复杂精细的纹理,史诗级构图,电影胶片颗粒。
  6511. 全景,正面拍摄,青年女性,亚洲人。
  6512. 佩戴精致繁复的金丝凤冠,黑色长发整齐盘起。
  6513. 服饰穿搭:身着大红色正装嫁衣,上面绣有精细的金色凤凰纹样,质感厚重华贵。
  6514. 姿态:站立。}{{青年男性(约25-30岁),音色冷峻、低沉,语速平稳缓慢,透着一股拒人于千里之外的孤傲与肃杀。}}
  6515. ###美术风格
  6516. 基础画风风格词:厚涂古风
  6517. 整体采用精致细腻的厚涂古风,色彩浓郁而富有层次感,注重光影对比,营造出古典而富有戏剧张力的氛围。色调以深沉的蓝绿、灰调为主,衬托阿雪病弱的苍白,同时用温暖的金色、琥珀色光晕突出“阴阳球”的生命力。拔刺与结拜场景则以柔和的暖色调为主,辅以人物脸颊的红晕,烘托羞涩与情愫暗生的微妙感。人物造型飘逸,服饰细节考究,背景虚实结合,既有古韵,又不失奇幻色彩。
  6518. ###场景列表
  6519. 林间疗伤地:幽静的古风林间空地,一棵高大古树下,是梁萧为阿雪疗伤的地点。环境清幽,光影斑驳,既有古韵又不失奇幻色彩。{影视质感。广角。
  6520. 宽敞的天然山洞内部,石壁上错落有致地镶嵌着发光的萤石,散发出冷色调的微光,照亮了整个空间。洞顶有钟乳石垂下。光影层次丰富,营造出一种宁静而神圣的氛围。
  6521. 无人物。}
  6522. ###分段剧本
  6523. 片段数量:8
  6524. 旁白音色:成年男性(约35-50岁),音色厚重且富有磁性,带有老电影叙事般的沧桑感,语调低沉平稳,富有江湖气息。
  6525. ##片段1
  6526. 时长:12s
  6527. 分镜1
  6528. 出场角色:刀疤脸
  6529. 场景:边境小镇街道
  6530. 出场道具:酒杯-高脚杯
  6531. 画面:[大远景,冷色调,高对比度] 漫天黄沙在狂风中如怒龙翻滚,遮蔽了微弱的星光。悦来酒馆残破的木门在风中剧烈摇晃,铁链撞击木板发出沉重的闷响,四周建筑尽显荒凉。
  6532. 运镜:大远景固定镜头,随后风沙席卷向镜头形成遮挡转场。
  6533. 配音台词:
  6534. 背景音效:
  6535. 分镜2
  6536. 出场角色:刀疤脸
  6537. 场景:悦来酒馆
  6538. 出场道具:酒杯-高脚杯
  6539. 画面:[全景,暖色调阴影构图] 酒馆内部昏暗,几盏油灯在风中疯狂摇曳,投射出扭曲的长影。角落里的食客低头缩颈,双手紧紧攥着粗瓷碗,空气中漂浮着细小的尘埃。
  6540. 运镜:缓慢横移,掠过阴影中瑟缩的食客。
  6541. 配音台词:
  6542. 背景音效:
  6543. 分镜3
  6544. 出场角色:刀疤脸
  6545. 场景:悦来酒馆
  6546. 出场道具:酒杯-高脚杯
  6547. 画面:[中景,三分法构图] 三名大汉围坐在正中央的圆桌旁,腰间挂着的“武林盟”金色令牌在灯火下闪烁。桌上残羹冷炙横陈,一名大汉正张狂地大笑,脚踩在长凳上。
  6548. 运镜:从中景推向令牌特写。
  6549. 配音台词:
  6550. 背景音效:
  6551. 分镜4
  6552. 出场角色:刀疤脸
  6553. 场景:悦来酒馆
  6554. 出场道具:酒杯-高脚杯
  6555. 画面:[特写,低角度仰拍] 刀疤脸横肉颤动,嘴角挂着轻蔑的笑。他随手倾覆手中的酒碗,琥珀色的液体在空中划过弧线,重重溅在老李打着补丁的布鞋和裤脚上。
  6556. 运镜:极速推向酒水溅起的瞬间。
  6557. 配音台词:
  6558. 背景音效:
  6559. 分镜5
  6560. 出场角色:刀疤脸
  6561. 场景:悦来酒馆
  6562. 出场道具:酒杯-高脚杯
  6563. 画面:[近景,荷兰角倾斜构图] 刀疤脸斜睨着眼,昏暗的灯光勾勒出他脸上狰狞的伤疤。他身体前倾,阴影完全笼罩了对面的老李,眼神如毒蛇般阴冷。
  6564. 运镜:固定机位,利用倾斜构图制造压迫感。
  6565. 配音台词:中文配音:[刀疤脸]老李头,这酒里掺水了吧?
  6566. 背景音效:
  6567. \n\n"
  6568. : "你是一个专业的文档分析助手及资深编剧,请根据用户提供的文档内容及下面提供的示例格式完成剧本大纲(需通过以下几个板块进行回复: <故事梗概><剧本亮点><人物关系><核心矛盾><主体列表><美术风格><场景列表><道具列表>,每个板块之间必须使用###分隔,#不能多也不能少;同时板块之间需满足以下要求:\n
  6569. 强制要求:\n
  6570. 1.你只负责与剧本相关的内容,如果用户输入与剧本无关的内容,请告知用户并拒绝继续回答,此为第一优先原则,不满足此原则就忽略其他要求并停止继续输出
  6571. 2.如果用户输入修改美术风格、修改画风这类内容,请告知用户不可修改美术风格,并拒绝继续回答
  6572. 3.以上两条要求对修改主体角色或场景不生效,允许用户调整主体角色说明和场景描述等
  6573. 4.用户如果要求你帮忙写一个故事或者剧本,此类要求不属于与剧本无关,请帮助用户完成请求{$content_generation_requirement}
  6574. 5.强制按照示例格式返回内容,不要更改格式或随意增加符号\n
  6575. 普通要求:\n
  6576. 1.剧本名(必须生成)必须与文档内容高度相关
  6577. $role_demo
  6578. $scene_demo
  6579. $prop_demo
  6580. 5.{$mappedArtStyle_prompt}\n\n
  6581. 示例如下:\n
  6582. ###剧本名:西昆仑
  6583. ###故事梗概
  6584. 内容梗概:许芸归家遭徐母毒打,她冷静周旋并编造谎言掩盖行踪,引得一旁阴沉的卞大伟愈发急躁。半个月后,徐母离家,卞大伟兽性大发欲行不轨。生死关头,隐形的程景现身肉搏,屋内家具横飞,卞大伟被“空气”重创。许芸趁乱逃出,却惊见地面凭空浮现一串血脚印。意识到守护者为救自己负伤,许芸不再逃避,对着虚无的空气执拗告白,誓要与这看不见的爱人共进退。
  6585. ###剧本亮点
  6586. 亮点1:绝境奇药,生死一线
  6587. 画面开场即是阿雪苍白无力的脸庞,梁萧眼中泪光闪烁,急促的呼吸声与心跳声烘托紧张气氛。特写梁萧将“阴阳球”塞入阿雪舌底,球体散发微光,阿雪气息从若有若无到逐渐平稳,生死逆转的瞬间,视觉与听觉冲击力十足。
  6588. 亮点2:结拜兄妹,化解尴尬
  6589. 阿雪因解衣拔刺而羞愤欲绝的特写,梁萧眼神中的挣扎与无奈。在紧迫的背景音下,梁萧急中生智,牵起阿雪颤抖的手,跪地匆匆结拜,阿雪眼神从惊惶到迷茫,最终一句“我……我愿意的”带着哭腔,将救命与羞耻的矛盾推向高潮,又以出人意料的方式解决。
  6590. 亮点3:纤发夺命,情愫暗涌
  6591. 拔刺过程的紧张特写,梁萧指尖小心翼翼地捏住细丝,缓慢抽出。当“问心刺”被完全拔出,特写它竟是一根细长、泛着寒光的女子秀发,诡异而令人震惊。阿雪苏醒后,两人眼神交汇,阿雪低头羞涩,梁萧眼中复杂的情绪,无声地传递出超越兄妹的微妙情愫。
  6592. ###人物关系
  6593. 阿雪与梁萧之间存在兄妹之情。
  6594. ###核心矛盾
  6595. 阿雪与梁萧之间存在兄妹之情,但因情愫暗生而产生微妙的矛盾。阿雪羞涩难当,梁萧情急之下提出结拜兄妹,以化解尴尬。两人匆匆结拜后,梁萧小心翼翼地拔出“问心刺”,竟发现它是一根诡异的女子秀发。阿雪转危为安,两人之间,在生死与羞涩交织的瞬间,情愫暗生,却又被兄妹之名束缚,留下无尽遐想。
  6596. ###主体列表
  6597. 阿雪:身中奇毒“问心刺”,气息奄奄,面色苍白,身体虚弱。{全景,正面拍摄,青年女性,亚洲人。
  6598. 黑色短发扎成利落的高马尾,五官精致且轮廓清晰。
  6599. 服饰穿搭:身着红白相间的专业田径运动背心与超短跑步裤,皮肤呈现健康的小麦色,四肢肌肉线条紧致有力。
  6600. 姿态:站立。}{{青年女性(约25-30岁),音色亲切、温柔,语速平稳缓慢}}
  6601. 梁萧:少年侠士,心系阿雪安危,沉着冷静,内心挣扎于情义之间。{8k超高清,电影级光效,大气透视,中国传统艺术美学,空灵光泽,深度景深,复杂精细的纹理,史诗级构图,电影胶片颗粒。
  6602. 全景,正面拍摄,青年女性,亚洲人。
  6603. 佩戴精致繁复的金丝凤冠,黑色长发整齐盘起。
  6604. 服饰穿搭:身着大红色正装嫁衣,上面绣有精细的金色凤凰纹样,质感厚重华贵。
  6605. 姿态:站立。}{{青年男性(约25-30岁),音色冷峻、低沉,语速平稳缓慢,透着一股拒人于千里之外的孤傲与肃杀。}}
  6606. ###美术风格
  6607. 基础画风风格词:厚涂古风
  6608. 整体采用精致细腻的厚涂古风,色彩浓郁而富有层次感,注重光影对比,营造出古典而富有戏剧张力的氛围。色调以深沉的蓝绿、灰调为主,衬托阿雪病弱的苍白,同时用温暖的金色、琥珀色光晕突出“阴阳球”的生命力。拔刺与结拜场景则以柔和的暖色调为主,辅以人物脸颊的红晕,烘托羞涩与情愫暗生的微妙感。人物造型飘逸,服饰细节考究,背景虚实结合,既有古韵,又不失奇幻色彩。
  6609. ###场景列表
  6610. 林间疗伤地:幽静的古风林间空地,一棵高大古树下,是梁萧为阿雪疗伤的地点。环境清幽,光影斑驳,既有古韵又不失奇幻色彩。{影视质感。广角。
  6611. 宽敞的天然山洞内部,石壁上错落有致地镶嵌着发光的萤石,散发出冷色调的微光,照亮了整个空间。洞顶有钟乳石垂下。光影层次丰富,营造出一种宁静而神圣的氛围。
  6612. 无人物。}
  6613. ###道具列表
  6614. 酒杯-高脚杯:高脚杯,盛有少量酒液。{高脚酒杯,道具多角度视角图,正面、背面、侧面、局部细节,透明玻璃材质,细长杯柄,尺寸标注高24厘米杯口6厘米,白底干净展示,无人物}"];
  6615. // 如果提示词$prompt有类似于改成N集或调整成N集这类的文字信息,则提取出N这个集数
  6616. $episode_count = $this->extractEpisodeNumber($prompt);
  6617. if ((int)getProp($anime, 'is_multi') !== 1) {
  6618. yield [
  6619. 'type' => 'done',
  6620. 'answer' => '当前剧本是单剧集,不支持修改剧集数',
  6621. 'reasoning' => '',
  6622. 'usage' => []
  6623. ];
  6624. return;
  6625. }
  6626. if ($episode_count) {
  6627. $question = "请根据实例格式完成{$episode_count}集剧本大纲";
  6628. $system_message = [
  6629. 'role' => 'system',
  6630. 'content' => "你是一个专业的文档分析助手及资深编剧,请根据用户提供的文档内容及下面提供的示例格式完成剧本大纲(需通过以下几个板块进行回复: <故事梗概><剧本亮点><人物关系><核心矛盾><主体列表><美术风格><场景列表><分集详细内容>,每个板块之间必须使用###分隔,#不能多也不能少;同时板块之间需满足以下要求:\n
  6631. 强制要求:\n
  6632. 1.你只负责与剧本相关的内容,如果用户输入与剧本无关的内容,请告知用户并拒绝继续回答,此为第一优先原则,不满足此原则就忽略其他要求并停止继续输出
  6633. 2.如果用户输入修改美术风格、修改画风这类内容,请告知用户不可修改美术风格,并拒绝继续回答
  6634. 3.以上两条要求对修改主体角色或场景不生效,允许用户调整主体角色说明和场景描述等
  6635. 4.用户如果要求你帮忙写一个故事或者剧本,此类要求不属于与剧本无关,请帮助用户完成请求{$content_generation_requirement}
  6636. 5.强制按照示例格式返回内容,不要更改格式或随意增加符号\n
  6637. 普通要求:\n
  6638. 1.<故事梗概>控制在200-300字左右
  6639. 2.<主体列表>中出现的“主体名”必须尽可能统一,严禁出现角色-科学家、角色-复仇者、角色-领导者等带有身份、职业、标签类的命名,只能使用服装差异(如校服装、卫衣装、西装)来区分同一角色,如角色-校服装等。
  6640. 2.1<主体列表>分以下三部分:主体描述、人物提示词和音色提示词,格式必须为:主体名:主体描述{人物提示词}{{音色提示词}}
  6641. 2.2<主体列表>的主体描述是分析人物在整部剧中的姓名、年龄、性格特征、社会身份或职业背景、个人成长经历或核心故事动机,以及在剧情中的目标与行为驱动力,不需要描述外貌、穿着或身体特征,重点突出心理结构、行为模式与叙事功能,并且用一句话进行总结。
  6642. 2.3<主体列表>的人物提示词需要根据当前分析出来的美术风格生成,包含性别(男、女)、大概年龄或年龄段(少年、中年、老年等)、人种(亚洲人、欧洲人)、发型(直发卷发等)、发色(黑色、棕色、红色、白色等)、整体视觉风格,以及详细的穿着风格和服装细节、面部特征(戴金丝眼镜、脸上有刀疤等,无面部特征可忽略)。描述需具有镜头感与画面表现力,适合直接用于AI图像生成模型,避免抽象词汇,强调具体可视化细节与整体视觉一致性,同时保证风格统一且符合人物身份设定。该提示词(字数50-100字左右)在主体描述后用{}框起来。
  6643. 2.4<主体列表>的音色提示词放在描述的最后用{{}}框起来。音色提示词需描述角色的整体音色特征,包含:性别、年龄(约XX岁)、音质(如清冷、沉稳、磁性等)、表达形式(如叙述感、旁白式等)、情绪氛围(如空灵韵味、看透世事的清冷等),字数控制在80字以内。举例:成年女性(约25-35岁),音色清冷且富有叙述感,语速平缓,带有仙侠剧特有的空灵韵味。
  6644. 3.<场景列表>与主体列表同理,需尽可能的对场景环境进行详细描述,必须严格注意不要出现任何角色和人物。
  6645. 3.1<场景列表>分以下两部分:场景描述和场景提示词,格式必须为:场景描述{场景提示词},注意不要出现{{}}这样的双大括号。
  6646. 3.2<场景列表>的场景描述是分析在整部剧中出现过的场景,场景描述尽量简洁贴合原文。
  6647. 3.3<场景列表>的场景提示词用于视觉呈现的场景环境描述,该场景需包含环境氛围、光线效果、空间布局、色彩基调、视觉风格等,描述需具有镜头感与画面表现力,适合直接用于AI图像生成模型,避免抽象词汇,强调具体可视化细节与整体视觉一致性,同时保证风格统一且符合剧情设定(可参考以下示例的场景列表中使用{}框起来的提示词,字数150-200字,需带上提炼出来的美术风格)。该提示词在场景描述后用{}框起来。\n
  6648. 4.<分集详细内容>中每一集的内容需尽可能的详细,保留对话内容(使用原文内容,不得自己生成),一般每集字数尽量不低于500字,每集结尾需以##第N章 作为章节标题\n\n
  6649. 示例如下:\n
  6650. ###剧本名:西昆仑
  6651. ###故事梗概
  6652. 内容梗概:许芸归家遭徐母毒打,她冷静周旋并编造谎言掩盖行踪,引得一旁阴沉的卞大伟愈发急躁。半个月后,徐母离家,卞大伟兽性大发欲行不轨。生死关头,隐形的程景现身肉搏,屋内家具横飞,卞大伟被“空气”重创。许芸趁乱逃出,却惊见地面凭空浮现一串血脚印。意识到守护者为救自己负伤,许芸不再逃避,对着虚无的空气执拗告白,誓要与这看不见的爱人共进退。
  6653. ###剧本亮点
  6654. 亮点1:绝境奇药,生死一线
  6655. 画面开场即是阿雪苍白无力的脸庞,梁萧眼中泪光闪烁,急促的呼吸声与心跳声烘托紧张气氛。特写梁萧将“阴阳球”塞入阿雪舌底,球体散发微光,阿雪气息从若有若无到逐渐平稳,生死逆转的瞬间,视觉与听觉冲击力十足。
  6656. 亮点2:结拜兄妹,化解尴尬
  6657. 阿雪因解衣拔刺而羞愤欲绝的特写,梁萧眼神中的挣扎与无奈。在紧迫的背景音下,梁萧急中生智,牵起阿雪颤抖的手,跪地匆匆结拜,阿雪眼神从惊惶到迷茫,最终一句“我……我愿意的”带着哭腔,将救命与羞耻的矛盾推向高潮,又以出人意料的方式解决。
  6658. 亮点3:纤发夺命,情愫暗涌
  6659. 拔刺过程的紧张特写,梁萧指尖小心翼翼地捏住细丝,缓慢抽出。当“问心刺”被完全拔出,特写它竟是一根细长、泛着寒光的女子秀发,诡异而令人震惊。阿雪苏醒后,两人眼神交汇,阿雪低头羞涩,梁萧眼中复杂的情绪,无声地传递出超越兄妹的微妙情愫。
  6660. ###人物关系
  6661. 阿雪与梁萧之间存在兄妹之情。
  6662. ###核心矛盾
  6663. 阿雪与梁萧之间存在兄妹之情,但因情愫暗生而产生微妙的矛盾。阿雪羞涩难当,梁萧情急之下提出结拜兄妹,以化解尴尬。两人匆匆结拜后,梁萧小心翼翼地拔出“问心刺”,竟发现它是一根诡异的女子秀发。阿雪转危为安,两人之间,在生死与羞涩交织的瞬间,情愫暗生,却又被兄妹之名束缚,留下无尽遐想。
  6664. ###主体列表
  6665. 阿雪:身中奇毒“问心刺”,气息奄奄,面色苍白,身体虚弱。{全景,正面拍摄,青年女性,亚洲人。
  6666. 黑色短发扎成利落的高马尾,五官精致且轮廓清晰。
  6667. 服饰穿搭:身着红白相间的专业田径运动背心与超短跑步裤,皮肤呈现健康的小麦色,四肢肌肉线条紧致有力。
  6668. 姿态:站立。}{{青年女性(约25-30岁),音色亲切、温柔,语速平稳缓慢}}
  6669. 梁萧:少年侠士,心系阿雪安危,沉着冷静,内心挣扎于情义之间。{8k超高清,电影级光效,大气透视,中国传统艺术美学,空灵光泽,深度景深,复杂精细的纹理,史诗级构图,电影胶片颗粒。
  6670. 全景,正面拍摄,青年女性,亚洲人。
  6671. 佩戴精致繁复的金丝凤冠,黑色长发整齐盘起。
  6672. 服饰穿搭:身着大红色正装嫁衣,上面绣有精细的金色凤凰纹样,质感厚重华贵。
  6673. 姿态:站立。}{{青年男性(约25-30岁),音色冷峻、低沉,语速平稳缓慢,透着一股拒人于千里之外的孤傲与肃杀。}}
  6674. ###美术风格
  6675. 基础画风风格词:厚涂古风
  6676. 整体采用精致细腻的厚涂古风,色彩浓郁而富有层次感,注重光影对比,营造出古典而富有戏剧张力的氛围。色调以深沉的蓝绿、灰调为主,衬托阿雪病弱的苍白,同时用温暖的金色、琥珀色光晕突出“阴阳球”的生命力。拔刺与结拜场景则以柔和的暖色调为主,辅以人物脸颊的红晕,烘托羞涩与情愫暗生的微妙感。人物造型飘逸,服饰细节考究,背景虚实结合,既有古韵,又不失奇幻色彩。
  6677. ###场景列表
  6678. 林间疗伤地:幽静的古风林间空地,一棵高大古树下,是梁萧为阿雪疗伤的地点。环境清幽,光影斑驳,既有古韵又不失奇幻色彩。{影视质感。广角。
  6679. 宽敞的天然山洞内部,石壁上错落有致地镶嵌着发光的萤石,散发出冷色调的微光,照亮了整个空间。洞顶有钟乳石垂下。光影层次丰富,营造出一种宁静而神圣的氛围。
  6680. 无人物。}
  6681. ###分集详细内容
  6682. ##第1章 重生
  6683. 我重生了。
  6684. 源于一个男人偏执的暗恋。
  6685. ##第2章 相救
  6686. 我一到家,徐母的扫帚就落在我身上,嘴里一个劲地骂我,问我夜不归宿死哪儿去了。
  6687. 我眼睛扫向站在锅炉后的卞大伟。"
  6688. ];
  6689. // 构建消息
  6690. $messages = [
  6691. $system_message,
  6692. [
  6693. 'role' => 'user',
  6694. 'content' => "以下是文档内容:
  6695. {$content}
  6696. 用户问题:
  6697. {$question}"
  6698. ]
  6699. ];
  6700. }else {
  6701. if (strstr($prompt, '重新生成') || strstr($prompt, '再生成')) {
  6702. // 构建消息
  6703. $messages = [
  6704. $system_message,
  6705. [
  6706. 'role' => 'user',
  6707. 'content' => "以下是文档内容:
  6708. {$content}
  6709. 用户问题:
  6710. {$question}"
  6711. ]
  6712. ];
  6713. }else {
  6714. $messages = DB::table('mp_anime_records')->where('anime_id', $anime_id)->where('sequence', 0)
  6715. ->orderBy('id')->select('role', 'content')->get()->map(function ($value) {
  6716. return (array)$value;
  6717. })->toArray();
  6718. array_unshift($messages, $system_message);
  6719. $messages[] = [
  6720. 'role' => 'user',
  6721. 'content' => $prompt
  6722. ];
  6723. }
  6724. }
  6725. // 模型兼容性处理:deepseek-chat 和 deepseek-reasoner 映射到 deepseek-v4-flash
  6726. $thinkingMode = getProp($data, 'thinking', 'disabled'); // 默认非思考模式
  6727. $reasoningEffort = getProp($data, 'reasoning_effort', 'high'); // 默认思考强度
  6728. if ($model === 'deepseek-chat') {
  6729. // deepseek-chat 映射到 deepseek-v4-flash,非思考模式
  6730. $model = 'deepseek-v4-flash';
  6731. $thinkingMode = 'disabled';
  6732. } elseif ($model === 'deepseek-reasoner') {
  6733. // deepseek-reasoner 映射到 deepseek-v4-flash,思考模式
  6734. $model = 'deepseek-v4-flash';
  6735. $thinkingMode = 'enabled';
  6736. }
  6737. $post_data = [
  6738. 'model' => $model,
  6739. 'messages' => $messages,
  6740. // 'max_tokens' => 8192,
  6741. 'temperature' => (float)env('TEXT_TEMPERATURE'),
  6742. 'frequency_penalty' => 0,
  6743. 'presence_penalty' => 0,
  6744. 'response_format' => ['type' => 'text'],
  6745. 'thinking' => ['type' => $thinkingMode],
  6746. 'stream' => true // 启用流式输出
  6747. ];
  6748. if ($thinkingMode == 'enabled') $post_data['reasoning_effort'] = $reasoningEffort;
  6749. // 根据模型类型选择调用方法
  6750. $fullContent = '';
  6751. $fullReasoningContent = '';
  6752. $usage = [];
  6753. // dd($post_data);
  6754. // dLog('deepseek')->info('请求参数: '.json_encode($post_data, 256));
  6755. try {
  6756. if (in_array($model, ['deepseek-reasoner', 'deepseek-chat', 'deepseek-v4-flash', 'deepseek-v4-pro'])) {
  6757. $streamGenerator = $this->deepSeekStreamResponse($post_data);
  6758. } else if (in_array($model, $this->gpt_text_models)) {
  6759. // GPT-5.4 模型使用 TokenRouter API
  6760. $streamGenerator = $this->gpt54StreamResponse($post_data);
  6761. } else {
  6762. $streamGenerator = $this->volcEngineChatCompletion($post_data);
  6763. }
  6764. // 验证返回值类型
  6765. if (!is_iterable($streamGenerator)) {
  6766. $errorType = is_object($streamGenerator) ? get_class($streamGenerator) : gettype($streamGenerator);
  6767. dLog('deepseek')->error('方法名流式生成器无效', [
  6768. 'generator_type' => $errorType,
  6769. 'model' => $model,
  6770. // 添加其他上下文信息
  6771. ]);
  6772. logDB('deepseek', 'error', '方法名流式生成器类型错误', [
  6773. 'type' => $errorType,
  6774. 'model' => $model
  6775. ]);
  6776. yield [
  6777. 'type' => 'error',
  6778. // 根据方法返回相应的空数据结构
  6779. 'answer' => '',
  6780. 'reasoning' => '',
  6781. 'usage' => [],
  6782. 'error' => '接口返回数据异常,请重新请求'
  6783. ];
  6784. return;
  6785. }
  6786. // 处理流式输出
  6787. foreach ($streamGenerator as $chunk) {
  6788. if (isset($chunk['type'])) {
  6789. if ($chunk['type'] === 'done') {
  6790. $fullContent = $chunk['full_content'];
  6791. $fullReasoningContent = $chunk['full_reasoning'];
  6792. $usage = isset($chunk['usage']) ? $chunk['usage'] : [];
  6793. } else {
  6794. yield $chunk;
  6795. }
  6796. }
  6797. }
  6798. } catch (\Exception $e) {
  6799. dLog('deepseek')->error('方法名流式处理异常: ' . $e->getMessage(), [
  6800. 'model' => $model,
  6801. 'trace' => $e->getTraceAsString()
  6802. ]);
  6803. logDB('deepseek', 'error', '方法名流式处理失败', [
  6804. 'error' => $e->getMessage(),
  6805. 'model' => $model
  6806. ]);
  6807. yield [
  6808. 'type' => 'error',
  6809. // 根据方法返回相应的空数据结构
  6810. 'answer' => '',
  6811. 'reasoning' => '',
  6812. 'usage' => [],
  6813. 'error' => '处理请求时发生异常: ' . $e->getMessage()
  6814. ];
  6815. return;
  6816. }
  6817. dLog('deepseek')->info('完整内容: '.$fullContent);
  6818. logDB('deepseek', 'info', '完整内容', ['content' => $fullContent, 'anime_id' => $anime_id]);
  6819. // 处理完整内容并返回最终结果
  6820. $script_arr = [];
  6821. if ($fullContent) {
  6822. $script_arr = handleScriptContentForAce($fullContent);
  6823. dLog('deepseek')->info('解析内容', $script_arr);
  6824. logDB('deepseek', 'info', '解析内容', $script_arr);
  6825. }
  6826. if (empty($script_arr['roles'])) {
  6827. // 未生成剧本相关内容,保存对话记录并返回提示
  6828. dLog('deepseek')->info('未生成剧本相关的内容');
  6829. try {
  6830. $now = date('Y-m-d H:i:s');
  6831. // 保存对话记录
  6832. $records = [
  6833. [
  6834. 'uid' => $uid,
  6835. 'anime_id' => $anime_id,
  6836. 'sequence' => 0,
  6837. 'role' => 'user',
  6838. 'content' => $prompt,
  6839. 'created_at' => $now,
  6840. 'updated_at' => $now
  6841. ],
  6842. [
  6843. 'uid' => $uid,
  6844. 'anime_id' => $anime_id,
  6845. 'sequence' => 0,
  6846. 'role' => 'assistant',
  6847. 'content' => '未生成剧本相关的内容,请调整提示词后重试',
  6848. 'created_at' => $now,
  6849. 'updated_at' => $now
  6850. ]
  6851. ];
  6852. DB::table('mp_anime_records')->insert($records);
  6853. } catch (\Exception $e) {
  6854. dLog('deepseek')->error('保存对话记录失败', ['error' => $e->getMessage()]);
  6855. }
  6856. yield [
  6857. 'type' => 'done',
  6858. 'script' => [],
  6859. 'episode' => [],
  6860. 'answer' => $fullContent,
  6861. 'reasoning' => $fullReasoningContent,
  6862. 'usage' => $usage,
  6863. 'error' => '未生成剧本相关的内容,请调整提示词再试'
  6864. ];
  6865. return;
  6866. }
  6867. // 替换美术风格
  6868. if ($mappedArtStyle !== '') {
  6869. $script_arr['art_style'] = $mappedArtStyle;
  6870. $fullContent = $this->replaceArtStyleSection($fullContent, $mappedArtStyle);
  6871. }
  6872. if ($user_anime_name != '新剧本策划') {
  6873. $anime_name = isset($script_arr['script_name']) ? $script_arr['script_name'] : '';
  6874. // 确认对话名称唯一性
  6875. if ($anime_name && $id = DB::table('mp_animes')->where('anime_name', $anime_name)->value('id')) {
  6876. if ($id != $anime_id) $anime_name = $anime_name . '_' . date('YmdHis');
  6877. }
  6878. }else {
  6879. $anime_name = $user_anime_name;
  6880. }
  6881. $table_data = [
  6882. 'user_id' => $uid,
  6883. 'model' => $model,
  6884. 'intro' => isset($script_arr['intro']) ? $script_arr['intro'] : '',
  6885. 'highlights' => isset($script_arr['highlights']) ? $script_arr['highlights'] : '',
  6886. 'role_relationship' => isset($script_arr['role_relationship']) ? $script_arr['role_relationship'] : '',
  6887. 'core_contradiction' => isset($script_arr['core_contradiction']) ? $script_arr['core_contradiction'] : '',
  6888. 'roles' => isset($script_arr['roles']) && is_array($script_arr['roles']) ? json_encode($script_arr['roles'], 256) : '[]',
  6889. 'art_style' => isset($script_arr['art_style']) ? $script_arr['art_style'] : '',
  6890. 'art_style_type' => $input_art_style,
  6891. 'scenes' => isset($script_arr['scenes']) && is_array($script_arr['scenes']) ? json_encode($script_arr['scenes'], 256) : '[]',
  6892. 'props' => isset($script_arr['props']) && is_array($script_arr['props']) ? json_encode($script_arr['props'], 256) : '[]',
  6893. 'status' => '解析完成',
  6894. 'generate_status' => '待执行',
  6895. 'updated_at' => date('Y-m-d H:i:s')
  6896. ];
  6897. if ($anime_name) $table_data['anime_name'] = $anime_name;
  6898. // 如果是修改集数,则将content内容更新(会改变原文)
  6899. if (isset($episode_count) && $episode_count > 0) {
  6900. if (isset($script_arr['content']) && $script_arr['content']) $table_data['content'] = $script_arr['content'];
  6901. $table_data['start_episode_sequence'] = 1;
  6902. $table_data['end_episode_sequence'] = $table_data['episode_num'] = $episode_count;
  6903. }else {
  6904. // 如果需要生成原文内容,从script_arr中提取
  6905. if ($need_generate_content && isset($script_arr['content']) && $script_arr['content']) {
  6906. $table_data['content'] = $script_arr['content'];
  6907. dLog('deepseek')->info('从AI生成结果中提取原文内容', ['content_length' => strlen($script_arr['content'])]);
  6908. if (!$table_data['content']) {
  6909. yield [
  6910. 'type' => 'done',
  6911. 'script' => [],
  6912. 'episode' => [],
  6913. 'answer' => $fullContent,
  6914. 'reasoning' => $fullReasoningContent,
  6915. 'usage' => $usage,
  6916. 'error' => '未生成剧本内容,请调整提示词再试'
  6917. ];
  6918. return;
  6919. }
  6920. }
  6921. if (isset($table_data['content']) && $table_data['content']) {
  6922. $chapters = splitContent($table_data['content']);
  6923. $chapter_count = count($chapters);
  6924. if ($chapter_count > 0) {
  6925. $table_data['start_episode_sequence'] = 1;
  6926. $table_data['end_episode_sequence'] = $table_data['episode_num'] = $chapter_count;
  6927. }
  6928. }
  6929. }
  6930. if ($extra_products) {
  6931. $table_data['extra_products'] = json_encode($extra_products, 256);
  6932. }
  6933. $single_episode = [];
  6934. try {
  6935. DB::beginTransaction();
  6936. $now = date('Y-m-d H:i:s');
  6937. // 更新动漫大纲
  6938. $boolen = DB::table('mp_animes')->where('id', $anime_id)->update($table_data);
  6939. if (!$boolen) {
  6940. dLog('deepseek')->info('对话修改失败', $table_data);
  6941. logDB('deepseek', 'error', '对话修改失败', ['anime_id' => $anime_id]);
  6942. Utils::throwError('20003:对话修改失败');
  6943. }
  6944. // 保存对话记录
  6945. $records = [
  6946. [
  6947. 'uid' => $uid,
  6948. 'anime_id' => $anime_id,
  6949. 'sequence' => 0,
  6950. 'role' => 'user',
  6951. 'content' => $prompt,
  6952. 'created_at' => $now,
  6953. 'updated_at' => $now
  6954. ],
  6955. [
  6956. 'uid' => $uid,
  6957. 'anime_id' => $anime_id,
  6958. 'sequence' => 0,
  6959. 'role' => 'assistant',
  6960. // 'content' => '我已按照您的要求完成策划并将内容更新到您右侧的策划文档。',
  6961. 'content' => $fullContent,
  6962. 'created_at' => $now,
  6963. 'updated_at' => $now
  6964. ]
  6965. ];
  6966. // 保存对话记录
  6967. $boolen3 = DB::table('mp_anime_records')->insert($records);
  6968. if (!$boolen3) {
  6969. Utils::throwError('20003:对话记录保存失败');
  6970. }
  6971. // 单剧集模式:生成并保存剧集信息
  6972. if ($is_single) {
  6973. $anime_name = getProp($anime, 'anime_name', '未命名');
  6974. $episode_arr = $this->buildSingleEpisodeFromScript($script_arr, $fullContent, $anime_name);
  6975. if (empty($episode_arr['acts'])) {
  6976. Utils::throwError('20003:单剧集分镜内容解析失败,请确认输出格式');
  6977. }
  6978. $saveResult = $this->saveEpisodeVersionData(
  6979. $anime_id,
  6980. 1,
  6981. $episode_arr,
  6982. is_array(getProp($script_arr, 'roles')) ? getProp($script_arr, 'roles') : [],
  6983. is_array(getProp($script_arr, 'scenes')) ? getProp($script_arr, 'scenes') : [],
  6984. is_array(getProp($script_arr, 'props')) ? getProp($script_arr, 'props') : [],
  6985. null,
  6986. null,
  6987. false,
  6988. $content,
  6989. $now,
  6990. $ref_products
  6991. );
  6992. $single_episode = $saveResult['episode'];
  6993. $episode_id = $saveResult['episode_id'];
  6994. $boolen5 = DB::table('mp_animes')->where('id', $anime_id)->update([
  6995. 'roles' => json_encode($saveResult['merged_roles'], 256),
  6996. 'scenes' => json_encode($saveResult['merged_scenes'], 256),
  6997. 'props' => json_encode($saveResult['merged_props'], 256),
  6998. 'updated_at' => $now
  6999. ]);
  7000. if ($boolen5 === false) {
  7001. Utils::throwError('20003:单剧集主表资源同步失败');
  7002. }
  7003. $table_data['roles'] = json_encode($saveResult['merged_roles'], 256);
  7004. $table_data['scenes'] = json_encode($saveResult['merged_scenes'], 256);
  7005. $table_data['props'] = json_encode($saveResult['merged_props'], 256);
  7006. $episode_record_content = '确认分镜大纲';
  7007. if ($content !== '') {
  7008. // $episode_record_content .= "\n\n###上传内容\n" . $content;
  7009. }
  7010. $episode_records = [
  7011. [
  7012. 'uid' => $uid,
  7013. 'anime_id' => $anime_id,
  7014. 'role' => 'user',
  7015. 'content' => $episode_record_content,
  7016. 'sequence' => 1,
  7017. 'episode_id' => $episode_id,
  7018. 'created_at' => $now,
  7019. 'updated_at' => $now
  7020. ],
  7021. [
  7022. 'uid' => $uid,
  7023. 'anime_id' => $anime_id,
  7024. 'role' => 'assistant',
  7025. 'content' => $fullContent,
  7026. // 'content' => '我已按照您的要求完成策划并将内容更新到您右侧的策划文档。',
  7027. 'sequence' => 1,
  7028. 'episode_id' => $episode_id,
  7029. 'created_at' => $now,
  7030. 'updated_at' => $now
  7031. ]
  7032. ];
  7033. $boolen4 = DB::table('mp_anime_records')->insert($episode_records);
  7034. if (!$boolen4) {
  7035. Utils::throwError('20003:单剧集分镜记录保存失败');
  7036. }
  7037. }
  7038. }catch (\Exception $e) {
  7039. DB::rollBack();
  7040. dLog('deepseek')->info('修改对话错误信息: '.$e->getMessage());
  7041. logDB('deepseek', 'error', '修改对话失败', ['error' => $e->getMessage(), 'anime_id' => $anime_id]);
  7042. yield [
  7043. 'type' => 'done',
  7044. 'answer' => $fullContent,
  7045. 'reasoning' => $fullReasoningContent,
  7046. 'usage' => $usage,
  7047. 'error' => $e->getMessage(),
  7048. ];
  7049. return;
  7050. }
  7051. DB::commit();
  7052. dLog('deepseek')->info('保存完毕');
  7053. if ($is_single && !empty($single_episode)) {
  7054. // $this->batchSetGlobalRoleImg([
  7055. // 'anime_id' => $anime_id,
  7056. // ]);
  7057. // $this->batchSetGlobalSceneImg([
  7058. // 'anime_id' => $anime_id,
  7059. // ]);
  7060. // // 将全局角色和场景的task_id、task_status和url继承给当前分集
  7061. // $this->inheritGlobalImagesToEpisodes($anime_id, $episode_id);
  7062. }
  7063. $table_data['anime_id'] = $anime_id;
  7064. $table_data['roles'] = json_decode($table_data['roles'], true);
  7065. $table_data['scenes'] = json_decode($table_data['scenes'], true);
  7066. $table_data['props'] = json_decode($table_data['props'], true);
  7067. unset($table_data['updated_at']);
  7068. unset($table_data['status']);
  7069. yield [
  7070. 'type' => 'done',
  7071. 'script' => $table_data,
  7072. 'episode' => $single_episode,
  7073. 'answer' => $fullContent,
  7074. 'reasoning' => $fullReasoningContent,
  7075. 'usage' => $usage
  7076. ];
  7077. }
  7078. public function chatForAce($data) {
  7079. $uid = Site::getUid();
  7080. $anime_id = getProp($data, 'anime_id');
  7081. $file = getProp($data, 'file');
  7082. $content = getProp($data, 'content', '');
  7083. $bid = getProp($data, 'bid', 0);
  7084. $script_id = getProp($data, 'script_id', 0);
  7085. $episode_number = getProp($data, 'episode_number', 1);
  7086. $prompt = trim((string)getProp($data, 'prompt', '确认分镜大纲'));
  7087. $anime = DB::table('mp_animes')->where('id', $anime_id)->first();
  7088. if (!$anime) Utils::throwError('20003:该对话不存在!');
  7089. if ((int)getProp($anime, 'is_multi') !== 1 && (int)$episode_number !== 1) Utils::throwError('20003:单剧集不支持其他剧集序号');
  7090. $current_episode = DB::table('mp_anime_episodes')->where('anime_id', $anime_id)->where('episode_number', $episode_number)->where('is_default', 1)->first();
  7091. $base_episode = $current_episode ?: DB::table('mp_anime_episodes')->where('anime_id', $anime_id)->where('episode_number', $episode_number)->orderByDesc('id')->first();
  7092. $roles = $base_episode ? json_decode((string)getProp($base_episode, 'roles'), true) : json_decode((string)getProp($anime, 'roles'), true);
  7093. $scenes = $base_episode ? json_decode((string)getProp($base_episode, 'scenes'), true) : json_decode((string)getProp($anime, 'scenes'), true);
  7094. $roles = is_array($roles) ? $roles : [];
  7095. $scenes = is_array($scenes) ? $scenes : [];
  7096. $extra_products = getProp($data, 'products', []);
  7097. if (is_string($extra_products)) $extra_products = json_decode($extra_products, true);
  7098. // 如果anime有关联的script_id,则从mp_script_product_mappings中查询资产并合并到extra_products
  7099. $anime_script_id = getProp($anime, 'script_id');
  7100. if ($anime_script_id) {
  7101. $cpid = Site::getCpid();
  7102. $script_products_mappings = DB::table('mp_script_product_mappings as mapping')
  7103. ->join('mp_products as product', 'mapping.product_id', '=', 'product.id')
  7104. ->where('mapping.script_id', $anime_script_id)
  7105. ->where('product.cpid', $cpid)
  7106. ->where('product.is_deleted', 0);
  7107. // 如果提供了 episode_number,则过滤指定集数
  7108. if ($episode_number !== null && $episode_number !== '') {
  7109. $script_products_mappings->where('mapping.episode_number', $episode_number);
  7110. }
  7111. $mappings = $script_products_mappings->select(
  7112. 'mapping.product_id',
  7113. 'mapping.episode_number',
  7114. 'product.product_name',
  7115. 'product.type',
  7116. 'product.product',
  7117. 'product.pic_prompt',
  7118. 'product.url',
  7119. 'product.pic_task_id',
  7120. 'product.pic_task_status',
  7121. 'product.three_view_image_url'
  7122. )
  7123. ->get();
  7124. // 按 product_id 分组,合并 episode_number
  7125. $productMap = [];
  7126. foreach ($mappings as $item) {
  7127. $product_id = $item->product_id;
  7128. $product_name = $item->product_name;
  7129. // 处理product_name两边的符号
  7130. $product_name = preg_replace('/^[\s*\[\]【】[]{}{}\x{3000}]+|[\s*\[\]【】[]{}{}\x{3000}]+$/u', '', $product_name);
  7131. if (!isset($productMap[$product_id])) {
  7132. $productMap[$product_id] = [
  7133. 'product_id' => $product_id,
  7134. 'product_name' => $product_name,
  7135. 'type' => (int)$item->type,
  7136. 'product' => (int)$item->product,
  7137. 'pic_prompt' => $item->pic_prompt,
  7138. 'url' => $item->url,
  7139. 'pic_task_id' => $item->pic_task_id,
  7140. 'pic_task_status' => $item->pic_task_status,
  7141. 'episode_numbers' => [],
  7142. ];
  7143. }
  7144. // 添加 episode_number(去重)
  7145. if (!in_array($item->episode_number, $productMap[$product_id]['episode_numbers'])) {
  7146. $productMap[$product_id]['episode_numbers'][] = $item->episode_number;
  7147. }
  7148. }
  7149. // 将查询到的剧本资产合并到extra_products中
  7150. // 先构建extra_products的索引(以product_id+episode_number为key)
  7151. $extraProductsMap = [];
  7152. foreach ($extra_products as $item) {
  7153. $key = getProp($item, 'product_id') . '_' . getProp($item, 'episode_number', '');
  7154. $extraProductsMap[$key] = $item;
  7155. }
  7156. // 合并剧本资产(去重:product_id+episode_number)
  7157. foreach ($productMap as $product) {
  7158. foreach ($product['episode_numbers'] as $ep_num) {
  7159. $key = $product['product_id'] . '_' . $ep_num;
  7160. // 如果不存在则添加
  7161. if (!isset($extraProductsMap[$key])) {
  7162. $extraProductsMap[$key] = [
  7163. 'product_id' => $product['product_id'],
  7164. 'product_name' => $product['product_name'],
  7165. 'type' => $product['type'],
  7166. 'product' => $product['product'],
  7167. 'pic_prompt' => $product['pic_prompt'],
  7168. 'url' => $product['url'],
  7169. 'pic_task_id' => $product['pic_task_id'],
  7170. 'pic_task_status' => $product['pic_task_status'],
  7171. 'episode_number' => $ep_num,
  7172. ];
  7173. }
  7174. }
  7175. }
  7176. // 重新赋值给extra_products
  7177. $extra_products = array_values($extraProductsMap);
  7178. }
  7179. // 处理提示词
  7180. if ($prompt && $extra_products) {
  7181. // 遍历extra_products,将prompt中的{product_name}替换为实际的product_name
  7182. foreach($extra_products as $item) {
  7183. $product_name = getProp($item, 'product_name');
  7184. if ($product_name) {
  7185. // 替换 {product_name} 为 product_name
  7186. $prompt = str_replace('{' . $product_name . '}', $product_name, $prompt);
  7187. }
  7188. }
  7189. }
  7190. // 获取最后一集序号
  7191. $end_episode_sequence = getProp($anime, 'end_episode_sequence', 0);
  7192. if ($end_episode_sequence && $episode_number > $end_episode_sequence) Utils::throwError("20003:总集数只有{$end_episode_sequence}集,不允许继续策划下一集!");
  7193. // 转换主体列表和场景列表的格式
  7194. // 获取参考主体或场景
  7195. if ((int)$episode_number === 1) {
  7196. $ref_data = DB::table('mp_animes')->where('id', $anime_id)->first();
  7197. // $ref_data = []; // 第一集让AI自由发挥不再使用全局主体(会影响后续分集的继承问题)
  7198. }else {
  7199. $prev_episode_number = $episode_number - 1;
  7200. $ref_data = DB::table('mp_anime_episodes')->where('anime_id', $anime_id)->where('episode_number', $prev_episode_number)->where('is_default', 1)->first();
  7201. }
  7202. $ref_roles = getProp($ref_data, 'roles') ? json_decode(getProp($ref_data, 'roles'), true) : [];
  7203. $ref_scenes = getProp($ref_data, 'scenes') ? json_decode(getProp($ref_data, 'scenes'), true) : [];
  7204. $ref_props = getProp($ref_data, 'props') ? json_decode(getProp($ref_data, 'props'), true) : [];
  7205. // 合并anime_products和extra_products(extra_products优先,去重)
  7206. $anime_products = getProp($anime, 'extra_products');
  7207. $anime_products = $anime_products ? json_decode($anime_products, true) : [];
  7208. $ref_products = [];
  7209. foreach($anime_products as $item) {
  7210. $product_name = getProp($item, 'product_name');
  7211. $ref_products[$product_name] = $item;
  7212. }
  7213. // 处理extra_products,将其合并到ref_roles和ref_scenes中(入参优先)
  7214. $extra_roles = []; // 从extra_products中提取的角色
  7215. $extra_scenes = []; // 从extra_products中提取的场景
  7216. $extra_props = []; // 从extra_products中提取的道具
  7217. if ($extra_products && is_array($extra_products)) {
  7218. foreach($extra_products as $item) {
  7219. $product = (int)getProp($item, 'product');
  7220. $product_name = getProp($item, 'product_name');
  7221. if ($product_name == '旁白') continue;
  7222. $pic_prompt = getProp($item, 'pic_prompt');
  7223. $ref_products[$product_name] = $item;
  7224. if ($product === 1) {
  7225. // 角色
  7226. $extra_roles[$product_name] = [
  7227. 'role' => $product_name,
  7228. 'pic_prompt' => $pic_prompt,
  7229. 'url' => getProp($item, 'url', ''),
  7230. ];
  7231. } elseif ($product === 2) {
  7232. // 场景
  7233. $extra_scenes[$product_name] = [
  7234. 'scene' => $product_name,
  7235. 'pic_prompt' => $pic_prompt,
  7236. 'url' => getProp($item, 'url', ''),
  7237. ];
  7238. } elseif ($product === 3) {
  7239. // 道具
  7240. $extra_props[$product_name] = [
  7241. 'prop' => $product_name,
  7242. 'pic_prompt' => $pic_prompt,
  7243. 'url' => getProp($item, 'url', ''),
  7244. ];
  7245. }
  7246. }
  7247. }
  7248. // 合并ref_roles和extra_roles(extra_roles优先,去重)
  7249. $merged_roles = [];
  7250. foreach($ref_roles as $role) {
  7251. $role_name = getProp($role, 'role');
  7252. if (!isset($extra_roles[$role_name])) {
  7253. $merged_roles[$role_name] = $role;
  7254. }
  7255. }
  7256. // 添加extra_roles
  7257. foreach($extra_roles as $role_name => $role) {
  7258. $merged_roles[$role_name] = $role;
  7259. }
  7260. $ref_roles = array_values($merged_roles);
  7261. // 合并ref_scenes和extra_scenes(extra_scenes优先,去重)
  7262. $merged_scenes = [];
  7263. foreach($ref_scenes as $scene) {
  7264. $scene_name = getProp($scene, 'scene');
  7265. if (!isset($extra_scenes[$scene_name])) {
  7266. $merged_scenes[$scene_name] = $scene;
  7267. }
  7268. }
  7269. // 添加extra_scenes
  7270. foreach($extra_scenes as $scene_name => $scene) {
  7271. $merged_scenes[$scene_name] = $scene;
  7272. }
  7273. $ref_scenes = array_values($merged_scenes);
  7274. // 合并ref_props和extra_props(extra_props优先,去重)
  7275. $merged_props = [];
  7276. foreach($ref_props as $prop) {
  7277. $prop_name = getProp($prop, 'prop');
  7278. if (!isset($extra_props[$prop_name])) {
  7279. $merged_props[$prop_name] = $prop;
  7280. }
  7281. }
  7282. // 添加extra_props
  7283. foreach($extra_props as $prop_name => $prop) {
  7284. $merged_props[$prop_name] = $prop;
  7285. }
  7286. $ref_props = array_values($merged_props);
  7287. $roles_content = $this->buildEpisodeItemContent($ref_roles, 'role');
  7288. $scenes_content = $this->buildEpisodeItemContent($ref_scenes, 'scene');
  7289. $props_content = $this->buildEpisodeItemContent($ref_props, 'prop');
  7290. // 构建强制主体、场景和道具提示词
  7291. $forced_roles_prompt = "";
  7292. $forced_scenes_prompt = "";
  7293. $forced_props_prompt = "";
  7294. if (!empty($extra_roles)) {
  7295. $forced_roles_list = "";
  7296. foreach($extra_roles as $role_name => $role) {
  7297. $forced_roles_list .= $role_name . ":{" . getProp($role, 'pic_prompt') . "}\n";
  7298. }
  7299. $forced_roles_prompt = "\n\n【强制主体设定-优先级最高-不可修改】\n以下主体必须全部出现在<主体列表>中,这些主体的优先级最高,必须包含:\n" . $forced_roles_list . "\n格式要求:\n1. 主体名称:必须保持不变\n2. 主体描述:你必须根据剧情为每个主体生成主体描述(分析人物在整部剧中的姓名、年龄、性格特征、社会身份或职业背景、个人成长经历或核心故事动机,以及在剧情中的目标与行为驱动力,用一句话进行总结)\n3. 人物提示词:{}中的内容必须完整保留,不得修改\n4. 音色提示词:你必须根据角色特征生成音色提示词(描述角色的整体音色特征,包含:性别、年龄、音质、表达形式、情绪氛围,字数控制在80字以内),用{{}}框起来\n\n最终格式必须为:主体名:[你生成的主体描述]{人物提示词-保持不变}{{你生成的音色提示词}}\n\n【重要】以上每个主体在<主体列表>中的完整格式必须是:主体名:主体描述{人物提示词}{{音色提示词}},其中主体描述和音色提示词是你必须生成的内容,{}中的人物提示词必须原样保留。";
  7300. }
  7301. if (!empty($extra_scenes)) {
  7302. $forced_scenes_list = "";
  7303. foreach($extra_scenes as $scene_name => $scene) {
  7304. $forced_scenes_list .= $scene_name . ":{" . getProp($scene, 'pic_prompt') . "}\n";
  7305. }
  7306. $forced_scenes_prompt = "\n\n【强制场景设定-优先级最高-不可修改】\n以下场景必须全部出现在<场景列表>中,这些场景的优先级最高,必须包含:\n" . $forced_scenes_list . "\n格式要求:\n1. 场景名称:必须保持不变\n2. 场景描述:你必须根据剧情为每个场景生成场景描述(分析在整部剧中出现过的场景,场景描述尽量简洁贴合原文)\n3. 场景提示词:{}中的内容必须完整保留,不得修改\n\n最终格式必须为:场景名:[你生成的场景描述]{场景提示词-保持不变}\n\n【重要】以上每个场景在<场景列表>中的完整格式必须是:场景名:场景描述{场景提示词},其中场景描述是你必须生成的内容,{}中的场景提示词必须原样保留。";
  7307. }
  7308. if (!empty($extra_props)) {
  7309. $forced_props_list = "";
  7310. foreach($extra_props as $prop_name => $prop) {
  7311. $forced_props_list .= $prop_name . ":{" . getProp($prop, 'pic_prompt') . "}\n";
  7312. }
  7313. $forced_props_prompt = "\n\n【强制道具设定-优先级最高-不可修改】\n以下道具必须全部出现在<道具列表>中,这些道具的优先级最高,必须包含:\n" . $forced_props_list . "\n格式要求:\n1. 道具名称:必须保持不变\n2. 道具描述:你必须根据剧情为每个道具生成道具描述(分析在整部剧中出现过的道具,道具描述尽量简洁贴合原文)\n3. 道具提示词:{}中的内容必须完整保留,不得修改\n\n最终格式必须为:道具名:[你生成的道具描述]{道具提示词-保持不变}\n\n【重要】以上每个道具在<道具列表>中的完整格式必须是:道具名:道具描述{道具提示词},其中道具描述是你必须生成的内容,{}中的道具提示词必须原样保留。";
  7314. }
  7315. if ($anime_script_id) {
  7316. $role_demo = "2.<主体列表>只能使用以下主体,不得自定义内容(必需带上冒号后的具体描述以及{}和{{}}中的内容,原样输出)。{$forced_roles_prompt}";
  7317. }else if ($roles_content) {
  7318. $role_demo = "2.<主体列表>可在以下主体中选择多个(根据拆分出的分镜剧本来确认具体几个,不要出现旁白角色),不得自定义内容(必需带上冒号后的具体描述以及{}和{{}}中的内容,原样输出)。
  7319. 主体范围:\n {$roles_content}\n
  7320. 2.1如果本集剧情内容中出现了和给出的<主体列表>中不存在的新主体(或原主体发生了比较大的年龄、服装或身体变化),则不用在上述主体中选择,而是按照相同的格式新增一个主体显示在<主体列表>中。(以下是格式要求和生成要求,仅适用新出现的主体):
  7321. - 新主体分以下三部分:主体描述、人物提示词和音色提示词,格式必须为:主体名:主体描述{人物提示词}{{音色提示词}}
  7322. - 新主体的主体描述是分析人物在整部剧中的姓名、年龄、性格特征、社会身份或职业背景、个人成长经历或核心故事动机,以及在剧情中的目标与行为驱动力,不需要描述外貌、穿着或身体特征,重点突出心理结构、行为模式与叙事功能(缩略成一句话讲述完毕)。
  7323. - 新主体的人物提示词需要根据当前分析出来的美术风格生成(每个人物都只允许一套服装,如果多套服装则需区分主体名),包含性别(男、女)、大概年龄或年龄段(少年、中年、老年等)、人种(亚洲人、欧洲人)、发型(直发卷发等)、发色(黑色、棕色、红色、白色等)、整体视觉风格,以及详细的穿着风格和服装细节、面部特征(戴金丝眼镜、脸上有刀疤等,无面部特征可忽略)。描述需具有镜头感与画面表现力,适合直接用于AI图像生成模型,避免抽象词汇,强调具体可视化细节与整体视觉一致性,同时保证风格统一且符合人物身份设定。该提示词(字数50-100字左右)在主体描述后用{}框起来。
  7324. - 新主体的音色提示词放在描述的最后用{{}}框起来。音色提示词需描述角色的整体音色特征,包含:性别、年龄(约XX岁)、音质(如清冷、沉稳、磁性等)、表达形式(如叙述感、旁白式等)、情绪氛围(如空灵韵味、看透世事的清冷等),字数控制在80字以内。举例:成年女性(约25-35岁),音色清冷且富有叙述感,语速平缓,带有仙侠剧特有的空灵韵味。{$forced_roles_prompt}";
  7325. }else {
  7326. $role_demo = "2.<主体列表>中出现的“主体名”必须尽可能统一,严禁出现角色-科学家、角色-复仇者、角色-领导者等带有身份、职业、标签类的命名,只能使用服装差异(如校服装、卫衣装、西装)来区分同一角色,如角色-校服装等。
  7327. - <主体列表>分以下三部分:主体描述、人物提示词和音色提示词,格式必须为:主体名:主体描述{人物提示词}{{音色提示词}}
  7328. - <主体列表>的主体描述是分析人物在整部剧中的姓名、年龄、性格特征、社会身份或职业背景、个人成长经历或核心故事动机,以及在剧情中的目标与行为驱动力,不需要描述外貌、穿着或身体特征,重点突出心理结构、行为模式与叙事功能(缩略成一句话讲述完毕)。
  7329. - <主体列表>的人物提示词需要根据当前分析出来的美术风格生成(每个人物都只允许一套服装,如果多套服装则需区分主体名),包含性别(男、女)、大概年龄或年龄段(少年、中年、老年等)、人种(亚洲人、欧洲人)、发型(直发卷发等)、发色(黑色、棕色、红色、白色等)、整体视觉风格,以及详细的穿着风格和服装细节、面部特征(戴金丝眼镜、脸上有刀疤等,无面部特征可忽略)。描述需具有镜头感与画面表现力,适合直接用于AI图像生成模型,避免抽象词汇,强调具体可视化细节与整体视觉一致性,同时保证风格统一且符合人物身份设定。该提示词(字数50-100字左右)在主体描述后用{}框起来。
  7330. - <主体列表>的音色提示词放在描述的最后用{{}}框起来。音色提示词需描述角色的整体音色特征,包含:性别、年龄(约XX岁)、音质(如清冷、沉稳、磁性等)、表达形式(如叙述感、旁白式等)、情绪氛围(如空灵韵味、看透世事的清冷等),字数控制在80字以内。举例:成年女性(约25-35岁),音色清冷且富有叙述感,语速平缓,带有仙侠剧特有的空灵韵味。{$forced_roles_prompt}";
  7331. }
  7332. if ($anime_script_id) {
  7333. $scene_demo = "3.<场景列表>只能使用以下场景,不得自定义内容(必需带上冒号后的具体描述以及{}和{{}}中的内容,原样输出)。{$forced_scenes_prompt}";
  7334. }else if ($scenes_content) {
  7335. $scene_demo = "3.<场景列表>可在以下场景中选择多个(需带上冒号后的具体描述),根据拆分出的分镜剧本来确认具体几个,不得自定义(必需带上冒号后的具体描述以及{}中的内容,原样输出)。
  7336. 场景范围:\n {$scenes_content}\n
  7337. 3.1如果本集剧情内容中出现了和给出的<场景列表>中不存在的新场景,则不用在上述场景中选择,而是按照相同的格式新增一个场景显示在<场景列表>中,必须严格注意不要出现任何角色和人物。(以下是格式要求和生成要求,仅适用新出现的场景):。
  7338. - 新场景分以下两部分:场景描述和场景提示词,格式必须为:场景名:场景描述{场景提示词}
  7339. - 新场景的场景描述是分析在整部剧中出现过的场景,场景描述尽量简洁贴合原文。
  7340. - 新场景的场景提示词用于视觉呈现的场景环境描述,该场景需包含环境氛围、光线效果、空间布局、色彩基调、视觉风格等,描述需具有镜头感与画面表现力,适合直接用于AI图像生成模型,避免抽象词汇,强调具体可视化细节与整体视觉一致性,同时保证风格统一且符合剧情设定(可参考以下示例的场景列表中使用{}框起来的提示词,字数150-200字,需带上提炼出来的美术风格)。该提示词在场景描述后用{}框起来。{$forced_scenes_prompt}\n";
  7341. }else {
  7342. $scene_demo = "3.<场景列表>与主体列表同理,需尽可能的对场景环境进行详细描述,必须严格注意不要出现任何角色和人物。
  7343. - <场景列表>分以下两部分:场景描述和场景提示词,格式必须为:场景名:场景描述{场景提示词},注意不要出现{{}}这样的双大括号。
  7344. - <场景列表>的场景描述是分析在整部剧中出现过的场景,场景描述尽量简洁贴合原文。
  7345. - <场景列表>的场景提示词用于视觉呈现的场景环境描述,该场景需包含环境氛围、光线效果、空间布局、色彩基调、视觉风格等,描述需具有镜头感与画面表现力,适合直接用于AI图像生成模型,避免抽象词汇,强调具体可视化细节与整体视觉一致性,同时保证风格统一且符合剧情设定(可参考以下示例的场景列表中使用{}框起来的提示词,字数150-200字,需带上提炼出来的美术风格)。该提示词在场景描述后用{}框起来。{$forced_scenes_prompt}\n";
  7346. }
  7347. if ($anime_script_id) {
  7348. $prop_demo = "4.<道具列表>只能使用以下道具,不得自定义内容(必需带上冒号后的具体描述以及{}和{{}}中的内容,原样输出)。{$forced_props_prompt}";
  7349. }else if ($props_content) {
  7350. $prop_demo = "4.<道具列表>可在以下道具中选择多个(需带上冒号后的具体描述),根据拆分出的分镜剧本来确认具体几个,不得自定义(必需带上冒号后的具体描述以及{}中的内容,原样输出)。
  7351. 道具范围:\n {$props_content}\n
  7352. 4.1如果本集剧情内容中出现了和给出的<道具列表>中不存在的新道具,则不用在上述道具中选择,而是按照相同的格式新增一个道具显示在<道具列表>中,必须严格注意不要出现任何角色和人物。(以下是格式要求和生成要求,仅适用新出现的道具):。
  7353. - 新道具分以下两部分:道具描述和道具提示词,格式必须为:道具名:道具描述{道具提示词}
  7354. - 新道具的道具描述是分析在整部剧中出现过的道具,道具描述尽量简洁贴合原文。
  7355. - 新道具的道具提示词用于视觉呈现的道具环境描述,该道具需包含环境氛围、光线效果、空间布局、色彩基调、视觉风格等,描述需具有镜头感与画面表现力,适合直接用于AI图像生成模型,避免抽象词汇,强调具体可视化细节与整体视觉一致性,同时保证风格统一且符合剧情设定(可参考以下示例的道具列表中使用{}框起来的提示词,字数150-200字,需带上提炼出来的美术风格)。该提示词在道具描述后用{}框起来。{$forced_scenes_prompt}\n";
  7356. }else {
  7357. $prop_demo = "4.<道具列表>与主体列表同理,需尽可能的对道具环境进行详细描述,必须严格注意不要出现任何角色和人物。
  7358. - <道具列表>分以下两部分:道具描述和道具提示词,格式必须为:道具名:道具描述{道具提示词},注意不要出现{{}}这样的双大括号。
  7359. - <道具列表>的道具描述是分析在整部剧中出现过的道具,道具描述尽量简洁贴合原文。
  7360. - <道具列表>的道具提示词用于视觉呈现的道具环境描述,该道具需包含环境氛围、光线效果、空间布局、色彩基调、视觉风格等,描述需具有镜头感与画面表现力,适合直接用于AI图像生成模型,避免抽象词汇,强调具体可视化细节与整体视觉一致性,同时保证风格统一且符合剧情设定(可参考以下示例的道具列表中使用{}框起来的提示词,字数150-200字,需带上提炼出来的美术风格)。该提示词在道具描述后用{}框起来。{$forced_scenes_prompt}\n";
  7361. }
  7362. // 提取文件内容
  7363. if ($file) {
  7364. $uploaded_content = $this->extractFileContent($file);
  7365. if (!$uploaded_content) {
  7366. Utils::throwError('20003:无法提取文件内容,请检查文件格式');
  7367. }
  7368. } elseif ($script_id) {
  7369. $uploaded_content = $this->getContentByScriptId($script_id);
  7370. if (!$uploaded_content) {
  7371. Utils::throwError('20003:无法获取剧本内容,请检查剧本');
  7372. }
  7373. } elseif ($bid) {
  7374. $uploaded_content = $this->getContentByBid($bid);
  7375. if (!$uploaded_content) {
  7376. Utils::throwError('20003:无法获取书籍内容,请检查书籍');
  7377. }
  7378. } elseif ($content) {
  7379. $uploaded_content = filterContent((string)getProp($data, 'content', ''));
  7380. }
  7381. // elseif ($prompt) {
  7382. // $uploaded_content = filterContent($prompt);
  7383. // }
  7384. else {
  7385. $uploaded_content = '';
  7386. }
  7387. // 美术风格
  7388. $input_art_style = getProp($data, 'art_style');
  7389. if (!$input_art_style) {
  7390. $mappedArtStyle = getProp($anime, 'art_style');
  7391. }else {
  7392. $mappedArtStyle = $this->getArtStylePromptByInput($input_art_style);
  7393. }
  7394. if (!$mappedArtStyle) {
  7395. $mappedArtStyle_prompt = '美术风格:根据剧本内容自定义美术风格';
  7396. }else {
  7397. if (strstr($mappedArtStyle, '基础画风风格词')) {
  7398. $mappedArtStyle_prompt = "美术风格强制设置如下(原样输出,不得更改任何内容):\n{$mappedArtStyle}\n";
  7399. }else {
  7400. $art_style_type = $input_art_style ? $input_art_style : getProp($anime, 'art_style_type');
  7401. $mappedArtStyle_prompt = "美术风格强制设置如下(原样输出,不得更改任何内容):\n基础画风风格词: {$art_style_type}\n{$mappedArtStyle}\n";
  7402. }
  7403. }
  7404. $prompt = trim((string)getProp($data, 'prompt', '确认分镜大纲'));
  7405. // $demo = "你是一个专业的文档分析助手及资深编剧,请根据用户提供的文档内容完成示例格式的内容输出(需包含以下几个板块: <剧集标题><故事梗概><美术风格><旁白音色提示词><主体列表><场景列表><分段剧本>,每个板块之间必须使用###分隔,#不能多也不能少;同时板块之间需满足以下要求:\n
  7406. // 强制要求:
  7407. // 1.你只负责与剧本相关的内容,如果用户输入与剧本无关的内容,请告知用户并拒绝继续回答,此为第一优先原则,不满足此原则就忽略其他要求并停止继续输出
  7408. // 2.如果用户输入修改美术风格、修改画风这类内容,请告知用户不可修改美术风格,并拒绝继续回答
  7409. // 3.以上两条要求对修改主体角色或场景不生效,允许用户调整主体角色说明和场景描述等
  7410. // 4.用户如果要求你帮忙写一个故事或者剧本,此类要求不属于与剧本无关,请帮助用户完成请求
  7411. // 5.强制按照示例格式返回内容,不要更改格式或随意增加符号
  7412. // 6.如果给出的本集剧情内容是剧本格式,则不要改动剧本内容(必须强制使用原文内容),严格按照剧本的旁白和台词进行分镜的策划,不要跳过任何剧情
  7413. // 7.分镜不是二次创作,必须严格“原文拆句”。优先把原文中可直接成镜头的句子拆成分镜,禁止把两句合并后再脑补过渡。
  7414. // 8.画面描述必须直接使用,禁止新增任何原文没有写出的动作、人物、道具、地点、气氛、结果或因果。
  7415. // 9.不要把“打开衣柜”扩写成“伸手轻抚嫁衣”,不要把“管家拎着两个箱子跟在后面”改成“沈耀和管家一起拎箱子”。主语、动作、数量、先后顺序必须完全按原文。
  7416. // 10.分镜要和场景列表、人物主体保持一致\n
  7417. // 普通要求:
  7418. // 1.剧集标题必须与文档内容高度相关,剧集序号是{$episode_number}。
  7419. // {$role_demo}
  7420. // {$scene_demo}
  7421. // 4.<分段剧本>按照“分段模式”进行拆分和组织,要求如下:
  7422. // 4.1片段分割逻辑(优先级从高到低):
  7423. // - 第一优先级:时长上限(单个片段不超过15秒,超过必须切为新片段)
  7424. // - 第二优先级:叙事节拍Beat(一个完整的事件/动作/情绪起落单元,如一段对话的来回、一个动作序列:推门→看见→震惊、一次闪回/回忆、旁白+画面组合)
  7425. // - 第三优先级:语义块(按“谁、在哪、做什么、情绪怎样”聚合,如同一段旁白/独白、同一个角色的连续动作、同一个视角的连续镜头)
  7426. // - 只要事件没结束、情绪没断,哪怕换场景,也留在同一个片段里
  7427. // 4.2片段结构:片段数量+旁白音色+多个片段(每个片段由多个分镜组合而成(片段序号格式:片段1、片段2...))
  7428. // - 片段数量格式为: 片段数量:8
  7429. // - 旁白音色需描述旁白的整体音色特征,包含:性别、年龄(约XX岁)、音质(如清冷、沉稳、磁性等)、表达形式(如叙述感、旁白式等)、情绪氛围(如空灵韵味、看透世事的清冷等),字数控制在80字以内。举例:成年女性(约25-35岁),音色清冷且富有叙述感,语速平缓,带有仙侠剧特有的空灵韵味。
  7430. // - 片段序号格式必须如下: ##片段+片段序号\n时长:xxs,例如: ##片段1\n时长:12s
  7431. // 4.3分镜结构:每个分镜包含以下字段:
  7432. // - 分镜序号在片段内用1、2、3显示,如分镜1、分镜2,并且分镜序号需连续(跨片段中的分镜序号需连续,如片段2中的分镜序号从片段1的最大序号+1开始)
  7433. // - 场景:必须选择本集中的<场景列表>中的一个(不带详细表述)
  7434. // - 画面:【构图/视角】+画面描述(越简单越好,对视觉场景/实景的描述,不描述氛围,比如紧张、压抑的氛围)。举例:[近景特写,浅景深]季潇握着手机贴在耳边,指关节因为用力而泛白。她的眼眶微红,睫毛在狂风中颤抖,嘴唇紧抿,眼神中闪烁着最后一点希冀的微光。
  7435. // - 画面中如果出现主体,只能选择上述主体列表中的一个,主体的名称也需要保持一致(不带主体具体描述)
  7436. // - 运镜:场景+画面描述+运镜
  7437. // - 配音台词:格式为“中文配音:[角色]台词”,角色配音台词和语言由模型匹配生成,角色必须对应本集中的<主体列表>中的一个(非对话内容则统一固定为“旁白”角色)
  7438. // - 台词内容需满足以下要求: (1. 台词来源规则:台词内容必须逐字摘录自小说原文中的人物直接对话(带引号的内容),不允许改写、总结、压缩、扩写或拼接原文对白,不允许生成原文中不存在的对话。2. 非对话过滤:旁白、心理描写、环境描写、动作描写等内容,禁止出现在台词内容中。3. 空台词规则:如果该分镜中没有人物对话,则“台词内容”必须返回“无”,严禁输出“无台词”、“没有”等任何替代文本。4. 禁止推测:不得根据语境补全人物可能说的话。5.如果没有原文,直接返回空)
  7439. // - 背景音效:背景音效需根据内容和画面生成,贴合当前画面描述和动作,例如:背景音效:高跟鞋的脚本声
  7440. // 5.$mappedArtStyle_prompt\n\n
  7441. // 示例格式:\n
  7442. // 第1集:隐形的守护者
  7443. // ###故事梗概
  7444. // 内容梗概:许芸归家遭徐母毒打,她冷静周旋并编造谎言掩盖行踪,引得一旁阴沉的卞大伟愈发急躁。半个月后,徐母离家,卞大伟兽性大发欲行不轨。生死关头,隐形的程景现身肉搏,屋内家具横飞,卞大伟被“空气”重创。许芸趁乱逃出,却惊见地面凭空浮现一串血脚印。意识到守护者为救自己负伤,许芸不再逃避,对着虚无的空气执拗告白,誓要与这看不见的爱人共进退。
  7445. // ###美术风格
  7446. // 基础画风风格词:胡金铨武侠
  7447. // 视觉风格描述:整体采用复古武侠电影美学,以低饱和度的青灰与墨色调为主,营造冷峻、肃杀的江湖意境。光影上运用强烈的侧逆光与深邃硬阴影,完美契合“墨影剑客”神秘莫测的特质。画面带有35mm胶片的粗粝质感,构图简约且富有张力,展现出深沉的复仇叙事氛围。
  7448. // ###主体列表
  7449. // 陆沉:冷酷神秘的复仇剑客,陆家庄唯一幸存者,身负绝世武功与血海深仇。{全景,正面拍摄,青年男性,亚洲人,黑色长发束起,五官轮廓深邃。服饰穿搭:黑色连帽斗篷,深灰色交领劲装,黑色束腰,背负一柄漆黑宽大的无锋重剑。姿态:站立。}{{青年男性(约25-30岁),音色冷峻、低沉,语速平稳缓慢,透着一股拒人于千里之外的孤傲与肃杀。}}
  7450. // 刀疤脸:武林盟的嚣张爪牙,性格暴戾、欺软怕硬,是赵无极麾下的打手。{全景,正面拍摄,中年男性,亚洲人,短发,左脸有一道明显的深长刀疤。服饰穿搭:土黄色粗布武士服,腰间挂着一枚古铜色的“武林盟”令牌。姿态:站立。}{{中年男性(约35-45岁),音色粗犷、沙哑,语气嚣张跋扈,带有明显的威胁感和市井痞气。}}
  7451. // 老李:悦来酒馆的老板,胆小卑微的底层百姓,在乱世中艰难求生。{全景,正面拍摄,老年男性,亚洲人,灰白乱发,面容消瘦且布满皱纹。服饰穿搭:破旧的深蓝色粗布长袍,腰间系着一条带有污渍的灰色围裙。姿态:站立。}{{老年男性(约60岁以上),音色苍老、沙哑且带有颤抖,语气唯唯诺诺,充满了卑微与惊恐。}}
  7452. // ###场景列表
  7453. // 边境小镇街道:夜幕笼罩下的边陲小镇,风沙肆虐,街道两旁是破旧的木质建筑,透着一股荒凉与肃杀的气息,是故事发生的地理背景。{远景,夜幕下的边境小镇,破败的木质建筑错落有致,风沙在空旷的街道上飞扬,远处有微弱的灯火。无人物。}
  7454. // 悦来酒馆:酒馆内部陈设简陋,木质桌椅散乱分布,柜台上摆放着酒坛。室内光线昏暗,只有几盏摇曳的油灯提供微弱的暖光,与室外的冷调形成对比。{室内场景,昏暗的古风酒馆内部,粗糙的木质桌椅,木质柜台与酒坛,空气中浮动着尘埃,强烈的侧逆光勾勒出环境轮廓,深邃的硬阴影。无人物。}
  7455. // ###分段剧本
  7456. // 片段数量:8
  7457. // 旁白音色:成年男性(约35-50岁),音色厚重且富有磁性,带有老电影叙事般的沧桑感,语调低沉平稳,富有江湖气息。
  7458. // ##片段1
  7459. // 时长:12s
  7460. // 分镜1
  7461. // 场景:边境小镇街道
  7462. // 画面:[大远景,冷色调,高对比度] 漫天黄沙在狂风中如怒龙翻滚,遮蔽了微弱的星光。悦来酒馆残破的木门在风中剧烈摇晃,铁链撞击木板发出沉重的闷响,四周建筑尽显荒凉。
  7463. // 运镜:大远景固定镜头,随后风沙席卷向镜头形成遮挡转场。
  7464. // 配音台词:
  7465. // 背景音效:
  7466. // 分镜2
  7467. // 场景:悦来酒馆
  7468. // 画面:[全景,暖色调阴影构图] 酒馆内部昏暗,几盏油灯在风中疯狂摇曳,投射出扭曲的长影。角落里的食客低头缩颈,双手紧紧攥着粗瓷碗,空气中漂浮着细小的尘埃。
  7469. // 运镜:缓慢横移,掠过阴影中瑟缩的食客。
  7470. // 配音台词:
  7471. // 背景音效:
  7472. // 分镜3
  7473. // 场景:悦来酒馆
  7474. // 画面:[中景,三分法构图] 三名大汉围坐在正中央的圆桌旁,腰间挂着的“武林盟”金色令牌在灯火下闪烁。桌上残羹冷炙横陈,一名大汉正张狂地大笑,脚踩在长凳上。
  7475. // 运镜:从中景推向令牌特写。
  7476. // 配音台词:
  7477. // 背景音效:
  7478. // 分镜4
  7479. // 场景:悦来酒馆
  7480. // 画面:[特写,低角度仰拍] 刀疤脸横肉颤动,嘴角挂着轻蔑的笑。他随手倾覆手中的酒碗,琥珀色的液体在空中划过弧线,重重溅在老李打着补丁的布鞋和裤脚上。
  7481. // 运镜:极速推向酒水溅起的瞬间。
  7482. // 配音台词:
  7483. // 背景音效:
  7484. // 分镜5
  7485. // 镜头描述
  7486. // 场景:悦来酒馆
  7487. // 画面:[近景,荷兰角倾斜构图] 刀疤脸斜睨着眼,昏暗的灯光勾勒出他脸上狰狞的伤疤。他身体前倾,阴影完全笼罩了对面的老李,眼神如毒蛇般阴冷。
  7488. // 运镜:固定机位,利用倾斜构图制造压迫感。
  7489. // 配音台词:中文配音:[刀疤脸]老李头,这酒里掺水了吧?
  7490. // 背景音效:
  7491. // \n\n";
  7492. $demo = "你是一个国际顶尖的执行导演/编剧,熟悉各种风格的影视化落地,我需要你将这个剧本调整一下,将其变成一个高质量的影视分镜剧本(需包含以下几个板块: <剧集标题><故事梗概><美术风格><旁白音色提示词><主体列表><场景列表><道具列表><分段剧本>,每个板块之间必须使用###分隔,#不能多也不能少),要求画面和构图等进行高质量影视化改编,快节奏,改编的格式为先建立主体角色库、场景建库(其中场景建库的时候请分析故事发生的时候场景为白天还是晚上,建库的时候一起标注出来)以及关键的道具库。
  7493. 与此同时请将这个文本的情绪做一个分析,并且根据我下面提供的《情绪-视听语言映射表》进行一个文本情绪与视听语言的内容匹配。然后将每一个分镜按照「场景/场景时间(白天/晚上/傍晚等)」「画面」「运镜」「配音台词」「背景音效」的格式来划分,请按照每分钟25个左右的分镜的节奏帮我生成(这是一个整体性的标准,如果文本的情绪分析需要更多或者更少的镜头数量,请根据具体情况调整),分镜头请细腻的拆分文本中的内容,将动作、场景转换、事件的逻辑关系等内容清晰的交代出来,分镜之间需要呈现场景之间的转换逻辑,不要突然跳到下一个场景之中。于此同时保持镜头剪辑的顿挫感,节奏不要太平均。
  7494. 每一个分镜的「画面」请参考上一个分镜中人物的状态/动作和位置来写,保持人物状态以及在场景中的位置的一致性,不要断裂感,同时也不要直接在内容里写“参考上个分镜”这种话,因为视频模型无法识别,使用模型可以直接识别的文本内容。每一个分镜中需要出现的内容都请标出,例如出场角色,出场道具等等。请尽可能详细的描述画面内容。
  7495. 「背景音效」层面不要生成背景音乐,只需要生成音效和角色台词或者旁白,台词请先标注说台词的角色,旁白和角色心理活动时注明角色不要张嘴说话。\n
  7496. 普通要求:
  7497. 1.剧集标题必须与文档内容高度相关,剧集序号是{$episode_number}。
  7498. {$role_demo}
  7499. {$scene_demo}
  7500. {$prop_demo}
  7501. 5.<分段剧本>按照“分段模式”进行拆分和组织,要求如下:
  7502. 5.1片段分割逻辑(优先级从高到低):
  7503. - 第一优先级:时长上限(单个片段不超过15秒,超过必须切为新片段)
  7504. - 第二优先级:叙事节拍Beat(一个完整的事件/动作/情绪起落单元,如一段对话的来回、一个动作序列:推门→看见→震惊、一次闪回/回忆、旁白+画面组合)
  7505. - 第三优先级:语义块(按“谁、在哪、做什么、情绪怎样”聚合,如同一段旁白/独白、同一个角色的连续动作、同一个视角的连续镜头)
  7506. - 只要事件没结束、情绪没断,哪怕换场景,也留在同一个片段里
  7507. 5.2片段结构:片段数量+旁白音色+多个片段(每个片段由多个分镜组合而成(片段序号格式:片段1、片段2...))
  7508. - 片段数量格式为: 片段数量:8
  7509. - 旁白音色需描述旁白的整体音色特征,包含:性别、年龄(约XX岁)、音质(如清冷、沉稳、磁性等)、表达形式(如叙述感、旁白式等)、情绪氛围(如空灵韵味、看透世事的清冷等),字数控制在80字以内。举例:成年女性(约25-35岁),音色清冷且富有叙述感,语速平缓,带有仙侠剧特有的空灵韵味。
  7510. - 片段序号格式必须如下: ##片段+片段序号\n时长:xxs,例如: ##片段1\n时长:12s
  7511. 5.3分镜结构:每个分镜包含以下字段:
  7512. - 分镜序号在片段内用1、2、3显示,如分镜1、分镜2,并且分镜序号需连续(跨片段中的分镜序号需连续,如片段2中的分镜序号从片段1的最大序号+1开始),分镜序号前后不要带任何其他符号,特别是*符号。
  7513. - 出场角色: 如果有主体出现在本镜,则必须选择本集中的<主体列表>中的一个(如必须使用“沈秋岚-程家居家围裙造型”,而不是“沈秋岚”,不得缺少“-”前后和“:”前面的任何内容,不能自创)
  7514. - 场景:必须选择本集中的<场景列表>中的一个(如需使用“酒店会客室-景池筹备会版”,而不是“酒店会客室”,不得缺少“-”前后和“:”前面的任何内容,不能自创)
  7515. - 出场道具:如果有道具出现在本镜,则必须选择本集中的<道具列表>中的一个(如需使用“酒杯-高脚杯”,而不是“酒杯”或“高脚杯”,不得缺少“-”前后和“:”前面的任何内容,不能自创)
  7516. - 画面:【构图/视角】+画面描述(越简单越好,对视觉场景/实景的描述,不描述氛围,比如紧张、压抑的氛围)。举例:[近景特写,浅景深]季潇握着手机贴在耳边,指关节因为用力而泛白。她的眼眶微红,睫毛在狂风中颤抖,嘴唇紧抿,眼神中闪烁着最后一点希冀的微光。
  7517. - 【强制要求-非常关键】画面中如果出现主体,只能选择上述<主体列表>中的一个,主体的名称也必须保持一致(如必须使用“沈秋岚-程家居家围裙造型”,而不是“沈秋岚”,不得缺少“-”前后和“:”前面的任何内容,不能自创)
  7518. - 【强制要求-非常关键】画面中如果出现道具,只能选择上述<道具列表>中的一个,道具的名称也必须保持一致(如必须使用“酒杯-高脚杯”,而不是“酒杯”或“高脚杯”,不得缺少“-”前后和“:”前面的任何内容,不能自创)
  7519. - 运镜:场景+画面描述+运镜
  7520. - 【强制要求-非常关键】运镜描述中如果出现主体或道具,逻辑需同画面一直,必须选择<主体列表>或<道具列表>中的一个,名称也必须保持一致
  7521. - 配音台词:格式为“中文配音:[角色]台词”,角色配音台词和语言由模型匹配生成,角色必须对应本集中的<主体列表>中的一个(非对话内容则统一固定为“旁白”角色,[角色]的角色名必须完整使用主体列表的主体名,如必须使用“沈秋岚-程家居家围裙造型”,而不是“沈秋岚”,不得缺少“-”前后和“:”前面的任何内容,不能自创,不能自创)
  7522. - 台词内容需满足以下要求: (1. 台词来源规则:台词内容必须逐字摘录自小说原文中的人物直接对话(带引号的内容),不允许改写、总结、压缩、扩写或拼接原文对白,不允许生成原文中不存在的对话。2. 非对话过滤:旁白、心理描写、环境描写、动作描写等内容,禁止出现在台词内容中。3. 空台词规则:如果该分镜中没有人物对话,则“台词内容”必须返回“无”,严禁输出“无台词”、“没有”等任何替代文本。4. 禁止推测:不得根据语境补全人物可能说的话。5.如果没有原文,直接返回空)
  7523. - 背景音效:背景音效需根据内容和画面生成,贴合当前画面描述和动作,例如:背景音效:高跟鞋的脚本声
  7524. 6.《情绪-视听语言映射表》:
  7525. 6.1 场景空间与时间心理学 (Scene & Temporality)
  7526. 维度 | 视听特征 | 对应核心情绪 | 心理学/叙事原理
  7527. -----|---------|------------|----------------
  7528. 场景空间 | 封闭狭小 (Corridors/Closets) | 压抑、幽闭恐惧 | 物理限制映射心理自由的剥夺。
  7529. 场景空间 | 极度开阔 (Empty Plains/Desert) | 孤独、渺小、疏离 | 剥离社会性支撑,强化个体的虚无感。
  7530. 时间选择 | 黄金时刻 (Golden Hour) | 怀旧、温情、希望 | 柔和漫反射光线符合大脑对“美好记忆”的视觉加工。
  7531. 时间选择 | 蓝调时刻/深夜 (Blue/Night) | 冷漠、忧郁、未知危险 | 冷色调抑制血清素,增强感官的不安全感。
  7532. 6.2 剪辑节奏与感知阈值 (Shot Duration & Rhythm)
  7533. 维度 | 视听特征 | 对应核心情绪 | 心理学/叙事原理
  7534. -----|---------|------------|----------------
  7535. 长镜头 | >15秒的静止或缓慢移动 | 沉思、肃穆、煎熬 | 强迫观众进入实时流逝,产生生理性的存在感。
  7536. 快切剪辑 | <2秒的频繁切换 | 混乱、亢奋、惊恐 | 模拟高肾上腺素下的视觉捕捉,剥夺深度思考时间。
  7537. 节奏错位 | 非同步切分 (L-cut/J-cut) | 扭曲、不协调 | 破坏连续性假定,产生心理上的不适与悬疑感。
  7538. 6.3 运镜调度与情绪调动 (Cinematic Movement & Affect)
  7539. 运镜方式 | 物理特征 | 心理/情绪功能 | 专业应用场景
  7540. --------|---------|--------------|-------------
  7541. 推镜头 (Dolly In) | 摄影机物理接近主体 | 专注、发现、心理逼近。通过压缩背景空间,强制观众忽略环境,进入主体的内心世界。 | 角色顿悟、秘密揭晓、情感升温。
  7542. 拉镜头 (Dolly Out) | 摄影机物理远离主体 | 疏离、解脱、宿命感。将主体置于广阔背景中,显示主体的渺小或强调事情已成定局。 | 悲剧结尾、孤独的告别、审视全局。
  7543. 摇镜头 (Pan/Tilt) | 轴心转动,视点改变 | 观察、审读、惊奇感。模拟人眼转头,用于揭示空间关系或进行逻辑上的“连接”。 | 发现潜伏的危机、环视战场、建立空间地理志。
  7544. 跟拍 (Tracking Shot) | 保持与主体同速移动 | 强烈的参与感、伴随性焦虑。让观众感觉自己是角色的共谋者或影子,产生“实时感”。 | 逃亡、快步穿行于走廊、展示角色的行动力。
  7545. 横移 (Truck/Side Track) | 与主体平行横向移动 | 客观审视、叙事流逝。像卷轴画一样展开,产生一种冷静、观察者的旁白视角。 | 展示环境细节、两个角色在边走边谈时的心理博弈。
  7546. 手持/肩扛 (Handheld) | 生理性不规则晃动 | 不安、真实感、心理动荡。模拟肉眼观察,通过不稳定性唤起观众的本能警觉。 | 冲突现场、纪录片式纪实感、角色精神崩溃。
  7547. 斯坦尼康 (Steadicam) | 流畅、近乎滑行的移动 | 全知感、梦幻、无缝观察。消除物理重力感,产生一种“上帝视角”或“游魂般”的观察。 | 漫长而复杂的转场、舞会等优雅场景的穿梭。
  7548. 希区柯克变焦 (Dolly Zoom) | 推进同时反向变焦 | 眩晕、世界崩塌、极度惊骇。空间透视的物理扭曲直接引发生理性失衡。 | 角色得知真相的瞬间、高度恐惧。
  7549. 升降/摇臂 (Crane Shot) | 垂直或斜向空间位移 | 释放、崇高、超越性。打破二维平面的限制,将情绪从微观拉向宏观。 | 史诗感的结局、战场全景、情绪的爆发式升华。
  7550. 6.4 构图、色彩与符号学 (Composition & Aesthetics)
  7551. 维度 | 视听特征 | 对应核心情绪 | 心理学原理
  7552. -----|---------|------------|------------
  7553. 角度 | 仰角 (Low Angle) | 威严、恐惧、崇高 | 模拟幼年视角,确立权力层级。
  7554. 角度 | 俯角 (High Angle) | 脆弱、无助、卑微 | 模拟审视感,削弱主体力量。
  7555. 构图 | 荷兰坡 (Dutch Tilt) | 疯狂、崩溃、失衡 | 重力轴偏离导致前庭系统产生失衡反应。
  7556. 色彩 | 极高饱和度/冷暖撞色 | 狂喜、冲突、超现实 | 强烈的视觉刺激诱发情绪阈值波动。
  7557. 6.5 进阶视听修辞与认知干预 (Advanced AV Rhetoric)
  7558. 修辞策略 | 技术实现 | 心理/情绪效应 | 理论基石
  7559. --------|---------|--------------|----------
  7560. 声画对位 (Contrapuntal AV) | 在极端残酷/激烈的画面中配以极其舒缓优雅的音乐(如古典乐)。 | 荒诞恐怖感、神圣的残酷、间离效果。通过感官冲突迫使观众从原始情绪中抽离,进入形而上的思考。 | 安德烈·塔可夫斯基《雕刻时光》、库布里克式美学。
  7561. 非平衡构图 (Compositional Tension) | 突破平衡法则,将视觉重点(Eye-tracking)置于画面边缘或极端角落。 | 本能警觉、不安全感、期待感。利用大脑对“视觉缺失”的补充本能,暗示画面外存在不可见的威胁。 | 格式塔心理学、眼动追踪实验。
  7562. 认知负荷调控 (Neurocinematics) | 利用快速剪辑抑制前额叶皮层(理性区),激活杏仁核(情绪区)。 | 纯粹感官化、生存模式切换。若要观众思考,则延长镜头以激活认知分析;若要观众受惊,则通过视觉过载切断其逻辑判断。 | 神经电影学 (Neurocinematics)。
  7563. 6.6 声音设计与潜意识影响 (Soundscape)
  7564. 维度 | 视听特征 | 对应核心情绪 | 心理学/生理学原理
  7565. -----|---------|------------|------------------
  7566. 音色 | 极低频音 (Infra-sound) | 潜伏恐惧、生理不安 | 模仿自然灾害频率,唤醒生物避害本能。
  7567. 环境声 | 极度死寂 (Silence) | 震惊、神圣、虚无 | 听觉剥夺放大视觉信号,产生心理张力。
  7568. 非现场音 | 不和谐音/尖锐音效 | 精神紧绷、躁郁 | 高频声音直接刺激杏仁核,引发防御机制。
  7569. 理论基石:
  7570. - The Five C's of Cinematography by Joseph V. Mascelli
  7571. - Film Art: An Introduction by David Bordwell
  7572. - Sight, Sound, Motion by Herbert Zettl
  7573. - Notes on the Cinematograph by Robert Bresson
  7574. \n\n
  7575. 7.{$mappedArtStyle_prompt}
  7576. 示例格式:\n
  7577. 第1集:隐形的守护者
  7578. ###故事梗概
  7579. 内容梗概:许芸归家遭徐母毒打,她冷静周旋并编造谎言掩盖行踪,引得一旁阴沉的卞大伟愈发急躁。半个月后,徐母离家,卞大伟兽性大发欲行不轨。生死关头,隐形的程景现身肉搏,屋内家具横飞,卞大伟被“空气”重创。许芸趁乱逃出,却惊见地面凭空浮现一串血脚印。意识到守护者为救自己负伤,许芸不再逃避,对着虚无的空气执拗告白,誓要与这看不见的爱人共进退。
  7580. ###美术风格
  7581. 基础画风风格词:胡金铨武侠
  7582. 视觉风格描述:整体采用复古武侠电影美学,以低饱和度的青灰与墨色调为主,营造冷峻、肃杀的江湖意境。光影上运用强烈的侧逆光与深邃硬阴影,完美契合“墨影剑客”神秘莫测的特质。画面带有35mm胶片的粗粝质感,构图简约且富有张力,展现出深沉的复仇叙事氛围。
  7583. ###主体列表
  7584. 陆沉:冷酷神秘的复仇剑客,陆家庄唯一幸存者,身负绝世武功与血海深仇。{全景,正面拍摄,青年男性,亚洲人,黑色长发束起,五官轮廓深邃。服饰穿搭:黑色连帽斗篷,深灰色交领劲装,黑色束腰,背负一柄漆黑宽大的无锋重剑。姿态:站立。}{{青年男性(约25-30岁),音色冷峻、低沉,语速平稳缓慢,透着一股拒人于千里之外的孤傲与肃杀。}}
  7585. 刀疤脸:武林盟的嚣张爪牙,性格暴戾、欺软怕硬,是赵无极麾下的打手。{全景,正面拍摄,中年男性,亚洲人,短发,左脸有一道明显的深长刀疤。服饰穿搭:土黄色粗布武士服,腰间挂着一枚古铜色的“武林盟”令牌。姿态:站立。}{{中年男性(约35-45岁),音色粗犷、沙哑,语气嚣张跋扈,带有明显的威胁感和市井痞气。}}
  7586. 老李:悦来酒馆的老板,胆小卑微的底层百姓,在乱世中艰难求生。{全景,正面拍摄,老年男性,亚洲人,灰白乱发,面容消瘦且布满皱纹。服饰穿搭:破旧的深蓝色粗布长袍,腰间系着一条带有污渍的灰色围裙。姿态:站立。}{{老年男性(约60岁以上),音色苍老、沙哑且带有颤抖,语气唯唯诺诺,充满了卑微与惊恐。}}
  7587. ###场景列表
  7588. 边境小镇街道:夜幕笼罩下的边陲小镇,风沙肆虐,街道两旁是破旧的木质建筑,透着一股荒凉与肃杀的气息,是故事发生的地理背景。{远景,夜幕下的边境小镇,破败的木质建筑错落有致,风沙在空旷的街道上飞扬,远处有微弱的灯火。无人物。}
  7589. 悦来酒馆:酒馆内部陈设简陋,木质桌椅散乱分布,柜台上摆放着酒坛。室内光线昏暗,只有几盏摇曳的油灯提供微弱的暖光,与室外的冷调形成对比。{室内场景,昏暗的古风酒馆内部,粗糙的木质桌椅,木质柜台与酒坛,空气中浮动着尘埃,强烈的侧逆光勾勒出环境轮廓,深邃的硬阴影。无人物。}
  7590. ###道具列表
  7591. 全家福照片:一张全家福照片{AI真人短剧,横屏16:9,8K电影级写实,无人物实体出镜的道具参考图,家庭全家福相框,多角度视角图,正面、背面、侧面、局部细节,木质或金属相框,照片内容可模糊表现多人合影构图,重点展示边缘站位感,相框尺寸标注25厘米×20厘米×2厘米,白底产品级干净展示}
  7592. 酒杯-高脚杯:一个高脚杯{AI真人短剧,横屏16:9,8K电影级写实,高脚酒杯,道具多角度视角图,正面、背面、侧面、局部细节,透明玻璃材质,细长杯柄,尺寸标注高24厘米杯口6厘米,白底干净展示,无人物}
  7593. ###分段剧本
  7594. 片段数量:8
  7595. 旁白音色:成年男性(约35-50岁),音色厚重且富有磁性,带有老电影叙事般的沧桑感,语调低沉平稳,富有江湖气息。
  7596. ##片段1
  7597. 时长:12s
  7598. 分镜1
  7599. 出场角色:刀疤脸
  7600. 场景:边境小镇街道
  7601. 出场道具:酒杯-高脚杯
  7602. 画面:[大远景,冷色调,高对比度] 漫天黄沙在狂风中如怒龙翻滚,遮蔽了微弱的星光。悦来酒馆残破的木门在风中剧烈摇晃,铁链撞击木板发出沉重的闷响,四周建筑尽显荒凉。
  7603. 运镜:大远景固定镜头,随后风沙席卷向镜头形成遮挡转场。
  7604. 配音台词:
  7605. 背景音效:
  7606. 分镜2
  7607. 出场角色:刀疤脸
  7608. 场景:悦来酒馆
  7609. 出场道具:酒杯-高脚杯
  7610. 画面:[全景,暖色调阴影构图] 酒馆内部昏暗,几盏油灯在风中疯狂摇曳,投射出扭曲的长影。角落里的食客低头缩颈,双手紧紧攥着粗瓷碗,空气中漂浮着细小的尘埃。
  7611. 运镜:缓慢横移,掠过阴影中瑟缩的食客。
  7612. 配音台词:
  7613. 背景音效:
  7614. 分镜3
  7615. 出场角色:刀疤脸
  7616. 场景:悦来酒馆
  7617. 出场道具:酒杯-高脚杯
  7618. 画面:[中景,三分法构图] 三名大汉围坐在正中央的圆桌旁,腰间挂着的“武林盟”金色令牌在灯火下闪烁。桌上残羹冷炙横陈,一名大汉正张狂地大笑,脚踩在长凳上。
  7619. 运镜:从中景推向令牌特写。
  7620. 配音台词:
  7621. 背景音效:
  7622. 分镜4
  7623. 出场角色:刀疤脸
  7624. 场景:悦来酒馆
  7625. 出场道具:酒杯-高脚杯
  7626. 画面:[特写,低角度仰拍] 刀疤脸横肉颤动,嘴角挂着轻蔑的笑。他随手倾覆手中的酒碗,琥珀色的液体在空中划过弧线,重重溅在老李打着补丁的布鞋和裤脚上。
  7627. 运镜:极速推向酒水溅起的瞬间。
  7628. 配音台词:
  7629. 背景音效:
  7630. 分镜5
  7631. 出场角色:刀疤脸
  7632. 场景:悦来酒馆
  7633. 出场道具:酒杯-高脚杯
  7634. 画面:[近景,荷兰角倾斜构图] 刀疤脸斜睨着眼,昏暗的灯光勾勒出他脸上狰狞的伤疤。他身体前倾,阴影完全笼罩了对面的老李,眼神如毒蛇般阴冷。
  7635. 运镜:固定机位,利用倾斜构图制造压迫感。
  7636. 配音台词:中文配音:[刀疤脸]老李头,这酒里掺水了吧?
  7637. 背景音效:
  7638. \n\n";
  7639. $origin_prompt = trim((string)getProp($data, 'prompt', '确认分镜大纲'));
  7640. $is_regenerate_version = !in_array($origin_prompt, ['确认分镜大纲', '继续策划下一集'], true);
  7641. $is_global_generate_pics = $origin_prompt == '确认分镜大纲' ? 1 : 0;
  7642. $prompt = $origin_prompt;
  7643. $is_single = (int)getProp($anime, 'is_multi') !== 1;
  7644. // 获取章节内容
  7645. $full_content = getProp($anime, 'content');
  7646. if ($uploaded_content) {
  7647. $full_content = $uploaded_content;
  7648. }
  7649. // 根据章节内容拆分章节
  7650. $chapters = splitContent($full_content);
  7651. $chapter_content = isset($chapters[($episode_number-1)]['content']) ? $chapters[($episode_number-1)]['content'] : '';
  7652. if (!$chapter_content) $chapter_content = $full_content; // 如果无法拆分章节则直接用原文
  7653. $messages = [];
  7654. if ($prompt == '确认分镜大纲') {
  7655. // 暂时保留
  7656. $content = $chapter_content;
  7657. if ($is_single) $content = $full_content; // 单剧集使用全文
  7658. if (!$content) {
  7659. Utils::throwError('20003:章节内容无法获取,请确认');
  7660. }
  7661. $question = $is_single
  7662. ? $demo . "请根据以上要求分析完整剧情,直接输出第1集完整单剧集分镜剧本,需一次性生成并可直接保存,剧情内容如下: \n\n$content"
  7663. : $demo . "请根据以上要求分析本章剧情,完成分镜剧本,本集剧情内容如下: \n\n$content";
  7664. // 构建消息
  7665. $messages[] =
  7666. [
  7667. 'role' => 'user',
  7668. 'content' => $question
  7669. ];
  7670. }else if ($prompt == '继续策划下一集') {
  7671. if ($is_single) {
  7672. Utils::throwError('20003:单剧集不支持继续策划下一集');
  7673. }
  7674. $content = $chapter_content;
  7675. if (!$content) {
  7676. Utils::throwError('20003:章节内容无法获取,请确认');
  7677. }
  7678. $question = $demo."请根据以上要求分析本集剧情内容,完成本集分镜剧本(需衔接上一集内容)";
  7679. // 获取上一集最后记录
  7680. $prev_sequence = $episode_number - 1;
  7681. $messages = $this->getEpisodeChatContent($anime_id, $prev_sequence, $content);
  7682. // 构建消息
  7683. $messages[] =
  7684. [
  7685. 'role' => 'user',
  7686. 'content' => $question
  7687. ];
  7688. // dd($messages);
  7689. }else {
  7690. $content = $uploaded_content ? $chapter_content : trim((string)getProp($base_episode, 'content'));
  7691. if (!$content) {
  7692. $content = $is_single ? $full_content : ($chapter_content ?: $full_content);
  7693. }
  7694. if (!$content) {
  7695. Utils::throwError('20003:章节内容无法获取,请确认');
  7696. }
  7697. $messages = $this->getEpisodeChatMessages($anime_id, $episode_number);
  7698. $targetEpisodeText = $is_single ? '第1集完整单剧集版本' : "第{$episode_number}集完整的新版本剧集";
  7699. $question = $demo . "\n请基于以上历史对话记录,重新生成{$targetEpisodeText},并严格按示例格式输出完整内容。\n";
  7700. if ($origin_prompt) {
  7701. $question .= "本次修改要求如下:\n{$origin_prompt}";
  7702. }
  7703. $messages[] =
  7704. [
  7705. 'role' => 'user',
  7706. 'content' => $question
  7707. ];
  7708. }
  7709. // 处理文本模型
  7710. $model = getProp($data, 'model');
  7711. if (!$model) {
  7712. // 用户没有输入,从anime表获取
  7713. $model = getProp($anime, 'model');
  7714. if (!$model) {
  7715. // anime表也没有,使用默认值
  7716. $model = 'deepseek-v4-pro';
  7717. }
  7718. }
  7719. // 验证模型是否在可用模型表中
  7720. if (!DB::table('mp_text_models')->where('model', $model)->where('is_enabled', 1)->exists()) {
  7721. $model = 'deepseek-v4-pro';
  7722. }
  7723. // 模型兼容性处理:deepseek-chat 和 deepseek-reasoner 映射到 deepseek-v4-flash
  7724. $thinkingMode = getProp($data, 'thinking', 'disabled'); // 默认非思考模式
  7725. $reasoningEffort = getProp($data, 'reasoning_effort', 'high'); // 默认思考强度
  7726. if ($model === 'deepseek-chat') {
  7727. // deepseek-chat 映射到 deepseek-v4-flash,非思考模式
  7728. $model = 'deepseek-v4-flash';
  7729. $thinkingMode = 'disabled';
  7730. } elseif ($model === 'deepseek-reasoner') {
  7731. // deepseek-reasoner 映射到 deepseek-v4-flash,思考模式
  7732. $model = 'deepseek-v4-flash';
  7733. $thinkingMode = 'enabled';
  7734. }
  7735. $post_data = [
  7736. 'model' => $model,
  7737. 'messages' => $messages,
  7738. // 'max_tokens' => 8192,
  7739. 'temperature' => (float)env('TEXT_TEMPERATURE'),
  7740. 'frequency_penalty' => 0,
  7741. 'presence_penalty' => 0,
  7742. 'response_format' => ['type' => 'text'],
  7743. 'thinking' => ['type' => $thinkingMode],
  7744. 'stream' => true // 启用流式输出
  7745. ];
  7746. if ($thinkingMode == 'enabled') $post_data['reasoning_effort'] = $reasoningEffort;
  7747. // 根据模型类型选择调用方法
  7748. $fullContent = '';
  7749. $fullReasoningContent = '';
  7750. $usage = [];
  7751. try {
  7752. if (in_array($model, ['deepseek-reasoner', 'deepseek-chat', 'deepseek-v4-flash', 'deepseek-v4-pro'])) {
  7753. // DeepSeek 官方模型使用 DeepSeek API
  7754. $streamGenerator = $this->deepSeekStreamResponse($post_data);
  7755. } else if (in_array($model, $this->gpt_text_models)) {
  7756. // GPT-5.4 模型使用 TokenRouter API
  7757. $streamGenerator = $this->gpt54StreamResponse($post_data);
  7758. } else {
  7759. // 其他模型使用火山引擎API
  7760. $streamGenerator = $this->volcEngineChatCompletion($post_data);
  7761. }
  7762. // 验证返回值类型
  7763. if (!is_iterable($streamGenerator)) {
  7764. $errorType = is_object($streamGenerator) ? get_class($streamGenerator) : gettype($streamGenerator);
  7765. dLog('deepseek')->error('chat流式生成器无效', [
  7766. 'generator_type' => $errorType,
  7767. 'model' => $model,
  7768. 'anime_id' => $anime_id,
  7769. 'episode_number' => $episode_number
  7770. ]);
  7771. logDB('deepseek', 'error', 'chat流式生成器类型错误', [
  7772. 'type' => $errorType,
  7773. 'model' => $model
  7774. ]);
  7775. yield [
  7776. 'type' => 'error',
  7777. 'episode' => [],
  7778. 'answer' => '',
  7779. 'reasoning' => '',
  7780. 'usage' => [],
  7781. 'error' => '接口返回数据异常,请重新请求'
  7782. ];
  7783. return;
  7784. }
  7785. // 处理流式输出
  7786. foreach ($streamGenerator as $chunk) {
  7787. if (isset($chunk['type'])) {
  7788. if ($chunk['type'] === 'done') {
  7789. // 最终结果
  7790. $fullContent = $chunk['full_content'];
  7791. $fullReasoningContent = $chunk['full_reasoning'];
  7792. $usage = isset($chunk['usage']) ? $chunk['usage'] : [];
  7793. } else {
  7794. // 逐块yield数据
  7795. yield $chunk;
  7796. }
  7797. }
  7798. }
  7799. } catch (\Exception $e) {
  7800. dLog('deepseek')->error('chat流式处理异常: ' . $e->getMessage(), [
  7801. 'model' => $model,
  7802. 'anime_id' => $anime_id,
  7803. 'episode_number' => $episode_number,
  7804. 'trace' => $e->getTraceAsString()
  7805. ]);
  7806. logDB('deepseek', 'error', 'chat流式处理失败', [
  7807. 'error' => $e->getMessage(),
  7808. 'model' => $model
  7809. ]);
  7810. yield [
  7811. 'type' => 'error',
  7812. 'episode' => [],
  7813. 'answer' => '',
  7814. 'reasoning' => '',
  7815. 'usage' => [],
  7816. 'error' => '处理请求时发生异常: ' . $e->getMessage()
  7817. ];
  7818. return;
  7819. }
  7820. dLog('deepseek')->info('完整内容: '.$fullContent);
  7821. logDB('deepseek', 'info', '完整内容', ['content' => $fullContent, 'anime_id' => $anime_id]);
  7822. // 处理完整内容并返回最终结果
  7823. $episode_arr = handleEpisodeContentForAce($fullContent);
  7824. logDB('deepseek', 'info', '解析内容', $episode_arr);
  7825. // // 如果有anime_script_id,进行主体和场景名称的智能匹配和替换(激进策略)
  7826. // if ($anime_script_id && !empty($extra_roles) && !empty($extra_scenes)) {
  7827. // $episode_arr = $this->matchAndReplaceRolesAndScenes($episode_arr, $extra_roles, $extra_scenes);
  7828. // logDB('deepseek', 'info', '匹配替换后的解析内容', $episode_arr);
  7829. // }
  7830. // 验证逻辑:如果anime_script_id有值,需要验证生成的主体和场景是否匹配
  7831. $max_retries = 3;
  7832. $retry_count = 0;
  7833. $validation_failed = false;
  7834. $validation_error_msg = '';
  7835. // 验证生成的内容
  7836. if ($anime_script_id) {
  7837. // 检查是否有acts数据
  7838. if (empty($episode_arr['acts'])) {
  7839. $validation_failed = true;
  7840. $validation_error_msg = '未生成分镜剧本相关的内容';
  7841. } else {
  7842. // 检查主体列表是否匹配 - 只验证生成的主体名是否都在预期列表中
  7843. $generated_roles = array_column($episode_arr['roles'], 'role');
  7844. // 过滤掉"旁白"角色
  7845. $generated_roles = array_filter($generated_roles, function($role) {
  7846. return $role !== '旁白';
  7847. });
  7848. $expected_roles = array_keys($extra_roles);
  7849. // 找出生成的主体中不在预期列表中的主体
  7850. $invalid_roles = array_diff($generated_roles, $expected_roles);
  7851. if (!empty($invalid_roles)) {
  7852. $validation_failed = true;
  7853. $validation_error_msg = '生成的主体列表包含不在【强制主体设定】中的主体:' . implode('、', $invalid_roles);
  7854. }
  7855. // 检查场景列表是否匹配 - 只验证生成的场景名是否都在预期列表中
  7856. if (!$validation_failed) {
  7857. $generated_scenes = array_column($episode_arr['scenes'], 'scene');
  7858. $expected_scenes = array_keys($extra_scenes);
  7859. // 找出生成的场景中不在预期列表中的场景
  7860. $invalid_scenes = array_diff($generated_scenes, $expected_scenes);
  7861. if (!empty($invalid_scenes)) {
  7862. $validation_failed = true;
  7863. $validation_error_msg = '生成的场景列表包含不在【强制场景设定】中的场景:' . implode('、', $invalid_scenes);
  7864. }
  7865. }
  7866. }
  7867. } else {
  7868. // 如果没有anime_script_id,只检查是否有acts数据
  7869. if (empty($episode_arr['acts'])) {
  7870. $validation_failed = true;
  7871. $validation_error_msg = '未生成分镜剧本相关的内容';
  7872. }
  7873. }
  7874. // 重试逻辑
  7875. while ($validation_failed && $retry_count < $max_retries) {
  7876. $retry_count++;
  7877. dLog('deepseek')->warning("验证失败,开始第{$retry_count}次重试", [
  7878. 'reason' => $validation_error_msg,
  7879. 'anime_id' => $anime_id,
  7880. 'episode_number' => $episode_number
  7881. ]);
  7882. logDB('deepseek', 'warning', "第{$retry_count}次重试", [
  7883. 'reason' => $validation_error_msg,
  7884. 'anime_id' => $anime_id
  7885. ]);
  7886. // 发送流式重试提示
  7887. yield [
  7888. 'type' => 'retry',
  7889. 'retry_count' => $retry_count,
  7890. 'reason' => $validation_error_msg
  7891. ];
  7892. // 构建重试提示词
  7893. $retry_prompt = "生成的剧本存在问题:{$validation_error_msg}。\n\n请严格按照要求重新生成,确保:\n";
  7894. if ($anime_script_id) {
  7895. $retry_prompt .= "1. 主体列表中的所有主体名称必须从【强制主体设定】中选择,不得使用其他主体名称\n";
  7896. $retry_prompt .= "2. 场景列表中的所有场景名称必须从【强制场景设定】中选择,不得使用其他场景名称\n";
  7897. $retry_prompt .= "3. 必须包含完整的分镜剧本内容\n";
  7898. } else {
  7899. $retry_prompt .= "1. 必须包含完整的分镜剧本内容\n";
  7900. }
  7901. // 添加重试消息到messages
  7902. $messages[] = [
  7903. 'role' => 'assistant',
  7904. 'content' => $fullContent
  7905. ];
  7906. $messages[] = [
  7907. 'role' => 'user',
  7908. 'content' => $retry_prompt
  7909. ];
  7910. // 更新post_data的messages
  7911. $post_data['messages'] = $messages;
  7912. // 重新调用API
  7913. try {
  7914. if (in_array($model, ['deepseek-reasoner', 'deepseek-chat', 'deepseek-v4-flash', 'deepseek-v4-pro'])) {
  7915. $streamGenerator = $this->deepSeekStreamResponse($post_data);
  7916. } else if (in_array($model, $this->gpt_text_models)) {
  7917. $streamGenerator = $this->gpt54StreamResponse($post_data);
  7918. } else {
  7919. $streamGenerator = $this->volcEngineChatCompletion($post_data);
  7920. }
  7921. // 处理流式输出
  7922. $fullContent = '';
  7923. $fullReasoningContent = '';
  7924. foreach ($streamGenerator as $chunk) {
  7925. if (isset($chunk['type'])) {
  7926. if ($chunk['type'] === 'done') {
  7927. $fullContent = $chunk['full_content'];
  7928. $fullReasoningContent = $chunk['full_reasoning'];
  7929. $usage = isset($chunk['usage']) ? $chunk['usage'] : [];
  7930. } else {
  7931. yield $chunk;
  7932. }
  7933. }
  7934. }
  7935. // 重新解析内容
  7936. dLog('deepseek')->info("第{$retry_count}次重试完整内容: " . $fullContent);
  7937. logDB('deepseek', 'info', "第{$retry_count}次重试解析内容", ['content' => $fullContent, 'anime_id' => $anime_id]);
  7938. $episode_arr = handleEpisodeContentForAce($fullContent);
  7939. // // 进行主体和场景名称的智能匹配和替换(激进策略)
  7940. // if ($anime_script_id && !empty($extra_roles) && !empty($extra_scenes)) {
  7941. // $episode_arr = $this->matchAndReplaceRolesAndScenes($episode_arr, $extra_roles, $extra_scenes);
  7942. // }
  7943. dLog('deepseek')->info('第'.$retry_count.'次重试后内容: '.$fullContent);
  7944. logDB('deepseek', 'info', "第{$retry_count}次重试解析内容", $episode_arr);
  7945. // 重新验证
  7946. $validation_failed = false;
  7947. $validation_error_msg = '';
  7948. if ($anime_script_id) {
  7949. if (empty($episode_arr['acts'])) {
  7950. $validation_failed = true;
  7951. $validation_error_msg = '未生成分镜剧本相关的内容';
  7952. } else {
  7953. // 检查主体列表 - 只验证生成的主体名是否都在预期列表中
  7954. $generated_roles = array_column($episode_arr['roles'], 'role');
  7955. // 过滤掉"旁白"角色
  7956. $generated_roles = array_filter($generated_roles, function($role) {
  7957. return $role !== '旁白';
  7958. });
  7959. $expected_roles = array_keys($extra_roles);
  7960. $invalid_roles = array_diff($generated_roles, $expected_roles);
  7961. if (!empty($invalid_roles)) {
  7962. $validation_failed = true;
  7963. $validation_error_msg = '生成的主体列表包含不在【强制主体设定】中的主体:' . implode('、', $invalid_roles);
  7964. }
  7965. // 检查场景列表 - 只验证生成的场景名是否都在预期列表中
  7966. if (!$validation_failed) {
  7967. $generated_scenes = array_column($episode_arr['scenes'], 'scene');
  7968. $expected_scenes = array_keys($extra_scenes);
  7969. $invalid_scenes = array_diff($generated_scenes, $expected_scenes);
  7970. if (!empty($invalid_scenes)) {
  7971. $validation_failed = true;
  7972. $validation_error_msg = '生成的场景列表包含不在【强制场景设定】中的场景:' . implode('、', $invalid_scenes);
  7973. }
  7974. }
  7975. }
  7976. } else {
  7977. if (empty($episode_arr['acts'])) {
  7978. $validation_failed = true;
  7979. $validation_error_msg = '未生成分镜剧本相关的内容';
  7980. }
  7981. }
  7982. } catch (\Exception $e) {
  7983. dLog('deepseek')->error("第{$retry_count}次重试异常: " . $e->getMessage(), [
  7984. 'trace' => $e->getTraceAsString()
  7985. ]);
  7986. break;
  7987. }
  7988. }
  7989. // 如果重试后仍然失败
  7990. if ($validation_failed) {
  7991. dLog('deepseek')->error('达到最大重试次数,仍未生成有效内容', [
  7992. 'retry_count' => $retry_count,
  7993. 'last_error' => $validation_error_msg
  7994. ]);
  7995. try {
  7996. $now = date('Y-m-d H:i:s');
  7997. $records = [
  7998. [
  7999. 'uid' => $uid,
  8000. 'anime_id' => $anime_id,
  8001. 'sequence' => $episode_number,
  8002. 'role' => 'user',
  8003. 'content' => $prompt,
  8004. 'created_at' => $now,
  8005. 'updated_at' => $now
  8006. ],
  8007. [
  8008. 'uid' => $uid,
  8009. 'anime_id' => $anime_id,
  8010. 'sequence' => $episode_number,
  8011. 'role' => 'assistant',
  8012. 'content' => $fullContent,
  8013. 'created_at' => $now,
  8014. 'updated_at' => $now
  8015. ]
  8016. ];
  8017. DB::table('mp_anime_records')->insert($records);
  8018. } catch (\Exception $e) {
  8019. dLog('deepseek')->error('保存对话记录失败', ['error' => $e->getMessage()]);
  8020. }
  8021. yield [
  8022. 'type' => 'done',
  8023. 'episode' => [],
  8024. 'answer' => $fullContent,
  8025. 'reasoning' => $fullReasoningContent,
  8026. 'usage' => $usage,
  8027. 'error' => "生成剧本有误,已重试{$retry_count}次仍失败,请稍后重试。错误原因:{$validation_error_msg}"
  8028. ];
  8029. return;
  8030. }
  8031. // 验证成功,记录日志
  8032. if ($retry_count > 0) {
  8033. dLog('deepseek')->info("经过{$retry_count}次重试后验证成功");
  8034. logDB('deepseek', 'info', '重试成功', ['retry_count' => $retry_count, 'anime_id' => $anime_id]);
  8035. }
  8036. // 老逻辑
  8037. $existing_roles = $base_episode ? json_decode((string)getProp($base_episode, 'roles'), true) : [];
  8038. $existing_scenes = $base_episode ? json_decode((string)getProp($base_episode, 'scenes'), true) : [];
  8039. $existing_props = $base_episode ? json_decode((string)getProp($base_episode, 'props'), true) : [];
  8040. $existing_roles = is_array($existing_roles) ? $existing_roles : [];
  8041. $existing_scenes = is_array($existing_scenes) ? $existing_scenes : [];
  8042. $existing_props = is_array($existing_props) ? $existing_props : [];
  8043. $now = date('Y-m-d H:i:s');
  8044. try {
  8045. DB::beginTransaction();
  8046. $saveResult = $this->saveEpisodeVersionData(
  8047. $anime_id,
  8048. $episode_number,
  8049. $episode_arr,
  8050. $existing_roles,
  8051. $existing_scenes,
  8052. $existing_props,
  8053. $current_episode,
  8054. $base_episode,
  8055. $is_regenerate_version,
  8056. $content,
  8057. $now,
  8058. $ref_products
  8059. );
  8060. $episode = $saveResult['episode'];
  8061. $episode_id = $saveResult['episode_id'];
  8062. $merged_roles = $saveResult['merged_roles'];
  8063. $merged_scenes = $saveResult['merged_scenes'];
  8064. $merged_props = $saveResult['merged_props'];
  8065. $record_content = $origin_prompt;
  8066. if ($uploaded_content !== '') {
  8067. // $record_content .= "\n\n###上传内容\n" . $uploaded_content;
  8068. }
  8069. $records = [
  8070. [
  8071. 'uid' => $uid,
  8072. 'anime_id' => $anime_id,
  8073. 'role' => 'user',
  8074. 'content' => $record_content,
  8075. 'sequence' => $episode_number,
  8076. 'episode_id' => $episode_id,
  8077. 'created_at' => $now,
  8078. 'updated_at' => $now
  8079. ],
  8080. [
  8081. 'uid' => $uid,
  8082. 'anime_id' => $anime_id,
  8083. 'role' => 'assistant',
  8084. 'content' => $fullContent,
  8085. // 'content' => '我已按照您的要求完成策划并将内容更新到您右侧的策划文档。',
  8086. 'sequence' => $episode_number,
  8087. 'episode_id' => $episode_id,
  8088. 'created_at' => $now,
  8089. 'updated_at' => $now
  8090. ]
  8091. ];
  8092. $boolen4 = DB::table('mp_anime_records')->insert($records);
  8093. if (!$boolen4) {
  8094. Utils::throwError('20003:对话记录保存失败');
  8095. }
  8096. // 保存模型到anime表
  8097. $update_anime_data = [
  8098. 'model' => $model,
  8099. 'updated_at' => $now
  8100. ];
  8101. if ($uploaded_content) {
  8102. $update_anime_data['content'] = $uploaded_content;
  8103. }
  8104. DB::table('mp_animes')->where('id', $anime_id)->update($update_anime_data);
  8105. }catch (\Exception $e) {
  8106. DB::rollBack();
  8107. dLog('deepseek')->info('新建对话错误信息: '.$e->getMessage());
  8108. yield [
  8109. 'type' => 'done',
  8110. 'answer' => $fullContent,
  8111. 'reasoning' => $fullReasoningContent,
  8112. 'usage' => $usage,
  8113. 'error' => $e->getMessage(),
  8114. ];
  8115. return;
  8116. }
  8117. DB::commit();
  8118. if ($is_global_generate_pics) {
  8119. // // 批量生成全局角色图片
  8120. // $this->batchSetGlobalRoleImg([
  8121. // 'anime_id' => $anime_id,
  8122. // ], true);
  8123. // // 批量生成全局场景图片
  8124. // $this->batchSetGlobalSceneImg([
  8125. // 'anime_id' => $anime_id,
  8126. // ], true);
  8127. // // 将全局角色和场景的task_id、task_status和url继承给当前分集
  8128. // $this->inheritGlobalImagesToEpisodes($anime_id, $episode_id);
  8129. }
  8130. $episode['episode_id'] = $episode_id;
  8131. $episode['roles'] = $merged_roles;
  8132. $episode['scenes'] = $merged_scenes;
  8133. $episode['props'] = $merged_props;
  8134. $episode['end_episode_sequence'] = $end_episode_sequence;
  8135. // 获取mp_animes表中的视频参数
  8136. $episode['video_params'] = [
  8137. 'video_model' => getProp($anime, 'video_model'),
  8138. 'video_resolution' => getProp($anime, 'video_resolution'),
  8139. 'ratio' => getProp($anime, 'video_ratio'),
  8140. ];
  8141. // $episode['acts'] = isset($episode_arr['acts']) && is_array($episode_arr['acts']) ? $episode_arr['acts'] : [];
  8142. yield [
  8143. 'type' => 'done',
  8144. 'episode' => $episode,
  8145. 'answer' => $fullContent,
  8146. 'reasoning' => $fullReasoningContent,
  8147. 'usage' => $usage
  8148. ];
  8149. }
  8150. /**
  8151. * chatForAce的非流式版本 - 用于定时任务
  8152. * 只获取最终 type=done 的数据,并验证必要字段
  8153. *
  8154. * @param array $data 请求数据
  8155. * @return array 生成结果
  8156. */
  8157. public function chatForAceNonStream($data) {
  8158. $finalResult = null;
  8159. // 调用流式方法,只保存 type=done 的数据
  8160. foreach ($this->chatForAce($data) as $chunk) {
  8161. // 只关注最终结果
  8162. if (isset($chunk['type']) && $chunk['type'] === 'done') {
  8163. $finalResult = $chunk;
  8164. break; // 找到 done 就退出循环
  8165. }
  8166. }
  8167. // 验证最终结果
  8168. if (!$finalResult) {
  8169. return ['error' => '生成失败:未获取到最终结果'];
  8170. }
  8171. // 检查是否有错误
  8172. if (isset($finalResult['error']) && $finalResult['error']) {
  8173. return $finalResult;
  8174. }
  8175. // 验证必要字段
  8176. $episode = $finalResult['episode'] ?? [];
  8177. // 验证 roles
  8178. if (empty($episode['roles']) || !is_array($episode['roles'])) {
  8179. return ['error' => '生成失败:主体列表(roles)为空或格式错误'];
  8180. }
  8181. // 验证 scenes
  8182. if (empty($episode['scenes']) || !is_array($episode['scenes'])) {
  8183. return ['error' => '生成失败:场景列表(scenes)为空或格式错误'];
  8184. }
  8185. // 验证 props(道具可以为空,但必须存在且为数组)
  8186. if (!isset($episode['props']) || !is_array($episode['props'])) {
  8187. $episode['props'] = [];
  8188. }
  8189. // 验证 acts(分镜剧本)
  8190. if (empty($episode['acts']) || !is_array($episode['acts'])) {
  8191. return ['error' => '生成失败:分镜剧本(acts)为空或格式错误'];
  8192. }
  8193. // 更新验证后的 episode 数据
  8194. $finalResult['episode'] = $episode;
  8195. // 记录验证成功日志
  8196. dLog('deepseek')->info('chatForAceNonStream 验证通过', [
  8197. 'roles_count' => count($episode['roles']),
  8198. 'scenes_count' => count($episode['scenes']),
  8199. 'props_count' => count($episode['props']),
  8200. 'acts_count' => count($episode['acts'])
  8201. ]);
  8202. return $finalResult;
  8203. }
  8204. /**
  8205. * 批量生成多个分集
  8206. *
  8207. * @param array $data 请求数据
  8208. * @return array 任务信息
  8209. */
  8210. public function batchGenerateEpisodes($data) {
  8211. $uid = Site::getUid();
  8212. $cpid = Site::getCpid();
  8213. $anime_id = getProp($data, 'anime_id');
  8214. $generate_episode_number = (int)getProp($data, 'generate_episode_number', 1);
  8215. if (!$anime_id) {
  8216. Utils::throwError('20003:anime_id参数缺失');
  8217. }
  8218. if ($generate_episode_number < 1) {
  8219. Utils::throwError('20003:生成集数必须大于0');
  8220. }
  8221. // 获取动漫信息
  8222. $anime = DB::table('mp_animes')->where('id', $anime_id)->first();
  8223. if (!$anime) {
  8224. Utils::throwError('20003:该剧集不存在');
  8225. }
  8226. // 检查是否是全能模式
  8227. if ((int)getProp($anime, 'ace_mode') !== 1) {
  8228. Utils::throwError('20003:只有全能模式才支持批量生成');
  8229. }
  8230. // 检查是否是多剧集模式
  8231. if ((int)getProp($anime, 'is_multi') !== 1) {
  8232. Utils::throwError('20003:单剧集不支持批量生成');
  8233. }
  8234. // 获取当前已生成的最大集数
  8235. $currentMaxEpisode = DB::table('mp_anime_episodes')
  8236. ->where('anime_id', $anime_id)
  8237. ->where('is_default', 1)
  8238. ->max('episode_number');
  8239. $currentMaxEpisode = $currentMaxEpisode ?: 0;
  8240. // 确定起始集数
  8241. $startEpisodeNumber = $currentMaxEpisode + 1;
  8242. // 计算结束集数
  8243. $endEpisodeNumber = $startEpisodeNumber + $generate_episode_number - 1;
  8244. // 检查是否超过总集数限制
  8245. $end_episode_sequence = getProp($anime, 'end_episode_sequence');
  8246. if ($end_episode_sequence && $endEpisodeNumber > $end_episode_sequence) {
  8247. Utils::throwError("20003:总集数只有{$end_episode_sequence}集,无法生成到第{$endEpisodeNumber}集");
  8248. }
  8249. $now = date('Y-m-d H:i:s');
  8250. $createdTasks = [];
  8251. $skippedTasks = [];
  8252. // 为每一集创建详情记录
  8253. for ($episodeNumber = $startEpisodeNumber; $episodeNumber <= $endEpisodeNumber; $episodeNumber++) {
  8254. // 检查是否已有该集的任务记录
  8255. $existingTask = DB::table('mp_batch_episode_generation_details')
  8256. ->where('anime_id', $anime_id)
  8257. ->where('episode_number', $episodeNumber)
  8258. ->first();
  8259. if ($existingTask) {
  8260. // 如果已存在且未完成,跳过
  8261. if (in_array($existingTask->status, ['pending', 'processing'])) {
  8262. $skippedTasks[] = $episodeNumber;
  8263. continue;
  8264. }
  8265. // 如果是失败状态,可以重新创建(删除旧记录)
  8266. if ($existingTask->status === 'failed') {
  8267. DB::table('mp_batch_episode_generation_details')
  8268. ->where('id', $existingTask->id)
  8269. ->delete();
  8270. }
  8271. // 如果是已完成状态,也跳过
  8272. if ($existingTask->status === 'completed') {
  8273. $skippedTasks[] = $episodeNumber;
  8274. continue;
  8275. }
  8276. }
  8277. // 准备任务数据
  8278. $taskData = [
  8279. 'anime_id' => $anime_id,
  8280. 'uid' => $uid,
  8281. 'cpid' => $cpid,
  8282. 'episode_number' => $episodeNumber,
  8283. 'status' => 'pending',
  8284. 'request_data' => json_encode($data, JSON_UNESCAPED_UNICODE),
  8285. 'retry_count' => 0,
  8286. 'created_at' => $now,
  8287. 'updated_at' => $now
  8288. ];
  8289. // 创建任务记录
  8290. $taskId = DB::table('mp_batch_episode_generation_details')->insertGetId($taskData);
  8291. if ($taskId) {
  8292. $createdTasks[] = $episodeNumber;
  8293. }
  8294. }
  8295. if (empty($createdTasks)) {
  8296. if (!empty($skippedTasks)) {
  8297. Utils::throwError('20003:所有集数都已存在任务记录,无需重复创建。已跳过集数:' . implode(',', $skippedTasks));
  8298. } else {
  8299. Utils::throwError('20003:创建批量生成任务失败');
  8300. }
  8301. }
  8302. return [
  8303. 'anime_id' => $anime_id,
  8304. 'start_episode' => $startEpisodeNumber,
  8305. 'end_episode' => $endEpisodeNumber,
  8306. 'total_episodes' => $generate_episode_number,
  8307. 'created_episodes' => $createdTasks,
  8308. 'skipped_episodes' => $skippedTasks,
  8309. 'message' => "已创建批量生成任务,将生成第{$startEpisodeNumber}集到第{$endEpisodeNumber}集,共{$generate_episode_number}集。" .
  8310. "已创建: " . implode(',', $createdTasks) .
  8311. (!empty($skippedTasks) ? ";已跳过: " . implode(',', $skippedTasks) : "")
  8312. ];
  8313. }
  8314. /**
  8315. * 获取批量生成任务状态
  8316. *
  8317. * @param array $data 请求数据
  8318. * @return array 任务状态信息
  8319. */
  8320. public function getBatchGenerationTaskStatus($data) {
  8321. $anime_id = getProp($data, 'anime_id');
  8322. if (!$anime_id) {
  8323. Utils::throwError('20003:anime_id参数缺失');
  8324. }
  8325. // 获取该anime的所有任务
  8326. $tasks = DB::table('mp_batch_episode_generation_details')
  8327. ->where('anime_id', $anime_id)
  8328. ->orderBy('episode_number')
  8329. ->get()
  8330. ->map(function($item) {
  8331. return [
  8332. 'id' => $item->id,
  8333. 'episode_number' => $item->episode_number,
  8334. 'status' => $item->status,
  8335. 'error_message' => $item->error_message,
  8336. 'retry_count' => $item->retry_count,
  8337. 'created_at' => $item->created_at,
  8338. 'updated_at' => $item->updated_at,
  8339. 'completed_at' => $item->completed_at
  8340. ];
  8341. })
  8342. ->toArray();
  8343. if (empty($tasks)) {
  8344. Utils::throwError('20003:该剧集没有批量生成任务');
  8345. }
  8346. // 统计各状态数量
  8347. $totalCount = count($tasks);
  8348. $pendingCount = 0;
  8349. $processingCount = 0;
  8350. $completedCount = 0;
  8351. $failedCount = 0;
  8352. foreach ($tasks as $task) {
  8353. switch ($task['status']) {
  8354. case 'pending':
  8355. $pendingCount++;
  8356. break;
  8357. case 'processing':
  8358. $processingCount++;
  8359. break;
  8360. case 'completed':
  8361. $completedCount++;
  8362. break;
  8363. case 'failed':
  8364. $failedCount++;
  8365. break;
  8366. }
  8367. }
  8368. // 计算进度百分比
  8369. $progress = 0;
  8370. if ($totalCount > 0) {
  8371. $progress = round(($completedCount / $totalCount) * 100, 2);
  8372. }
  8373. // 判断整体状态
  8374. $overallStatus = 'processing';
  8375. if ($completedCount === $totalCount) {
  8376. $overallStatus = 'completed';
  8377. } elseif ($pendingCount === $totalCount) {
  8378. $overallStatus = 'pending';
  8379. } elseif ($failedCount > 0 && ($pendingCount + $processingCount) === 0) {
  8380. $overallStatus = 'failed';
  8381. }
  8382. return [
  8383. 'anime_id' => $anime_id,
  8384. 'total_episodes' => $totalCount,
  8385. 'pending_count' => $pendingCount,
  8386. 'processing_count' => $processingCount,
  8387. 'completed_count' => $completedCount,
  8388. 'failed_count' => $failedCount,
  8389. 'progress' => $progress,
  8390. 'overall_status' => $overallStatus,
  8391. 'tasks' => $tasks
  8392. ];
  8393. }
  8394. /**
  8395. * 智能匹配并替换主体和场景名称
  8396. * 如果生成的主体或场景名称是强制设定名称的子串,则自动替换为完整名称
  8397. *
  8398. * @param array $episode_arr 解析后的剧集数据
  8399. * @param array $extra_roles 强制主体设定(key为主体名称)
  8400. * @param array $extra_scenes 强制场景设定(key为场景名称)
  8401. * @return array 替换后的剧集数据
  8402. */
  8403. private function matchAndReplaceRolesAndScenes($episode_arr, $extra_roles, $extra_scenes) {
  8404. $replaced_count = 0;
  8405. // 1. 处理主体列表
  8406. if (!empty($episode_arr['roles'])) {
  8407. foreach ($episode_arr['roles'] as &$role) {
  8408. $generated_role_name = $role['role'] ?? '';
  8409. // 跳过旁白
  8410. if ($generated_role_name === '旁白') {
  8411. continue;
  8412. }
  8413. // 如果生成的主体名不在强制设定中,尝试模糊匹配
  8414. if (!isset($extra_roles[$generated_role_name])) {
  8415. $matched_role = $this->findMatchingName($generated_role_name, array_keys($extra_roles));
  8416. if ($matched_role) {
  8417. dLog('deepseek')->info("主体名称替换: {$generated_role_name} => {$matched_role}");
  8418. $role['role'] = $matched_role;
  8419. $replaced_count++;
  8420. }
  8421. }
  8422. }
  8423. }
  8424. // 2. 处理场景列表
  8425. if (!empty($episode_arr['scenes'])) {
  8426. foreach ($episode_arr['scenes'] as &$scene) {
  8427. $generated_scene_name = $scene['scene'] ?? '';
  8428. // 如果生成的场景名不在强制设定中,尝试模糊匹配
  8429. if (!isset($extra_scenes[$generated_scene_name])) {
  8430. $matched_scene = $this->findMatchingName($generated_scene_name, array_keys($extra_scenes));
  8431. if ($matched_scene) {
  8432. dLog('deepseek')->info("场景名称替换: {$generated_scene_name} => {$matched_scene}");
  8433. $scene['scene'] = $matched_scene;
  8434. $replaced_count++;
  8435. }
  8436. }
  8437. }
  8438. }
  8439. // 3. 处理分段剧本中的主体和场景引用(全能模式下只使用segment_content字段)
  8440. if (!empty($episode_arr['acts'])) {
  8441. foreach ($episode_arr['acts'] as &$act) {
  8442. if (!empty($act['segments'])) {
  8443. foreach ($act['segments'] as &$segment) {
  8444. if (!empty($segment['segment_content'])) {
  8445. $original_content = $segment['segment_content'];
  8446. $replaced_content = $original_content;
  8447. // 替换场景名 - 在文本中查找并替换
  8448. foreach (array_keys($extra_scenes) as $full_scene_name) {
  8449. // 尝试找到可能的短名称
  8450. $potential_short_names = [];
  8451. // 提取场景名的主要部分(冒号之前)
  8452. if (mb_strpos($full_scene_name, ':') !== false) {
  8453. $short_name = mb_substr($full_scene_name, 0, mb_strpos($full_scene_name, ':'));
  8454. $potential_short_names[] = $short_name;
  8455. } elseif (mb_strpos($full_scene_name, ':') !== false) {
  8456. $short_name = mb_substr($full_scene_name, 0, mb_strpos($full_scene_name, ':'));
  8457. $potential_short_names[] = $short_name;
  8458. }
  8459. // 替换场景字段中的短名称
  8460. foreach ($potential_short_names as $short_name) {
  8461. if ($short_name !== $full_scene_name) {
  8462. $pattern = '/(?<=场景:|场景:|拍摄场景:|拍摄场景:|背景场景:|背景场景:|环境:|环境:)' . preg_quote($short_name, '/') . '(?=\s|$|\n)/u';
  8463. $new_content = preg_replace($pattern, $full_scene_name, $replaced_content);
  8464. if ($new_content !== $replaced_content) {
  8465. $replaced_content = $new_content;
  8466. $replaced_count++;
  8467. dLog('deepseek')->info("场景名替换: {$short_name} => {$full_scene_name}");
  8468. }
  8469. }
  8470. }
  8471. }
  8472. // 替换配音角色名(跳过旁白)
  8473. foreach (array_keys($extra_roles) as $full_role_name) {
  8474. if ($full_role_name === '旁白') {
  8475. continue;
  8476. }
  8477. // 尝试找到可能的短名称
  8478. $potential_short_names = [];
  8479. // 提取角色名的主要部分(短横线之前)
  8480. if (mb_strpos($full_role_name, '-') !== false) {
  8481. $short_name = mb_substr($full_role_name, 0, mb_strpos($full_role_name, '-'));
  8482. $potential_short_names[] = $short_name;
  8483. }
  8484. // 替换配音台词中的短名称
  8485. foreach ($potential_short_names as $short_name) {
  8486. if ($short_name !== $full_role_name) {
  8487. $pattern = '/(?<=配音台词:\[|配音台词:\[|中文配音:\[|中文配音:\[)\s*' . preg_quote($short_name, '/') . '\s*(?=\])/u';
  8488. $new_content = preg_replace($pattern, $full_role_name, $replaced_content);
  8489. if ($new_content !== $replaced_content) {
  8490. $replaced_content = $new_content;
  8491. $replaced_count++;
  8492. dLog('deepseek')->info("角色名替换: {$short_name} => {$full_role_name}");
  8493. }
  8494. }
  8495. }
  8496. }
  8497. // 如果有替换,更新segment_content
  8498. if ($replaced_content !== $original_content) {
  8499. $segment['segment_content'] = $replaced_content;
  8500. }
  8501. }
  8502. }
  8503. }
  8504. }
  8505. }
  8506. if ($replaced_count > 0) {
  8507. logDB('deepseek', 'info', '主体和场景名称智能替换', [
  8508. 'replaced_count' => $replaced_count
  8509. ]);
  8510. }
  8511. return $episode_arr;
  8512. }
  8513. /**
  8514. * 查找匹配的名称
  8515. * 规则:如果生成的名称是强制设定名称的子串(开头部分),则返回匹配的强制设定名称
  8516. *
  8517. * @param string $generated_name 生成的名称
  8518. * @param array $expected_names 预期的名称列表
  8519. * @return string|null 匹配到的名称,如果没有匹配则返回null
  8520. */
  8521. private function findMatchingName($generated_name, $expected_names) {
  8522. if (empty($generated_name)) {
  8523. return null;
  8524. }
  8525. // 尝试精确匹配
  8526. if (in_array($generated_name, $expected_names)) {
  8527. return $generated_name;
  8528. }
  8529. // 尝试模糊匹配:生成的名称是否为某个预期名称的开头部分
  8530. foreach ($expected_names as $expected_name) {
  8531. // 检查生成的名称是否是预期名称的开头(如"沈秋岚"是"沈秋岚-程家居家围裙造型"的开头)
  8532. if (mb_strpos($expected_name, $generated_name) === 0) {
  8533. return $expected_name;
  8534. }
  8535. }
  8536. // 更宽松的匹配:检查生成的名称是否包含在预期名称中的任意位置
  8537. // 这样可以处理一些变体,但优先级较低
  8538. foreach ($expected_names as $expected_name) {
  8539. if (mb_strpos($expected_name, $generated_name) !== false) {
  8540. return $expected_name;
  8541. }
  8542. }
  8543. return null;
  8544. }
  8545. /**
  8546. * 重新生成分段剧本
  8547. * @param array $data 包含以下字段:
  8548. * - prompt: string|null 用户修改要求(可选)
  8549. * - template_id: int|null 提示词模板ID(可选)
  8550. * - act_id: int|null 单个片段ID(与episode_id二选一)
  8551. * - episode_id: int|null 剧集ID,用于重新生成整个剧集的所有片段(与act_id二选一)
  8552. * @return array 返回生成结果
  8553. */
  8554. public function regenerateSegmentScript($data) {
  8555. $uid = Site::getUid();
  8556. $prompt = trim((string)getProp($data, 'prompt', ''));
  8557. $template_id = getProp($data, 'template_id', 0);
  8558. $act_id = getProp($data, 'act_id', 0);
  8559. $episode_id = getProp($data, 'episode_id', 0);
  8560. // 验证:prompt和template_id至少提供一个
  8561. if (empty($prompt) && empty($template_id)) {
  8562. Utils::throwError('20003:请提供修改要求或选择提示词模板');
  8563. }
  8564. // 验证:act_id和episode_id二选一
  8565. if (empty($act_id) && empty($episode_id)) {
  8566. Utils::throwError('20003:请提供片段ID或剧集ID');
  8567. }
  8568. if (!empty($act_id) && !empty($episode_id)) {
  8569. Utils::throwError('20003:片段ID和剧集ID只能选择一个');
  8570. }
  8571. // 如果提供了template_id,获取模板提示词
  8572. $template_prompt = '';
  8573. if ($template_id > 0) {
  8574. $template = DB::table('mp_prompt_templates')
  8575. ->where('id', $template_id)
  8576. ->where('is_deleted', 0)
  8577. ->first();
  8578. if (!$template) {
  8579. Utils::throwError('20003:提示词模板不存在或已删除');
  8580. }
  8581. $template_prompt = $template->template_prompt ?? '';
  8582. }
  8583. // 合并用户提示词和模板提示词
  8584. $final_prompt = '';
  8585. if (!empty($template_prompt)) {
  8586. $final_prompt = $template_prompt;
  8587. if (!empty($prompt)) {
  8588. $final_prompt .= "\n\n补充要求:" . $prompt;
  8589. }
  8590. } else {
  8591. $final_prompt = $prompt;
  8592. }
  8593. // 获取需要重新生成的内容参考
  8594. $reference_content = '';
  8595. $target_episode_id = 0;
  8596. $target_anime_id = 0;
  8597. $target_episode_number = 0;
  8598. if ($act_id > 0) {
  8599. // 单个片段模式:获取该片段的内容
  8600. $segment = DB::table('mp_episode_segments')
  8601. ->where('id', $act_id)
  8602. ->first();
  8603. if (!$segment) {
  8604. Utils::throwError('20003:片段不存在');
  8605. }
  8606. $target_episode_id = $segment->episode_id;
  8607. $target_anime_id = $segment->anime_id;
  8608. $target_episode_number = $segment->episode_number;
  8609. $reference_content = $segment->act_content ?? '';
  8610. $reference_content = "\n\n【原分段剧本内容】\n{$reference_content}";
  8611. } else {
  8612. // 整个剧集模式:获取所有片段的内容
  8613. $segments = DB::table('mp_episode_segments')
  8614. ->where('episode_id', $episode_id)
  8615. ->orderBy('act_number')
  8616. ->get();
  8617. if ($segments->isEmpty()) {
  8618. Utils::throwError('20003:该剧集没有片段数据');
  8619. }
  8620. $target_episode_id = $episode_id;
  8621. $target_anime_id = $segments[0]->anime_id;
  8622. $target_episode_number = $segments[0]->episode_number;
  8623. // 拼接所有片段内容,保留格式用于AI理解
  8624. $act_contents = [];
  8625. foreach ($segments as $seg) {
  8626. $act_number = $seg->act_number;
  8627. $act_content = $seg->act_content ?? '';
  8628. if (!empty($act_content)) {
  8629. $act_contents[] = "##片段{$act_number}\n" . $act_content;
  8630. }
  8631. }
  8632. $reference_content = implode("\n\n", $act_contents);
  8633. $episode_content = DB::table('mp_anime_episodes')->where('id', $episode_id)->value('content');
  8634. if ($episode_content) {
  8635. $reference_content = "\n\n【本集原始内容】\n{$episode_content}\n\n【本集生成剧本内容】\n{$reference_content}";
  8636. }else {
  8637. $reference_content = "\n\n【原分段剧本内容】\n{$reference_content}";
  8638. }
  8639. }
  8640. if (empty($reference_content)) {
  8641. Utils::throwError('20003:没有可参考的片段内容');
  8642. }
  8643. // 获取剧集的基本信息(intro、art_style、roles、scenes)
  8644. $episode = DB::table('mp_anime_episodes')
  8645. ->where('id', $target_episode_id)
  8646. ->first();
  8647. if (!$episode) {
  8648. Utils::throwError('20003:剧集不存在');
  8649. }
  8650. $anime = DB::table('mp_animes')->where('id', $target_anime_id)->first();
  8651. $anime_script_id = getProp($anime, 'script_id');
  8652. $intro = $episode->intro ?? '';
  8653. $art_style = $episode->art_style ?? '';
  8654. $roles = json_decode($episode->roles ?? '[]', true);
  8655. $scenes = json_decode($episode->scenes ?? '[]', true);
  8656. $props = json_decode($episode->props ?? '[]', true);
  8657. // 构建提示词中的主体列表和场景列表参考
  8658. $roles_ref = '';
  8659. if (!empty($roles) && is_array($roles)) {
  8660. $roles_list = [];
  8661. foreach ($roles as $role) {
  8662. $role_name = getProp($role, 'role', '');
  8663. $role_desc = getProp($role, 'description', '');
  8664. $pic_prompt = getProp($role, 'pic_prompt', '');
  8665. $voice_prompt = getProp($role, 'voice_prompt', '');
  8666. if (!empty($role_name)) {
  8667. $role_line = $role_name;
  8668. if (!empty($role_desc)) $role_line .= ":" . $role_desc;
  8669. if (!empty($pic_prompt)) $role_line .= "{" . $pic_prompt . "}";
  8670. if (!empty($voice_prompt)) $role_line .= "{{" . $voice_prompt . "}}";
  8671. $roles_list[] = $role_line;
  8672. }
  8673. }
  8674. if (!empty($roles_list)) {
  8675. $roles_ref = "\n\n【主体列表参考】\n" . implode("\n", $roles_list);
  8676. }
  8677. }
  8678. $scenes_ref = '';
  8679. if (!empty($scenes) && is_array($scenes)) {
  8680. $scenes_list = [];
  8681. foreach ($scenes as $scene) {
  8682. $scene_name = getProp($scene, 'scene', '');
  8683. $scene_desc = getProp($scene, 'description', '');
  8684. $pic_prompt = getProp($scene, 'pic_prompt', '');
  8685. if (!empty($scene_name)) {
  8686. $scene_line = $scene_name;
  8687. if (!empty($scene_desc)) $scene_line .= ":" . $scene_desc;
  8688. if (!empty($pic_prompt)) $scene_line .= "{" . $pic_prompt . "}";
  8689. $scenes_list[] = $scene_line;
  8690. }
  8691. }
  8692. if (!empty($scenes_list)) {
  8693. $scenes_ref = "\n\n【场景列表参考】\n" . implode("\n", $scenes_list);
  8694. }
  8695. }
  8696. $props_ref = '';
  8697. if (!empty($props) && is_array($props)) {
  8698. $props_list = [];
  8699. foreach ($props as $prop) {
  8700. $prop_name = getProp($prop, 'prop', '');
  8701. $prop_desc = getProp($prop, 'description', '');
  8702. $pic_prompt = getProp($prop, 'pic_prompt', '');
  8703. if (!empty($prop_name)) {
  8704. $prop_line = $prop_name;
  8705. if (!empty($prop_desc)) $prop_line .= ":" . $prop_desc;
  8706. if (!empty($pic_prompt)) $prop_line .= "{" . $pic_prompt . "}";
  8707. $props_list[] = $prop_line;
  8708. }
  8709. }
  8710. if (!empty($props_list)) {
  8711. $props_ref = "\n\n【道具列表参考】\n" . implode("\n", $props_list);
  8712. }
  8713. }
  8714. // 构建美术风格参考
  8715. $art_style_ref = '';
  8716. if (!empty($art_style)) {
  8717. $art_style_ref = "\n\n【美术风格参考】\n" . $art_style;
  8718. }
  8719. // 构建内容简介参考
  8720. $intro_ref = '';
  8721. if (!empty($intro)) {
  8722. $intro_ref = "\n\n【内容简介参考】\n" . $intro;
  8723. }
  8724. // 构建完整的AI提示词
  8725. // $system_prompt = "你是一个专业的剧本编剧和影视导演,擅长根据已有的分段剧本进行优化和调整。你需要严格按照用户的要求重新生成分段剧本内容,保持原有的格式和结构。";
  8726. $user_prompt = "请根据以下要求重新生成分段剧本:\n\n【用户要求】\n{$final_prompt}";
  8727. $user_prompt .= $intro_ref;
  8728. $user_prompt .= $art_style_ref;
  8729. $user_prompt .= $reference_content;
  8730. // $user_prompt .= $roles_ref;
  8731. // $user_prompt .= $scenes_ref;
  8732. $system_prompt = "\n\n【强制要求】\n";
  8733. $system_prompt .= "- 请仅生成<分段剧本>部分,不要生成其他任何内容:";
  8734. $system_prompt .= "- 第一优先级:片段时长上限(单个片段不超过15秒,超过必须切为新片段)";
  8735. $system_prompt .= "- 每个分镜包含:分镜序号、出场角色、场景、出场道具、画面、运镜、配音台词、背景音效\n";
  8736. $system_prompt .= "- 场景必须从【场景列表参考】中选择(如果提供了场景列表),场景名必须精确匹配【场景列表参考】中的名称(如需匹配“酒店会客室-景池筹备会版”,而不是“酒店会客室”,不得缺少“-”前后和“:”前面的任何内容,不能自创,不能自创){$scenes_ref}\n";
  8737. $system_prompt .= "- 出场角色(如果有出现在本分镜)必须从【主体列表参考】中选择(如果提供了主体列表),角色名必须精准匹配【主体列表参考】中的名称(如需匹配“沈秋岚-程家居家围裙造型”,而不是“沈秋岚”,不得缺少“-”前后和“:”前面的任何内容,不能自创,不能自创){$roles_ref}\n";
  8738. $system_prompt .= "- 出场道具(如果有出现在本分镜)必须从【道具列表参考】中选择(如果提供了道具列表),道具名必须精准匹配【道具列表参考】中的名称(如需匹配“智能手机-黑色版”,而不是“智能手机”,不得缺少“-”前后和“:”前面的任何内容,不能自创,不能自创){$props_ref}\n";
  8739. $system_prompt .= "- 【重要】在“画面:”和“运镜:”描述中,如果提到角色或道具,必须使用【主体列表参考】或【道具列表参考】中的完整名称,一个字都不能少,一个字都不能改。例如:正确写法“运镜:镜头推向{林启明-黑色大衣七爷造型}”,错误写法“运镜:镜头推向林启明”(缺少造型后缀)。必须包含“-”及其后面的所有内容,不得简化、不得省略、不得自行修改\n";
  8740. $system_prompt .= "- 保持美术风格的一致性(如果提供了美术风格参考)\n";
  8741. $system_prompt .= "- 参考示例格式如下,此为第一优先规则,必须按以下格式生成内容,请忽略其他任何提示词部分关于规则的描述:
  8742. ###分段剧本
  8743. 片段数量:8
  8744. 旁白音色:成年男性(约35-50岁),音色厚重且富有磁性,带有老电影叙事般的沧桑感,语调低沉平稳,富有江湖气息。
  8745. ##片段1
  8746. 时长:12s
  8747. 分镜1
  8748. 出场角色:刀疤脸
  8749. 场景:边境小镇街道
  8750. 出场道具:酒杯-高脚杯
  8751. 画面:[大远景,冷色调,高对比度] 漫天黄沙在狂风中如怒龙翻滚,遮蔽了微弱的星光。悦来酒馆残破的木门在风中剧烈摇晃,铁链撞击木板发出沉重的闷响,四周建筑尽显荒凉。
  8752. 运镜:大远景固定镜头,随后风沙席卷向镜头形成遮挡转场。
  8753. 配音台词:
  8754. 背景音效:
  8755. 分镜2
  8756. 出场角色:刀疤脸
  8757. 场景:悦来酒馆
  8758. 出场道具:酒杯-高脚杯
  8759. 画面:[全景,暖色调阴影构图] 酒馆内部昏暗,几盏油灯在风中疯狂摇曳,投射出扭曲的长影。角落里的食客低头缩颈,双手紧紧攥着粗瓷碗,空气中漂浮着细小的尘埃。
  8760. 运镜:缓慢横移,掠过阴影中瑟缩的食客。
  8761. 配音台词:
  8762. 背景音效:
  8763. 分镜3
  8764. 出场角色:刀疤脸
  8765. 场景:悦来酒馆
  8766. 出场道具:酒杯-高脚杯
  8767. 画面:[中景,三分法构图] 三名大汉围坐在正中央的圆桌旁,腰间挂着的“武林盟”金色令牌在灯火下闪烁。桌上残羹冷炙横陈,一名大汉正张狂地大笑,脚踩在长凳上。
  8768. 运镜:从中景推向令牌特写。
  8769. 配音台词:
  8770. 背景音效:
  8771. 分镜4
  8772. 出场角色:刀疤脸
  8773. 场景:悦来酒馆
  8774. 出场道具:酒杯-高脚杯
  8775. 画面:[特写,低角度仰拍] 刀疤脸横肉颤动,嘴角挂着轻蔑的笑。他随手倾覆手中的酒碗,琥珀色的液体在空中划过弧线,重重溅在老李打着补丁的布鞋和裤脚上。
  8776. 运镜:极速推向酒水溅起的瞬间。
  8777. 配音台词:
  8778. 背景音效:
  8779. 分镜5
  8780. 出场角色:刀疤脸
  8781. 场景:悦来酒馆
  8782. 出场道具:酒杯-高脚杯
  8783. 画面:[近景,荷兰角倾斜构图] 刀疤脸斜睨着眼,昏暗的灯光勾勒出他脸上狰狞的伤疤。他身体前倾,阴影完全笼罩了对面的老李,眼神如毒蛇般阴冷。
  8784. 运镜:固定机位,利用倾斜构图制造压迫感。
  8785. 配音台词:中文配音:[刀疤脸]老李头,这酒里掺水了吧?
  8786. 背景音效:";
  8787. // 获取模型配置
  8788. $model = getProp($data, 'model');
  8789. if (!$model) {
  8790. $model = $anime ? ($anime->model ?? 'deepseek-v4-pro') : 'deepseek-v4-pro';
  8791. }
  8792. // 验证模型是否在可用模型表中
  8793. if (!DB::table('mp_text_models')->where('model', $model)->where('is_enabled', 1)->exists()) {
  8794. $model = 'deepseek-v4-pro';
  8795. }
  8796. // 模型兼容性处理
  8797. $thinkingMode = 'disabled';
  8798. $reasoningEffort = 'high';
  8799. if ($model === 'deepseek-chat') {
  8800. $model = 'deepseek-v4-flash';
  8801. $thinkingMode = 'disabled';
  8802. } elseif ($model === 'deepseek-reasoner') {
  8803. $model = 'deepseek-v4-flash';
  8804. $thinkingMode = 'enabled';
  8805. }
  8806. // 构建消息
  8807. $messages = [
  8808. [
  8809. 'role' => 'system',
  8810. 'content' => $system_prompt
  8811. ],
  8812. [
  8813. 'role' => 'user',
  8814. 'content' => $user_prompt
  8815. ]
  8816. ];
  8817. // dd($messages);
  8818. // 构建请求参数
  8819. $post_data = [
  8820. 'model' => $model,
  8821. 'messages' => $messages,
  8822. 'temperature' => (float)env('TEXT_TEMPERATURE'),
  8823. 'frequency_penalty' => 0,
  8824. 'presence_penalty' => 0,
  8825. 'response_format' => ['type' => 'text'],
  8826. 'thinking' => ['type' => $thinkingMode],
  8827. 'stream' => false // 非流式输出
  8828. ];
  8829. if ($thinkingMode == 'enabled') $post_data['reasoning_effort'] = $reasoningEffort;
  8830. // 调用AI生成新的分段剧本
  8831. try {
  8832. $fullContent = '';
  8833. $usage = [];
  8834. // 根据模型类型选择调用方法
  8835. if (in_array($model, ['deepseek-reasoner', 'deepseek-chat', 'deepseek-v4-flash', 'deepseek-v4-pro'])) {
  8836. // DeepSeek 官方模型使用 DeepSeek API
  8837. $chatResult = $this->chatOnly($post_data);
  8838. } else if (in_array($model, $this->gpt_text_models)) {
  8839. // GPT 模型使用 TokenRouter API
  8840. $chatResult = $this->gpt54ChatOnly($post_data);
  8841. } else {
  8842. // 其他模型使用火山引擎API
  8843. $chatResult = $this->volcEngineChatCompletion($post_data);
  8844. }
  8845. if (is_array($chatResult)) {
  8846. $fullContent = $chatResult['fullContent'] ?? '';
  8847. $usage = $chatResult['usage'] ?? [];
  8848. }
  8849. $generated_content = $fullContent;
  8850. if (empty($generated_content)) {
  8851. Utils::throwError('20003:AI生成内容为空,请重试');
  8852. }
  8853. // 解析生成的内容 - 按片段分割
  8854. $parsed_segments = [];
  8855. // 先在开头添加换行符,确保第1片段也能被正确分割
  8856. $normalizedText = "\n" . $generated_content;
  8857. $parts = preg_split('/\n\s*##/', $normalizedText);
  8858. foreach ($parts as $part) {
  8859. $part = trim($part);
  8860. if (empty($part)) continue;
  8861. // 匹配"片段X"格式
  8862. if (!preg_match('/^片段\d+/', $part)) {
  8863. continue;
  8864. }
  8865. // 分离标题和内容
  8866. $lines = explode("\n", $part, 2);
  8867. $actTitle = trim($lines[0]);
  8868. $actContent = isset($lines[1]) ? trim($lines[1]) : '';
  8869. // 解析标题,提取序号
  8870. $actNumber = 0;
  8871. if (preg_match('/^片段(\d+)\s*$/u', $actTitle, $segmentTitleMatch)) {
  8872. $actNumber = intval($segmentTitleMatch[1]);
  8873. } else {
  8874. $actNumber = count($parsed_segments) + 1;
  8875. }
  8876. // 提取时长(仅保留数字)
  8877. $actDuration = 0;
  8878. if (preg_match('/时长[::]\s*([^\n]+)/u', $actContent, $actDurationMatch)) {
  8879. $actDurationStr = trim($actDurationMatch[1]);
  8880. // 提取数字部分(支持整数和小数)
  8881. if (preg_match('/([-+]?[0-9]*\.?[0-9]+)/', $actDurationStr, $numMatch)) {
  8882. $actDuration = (float)$numMatch[1];
  8883. }
  8884. }
  8885. // 清理act_content:去除时长、旁白音色等非分镜内容行
  8886. // 只保留分镜内容,并确保分镜标记使用【】格式
  8887. $cleaned_content = '';
  8888. $content_lines = explode("\n", $actContent);
  8889. $is_capturing = false; // 标记是否开始捕获分镜内容
  8890. $count = 0;
  8891. foreach ($content_lines as $line) {
  8892. $trimmed_line = trim($line);
  8893. // 跳过时长和旁白音色行
  8894. if (preg_match('/^(时长|旁白音色)[::]/u', $trimmed_line)) {
  8895. continue;
  8896. }
  8897. // 检测是否是分镜开始
  8898. // 支持格式:【分镜X】、【镜头X】、分镜X、镜头X
  8899. if (preg_match('/^(?:【)?(分镜|镜头)(\d+)(?:】)?/u', $trimmed_line, $shot_match)) {
  8900. $count++;
  8901. $is_capturing = true;
  8902. // 如果没有【】,则添加
  8903. if (!preg_match('/^【/u', $trimmed_line)) {
  8904. $trimmed_line = preg_replace('/^(分镜|镜头)(\d+)/u', '【$1$2】', $trimmed_line);
  8905. }
  8906. if ($count > 1) $trimmed_line = "\n".$trimmed_line;
  8907. }
  8908. // 如果已经开始捕获,则添加该行
  8909. if ($is_capturing && !empty($trimmed_line)) {
  8910. $cleaned_content .= $trimmed_line."\n";
  8911. }
  8912. }
  8913. $cleaned_content = str_replace(["@", "{", "}"], "", $cleaned_content);
  8914. $parsed_segments[] = [
  8915. 'act_number' => $actNumber,
  8916. 'act_title' => $actTitle,
  8917. 'act_duration' => $actDuration,
  8918. 'act_content' => $cleaned_content,
  8919. ];
  8920. }
  8921. if (empty($parsed_segments)) {
  8922. Utils::throwError('20003:无法解析生成的分段剧本,请检查格式');
  8923. }
  8924. // 收集所有资产名称(角色、场景、道具)
  8925. $product_names = [];
  8926. // 收集角色名称
  8927. if (!empty($roles) && is_array($roles)) {
  8928. foreach ($roles as $role) {
  8929. $role_name = getProp($role, 'role', '');
  8930. if (!empty($role_name)) {
  8931. $product_names[] = $role_name;
  8932. }
  8933. }
  8934. }
  8935. // 收集场景名称
  8936. if (!empty($scenes) && is_array($scenes)) {
  8937. foreach ($scenes as $scene) {
  8938. $scene_name = getProp($scene, 'scene', '');
  8939. if (!empty($scene_name)) {
  8940. $product_names[] = $scene_name;
  8941. }
  8942. }
  8943. }
  8944. // 收集道具名称
  8945. if (!empty($props) && is_array($props)) {
  8946. foreach ($props as $prop) {
  8947. $prop_name = getProp($prop, 'prop', '');
  8948. if (!empty($prop_name)) {
  8949. $product_names[] = $prop_name;
  8950. }
  8951. }
  8952. }
  8953. // 去重并按长度降序排序(避免短名称先匹配到长名称的一部分)
  8954. $product_names = array_unique($product_names);
  8955. usort($product_names, function($a, $b) {
  8956. return mb_strlen($b) - mb_strlen($a);
  8957. });
  8958. // 处理每个片段的 act_show_content
  8959. foreach ($parsed_segments as &$segment) {
  8960. $act_content = getProp($segment, 'act_content', '');
  8961. if (empty($act_content)) {
  8962. $segment['act_show_content'] = '';
  8963. continue;
  8964. }
  8965. $processed_content = $act_content;
  8966. // 统一替换所有资产名称为 {资产名} 格式
  8967. // 使用占位符避免嵌套替换问题
  8968. $placeholder_map = [];
  8969. $placeholder_index = 0;
  8970. foreach ($product_names as $product_name) {
  8971. // 转义特殊字符
  8972. $escaped_product = preg_quote($product_name, '/');
  8973. // 检查是否匹配且未被 {} 包裹
  8974. $processed_content = preg_replace_callback(
  8975. '/(?<![{])(' . $escaped_product . ')(?![}])/u',
  8976. function($matches) use (&$placeholder_map, &$placeholder_index) {
  8977. // 使用唯一占位符
  8978. $placeholder = '<<<PLACEHOLDER_' . $placeholder_index . '>>>';
  8979. $placeholder_map[$placeholder] = '{' . $matches[1] . '}';
  8980. $placeholder_index++;
  8981. return $placeholder;
  8982. },
  8983. $processed_content
  8984. );
  8985. }
  8986. // 将所有占位符替换回实际内容
  8987. foreach ($placeholder_map as $placeholder => $replacement) {
  8988. $processed_content = str_replace($placeholder, $replacement, $processed_content);
  8989. }
  8990. // 处理【镜头X】或【分镜X】重新编号为从1开始的连续整数【镜头X】
  8991. $shot_counter = 0;
  8992. $processed_content = preg_replace_callback(
  8993. '/【(?:镜头|分镜)(\d+)】/u',
  8994. function($matches) use (&$shot_counter) {
  8995. $shot_counter++;
  8996. return '【镜头' . $shot_counter . '】';
  8997. },
  8998. $processed_content
  8999. );
  9000. $segment['act_show_content'] = $processed_content;
  9001. }
  9002. unset($segment); // 解除引用
  9003. // 保存到数据库
  9004. $now = date('Y-m-d H:i:s');
  9005. $saved_acts = []; // 用于记录保存后的片段信息
  9006. if ($act_id > 0) {
  9007. // 单个片段模式:更新单条记录
  9008. if (count($parsed_segments) > 0) {
  9009. $new_segment = $parsed_segments[0];
  9010. $update_data = [
  9011. 'act_content' => getProp($new_segment, 'act_content', ''),
  9012. 'act_show_content' => getProp($new_segment, 'act_show_content', ''),
  9013. 'act_title' => getProp($new_segment, 'act_title', ''),
  9014. 'act_duration' => getProp($new_segment, 'act_duration', 0),
  9015. 'updated_at' => $now,
  9016. ];
  9017. DB::table('mp_episode_segments')
  9018. ->where('id', $act_id)
  9019. ->update($update_data);
  9020. // 获取更新后的记录
  9021. $updated_act = DB::table('mp_episode_segments')
  9022. ->where('id', $act_id)
  9023. ->first();
  9024. if ($updated_act) {
  9025. $saved_acts[] = [
  9026. 'act_id' => $updated_act->id,
  9027. 'act_number' => $updated_act->act_number,
  9028. 'act_duration' => $updated_act->video_duration ? $updated_act->video_duration : $updated_act->act_duration,
  9029. 'act_content' => $updated_act->act_content,
  9030. 'act_show_content' => $updated_act->act_show_content,
  9031. 'video_url' => $updated_act->video_url ?? '',
  9032. 'video_duration' => $updated_act->video_duration ?? 0,
  9033. 'video_time_point_start' => $updated_act->video_time_point_start ?? 0,
  9034. 'video_time_point_end' => $updated_act->video_time_point_end ?? 0,
  9035. ];
  9036. }
  9037. dLog('deepseek')->info('单个片段重新生成成功', ['act_id' => $act_id]);
  9038. }
  9039. } else {
  9040. // 整个剧集模式:删除原有记录并批量保存新记录
  9041. DB::beginTransaction();
  9042. try {
  9043. // 删除原有的所有片段记录
  9044. DB::table('mp_episode_segments')
  9045. ->where('episode_id', $target_episode_id)
  9046. ->delete();
  9047. // 批量插入新的片段记录
  9048. $segments_to_insert = [];
  9049. foreach ($parsed_segments as $index => $segment) {
  9050. $act_number = $index + 1;
  9051. $segments_to_insert[] = [
  9052. 'anime_id' => $target_anime_id,
  9053. 'episode_id' => $target_episode_id,
  9054. 'episode_number' => $target_episode_number,
  9055. 'act_number' => $act_number,
  9056. 'act_title' => getProp($segment, 'act_title', ''),
  9057. 'act_duration' => getProp($segment, 'act_duration', 0),
  9058. 'act_content' => getProp($segment, 'act_content', ''),
  9059. 'act_show_content' => getProp($segment, 'act_show_content', ''),
  9060. 'created_at' => $now,
  9061. 'updated_at' => $now,
  9062. ];
  9063. }
  9064. if (!empty($segments_to_insert)) {
  9065. DB::table('mp_episode_segments')->insert($segments_to_insert);
  9066. }
  9067. DB::commit();
  9068. // 查询保存后的所有片段记录
  9069. $saved_segments = DB::table('mp_episode_segments')
  9070. ->where('episode_id', $target_episode_id)
  9071. ->orderBy('act_number')
  9072. ->get();
  9073. foreach ($saved_segments as $saved_segment) {
  9074. $saved_acts[] = [
  9075. 'act_id' => $saved_segment->id,
  9076. 'act_number' => $saved_segment->act_number,
  9077. 'act_duration' => $saved_segment->video_duration ? $saved_segment->video_duration : $saved_segment->act_duration,
  9078. 'act_content' => $saved_segment->act_content,
  9079. 'act_show_content' => $saved_segment->act_show_content,
  9080. 'video_url' => $saved_segment->video_url ?? '',
  9081. 'video_duration' => $saved_segment->video_duration ?? 0,
  9082. 'video_time_point_start' => $saved_segment->video_time_point_start ?? 0,
  9083. 'video_time_point_end' => $saved_segment->video_time_point_end ?? 0,
  9084. ];
  9085. }
  9086. dLog('deepseek')->info('整个剧集片段重新生成成功', [
  9087. 'episode_id' => $target_episode_id,
  9088. 'segments_count' => count($segments_to_insert)
  9089. ]);
  9090. } catch (\Exception $e) {
  9091. DB::rollBack();
  9092. dLog('deepseek')->error('保存重新生成的片段失败: ' . $e->getMessage());
  9093. Utils::throwError('20003:保存失败,请重试');
  9094. }
  9095. }
  9096. // 构造返回数据结构(参考AnimeService返回格式,但不包含products)
  9097. return [
  9098. 'anime_id' => $target_anime_id,
  9099. 'episode_id' => $target_episode_id,
  9100. 'title' => getProp($episode, 'title', ''),
  9101. 'episode_number' => $target_episode_number,
  9102. 'is_generated' => getProp($episode, 'is_generated', 0),
  9103. 'acts' => $saved_acts,
  9104. ];
  9105. } catch (\Exception $e) {
  9106. dLog('deepseek')->error('重新生成分段剧本失败: ' . $e->getMessage());
  9107. throw $e;
  9108. }
  9109. }
  9110. private function buildSingleEpisodeFromScript(array $script_arr, string $fullContent, string $animeName = ''): array
  9111. {
  9112. $episode_arr = [
  9113. 'episode_title' => $animeName, // 单剧集默认使用剧本名
  9114. 'intro' => getProp($script_arr, 'intro'),
  9115. 'art_style' => getProp($script_arr, 'art_style'),
  9116. 'roles' => is_array(getProp($script_arr, 'roles')) ? getProp($script_arr, 'roles') : [],
  9117. 'scenes' => is_array(getProp($script_arr, 'scenes')) ? getProp($script_arr, 'scenes') : [],
  9118. 'props' => is_array(getProp($script_arr, 'props')) ? getProp($script_arr, 'props') : [],
  9119. 'acts' => is_array(getProp($script_arr, 'acts')) ? getProp($script_arr, 'acts') : [],
  9120. ];
  9121. if (empty($episode_arr['acts'])) {
  9122. $fallback_episode_arr = handleEpisodeContent($fullContent);
  9123. if (!empty($fallback_episode_arr['acts'])) {
  9124. $episode_arr = array_merge($fallback_episode_arr, [
  9125. 'intro' => getProp($fallback_episode_arr, 'intro') ?: getProp($script_arr, 'intro'),
  9126. 'art_style' => getProp($fallback_episode_arr, 'art_style') ?: getProp($script_arr, 'art_style'),
  9127. 'roles' => !empty(getProp($fallback_episode_arr, 'roles')) ? getProp($fallback_episode_arr, 'roles') : getProp($script_arr, 'roles', []),
  9128. 'scenes' => !empty(getProp($fallback_episode_arr, 'scenes')) ? getProp($fallback_episode_arr, 'scenes') : getProp($script_arr, 'scenes', []),
  9129. ]);
  9130. }
  9131. }
  9132. // if (!getProp($episode_arr, 'episode_title')) {
  9133. // $episode_title = '';
  9134. // $episodes = getProp($script_arr, 'episodes', []);
  9135. // if (is_array($episodes) && !empty($episodes[0]['title'])) {
  9136. // $episode_title = '第1集:' . $episodes[0]['title'];
  9137. // }
  9138. // if (!$episode_title) {
  9139. // $episode_title = '第1集:' . ($animeName ?: '未命名');
  9140. // }
  9141. // $episode_arr['episode_title'] = $episode_title;
  9142. // }
  9143. return $episode_arr;
  9144. }
  9145. private function saveEpisodeVersionData(
  9146. int $anime_id,
  9147. int $episode_number,
  9148. array $episode_arr,
  9149. array $existing_roles,
  9150. array $existing_scenes,
  9151. array $existing_props,
  9152. $current_episode,
  9153. $base_episode,
  9154. bool $is_regenerate_version,
  9155. string $content,
  9156. string $now,
  9157. array $ref_products = []
  9158. ): array {
  9159. $generated_roles = isset($episode_arr['roles']) && is_array($episode_arr['roles']) ? $episode_arr['roles'] : [];
  9160. $generated_scenes = isset($episode_arr['scenes']) && is_array($episode_arr['scenes']) ? $episode_arr['scenes'] : [];
  9161. $generated_props = isset($episode_arr['props']) && is_array($episode_arr['props']) ? $episode_arr['props'] : [];
  9162. // 过滤掉关键字段为空的条目
  9163. $merged_roles = array_values(array_filter($generated_roles, function ($item) {
  9164. return !empty($item['role'] ?? null);
  9165. }));
  9166. $merged_scenes = array_values(array_filter($generated_scenes, function ($item) {
  9167. return !empty($item['scene'] ?? null);
  9168. }));
  9169. $merged_props = array_values(array_filter($generated_props, function ($item) {
  9170. return !empty($item['prop'] ?? null);
  9171. }));
  9172. // $merged_roles = $this->mergeEpisodeResourceItems($existing_roles, $generated_roles, 'role');
  9173. // $merged_scenes = $this->mergeEpisodeResourceItems($existing_scenes, $generated_scenes, 'scene');
  9174. // 获取 mp_animes 表中的全局 roles 和 scenes 用于对比
  9175. $anime = DB::table('mp_animes')->where('id', $anime_id)->first();
  9176. $ace_mode = getProp($anime, 'ace_mode');
  9177. dLog('deepseek')->info('ace_mode', ['ace_mode' => $ace_mode]);
  9178. $global_roles = json_decode(getProp($anime, 'roles'), true);
  9179. $global_scenes = json_decode(getProp($anime, 'scenes'), true);
  9180. $global_roles = is_array($global_roles) ? $global_roles : [];
  9181. $global_scenes = is_array($global_scenes) ? $global_scenes : [];
  9182. $art_style = getProp($episode_arr, 'art_style') ?: getProp($anime, 'art_style');
  9183. $art_style_type = getProp($anime, 'art_style_type');
  9184. // 检查并创建 roles 的图片生成任务
  9185. // $merged_roles = $this->checkAndCreateImageTasks($merged_roles, $global_roles, 'role', $art_style);
  9186. // 检查并创建 scenes 的图片生成任务
  9187. // $merged_scenes = $this->checkAndCreateImageTasks($merged_scenes, $global_scenes, 'scene', $art_style);
  9188. $arr = $this->batchSetEpisodeRolesAndScenesImg($anime_id, $episode_number, $merged_roles, $merged_scenes, $merged_props, $ref_products, $art_style_type);
  9189. if ($arr && is_array($arr)) {
  9190. $merged_roles = $arr['roles'];
  9191. $merged_scenes = $arr['scenes'];
  9192. $merged_props = isset($arr['props']) ? $arr['props'] : [];
  9193. }
  9194. // 确保数据是数组类型
  9195. if (!is_array($merged_roles)) {
  9196. dLog('deepseek')->error('merged_roles不是数组类型', [
  9197. 'type' => gettype($merged_roles),
  9198. 'value' => $merged_roles
  9199. ]);
  9200. $merged_roles = [];
  9201. }
  9202. if (!is_array($merged_scenes)) {
  9203. dLog('deepseek')->error('merged_scenes不是数组类型', [
  9204. 'type' => gettype($merged_scenes),
  9205. 'value' => $merged_scenes
  9206. ]);
  9207. $merged_scenes = [];
  9208. }
  9209. if (!is_array($merged_props)) {
  9210. dLog('deepseek')->error('merged_props不是数组类型', [
  9211. 'type' => gettype($merged_props),
  9212. 'value' => $merged_props
  9213. ]);
  9214. $merged_props = [];
  9215. }
  9216. // 同步新出现的主体和场景到全局
  9217. // $this->syncNewResourcesToGlobal($anime_id, $merged_roles, $merged_scenes, $global_roles, $global_scenes);
  9218. $role_arr = [];
  9219. foreach ($merged_roles as $item) {
  9220. $role_arr[$item['role']] = $item;
  9221. }
  9222. $version_count = DB::table('mp_anime_episodes')
  9223. ->where('anime_id', $anime_id)
  9224. ->where('episode_number', $episode_number)
  9225. ->count('id');
  9226. $episode = [
  9227. 'anime_id' => $anime_id,
  9228. 'episode_number' => $episode_number,
  9229. 'title' => getProp($episode_arr, 'episode_title'),
  9230. 'content' => $content,
  9231. 'intro' => getProp($episode_arr, 'intro'),
  9232. 'art_style' => getProp($episode_arr, 'art_style'),
  9233. 'roles' => json_encode($merged_roles, 256),
  9234. 'scenes' => json_encode($merged_scenes, 256),
  9235. 'props' => json_encode($merged_props, 256),
  9236. 'generate_status' => '待执行',
  9237. 'generate_at' => $now,
  9238. 'is_default' => 1,
  9239. 'updated_at' => $now,
  9240. ];
  9241. $del_flag = false;
  9242. if ($is_regenerate_version) {
  9243. DB::table('mp_anime_episodes')
  9244. ->where('anime_id', $anime_id)
  9245. ->where('episode_number', $episode_number)
  9246. ->update(['is_default' => 0, 'updated_at' => $now]);
  9247. $episode['sequence'] = $version_count + 1;
  9248. $episode['created_at'] = $now;
  9249. $episode['cpid'] = Site::getCpid();
  9250. $episode_id = DB::table('mp_anime_episodes')->insertGetId($episode);
  9251. if (!$episode_id) {
  9252. Utils::throwError('20003:创建剧集版本失败');
  9253. }
  9254. } else {
  9255. $target_episode = $current_episode ?: $base_episode;
  9256. if ($target_episode) {
  9257. $episode_id = getProp($target_episode, 'id');
  9258. $episode['sequence'] = getProp($target_episode, 'sequence', 1);
  9259. DB::table('mp_anime_episodes')
  9260. ->where('anime_id', $anime_id)
  9261. ->where('episode_number', $episode_number)
  9262. ->where('id', '<>', $episode_id)
  9263. ->update(['is_default' => 0, 'updated_at' => $now]);
  9264. $boolen = DB::table('mp_anime_episodes')->where('id', $episode_id)->update($episode);
  9265. if ($boolen === false) {
  9266. logDB('deepseek', 'error', '分集内容保存失败', ['anime_id' => $anime_id, 'episode_id' => $episode_id]);
  9267. Utils::throwError('20003:分集内容保存失败');
  9268. }
  9269. $del_flag = true;
  9270. } else {
  9271. DB::table('mp_anime_episodes')
  9272. ->where('anime_id', $anime_id)
  9273. ->where('episode_number', $episode_number)
  9274. ->update(['is_default' => 0, 'updated_at' => $now]);
  9275. $episode['sequence'] = $version_count > 0 ? ($version_count + 1) : 1;
  9276. $episode['created_at'] = $now;
  9277. $episode['cpid'] = Site::getCpid();
  9278. $episode_id = DB::table('mp_anime_episodes')->insertGetId($episode);
  9279. if (!$episode_id) {
  9280. logDB('deepseek', 'error', '分集内容保存失败', ['anime_id' => $anime_id, 'episode_number' => $episode_number]);
  9281. Utils::throwError('20003:分集内容保存失败');
  9282. }
  9283. }
  9284. }
  9285. $segments = [];
  9286. $acts = isset($episode_arr['acts']) && is_array($episode_arr['acts']) ? $episode_arr['acts'] : [];
  9287. // 如果是第2集及以后,获取上一集的主体音色数据
  9288. $previous_roles_voice = [];
  9289. if ($episode_number >= 2) {
  9290. $previous_episode = DB::table('mp_anime_episodes')
  9291. ->where('anime_id', $anime_id)
  9292. ->where('episode_number', $episode_number - 1)
  9293. ->where('is_default', 1)
  9294. ->first();
  9295. if ($previous_episode) {
  9296. $previous_roles = json_decode(getProp($previous_episode, 'roles'), true);
  9297. if (is_array($previous_roles)) {
  9298. foreach ($previous_roles as $prev_role) {
  9299. $role_name = getProp($prev_role, 'role');
  9300. if ($role_name) {
  9301. $previous_roles_voice[$role_name] = [
  9302. 'voice_name' => getProp($prev_role, 'voice_name'),
  9303. 'voice_type' => getProp($prev_role, 'voice_type'),
  9304. 'voice_audio_url' => getProp($prev_role, 'voice_audio_url'),
  9305. ];
  9306. $voice_prompt = getProp($prev_role, 'voice_prompt');
  9307. if ($voice_prompt) {
  9308. $previous_roles_voice[$role_name]['voice_prompt'] = $voice_prompt;
  9309. }
  9310. }
  9311. }
  9312. }
  9313. }
  9314. }
  9315. // 将继承的音色数据同步到当前集的主体列表
  9316. if (!empty($previous_roles_voice)) {
  9317. foreach ($merged_roles as &$role) {
  9318. $role_name = getProp($role, 'role');
  9319. if ($role_name && isset($previous_roles_voice[$role_name])) {
  9320. // 强制继承上一集的音色数据
  9321. $role['voice_name'] = $previous_roles_voice[$role_name]['voice_name'];
  9322. $role['voice_type'] = $previous_roles_voice[$role_name]['voice_type'];
  9323. $role['voice_audio_url'] = $previous_roles_voice[$role_name]['voice_audio_url'];
  9324. // 如果上一集有 voice_prompt 则继承,否则跳过
  9325. if (!empty($previous_roles_voice[$role_name]['voice_prompt'])) {
  9326. $role['voice_prompt'] = $previous_roles_voice[$role_name]['voice_prompt'];
  9327. }
  9328. }
  9329. }
  9330. unset($role); // 解除引用
  9331. // 更新 role_arr 以便后续使用
  9332. $role_arr = [];
  9333. foreach ($merged_roles as $item) {
  9334. $role_arr[$item['role']] = $item;
  9335. }
  9336. }
  9337. $emotion_list = DB::table('mp_emotion_list')->where('is_enabled', 1)->pluck('emotion_name', 'emotion_code')->toArray();
  9338. $emotion_list = array_flip($emotion_list);
  9339. foreach ($acts as $act) {
  9340. $act_segments = getProp($act, 'segments', []);
  9341. if (!is_array($act_segments)) {
  9342. continue;
  9343. }
  9344. if ((int)$ace_mode === 1) {
  9345. // ace_mode=1: 按幕合并 segment_content,每幕只存一条记录
  9346. $merged_parts = [];
  9347. foreach ($act_segments as $seg) {
  9348. $seg_num = getProp($seg, 'segment_number');
  9349. $seg_content = getProp($seg, 'segment_content');
  9350. $merged_parts[] = "【分镜{$seg_num}】\n{$seg_content}\n";
  9351. }
  9352. $act_content = implode("\n", $merged_parts);
  9353. $act_content = str_replace(["@", "{", "}"], "", $act_content);
  9354. $segments[] = [
  9355. 'anime_id' => $anime_id,
  9356. 'episode_id' => $episode_id,
  9357. 'episode_number' => $episode_number,
  9358. 'act_number' => getProp($act, 'act_number'),
  9359. 'act_title' => getProp($act, 'act_title'),
  9360. 'act_duration' => getProp($act, 'act_duration'),
  9361. 'act_content' => $act_content,
  9362. 'created_at' => $now,
  9363. 'updated_at' => $now
  9364. ];
  9365. } else {
  9366. foreach ($act_segments as $segment) {
  9367. $voice_actor = getProp($segment, 'voice_actor');
  9368. // 优先从上一集继承音色数据
  9369. $timbre_info = [];
  9370. if (isset($previous_roles_voice[$voice_actor])) {
  9371. // 从上一集继承音色数据
  9372. $timbre_info = $previous_roles_voice[$voice_actor];
  9373. } elseif (isset($role_arr[$voice_actor])) {
  9374. // 使用当前集的主体音色数据
  9375. $timbre_info = $role_arr[$voice_actor];
  9376. }
  9377. $voice_type = getProp($timbre_info, 'voice_type');
  9378. $timbre_emotion = DB::table('mp_timbres')->where('timbre_type', $voice_type)->value('emotion');
  9379. if ($timbre_emotion) {
  9380. $timbre_emotion = explode(',', $timbre_emotion);
  9381. } else {
  9382. $timbre_emotion = [];
  9383. }
  9384. $emotion = getProp($segment, 'emotion', '中性');
  9385. if (!in_array($emotion, $timbre_emotion)) {
  9386. $emotion = '中性';
  9387. }
  9388. $emotion_type = isset($emotion_list[$emotion]) ? $emotion_list[$emotion] : 'neutral';
  9389. $segments[] = [
  9390. 'anime_id' => $anime_id,
  9391. 'episode_id' => $episode_id,
  9392. 'episode_number' => $episode_number,
  9393. 'act_number' => getProp($act, 'act_number'),
  9394. 'act_title' => getProp($act, 'act_title'),
  9395. 'act_duration' => getProp($act, 'act_duration'),
  9396. 'segment_id' => getProp($segment, 'segment_id'),
  9397. 'segment_number' => getProp($segment, 'segment_number'),
  9398. 'segment_content' => getProp($segment, 'segment_content'),
  9399. 'description' => getProp($segment, 'description'),
  9400. 'composition' => getProp($segment, 'composition'),
  9401. 'camera_movement' => getProp($segment, 'camera_movement'),
  9402. 'voice_actor' => $voice_actor,
  9403. 'dialogue' => getProp($segment, 'dialogue'),
  9404. 'frame_type' => getProp($segment, 'frame_type'),
  9405. 'scene' => getProp($segment, 'scene'),
  9406. 'characters' => getProp($segment, 'characters'),
  9407. 'tail_frame' => getProp($segment, 'tail_frame'),
  9408. 'voice_name' => getProp($timbre_info, 'voice_name'),
  9409. 'voice_type' => $voice_type,
  9410. 'voice_audio_url' => getProp($timbre_info, 'voice_audio_url'),
  9411. 'emotion' => $emotion,
  9412. 'emotion_type' => $emotion_type,
  9413. 'gender' => getProp($segment, 'gender', '0'),
  9414. 'speed_ratio' => getProp($segment, 'speed_ratio', 0),
  9415. 'loudness_ratio' => getProp($segment, 'loudness_ratio', 0),
  9416. 'emotion_scale' => getProp($segment, 'emotion_scale', 4),
  9417. 'pitch' => getProp($segment, 'pitch', 0),
  9418. 'created_at' => $now,
  9419. 'updated_at' => $now
  9420. ];
  9421. }
  9422. }
  9423. }
  9424. if ($segments) {
  9425. if ($del_flag) {
  9426. DB::table('mp_episode_segments')
  9427. ->where('anime_id', $anime_id)
  9428. ->where('episode_id', $episode_id)
  9429. ->delete();
  9430. }
  9431. $boolen = DB::table('mp_episode_segments')->insert($segments);
  9432. if (!$boolen) {
  9433. logDB('deepseek', 'error', '分镜内容保存失败', ['anime_id' => $anime_id, 'episode_id' => $episode_id, 'segments_count' => count($segments)]);
  9434. Utils::throwError('20003:分镜内容保存失败');
  9435. }
  9436. }
  9437. dLog('deepseek')->info('segments', $segments);
  9438. // ace_mode=1: acts 返回值按合并格式调整
  9439. if ((int)$ace_mode === 1) {
  9440. $table_act_data = DB::table('mp_episode_segments')->where('episode_id', $episode_id)->orderBy('act_number')->select('id as act_id', 'act_number')->get();
  9441. $act_map = [];
  9442. foreach ($table_act_data as $item) {
  9443. $act_map[getProp($item, 'act_number')] = getProp($item, 'act_id');
  9444. }
  9445. $restructured_acts = [];
  9446. foreach ($acts as $act) {
  9447. $act_segments = getProp($act, 'segments', []);
  9448. if (!is_array($act_segments)) {
  9449. continue;
  9450. }
  9451. $merged_parts = [];
  9452. foreach ($act_segments as $seg) {
  9453. $seg_num = getProp($seg, 'segment_number');
  9454. $seg_content = getProp($seg, 'segment_content');
  9455. $merged_parts[] = "【分镜{$seg_num}】{$seg_content}\n";
  9456. }
  9457. $act_content = implode("\n", $merged_parts);
  9458. $act_content = str_replace(["@", "{", "}"], "", $act_content);
  9459. $restructured_acts[] = [
  9460. 'anime_id' => $anime_id,
  9461. 'episode_id' => $episode_id,
  9462. 'episode_number' => $episode_number,
  9463. 'act_id' => isset($act_map[getProp($act, 'act_number')]) ? $act_map[getProp($act, 'act_number')] : 0,
  9464. 'act_number' => getProp($act, 'act_number'),
  9465. 'act_title' => getProp($act, 'act_title'),
  9466. 'act_duration' => getProp($act, 'act_duration'),
  9467. 'act_content' => $act_content,
  9468. 'created_at' => $now,
  9469. 'updated_at' => $now,
  9470. ];
  9471. }
  9472. $acts = $restructured_acts;
  9473. }
  9474. $episode['episode_id'] = $episode_id;
  9475. $episode['roles'] = $merged_roles;
  9476. $episode['scenes'] = $merged_scenes;
  9477. $episode['props'] = $merged_props;
  9478. $episode['acts'] = $acts;
  9479. return [
  9480. 'episode' => $episode,
  9481. 'episode_id' => $episode_id,
  9482. 'merged_roles' => $merged_roles,
  9483. 'merged_scenes' => $merged_scenes,
  9484. 'merged_props' => $merged_props,
  9485. ];
  9486. }
  9487. private function buildEpisodeItemContent(array $items, string $nameKey): string
  9488. {
  9489. $content = '';
  9490. foreach ($items as $item) {
  9491. $name = trim((string)getProp($item, $nameKey));
  9492. if ($name === '' || $name === '旁白') {
  9493. continue;
  9494. }
  9495. $description = trim((string)getProp($item, 'description'));
  9496. $content .= $name . ': ' . $description;
  9497. if ($nameKey == 'role') {
  9498. $pic_prompt = trim(getProp($item, 'pic_prompt'));
  9499. if ($pic_prompt) $content .= '{'.$pic_prompt.'}';
  9500. $voice_name = trim(getProp($item, 'voice_name'));
  9501. if ($voice_name) $content .= '{{'.$voice_name.'}}';
  9502. $voice_prompt = trim(getProp($item, 'voice_prompt'));
  9503. if ($voice_prompt) $content .= '{{'.$voice_prompt.'}}';
  9504. }else {
  9505. $pic_prompt = trim(getProp($item, 'pic_prompt'));
  9506. if ($pic_prompt) $content .= '{'.$pic_prompt.'}';
  9507. }
  9508. $content .= "\n";
  9509. }
  9510. return trim($content);
  9511. }
  9512. private function getEpisodeChatContent($animeId, $sequence, $content) {
  9513. if ((int)$sequence <= 0) {
  9514. return [];
  9515. }
  9516. $origin_content = '';
  9517. if ($content) {
  9518. $origin_content = '本集剧情内容:'.$content;
  9519. }else {
  9520. $origin_content = DB::table('mp_animes')->where('id', $animeId)->value('content');
  9521. if ($origin_content) $origin_content = '剧本全文内容:'.$origin_content;
  9522. }
  9523. $ace_mode = DB::table('mp_animes')->where('id', $animeId)->value('ace_mode');
  9524. // 获取分集信息
  9525. $episode = DB::table('mp_anime_episodes')
  9526. ->where('anime_id', $animeId)
  9527. ->where('episode_number', $sequence)
  9528. ->where('is_default', 1)
  9529. ->first();
  9530. if (!$episode) {
  9531. return [];
  9532. }
  9533. $episode_id = getProp($episode, 'id');
  9534. $episode_number = getProp($episode, 'episode_number');
  9535. $title = getProp($episode, 'title');
  9536. $intro = getProp($episode, 'intro');
  9537. $art_style = getProp($episode, 'art_style');
  9538. $roles = json_decode(getProp($episode, 'roles'), true) ?: [];
  9539. $scenes = json_decode(getProp($episode, 'scenes'), true) ?: [];
  9540. // 组装纯文本内容
  9541. $content = '';
  9542. // 添加分集标题和梗概
  9543. $content .= "###第{$episode_number}集:{$title}\n\n";
  9544. $content .= "###故事梗概\n";
  9545. $content .= trim($intro) . "\n\n";
  9546. // 添加美术风格
  9547. $content .= "###美术风格\n";
  9548. $content .= trim($art_style) . "\n\n";
  9549. // 添加主体列表
  9550. $content .= "###主体列表\n";
  9551. $pangbai_voice_prompt = "";
  9552. foreach ($roles as $role) {
  9553. $name = getProp($role, 'role');
  9554. $description = getProp($role, 'description');
  9555. $pic_prompt = getProp($role, 'pic_prompt');
  9556. $voice_prompt = getProp($role, 'voice_prompt');
  9557. $voice_name = getProp($role, 'voice_name');
  9558. $content .= "{$name}: {$description}";
  9559. if ($pic_prompt) $content .= '{'.$pic_prompt.'}';
  9560. if ($voice_prompt) $content .= '{{'.$voice_prompt.'}}';
  9561. if ($voice_name) $content .= '{{'.$voice_name.'}}';
  9562. if ($name == '旁白') $pangbai_voice_prompt = $voice_prompt;
  9563. $content .= "\n";
  9564. }
  9565. $content .= "\n";
  9566. // 添加场景列表
  9567. $content .= "###场景列表\n";
  9568. foreach ($scenes as $scene) {
  9569. $name = getProp($scene, 'scene');
  9570. $description = getProp($scene, 'description');
  9571. $pic_prompt = getProp($scene, 'pic_prompt');
  9572. $content .= "{$name}: {$description}";
  9573. if ($pic_prompt) $content .= '{'.$pic_prompt.'}';
  9574. $content .= "\n";
  9575. }
  9576. $content .= "\n";
  9577. // 获取分镜信息
  9578. $segments = DB::table('mp_episode_segments')
  9579. ->where('anime_id', $animeId)
  9580. ->where('episode_id', $episode_id)
  9581. ->orderBy('segment_number')
  9582. ->get();
  9583. if ($segments && count($segments) > 0) {
  9584. if ((int)$ace_mode === 1) {
  9585. $content .= "###分段剧本\n";
  9586. // 获取片段数量
  9587. $act_count = DB::table('mp_episode_segments')->where('anime_id', $animeId)->where('episode_id', $episode_id)->groupBy('act_number')->count('act_number');
  9588. $content .= "片段数量:{$act_count}\n";
  9589. if ($pangbai_voice_prompt) $content .= "旁白音色:{$pangbai_voice_prompt}\n";
  9590. $content .= "\n";
  9591. }else {
  9592. $content .= "###分镜剧本\n";
  9593. }
  9594. // 按幕分组
  9595. $currentAct = null;
  9596. foreach ($segments as $segment) {
  9597. $act_number = getProp($segment, 'act_number');
  9598. $act_title = getProp($segment, 'act_title');
  9599. $act_duration = getProp($segment, 'act_duration');
  9600. $segment_number = getProp($segment, 'segment_number');
  9601. $segment_content = getProp($segment, 'segment_content');
  9602. $scene_description = getProp($segment, 'scene_description');
  9603. $scene_name = getProp($segment, 'scene_name');
  9604. $composition = getProp($segment, 'composition');
  9605. $camera_movement = getProp($segment, 'camera_movement');
  9606. $voice_type = getProp($segment, 'voice_type');
  9607. $characters = getProp($segment, 'characters');
  9608. $dialogue = getProp($segment, 'dialogue');
  9609. $frame_type = getProp($segment, 'frame_type');
  9610. $tail_frame_description = getProp($segment, 'tail_frame_description');
  9611. // 判断是否是全能模式
  9612. if ((int)$ace_mode === 1) { // 全能模式
  9613. // 如果是新的分段,添加分段标题
  9614. if ($act_number !== $currentAct) {
  9615. $currentAct = $act_number;
  9616. $content .= "##{$act_title}\n";
  9617. $content .= "时长:{$act_duration}s\n";
  9618. }
  9619. }else {
  9620. // 如果是新的幕,添加幕标题
  9621. if ($act_number !== $currentAct) {
  9622. $currentAct = $act_number;
  9623. $content .= "##第{$act_number}幕:{$scene_name}\n";
  9624. }
  9625. }
  9626. // 添加分镜信息
  9627. $content .= "分镜{$segment_number}\n";
  9628. $content .= "分镜内容:\n{$segment_content}\n";
  9629. // $content .= "画面描述:{$scene_description}\n";
  9630. // $content .= "场景:{$scene_name}\n";
  9631. // $content .= "构图设计:{$composition}\n";
  9632. // $content .= "运镜调度:{$camera_movement}\n";
  9633. // if (!empty($voice_type)) {
  9634. // $content .= "配音角色:{$voice_type}\n";
  9635. // }
  9636. // if (!empty($characters)) {
  9637. // $content .= "出镜角色:{$characters}\n";
  9638. // }
  9639. // if (!empty($dialogue)) {
  9640. // $content .= "台词内容:\"{$dialogue}\"\n";
  9641. // }
  9642. // $content .= "画面类型:{$frame_type}\n";
  9643. // $content .= "尾帧描述:{$tail_frame_description}\n";
  9644. $content .= "\n";
  9645. }
  9646. }
  9647. $content = trim($content);
  9648. if($content) $content = "上集剧本内容:\n{$content}";
  9649. return [
  9650. [
  9651. 'role' => 'user',
  9652. 'content' => $origin_content
  9653. ],
  9654. [
  9655. 'role' => 'assistant',
  9656. 'content' => $content
  9657. ]
  9658. ];
  9659. }
  9660. private function getEpisodeChatMessages($animeId, $sequence): array
  9661. {
  9662. if ((int)$sequence <= 0) {
  9663. return [];
  9664. }
  9665. return DB::table('mp_anime_records')
  9666. ->where('anime_id', $animeId)
  9667. ->where('sequence', $sequence)
  9668. ->where('episode_id', '>', 0)
  9669. ->select('role', 'content')
  9670. ->orderBy('created_at')
  9671. ->orderBy('id')
  9672. ->get()
  9673. ->map(function ($value) {
  9674. return (array)$value;
  9675. })
  9676. ->toArray();
  9677. }
  9678. private function mergeEpisodeResourceItems(array $existingItems, array $generatedItems, string $nameKey): array
  9679. {
  9680. $existingMap = [];
  9681. foreach ($existingItems as $item) {
  9682. $itemKey = $this->normalizeEpisodeResourceKey(getProp($item, $nameKey));
  9683. if ($itemKey === '') {
  9684. continue;
  9685. }
  9686. $existingMap[$itemKey] = $item;
  9687. }
  9688. if (!$generatedItems) {
  9689. return array_values($existingItems);
  9690. }
  9691. $merged = [];
  9692. foreach ($generatedItems as $item) {
  9693. $itemKey = $this->normalizeEpisodeResourceKey(getProp($item, $nameKey));
  9694. if ($itemKey === '') {
  9695. continue;
  9696. }
  9697. if (isset($existingMap[$itemKey])) {
  9698. if (trim((string)getProp($item, 'description')) === '') {
  9699. $merged[] = $existingMap[$itemKey];
  9700. continue;
  9701. }
  9702. // 检查内容是否发生变化
  9703. $isChanged = $this->isEpisodeResourceChanged($existingMap[$itemKey], $item, $nameKey);
  9704. if (!$isChanged) {
  9705. // nameKey 和 description 一致,继承现有项的 URL、task_id 和 task_status
  9706. $mergedItem = [
  9707. $nameKey => trim((string)getProp($item, $nameKey)),
  9708. 'description' => trim((string)getProp($item, 'description')),
  9709. ];
  9710. // 如果有 pic_prompt,添加到合并项中
  9711. $picPrompt = getProp($item, 'pic_prompt');
  9712. if (!empty($picPrompt)) {
  9713. $mergedItem['pic_prompt'] = trim((string)$picPrompt);
  9714. }
  9715. // 继承现有项的 URL
  9716. $existingUrl = getProp($existingMap[$itemKey], 'url');
  9717. if (!empty($existingUrl)) {
  9718. $mergedItem['url'] = $existingUrl;
  9719. }
  9720. // 继承现有项的 task_id
  9721. $existingTaskId = getProp($existingMap[$itemKey], 'task_id');
  9722. if (!empty($existingTaskId)) {
  9723. $mergedItem['task_id'] = $existingTaskId;
  9724. }
  9725. // 继承现有项的 task_status
  9726. $existingTaskStatus = getProp($existingMap[$itemKey], 'task_status');
  9727. if (!empty($existingTaskStatus)) {
  9728. $mergedItem['task_status'] = $existingTaskStatus;
  9729. }
  9730. // 保留生成项的音色字段
  9731. $voiceName = getProp($item, 'voice_name');
  9732. if (!empty($voiceName)) {
  9733. $mergedItem['voice_name'] = $voiceName;
  9734. }
  9735. $voiceType = getProp($item, 'voice_type');
  9736. if (!empty($voiceType)) {
  9737. $mergedItem['voice_type'] = $voiceType;
  9738. }
  9739. $audioUrl = getProp($item, 'voice_audio_url');
  9740. if (!empty($audioUrl)) {
  9741. $mergedItem['voice_audio_url'] = $audioUrl;
  9742. }
  9743. $merged[] = $mergedItem;
  9744. } else {
  9745. // nameKey 或 description 不一致,重置 URL、task_id 和 task_status,但保留音色字段
  9746. $mergedItem = [
  9747. $nameKey => trim((string)getProp($item, $nameKey)),
  9748. 'description' => trim((string)getProp($item, 'description')),
  9749. ];
  9750. // 如果有 pic_prompt,添加到合并项中
  9751. $picPrompt = getProp($item, 'pic_prompt');
  9752. if (!empty($picPrompt)) {
  9753. $mergedItem['pic_prompt'] = trim((string)$picPrompt);
  9754. }
  9755. // 保留生成项的音色字段
  9756. $voiceName = getProp($item, 'voice_name');
  9757. if (!empty($voiceName)) {
  9758. $mergedItem['voice_name'] = $voiceName;
  9759. }
  9760. $voiceType = getProp($item, 'voice_type');
  9761. if (!empty($voiceType)) {
  9762. $mergedItem['voice_type'] = $voiceType;
  9763. }
  9764. $audioUrl = getProp($item, 'voice_audio_url');
  9765. if (!empty($audioUrl)) {
  9766. $mergedItem['voice_audio_url'] = $audioUrl;
  9767. }
  9768. // 不继承 URL、task_id 和 task_status(重置状态)
  9769. $merged[] = $mergedItem;
  9770. }
  9771. } else {
  9772. // 新增项,保留生成项的所有字段
  9773. $merged[] = $this->resetEpisodeResourceItem($item, $nameKey, ['url', 'task_id', 'task_status', 'voice_name', 'voice_type', 'voice_audio_url', 'pic_prompt']);
  9774. }
  9775. }
  9776. return $merged ?: array_values($existingItems);
  9777. }
  9778. private function resetEpisodeResourceItem(array $item, string $nameKey, array $preserveFields = []): array
  9779. {
  9780. $resetItem = [
  9781. $nameKey => trim((string)getProp($item, $nameKey)),
  9782. 'description' => trim((string)getProp($item, 'description')),
  9783. ];
  9784. // 保留指定的字段
  9785. foreach ($preserveFields as $field) {
  9786. $value = getProp($item, $field);
  9787. if (!empty($value)) {
  9788. $resetItem[$field] = $value;
  9789. }
  9790. }
  9791. return $resetItem;
  9792. }
  9793. private function isEpisodeResourceChanged(array $existingItem, array $generatedItem, string $nameKey): bool
  9794. {
  9795. $existingKey = $this->normalizeEpisodeResourceKey(getProp($existingItem, $nameKey));
  9796. $generatedKey = $this->normalizeEpisodeResourceKey(getProp($generatedItem, $nameKey));
  9797. if ($existingKey !== $generatedKey) {
  9798. return true;
  9799. }
  9800. // 比较 description 是否变化
  9801. if (trim((string)getProp($existingItem, 'description')) !== trim((string)getProp($generatedItem, 'description'))) {
  9802. return true;
  9803. }
  9804. // 比较 pic_prompt 是否变化
  9805. return trim((string)getProp($existingItem, 'pic_prompt')) !== trim((string)getProp($generatedItem, 'pic_prompt'));
  9806. }
  9807. private function normalizeEpisodeResourceKey($value): string
  9808. {
  9809. $value = trim((string)$value);
  9810. if ($value === '') {
  9811. return '';
  9812. }
  9813. return strtolower((string)preg_replace('/\s+/u', '', $value));
  9814. }
  9815. // 生成全局角色图片
  9816. private function batchSetGlobalRoleImg($data, $is_force=false) {
  9817. $anime_id = getProp($data, 'anime_id');
  9818. if (!$anime_id) Utils::throwError('1002:请选择对话');
  9819. $anime = DB::table('mp_animes')->where('id', $anime_id)->where('is_deleted', 0)->first();
  9820. $roles = json_decode(getProp($anime, 'roles'), true) ?: [];
  9821. $art_style = getProp($anime, 'art_style');
  9822. $update_flag = false;
  9823. foreach ($roles as &$role) {
  9824. $role_name = getProp($role, 'role');
  9825. if ($role_name == '旁白') continue;
  9826. // 优先使用 pic_prompt,如果没有则使用 description
  9827. $pic_prompt = getProp($role, 'pic_prompt');
  9828. $description = !empty($pic_prompt) ? trim((string)$pic_prompt) : getProp($role, 'description');
  9829. // if ($art_style) $description = "美术风格:\n{$art_style}\n主体描述:{$description}\n图片要求:图片侧重点是人物,不要出现场景或背景,并且只能生成一个人物";
  9830. if ($art_style) $description = "主体描述:{$description}\n图片要求:图片侧重点是人物,不要出现场景或背景,并且只能生成一个人物";
  9831. // 参考图地址
  9832. $ref_img_url = getProp($role, 'url');
  9833. if (!$is_force && $ref_img_url) continue;
  9834. $update_flag = true;
  9835. // 此处调用AIImageGenerationService的生成图片任务接口: createImageGenerationTask(注意使用默认参数,prompt使用角色描述),并返回任务id
  9836. try {
  9837. $params = [
  9838. 'prompt' => $description,
  9839. // 'ref_img_urls' => !empty($ref_img_url) ? [$ref_img_url] : []
  9840. 'ref_img_urls' => []
  9841. ];
  9842. $task = $this->aiImageGenerationService->createImageGenerationTask($params);
  9843. $task_id = $task->id;
  9844. if (!$task_id) {
  9845. Utils::throwError("20003: 角色({$role_name})生成图片失败");
  9846. }
  9847. $role['task_id'] = $task_id;
  9848. $role['task_status'] = 'processing';
  9849. } catch (\Exception $e) {
  9850. Utils::throwError("20003:" . $e->getMessage());
  9851. }
  9852. }
  9853. if (!$update_flag) return true;
  9854. // 保存角色信息
  9855. $boolen = DB::table('mp_animes')->where('id', $anime_id)->update([
  9856. 'roles' => json_encode($roles, 256),
  9857. 'generate_status' => '执行中',
  9858. 'generate_at' => date('Y-m-d H:i:s'),
  9859. 'updated_at' => date('Y-m-d H:i:s')
  9860. ]);
  9861. if (!$boolen) {
  9862. Utils::throwError('20003:保存角色信息失败');
  9863. }
  9864. return $boolen;
  9865. }
  9866. // 生成全局场景图片
  9867. private function batchSetGlobalSceneImg($data, $is_force=false) {
  9868. $anime_id = getProp($data, 'anime_id');
  9869. if (!$anime_id) Utils::throwError('1002:请选择对话');
  9870. $anime = DB::table('mp_animes')->where('id', $anime_id)->where('is_deleted', 0)->first();
  9871. $scenes = json_decode(getProp($anime, 'scenes'), true) ?: [];
  9872. $art_style = getProp($anime, 'art_style');
  9873. $update_flag = false;
  9874. foreach ($scenes as &$scene) {
  9875. $scene_name = getProp($scene, 'scene');
  9876. // 优先使用 pic_prompt,如果没有则使用 description
  9877. $pic_prompt = getProp($scene, 'pic_prompt');
  9878. $description = !empty($pic_prompt) ? trim((string)$pic_prompt) : getProp($scene, 'description');
  9879. if ($art_style) $description = "场景描述:{$description}\n图片要求: 图片侧重点是场景,生成的是场景环境图片,不要出现人物(此为第一优先要求)";
  9880. // 参考图地址
  9881. $ref_img_url = getProp($scene, 'url');
  9882. if (!$is_force && $ref_img_url) continue;
  9883. $update_flag = true;
  9884. // 此处调用AIImageGenerationService的生成图片任务接口: createImageGenerationTask(注意使用默认参数,prompt使用角色描述),并返回任务id
  9885. try {
  9886. $params = [
  9887. 'prompt' => $description,
  9888. // 'ref_img_urls' => !empty($ref_img_url) ? [$ref_img_url] : [],
  9889. 'ref_img_urls' => []
  9890. ];
  9891. $task = $this->aiImageGenerationService->createImageGenerationTask($params);
  9892. $task_id = $task->id;
  9893. if (!$task_id) {
  9894. Utils::throwError("20003: 场景({$scene_name})生成图片失败");
  9895. }
  9896. $scene['task_id'] = $task_id;
  9897. $scene['task_status'] = 'processing';
  9898. } catch (\Exception $e) {
  9899. Utils::throwError("20003:" . $e->getMessage());
  9900. }
  9901. }
  9902. if (!$update_flag) return true;
  9903. // 保存角色信息
  9904. $boolen = DB::table('mp_animes')->where('id', $anime_id)->update([
  9905. 'scenes' => json_encode($scenes, 256),
  9906. 'generate_status' => '执行中',
  9907. 'generate_at' => date('Y-m-d H:i:s'),
  9908. 'updated_at' => date('Y-m-d H:i:s')
  9909. ]);
  9910. if (!$boolen) {
  9911. Utils::throwError('20003:保存角色信息失败');
  9912. }
  9913. return $boolen;
  9914. }
  9915. // 生成分镜主体、场景和道具图片
  9916. private function batchSetEpisodeRolesAndScenesImg($anime_id, $episode_number, $roles, $scenes, $props = [], $ref_products=[], $art_style_type='', $is_force=false) {
  9917. $character_prefix = '';
  9918. $scene_prefix = '';
  9919. $prop_prefix = '';
  9920. if ($art_style_type) {
  9921. $art_style_arr = $this->getArtStyleShortPromptByInput($art_style_type);
  9922. $character_prefix = isset($art_style_arr['character_prefix']) ? $art_style_arr['character_prefix'] : '';
  9923. $scene_prefix = isset($art_style_arr['scene_prefix']) ? $art_style_arr['scene_prefix'] : '';
  9924. $prop_prefix = isset($art_style_arr['scene_prefix']) ? $art_style_arr['scene_prefix'] : ''; // 道具使用场景的前缀
  9925. }
  9926. $update_flag = false;
  9927. // 获取上一集的roles、scenes和props数据
  9928. $prev_roles = [];
  9929. $prev_scenes = [];
  9930. $prev_props = [];
  9931. if ($episode_number > 1) {
  9932. $prev_episode = DB::table('mp_anime_episodes')
  9933. ->where('anime_id', $anime_id)
  9934. ->where('episode_number', $episode_number - 1)
  9935. ->where('is_default', 1)
  9936. ->first();
  9937. if ($prev_episode) {
  9938. $prev_roles = json_decode(getProp($prev_episode, 'roles'), true) ?: [];
  9939. $prev_scenes = json_decode(getProp($prev_episode, 'scenes'), true) ?: [];
  9940. $prev_props = json_decode(getProp($prev_episode, 'props'), true) ?: [];
  9941. dLog('deepseek')->info("获取上一集数据成功", [
  9942. 'anime_id' => $anime_id,
  9943. 'prev_episode_number' => $episode_number - 1,
  9944. 'prev_roles_count' => count($prev_roles),
  9945. 'prev_scenes_count' => count($prev_scenes),
  9946. 'prev_props_count' => count($prev_props)
  9947. ]);
  9948. }
  9949. }
  9950. // 处理角色图片生成
  9951. foreach ($roles as &$role) {
  9952. $role_name = getProp($role, 'role');
  9953. if ($role_name == '旁白') continue;
  9954. // 如果参考资产里有该角色,则直接使用该图片,不继续生成
  9955. if (isset($ref_products[$role_name])) {
  9956. $role['url'] = isset($ref_products[$role_name]['url']) ? $ref_products[$role_name]['url'] : '';
  9957. if ($role['url']) continue;
  9958. }
  9959. $role_description = getProp($role, 'description');
  9960. $role_pic_prompt = getProp($role, 'pic_prompt');
  9961. $role_url = getProp($role, 'url');
  9962. // 检查是否可以从上一集继承
  9963. $inherited = false;
  9964. if (!$is_force && !empty($prev_roles)) {
  9965. foreach ($prev_roles as $prev_role) {
  9966. $prev_role_name = getProp($prev_role, 'role');
  9967. $prev_description = getProp($prev_role, 'description');
  9968. $prev_pic_prompt = getProp($prev_role, 'pic_prompt');
  9969. $prev_url = getProp($prev_role, 'url');
  9970. $prev_task_id = getProp($prev_role, 'task_id');
  9971. $prev_task_status = getProp($prev_role, 'task_status');
  9972. // 如果role、description、pic_prompt都一致,且上一集已有url,则继承
  9973. if ($role_name == $prev_role_name
  9974. && $role_description == $prev_description
  9975. && $role_pic_prompt == $prev_pic_prompt
  9976. && !empty($prev_url)) {
  9977. $role['task_id'] = $prev_task_id;
  9978. $role['task_status'] = $prev_task_status;
  9979. $role['url'] = $prev_url;
  9980. $inherited = true;
  9981. dLog('deepseek')->info("角色({$role_name})从上一集继承图片数据", [
  9982. 'anime_id' => $anime_id,
  9983. 'episode_number' => $episode_number,
  9984. 'task_id' => $prev_task_id,
  9985. 'url' => $prev_url
  9986. ]);
  9987. break;
  9988. }
  9989. }
  9990. }
  9991. // 如果已继承或已有url,跳过生成
  9992. if ($inherited || (!$is_force && $role_url)) {
  9993. continue;
  9994. }
  9995. // 优先使用 pic_prompt,如果没有则使用 description
  9996. $pic_prompt = getProp($role, 'pic_prompt');
  9997. $description = !empty($pic_prompt) ? trim((string)$pic_prompt) : getProp($role, 'description');
  9998. $description = "{$character_prefix}。\n主体描述:{$description}\n超高清,高细节,主体突出,构图合理,画面干净,无场景或背景,单人物,无文字,无水印,无字幕,电影级光影,视觉焦点明确";
  9999. $update_flag = true;
  10000. // 调用AIImageGenerationService的生成图片任务接口
  10001. try {
  10002. $params = [
  10003. 'prompt' => $description,
  10004. 'ref_img_urls' => []
  10005. ];
  10006. $task = $this->aiImageGenerationService->createImageGenerationTask($params);
  10007. $task_id = $task->id;
  10008. if (!$task_id) {
  10009. dLog('deepseek')->error("角色({$role_name})生成图片失败");
  10010. continue; // 不中断,继续处理其他角色
  10011. }
  10012. $role['task_id'] = $task_id;
  10013. $role['task_status'] = 'processing';
  10014. dLog('deepseek')->info("角色({$role_name})创建图片生成任务成功", [
  10015. 'anime_id' => $anime_id,
  10016. 'episode_number' => $episode_number,
  10017. 'task_id' => $task_id
  10018. ]);
  10019. } catch (\Exception $e) {
  10020. dLog('deepseek')->error("角色({$role_name})创建图片生成任务失败: " . $e->getMessage());
  10021. // 不抛出异常,继续处理其他角色
  10022. }
  10023. }
  10024. // 处理场景图片生成
  10025. foreach ($scenes as &$scene) {
  10026. $scene_name = getProp($scene, 'scene');
  10027. $scene_description = getProp($scene, 'description');
  10028. $scene_pic_prompt = getProp($scene, 'pic_prompt');
  10029. $scene_url = getProp($scene, 'url');
  10030. // 如果参考资产里有该场景,则直接使用该图片,不继续生成
  10031. if (isset($ref_products[$scene_name])) {
  10032. $scene['url'] = isset($ref_products[$scene_name]['url']) ? $ref_products[$scene_name]['url'] : '';
  10033. if ($scene['url']) continue;
  10034. }
  10035. // 检查是否可以从上一集继承
  10036. $inherited = false;
  10037. if (!$is_force && !empty($prev_scenes)) {
  10038. foreach ($prev_scenes as $prev_scene) {
  10039. $prev_scene_name = getProp($prev_scene, 'scene');
  10040. $prev_description = getProp($prev_scene, 'description');
  10041. $prev_pic_prompt = getProp($prev_scene, 'pic_prompt');
  10042. $prev_url = getProp($prev_scene, 'url');
  10043. $prev_task_id = getProp($prev_scene, 'task_id');
  10044. $prev_task_status = getProp($prev_scene, 'task_status');
  10045. // 如果scene、description、pic_prompt都一致,且上一集已有url,则继承
  10046. if ($scene_name == $prev_scene_name
  10047. && $scene_description == $prev_description
  10048. && $scene_pic_prompt == $prev_pic_prompt
  10049. && !empty($prev_url)) {
  10050. $scene['task_id'] = $prev_task_id;
  10051. $scene['task_status'] = $prev_task_status;
  10052. $scene['url'] = $prev_url;
  10053. $inherited = true;
  10054. dLog('deepseek')->info("场景({$scene_name})从上一集继承图片数据", [
  10055. 'anime_id' => $anime_id,
  10056. 'episode_number' => $episode_number,
  10057. 'task_id' => $prev_task_id,
  10058. 'url' => $prev_url
  10059. ]);
  10060. break;
  10061. }
  10062. }
  10063. }
  10064. // 如果已继承或已有url,跳过生成
  10065. if ($inherited || (!$is_force && $scene_url)) {
  10066. continue;
  10067. }
  10068. // 优先使用 pic_prompt,如果没有则使用 description
  10069. $pic_prompt = getProp($scene, 'pic_prompt');
  10070. $description = !empty($pic_prompt) ? trim((string)$pic_prompt) : getProp($scene, 'description');
  10071. $description = "{$scene_prefix}。\n场景描述:{$description}\n无人物,超高清,高细节,主体突出,构图合理,画面干净,无文字,无水印,无字幕,电影级光影,视觉焦点明确";
  10072. $update_flag = true;
  10073. // 调用AIImageGenerationService的生成图片任务接口
  10074. try {
  10075. $params = [
  10076. 'prompt' => $description,
  10077. 'ref_img_urls' => []
  10078. ];
  10079. $task = $this->aiImageGenerationService->createImageGenerationTask($params);
  10080. $task_id = $task->id;
  10081. if (!$task_id) {
  10082. dLog('deepseek')->error("场景({$scene_name})生成图片失败");
  10083. continue; // 不中断,继续处理其他场景
  10084. }
  10085. $scene['task_id'] = $task_id;
  10086. $scene['task_status'] = 'processing';
  10087. dLog('deepseek')->info("场景({$scene_name})创建图片生成任务成功", [
  10088. 'anime_id' => $anime_id,
  10089. 'episode_number' => $episode_number,
  10090. 'task_id' => $task_id
  10091. ]);
  10092. } catch (\Exception $e) {
  10093. dLog('deepseek')->error("场景({$scene_name})创建图片生成任务失败: " . $e->getMessage());
  10094. // 不抛出异常,继续处理其他场景
  10095. }
  10096. }
  10097. // 处理道具图片生成(逻辑与场景一致)
  10098. foreach ($props as &$prop) {
  10099. $prop_name = getProp($prop, 'prop');
  10100. $prop_description = getProp($prop, 'description');
  10101. $prop_pic_prompt = getProp($prop, 'pic_prompt');
  10102. $prop_url = getProp($prop, 'url');
  10103. // 如果参考资产里有该道具,则直接使用该图片,不继续生成
  10104. if (isset($ref_products[$prop_name])) {
  10105. $prop['url'] = isset($ref_products[$prop_name]['url']) ? $ref_products[$prop_name]['url'] : '';
  10106. if ($prop['url']) continue;
  10107. }
  10108. // 检查是否可以从上一集继承
  10109. $inherited = false;
  10110. if (!$is_force && !empty($prev_props)) {
  10111. foreach ($prev_props as $prev_prop) {
  10112. $prev_prop_name = getProp($prev_prop, 'prop');
  10113. $prev_description = getProp($prev_prop, 'description');
  10114. $prev_pic_prompt = getProp($prev_prop, 'pic_prompt');
  10115. $prev_url = getProp($prev_prop, 'url');
  10116. $prev_task_id = getProp($prev_prop, 'task_id');
  10117. $prev_task_status = getProp($prev_prop, 'task_status');
  10118. // 如果prop、description、pic_prompt都一致,且上一集已有url,则继承
  10119. if ($prop_name == $prev_prop_name
  10120. && $prop_description == $prev_description
  10121. && $prop_pic_prompt == $prev_pic_prompt
  10122. && !empty($prev_url)) {
  10123. $prop['task_id'] = $prev_task_id;
  10124. $prop['task_status'] = $prev_task_status;
  10125. $prop['url'] = $prev_url;
  10126. $inherited = true;
  10127. dLog('deepseek')->info("道具({$prop_name})从上一集继承图片数据", [
  10128. 'anime_id' => $anime_id,
  10129. 'episode_number' => $episode_number,
  10130. 'task_id' => $prev_task_id,
  10131. 'url' => $prev_url
  10132. ]);
  10133. break;
  10134. }
  10135. }
  10136. }
  10137. // 如果已继承或已有url,跳过生成
  10138. if ($inherited || (!$is_force && $prop_url)) {
  10139. continue;
  10140. }
  10141. // 优先使用 pic_prompt,如果没有则使用 description
  10142. $pic_prompt = getProp($prop, 'pic_prompt');
  10143. $description = !empty($pic_prompt) ? trim((string)$pic_prompt) : getProp($prop, 'description');
  10144. $description = "{$prop_prefix}。\n道具描述:{$description}\n无人物,超高清,高细节,主体突出,构图合理,画面干净,无文字,无水印,无字幕,电影级光影,视觉焦点明确";
  10145. $update_flag = true;
  10146. // 调用AIImageGenerationService的生成图片任务接口
  10147. try {
  10148. $params = [
  10149. 'prompt' => $description,
  10150. 'ref_img_urls' => []
  10151. ];
  10152. $task = $this->aiImageGenerationService->createImageGenerationTask($params);
  10153. $task_id = $task->id;
  10154. if (!$task_id) {
  10155. dLog('deepseek')->error("道具({$prop_name})生成图片失败");
  10156. continue; // 不中断,继续处理其他道具
  10157. }
  10158. $prop['task_id'] = $task_id;
  10159. $prop['task_status'] = 'processing';
  10160. dLog('deepseek')->info("道具({$prop_name})创建图片生成任务成功", [
  10161. 'anime_id' => $anime_id,
  10162. 'episode_number' => $episode_number,
  10163. 'task_id' => $task_id
  10164. ]);
  10165. } catch (\Exception $e) {
  10166. dLog('deepseek')->error("道具({$prop_name})创建图片生成任务失败: " . $e->getMessage());
  10167. // 不抛出异常,继续处理其他道具
  10168. }
  10169. }
  10170. if (!$update_flag) return ['roles' => $roles, 'scenes' => $scenes, 'props' => $props];
  10171. // 将处理完毕的roles、scenes和props与全局(mp_animes)数据对比并合并
  10172. $this->syncRolesAndScenesToGlobal($anime_id, $roles, $scenes, $props);
  10173. // // 保存剧集的角色和场景信息
  10174. // $boolen = DB::table('mp_anime_episodes')->where('id', $episode_id)->update([
  10175. // 'roles' => json_encode($roles, 256),
  10176. // 'scenes' => json_encode($scenes, 256),
  10177. // 'generate_status' => '执行中',
  10178. // 'generate_at' => date('Y-m-d H:i:s'),
  10179. // 'updated_at' => date('Y-m-d H:i:s')
  10180. // ]);
  10181. // if (!$boolen) {
  10182. // dLog('deepseek')->error('保存剧集角色和场景信息失败', ['episode_id' => $episode_id]);
  10183. // Utils::throwError('20003:保存剧集角色和场景信息失败');
  10184. // }
  10185. dLog('deepseek')->info('剧集角色、场景和道具图片任务创建完成', [
  10186. // 'episode_id' => $episode_id,
  10187. 'roles_count' => count($roles),
  10188. 'scenes_count' => count($scenes),
  10189. 'props_count' => count($props)
  10190. ]);
  10191. return ['roles' => $roles, 'scenes' => $scenes, 'props' => $props];
  10192. }
  10193. /**
  10194. * 将剧集的roles、scenes和props同步到全局(mp_animes)
  10195. * 如果全局中不存在相同的role/scene/prop(名称、description、pic_prompt三项一致),则添加到全局
  10196. *
  10197. * @param int $anime_id 动漫对话ID
  10198. * @param array $episode_roles 剧集角色数据
  10199. * @param array $episode_scenes 剧集场景数据
  10200. * @param array $episode_props 剧集道具数据
  10201. * @return bool
  10202. */
  10203. private function syncRolesAndScenesToGlobal($anime_id, $episode_roles, $episode_scenes, $episode_props = []) {
  10204. // 获取全局数据
  10205. $anime = DB::table('mp_animes')->where('id', $anime_id)->where('is_deleted', 0)->first();
  10206. if (!$anime) {
  10207. dLog('deepseek')->warning('动漫对话不存在', ['anime_id' => $anime_id]);
  10208. return false;
  10209. }
  10210. $global_roles = json_decode(getProp($anime, 'roles'), true) ?: [];
  10211. $global_scenes = json_decode(getProp($anime, 'scenes'), true) ?: [];
  10212. $global_props = json_decode(getProp($anime, 'props'), true) ?: [];
  10213. $roles_added = false;
  10214. $roles_updated = false;
  10215. $scenes_added = false;
  10216. $props_added = false;
  10217. // 处理角色同步
  10218. foreach ($episode_roles as $episode_role) {
  10219. $episode_role_name = getProp($episode_role, 'role');
  10220. $episode_description = getProp($episode_role, 'description');
  10221. $episode_pic_prompt = getProp($episode_role, 'pic_prompt');
  10222. $episode_voice_prompt = getProp($episode_role, 'voice_prompt');
  10223. // 跳过旁白
  10224. if ($episode_role_name == '旁白') {
  10225. continue;
  10226. }
  10227. // 检查全局中是否已存在相同的角色
  10228. $exists = false;
  10229. $global_role_index = -1;
  10230. foreach ($global_roles as $index => $global_role) {
  10231. $global_role_name = getProp($global_role, 'role');
  10232. $global_description = getProp($global_role, 'description');
  10233. $global_pic_prompt = getProp($global_role, 'pic_prompt');
  10234. // 如果role、description、pic_prompt三项都一致,则认为已存在
  10235. if ($episode_role_name == $global_role_name
  10236. && $episode_description == $global_description
  10237. && $episode_pic_prompt == $global_pic_prompt) {
  10238. $exists = true;
  10239. $global_role_index = $index;
  10240. break;
  10241. }
  10242. }
  10243. // 如果不存在,则添加到全局
  10244. if (!$exists) {
  10245. $global_roles[] = $episode_role;
  10246. $roles_added = true;
  10247. dLog('deepseek')->info("角色({$episode_role_name})添加到全局", [
  10248. 'anime_id' => $anime_id,
  10249. 'role' => $episode_role_name
  10250. ]);
  10251. } else {
  10252. // 如果存在,且剧集有voice_prompt字段,将voice_prompt更新到全局
  10253. if (!empty($episode_voice_prompt)) {
  10254. $global_voice_prompt = getProp($global_roles[$global_role_index], 'voice_prompt');
  10255. // 如果全局没有voice_prompt或与剧集不一致,则更新
  10256. if ($global_voice_prompt !== $episode_voice_prompt) {
  10257. $global_roles[$global_role_index]['voice_prompt'] = $episode_voice_prompt;
  10258. $roles_updated = true;
  10259. dLog('deepseek')->info("角色({$episode_role_name})的voice_prompt更新到全局", [
  10260. 'anime_id' => $anime_id,
  10261. 'role' => $episode_role_name,
  10262. 'voice_prompt' => $episode_voice_prompt
  10263. ]);
  10264. }
  10265. }
  10266. }
  10267. }
  10268. // 处理场景同步
  10269. foreach ($episode_scenes as $episode_scene) {
  10270. $episode_scene_name = getProp($episode_scene, 'scene');
  10271. $episode_description = getProp($episode_scene, 'description');
  10272. $episode_pic_prompt = getProp($episode_scene, 'pic_prompt');
  10273. // 检查全局中是否已存在相同的场景
  10274. $exists = false;
  10275. foreach ($global_scenes as $global_scene) {
  10276. $global_scene_name = getProp($global_scene, 'scene');
  10277. $global_description = getProp($global_scene, 'description');
  10278. $global_pic_prompt = getProp($global_scene, 'pic_prompt');
  10279. // 如果scene、description、pic_prompt三项都一致,则认为已存在
  10280. if ($episode_scene_name == $global_scene_name
  10281. && $episode_description == $global_description
  10282. && $episode_pic_prompt == $global_pic_prompt) {
  10283. $exists = true;
  10284. break;
  10285. }
  10286. }
  10287. // 如果不存在,则添加到全局
  10288. if (!$exists) {
  10289. $global_scenes[] = $episode_scene;
  10290. $scenes_added = true;
  10291. dLog('deepseek')->info("场景({$episode_scene_name})添加到全局", [
  10292. 'anime_id' => $anime_id,
  10293. 'scene' => $episode_scene_name
  10294. ]);
  10295. }
  10296. }
  10297. // 处理道具同步(逻辑与场景一致)
  10298. foreach ($episode_props as $episode_prop) {
  10299. $episode_prop_name = getProp($episode_prop, 'prop');
  10300. $episode_description = getProp($episode_prop, 'description');
  10301. $episode_pic_prompt = getProp($episode_prop, 'pic_prompt');
  10302. // 检查全局中是否已存在相同的道具
  10303. $exists = false;
  10304. foreach ($global_props as $global_prop) {
  10305. $global_prop_name = getProp($global_prop, 'prop');
  10306. $global_description = getProp($global_prop, 'description');
  10307. $global_pic_prompt = getProp($global_prop, 'pic_prompt');
  10308. // 如果prop、description、pic_prompt三项都一致,则认为已存在
  10309. if ($episode_prop_name == $global_prop_name
  10310. && $episode_description == $global_description
  10311. && $episode_pic_prompt == $global_pic_prompt) {
  10312. $exists = true;
  10313. break;
  10314. }
  10315. }
  10316. // 如果不存在,则添加到全局
  10317. if (!$exists) {
  10318. $global_props[] = $episode_prop;
  10319. $props_added = true;
  10320. dLog('deepseek')->info("道具({$episode_prop_name})添加到全局", [
  10321. 'anime_id' => $anime_id,
  10322. 'prop' => $episode_prop_name
  10323. ]);
  10324. }
  10325. }
  10326. // 如果有新增或更新,则更新全局数据
  10327. if ($roles_added || $roles_updated || $scenes_added || $props_added) {
  10328. $update_data = ['updated_at' => date('Y-m-d H:i:s')];
  10329. if ($roles_added || $roles_updated) {
  10330. $update_data['roles'] = json_encode($global_roles, 256);
  10331. }
  10332. if ($scenes_added) {
  10333. $update_data['scenes'] = json_encode($global_scenes, 256);
  10334. }
  10335. if ($props_added) {
  10336. $update_data['props'] = json_encode($global_props, 256);
  10337. }
  10338. DB::table('mp_animes')->where('id', $anime_id)->update($update_data);
  10339. dLog('deepseek')->info('剧集数据同步到全局完成', [
  10340. 'anime_id' => $anime_id,
  10341. 'roles_added' => $roles_added,
  10342. 'roles_updated' => $roles_updated,
  10343. 'scenes_added' => $scenes_added,
  10344. 'props_added' => $props_added,
  10345. 'global_roles_count' => count($global_roles),
  10346. 'global_scenes_count' => count($global_scenes),
  10347. 'global_props_count' => count($global_props)
  10348. ]);
  10349. }
  10350. return true;
  10351. }
  10352. /**
  10353. * 将全局角色和场景的task_id、task_status和url继承给指定分集
  10354. *
  10355. * @param int $anime_id 动漫对话ID
  10356. * @param int $episode_id 分集ID
  10357. * @return bool
  10358. */
  10359. private function inheritGlobalImagesToEpisodes($anime_id, $episode_id) {
  10360. // 获取全局角色和场景数据
  10361. $anime = DB::table('mp_animes')->where('id', $anime_id)->where('is_deleted', 0)->first();
  10362. if (!$anime) {
  10363. dLog('deepseek')->warning('动漫对话不存在', ['anime_id' => $anime_id]);
  10364. return false;
  10365. }
  10366. $global_roles = json_decode(getProp($anime, 'roles'), true) ?: [];
  10367. $global_scenes = json_decode(getProp($anime, 'scenes'), true) ?: [];
  10368. // 获取指定的分集
  10369. $episode = DB::table('mp_anime_episodes')->where('id', $episode_id)->where('anime_id', $anime_id)->first();
  10370. if (!$episode) {
  10371. dLog('deepseek')->warning('分集不存在', ['anime_id' => $anime_id, 'episode_id' => $episode_id]);
  10372. return false;
  10373. }
  10374. $episode_roles = json_decode(getProp($episode, 'roles'), true) ?: [];
  10375. $episode_scenes = json_decode(getProp($episode, 'scenes'), true) ?: [];
  10376. $roles_updated = false;
  10377. $scenes_updated = false;
  10378. // 继承角色的task_id、task_status和url
  10379. foreach ($episode_roles as &$episode_role) {
  10380. $episode_role_name = getProp($episode_role, 'role');
  10381. $episode_description = getProp($episode_role, 'description');
  10382. $episode_pic_prompt = getProp($episode_role, 'pic_prompt');
  10383. $episode_url = getProp($episode_role, 'url');
  10384. // 跳过旁白角色
  10385. if ($episode_role_name == '旁白') {
  10386. continue;
  10387. }
  10388. // 如果剧集中已有URL,跳过
  10389. if (!empty($episode_url)) {
  10390. continue;
  10391. }
  10392. // 遍历全局角色数据,查找匹配的角色
  10393. foreach ($global_roles as $global_role) {
  10394. $global_role_name = getProp($global_role, 'role');
  10395. $global_description = getProp($global_role, 'description');
  10396. $global_pic_prompt = getProp($global_role, 'pic_prompt');
  10397. $global_url = getProp($global_role, 'url');
  10398. $global_task_id = getProp($global_role, 'task_id');
  10399. $global_task_status = getProp($global_role, 'task_status');
  10400. // 满足条件:1.角色名相同 2.描述相同 3.pic_prompt相同 4.剧集中URL为空
  10401. if ($episode_role_name == $global_role_name
  10402. && $episode_description == $global_description
  10403. && $episode_pic_prompt == $global_pic_prompt) {
  10404. // 继承 task_id、task_status 和 url
  10405. if (!empty($global_task_id)) {
  10406. $episode_role['task_id'] = $global_task_id;
  10407. $episode_role['task_status'] = $global_task_status;
  10408. $roles_updated = true;
  10409. dLog('deepseek')->info('剧集角色继承全局task_id', [
  10410. 'episode_id' => $episode_id,
  10411. 'role' => $episode_role_name,
  10412. 'task_id' => $global_task_id,
  10413. 'task_status' => $global_task_status
  10414. ]);
  10415. }
  10416. if (!empty($global_url)) {
  10417. $episode_role['url'] = $global_url;
  10418. $roles_updated = true;
  10419. dLog('deepseek')->info('剧集角色继承全局url', [
  10420. 'episode_id' => $episode_id,
  10421. 'role' => $episode_role_name,
  10422. 'url' => $global_url
  10423. ]);
  10424. }
  10425. break;
  10426. }
  10427. }
  10428. }
  10429. // 继承场景的task_id、task_status和url
  10430. foreach ($episode_scenes as &$episode_scene) {
  10431. $episode_scene_name = getProp($episode_scene, 'scene');
  10432. $episode_description = getProp($episode_scene, 'description');
  10433. $episode_pic_prompt = getProp($episode_scene, 'pic_prompt');
  10434. $episode_url = getProp($episode_scene, 'url');
  10435. // 如果剧集中已有URL,跳过
  10436. if (!empty($episode_url)) {
  10437. continue;
  10438. }
  10439. // 遍历全局场景数据,查找匹配的场景
  10440. foreach ($global_scenes as $global_scene) {
  10441. $global_scene_name = getProp($global_scene, 'scene');
  10442. $global_description = getProp($global_scene, 'description');
  10443. $global_pic_prompt = getProp($global_scene, 'pic_prompt');
  10444. $global_url = getProp($global_scene, 'url');
  10445. $global_task_id = getProp($global_scene, 'task_id');
  10446. $global_task_status = getProp($global_scene, 'task_status');
  10447. // 满足条件:1.场景名相同 2.描述相同 3.pic_prompt相同 4.剧集中URL为空
  10448. if ($episode_scene_name == $global_scene_name
  10449. && $episode_description == $global_description
  10450. && $episode_pic_prompt == $global_pic_prompt) {
  10451. // 继承 task_id、task_status 和 url
  10452. if (!empty($global_task_id)) {
  10453. $episode_scene['task_id'] = $global_task_id;
  10454. $episode_scene['task_status'] = $global_task_status;
  10455. $scenes_updated = true;
  10456. dLog('deepseek')->info('剧集场景继承全局task_id', [
  10457. 'episode_id' => $episode_id,
  10458. 'scene' => $episode_scene_name,
  10459. 'task_id' => $global_task_id,
  10460. 'task_status' => $global_task_status
  10461. ]);
  10462. }
  10463. if (!empty($global_url)) {
  10464. $episode_scene['url'] = $global_url;
  10465. $scenes_updated = true;
  10466. dLog('deepseek')->info('剧集场景继承全局url', [
  10467. 'episode_id' => $episode_id,
  10468. 'scene' => $episode_scene_name,
  10469. 'url' => $global_url
  10470. ]);
  10471. }
  10472. break;
  10473. }
  10474. }
  10475. }
  10476. // 如果有更新,则保存到数据库
  10477. if ($roles_updated || $scenes_updated) {
  10478. $update_data = ['updated_at' => date('Y-m-d H:i:s')];
  10479. if ($roles_updated) {
  10480. $update_data['roles'] = json_encode($episode_roles, 256);
  10481. }
  10482. if ($scenes_updated) {
  10483. $update_data['scenes'] = json_encode($episode_scenes, 256);
  10484. }
  10485. DB::table('mp_anime_episodes')->where('id', $episode_id)->update($update_data);
  10486. dLog('deepseek')->info('剧集继承全局图片数据完成', [
  10487. 'episode_id' => $episode_id,
  10488. 'roles_updated' => $roles_updated,
  10489. 'scenes_updated' => $scenes_updated
  10490. ]);
  10491. }
  10492. return true;
  10493. }
  10494. public function chatChangeImg($data) {
  10495. $segment = getProp($data, 'segment');
  10496. $segment_content = getProp($segment, 'segment_content');
  10497. $prompt = getProp($data, 'prompt');
  10498. $ref_img = getProp($data, 'ref_img');
  10499. $question = "请修改已有的内容{$segment_content}\n修改要求如下:\n{$prompt}";
  10500. // 处理文本模型
  10501. $model = getProp($data, 'model');
  10502. if (!$model) {
  10503. // 用户没有输入,从anime表获取
  10504. $segment_id = getProp($segment, 'segment_id');
  10505. if ($segment_id) {
  10506. $episode_id = DB::table('mp_episode_segments')->where('segment_id', $segment_id)->value('episode_id');
  10507. if ($episode_id) {
  10508. $anime_id = DB::table('mp_anime_episodes')->where('id', $episode_id)->value('anime_id');
  10509. if ($anime_id) {
  10510. $model = DB::table('mp_animes')->where('id', $anime_id)->value('model');
  10511. }
  10512. }
  10513. }
  10514. if (!$model) {
  10515. // anime表也没有,使用默认值
  10516. $model = 'doubao-seed-2-0-mini-260215';
  10517. }
  10518. }
  10519. // 验证模型是否在可用模型表中
  10520. if (!DB::table('mp_text_models')->where('model', $model)->where('is_enabled', 1)->exists()) {
  10521. $model = 'doubao-seed-2-0-mini-260215';
  10522. }
  10523. $messages[] =
  10524. [
  10525. 'role' => 'user',
  10526. 'content' => $question
  10527. ];
  10528. $post_data = [
  10529. 'model' => $model,
  10530. 'messages' => $messages,
  10531. // 'max_tokens' => 8192,
  10532. 'temperature' => 0.7,
  10533. 'frequency_penalty' => 0,
  10534. 'presence_penalty' => 0,
  10535. 'response_format' => ['type' => 'text'],
  10536. 'stream' => false // 是否启用流式输出
  10537. ];
  10538. if (in_array($model, ['deepseek-reasoner', 'deepseek-chat', 'deepseek-v4-flash', 'deepseek-v4-pro'])) {
  10539. // DeepSeek 官方模型使用 DeepSeek API
  10540. $chatResult = $this->chatOnly($post_data);
  10541. } else if (in_array($model, $this->gpt_text_models)) {
  10542. // GPT-5.4 模型使用 TokenRouter API
  10543. $chatResult = $this->gpt54ChatOnly($post_data);
  10544. } else {
  10545. // 其他模型使用火山引擎API
  10546. $chatResult = $this->volcEngineChatCompletion($post_data);
  10547. }
  10548. if (is_array($chatResult)) {
  10549. extract($chatResult);
  10550. }else {
  10551. Utils::throwError('20003: 接口调用失败!');
  10552. }
  10553. return [
  10554. 'type' => 'done',
  10555. // 'episode' => $episode,
  10556. 'answer' => $fullContent,
  10557. 'reasoning' => $fullReasoningContent,
  10558. 'usage' => $usage
  10559. ];
  10560. }
  10561. // 仅调用deepseek对话接口
  10562. private function chatOnly($post_data) {
  10563. $post_data['max_tokens'] = 300000;
  10564. $client = new Client(['timeout' => 1800, 'verify' => false]);
  10565. $result = $client->post($this->url, ['json' => $post_data, 'headers' => $this->headers]);
  10566. $response = $result->getBody()->getContents();
  10567. $response_arr = json_decode($response, true);
  10568. dLog('deepseek')->info('deepseek请求完成', ['response' => $response_arr]);
  10569. $fullContent = '';
  10570. $fullReasoningContent = [];
  10571. $usage = isset($response_arr['usage']) ? $response_arr['usage'] : [];
  10572. if (isset($response_arr['choices']) && count($response_arr['choices']) > 0) {
  10573. $fullContent = isset($response_arr['choices'][0]['message']['content']) ? $response_arr['choices'][0]['message']['content'] : '';
  10574. $fullReasoningContent = isset($response_arr['choices'][0]['message']['reasoning_content']) ? $response_arr['choices'][0]['message']['reasoning_content'] : '';
  10575. }
  10576. return [
  10577. 'fullContent' => $fullContent,
  10578. 'fullReasoningContent' => $fullReasoningContent,
  10579. 'usage' => $usage
  10580. ];
  10581. }
  10582. // 仅调用 GPT-5.4 对话接口(非流式)
  10583. private function gpt54ChatOnly($post_data) {
  10584. $apiKey = env('GPT_54_API_KEY');
  10585. if (empty($apiKey)) {
  10586. Utils::throwError('20003:GPT-5.4 API Key未配置');
  10587. }
  10588. // 先探活,服务不可用时自动重试
  10589. $this->ensureGptServiceAvailable();
  10590. $client = new Client(['timeout' => 1800, 'verify' => false]);
  10591. $headers = [
  10592. 'Authorization' => 'Bearer ' . $apiKey,
  10593. 'Content-Type' => 'application/json'
  10594. ];
  10595. // 移除 thinking 参数,GPT-5.4 不支持
  10596. if (isset($post_data['thinking'])) {
  10597. unset($post_data['thinking']);
  10598. }
  10599. if (isset($post_data['reasoning_effort'])) {
  10600. unset($post_data['reasoning_effort']);
  10601. }
  10602. $post_data['max_completion_tokens'] = 100000;
  10603. // 确保 stream 为 false
  10604. $post_data['stream'] = false;
  10605. $maxRetries = $this->gptRetryTimes();
  10606. $interval = $this->gptRetryInterval();
  10607. $attempt = 0;
  10608. while (true) {
  10609. try {
  10610. // 备用中转站地址: https://token.ithinkai.cn/v1/chat/completions
  10611. // 备用中转站地址2: https://api.nonelinear.com/v1/chat/completions
  10612. $result = $client->post('https://ai-api.kkidc.com/v1/chat/completions', [
  10613. 'json' => $post_data,
  10614. 'headers' => $headers
  10615. ]);
  10616. $response = $result->getBody()->getContents();
  10617. $response_arr = json_decode($response, true);
  10618. dLog('deepseek')->info('GPT-5.4请求完成', ['response' => $response_arr]);
  10619. $fullContent = '';
  10620. $usage = isset($response_arr['usage']) ? $response_arr['usage'] : [];
  10621. if (isset($response_arr['choices']) && count($response_arr['choices']) > 0) {
  10622. $fullContent = isset($response_arr['choices'][0]['message']['content']) ? $response_arr['choices'][0]['message']['content'] : '';
  10623. }
  10624. return [
  10625. 'fullContent' => $fullContent,
  10626. 'fullReasoningContent' => '', // GPT-5.4 不支持思考链
  10627. 'usage' => $usage
  10628. ];
  10629. } catch (\Exception $e) {
  10630. if (!$this->isGptRetryableException($e) || $attempt >= $maxRetries) {
  10631. dLog('deepseek')->error('GPT-5.4 请求失败: ' . $e->getMessage());
  10632. logDB('deepseek', 'error', 'GPT-5.4 请求失败', ['error' => $e->getMessage()]);
  10633. throw $e;
  10634. }
  10635. dLog('deepseek')->warning('GPT-5.4 请求失败,准备重试', [
  10636. 'retry' => $attempt + 1,
  10637. 'max_retries' => $maxRetries,
  10638. 'error' => $e->getMessage()
  10639. ]);
  10640. sleep($interval);
  10641. $attempt++;
  10642. }
  10643. }
  10644. }
  10645. private function splitContent($content) {
  10646. // 根据章节标题来拆分章节内容,返回包含标题和内容的二维数组
  10647. $chapters = [];
  10648. // 匹配章节标题格式:
  10649. // 1. 标题可能独占一行,也可能在正文末尾或中间
  10650. // 2. 格式支持:
  10651. // - **第一集**
  10652. // - 第一集:
  10653. // - ###第1章 重生
  10654. // - ##第2章 相救
  10655. // - 第三章 共处一室
  10656. // 3. 支持阿拉伯数字(0-9)和中文数字(一二两三四五六七八九十百千万)
  10657. // 4. 支持章节关键字:章、节、集、幕、场、回、话
  10658. // 5. "第"字与数字、数字与章节关键字之间可能有空格
  10659. // 6. 前后可能有#、*、·等修饰符号,后面可能有冒号、空格、标题文字等
  10660. // 先预处理:将标题前后添加换行符,确保标题能被正确识别和拆分
  10661. // 匹配模式:可能有前缀符号 + "第" + 空格(可选) + 数字 + 空格(可选) + 章节关键字 + 可能的标题内容
  10662. $pattern = '/([#*·\-_=\s]*)第\s*([一二两三四五六七八九十百千万0-9]+)\s*([章节集幕场回话])([^第\n]*?)(?=第\s*[一二两三四五六七八九十百千万0-9]+\s*[章节集幕场回话]|$)/u';
  10663. // 先在每个标题前插入换行符(如果前面不是换行的话)
  10664. $content = preg_replace('/([^\n])([#*·\-_=\s]*)第\s*([一二两三四五六七八九十百千万0-9]+)\s*([章节集幕场回话])/u', "$1\n\n$2第$3$4", $content);
  10665. // 现在用修改后的模式匹配(标题应该在行首或接近行首)
  10666. $pattern = '/^[#*·\s\-_=]*第\s*([一二两三四五六七八九十百千万0-9]+)\s*([章节集幕场回话]).*$/mu';
  10667. // 用正则找出所有章节标题的位置
  10668. if (preg_match_all($pattern, $content, $matches, PREG_OFFSET_CAPTURE)) {
  10669. $titleCount = count($matches[0]);
  10670. for ($i = 0; $i < $titleCount; $i++) {
  10671. // 获取当前章节标题
  10672. $titleLine = trim($matches[0][$i][0]);
  10673. // 去除标题开头的特殊符号
  10674. $cleanTitle = preg_replace('/^[#*·\-_=\s]+/', '', $titleLine);
  10675. // 去除标题结尾的冒号和特殊符号
  10676. $cleanTitle = preg_replace('/[#*·::\s]+$/', '', $cleanTitle);
  10677. $cleanTitle = trim($cleanTitle);
  10678. // 获取当前标题的结束位置
  10679. $titleEndPos = $matches[0][$i][1] + strlen($matches[0][$i][0]);
  10680. // 获取下一个章节标题的开始位置(如果存在)
  10681. $nextTitlePos = ($i < $titleCount - 1) ? $matches[0][$i + 1][1] : strlen($content);
  10682. // 提取章节内容(从标题结束到下一个标题开始)
  10683. $chapterContent = substr($content, $titleEndPos, $nextTitlePos - $titleEndPos);
  10684. // 清理内容:去除前后空白和分隔线
  10685. $chapterContent = trim($chapterContent);
  10686. $chapterContent = preg_replace('/^[\-\s]+/u', '', $chapterContent);
  10687. $chapterContent = preg_replace('/[\-\s]+$/u', '', $chapterContent);
  10688. if (!empty($cleanTitle) && !empty($chapterContent)) {
  10689. $chapters[] = [
  10690. 'title' => $cleanTitle,
  10691. 'content' => $chapterContent
  10692. ];
  10693. }
  10694. }
  10695. } else {
  10696. // 如果没有匹配到章节,返回整个内容
  10697. $chapters[] = [
  10698. 'title' => '',
  10699. 'content' => $content
  10700. ];
  10701. }
  10702. return $chapters;
  10703. }
  10704. public function getContentByBid($bid) {
  10705. $chapters = DB::table('chapters as c')->select('c.id', 'c.name', 'cc.content')
  10706. ->leftJoin('chapter_contents as cc', 'c.chapter_content_id', '=', 'cc.id')
  10707. ->where('c.bid', $bid)->where('c.is_check', 1)->where('c.is_deleted', 0)->orderBy('c.sequence')->get();
  10708. $content = '';
  10709. foreach ($chapters as $chapter) {
  10710. $content .= $chapter->content . PHP_EOL . PHP_EOL;
  10711. }
  10712. return $content;
  10713. }
  10714. public function getContentByScriptId($script_id) {
  10715. $content = '';
  10716. $contents = DB::table('mp_script_episode_group')->where('script_id', $script_id)->pluck('content')->toArray();
  10717. if ($contents) {
  10718. $content = implode(PHP_EOL, $contents);
  10719. }else {
  10720. $content = DB::table('mp_scripts')->where('id', $script_id)->value('content');
  10721. }
  10722. return $content;
  10723. }
  10724. /**
  10725. * 根据文件类型提取文本内容
  10726. *
  10727. * @param mixed $file 文件对象或文件路径
  10728. * @return string
  10729. */
  10730. public function extractFileContent($file) {
  10731. // 获取文件路径和扩展名
  10732. if (is_string($file)) {
  10733. $filePath = $file;
  10734. $extension = strtolower(pathinfo($file, PATHINFO_EXTENSION));
  10735. } else {
  10736. // Laravel UploadedFile 对象
  10737. $filePath = $file->getRealPath();
  10738. $extension = strtolower($file->getClientOriginalExtension());
  10739. }
  10740. $content = '';
  10741. switch ($extension) {
  10742. case 'txt':
  10743. $content = $this->extractTxtContent($filePath);
  10744. break;
  10745. case 'pdf':
  10746. $content = $this->extractPdfContent($filePath);
  10747. break;
  10748. case 'doc':
  10749. case 'docx':
  10750. $content = $this->extractWordContent($filePath);
  10751. break;
  10752. // case 'jpg':
  10753. // case 'jpeg':
  10754. // case 'png':
  10755. // case 'gif':
  10756. // case 'bmp':
  10757. // case 'webp':
  10758. // $content = $this->extractImageContent($filePath);
  10759. // break;
  10760. default:
  10761. Utils::throwError('20003:不支持的文件格式,支持:txt、pdf');
  10762. }
  10763. return $content;
  10764. }
  10765. /**
  10766. * 提取 TXT 文件内容
  10767. */
  10768. private function extractTxtContent($filePath) {
  10769. if (!file_exists($filePath)) {
  10770. Utils::throwError('20003:文件不存在');
  10771. }
  10772. $content = file_get_contents($filePath);
  10773. // 尝试检测并转换编码
  10774. $encoding = mb_detect_encoding($content, ['UTF-8', 'GBK', 'GB2312', 'BIG5'], true);
  10775. if ($encoding && $encoding !== 'UTF-8') {
  10776. $content = mb_convert_encoding($content, 'UTF-8', $encoding);
  10777. }
  10778. return trim($content);
  10779. }
  10780. /**
  10781. * 提取 PDF 文件内容
  10782. */
  10783. private function extractPdfContent($filePath) {
  10784. if (!file_exists($filePath)) {
  10785. Utils::throwError('20003:文件不存在');
  10786. }
  10787. try {
  10788. $parser = new PdfParser();
  10789. $pdf = $parser->parseFile($filePath);
  10790. $content = $pdf->getText();
  10791. return trim($content);
  10792. } catch (\Exception $e) {
  10793. dLog('deepseek')->error('PDF解析失败: ' . $e->getMessage());
  10794. logDB('deepseek', 'error', 'PDF解析失败', ['error' => $e->getMessage()]);
  10795. Utils::throwError('20003:PDF解析失败,请确保文件格式正确');
  10796. }
  10797. }
  10798. /**
  10799. * 提取 Word 文件内容(支持 doc 和 docx)
  10800. */
  10801. private function extractWordContent($filePath) {
  10802. if (!file_exists($filePath)) {
  10803. Utils::throwError('20003:文件不存在');
  10804. }
  10805. try {
  10806. $phpWord = WordIOFactory::load($filePath);
  10807. $content = '';
  10808. foreach ($phpWord->getSections() as $section) {
  10809. foreach ($section->getElements() as $element) {
  10810. $content .= $this->extractWordElementText($element);
  10811. }
  10812. }
  10813. return trim($content);
  10814. } catch (\Exception $e) {
  10815. dLog('deepseek')->error('Word解析失败: ' . $e->getMessage());
  10816. logDB('deepseek', 'error', 'Word解析失败', ['error' => $e->getMessage()]);
  10817. Utils::throwError('20003:Word解析失败,请确保文件格式正确');
  10818. }
  10819. }
  10820. /**
  10821. * 递归提取 Word 元素中的文本
  10822. */
  10823. private function extractWordElementText($element) {
  10824. $text = '';
  10825. if (method_exists($element, 'getText')) {
  10826. $text .= $element->getText() . "\n";
  10827. } elseif (method_exists($element, 'getElements')) {
  10828. foreach ($element->getElements() as $childElement) {
  10829. $text .= $this->extractWordElementText($childElement);
  10830. }
  10831. }
  10832. return $text;
  10833. }
  10834. /**
  10835. * 提取图片内容(使用火山引擎 OCR)
  10836. */
  10837. private function extractImageContent($filePath) {
  10838. if (!file_exists($filePath)) {
  10839. Utils::throwError('20003:文件不存在');
  10840. }
  10841. try {
  10842. // 读取图片并转换为 base64
  10843. $imageData = file_get_contents($filePath);
  10844. $base64Image = base64_encode($imageData);
  10845. // 调用火山引擎 OCR 服务
  10846. $content = $this->callVolcEngineOCR($base64Image);
  10847. return trim($content);
  10848. } catch (\Exception $e) {
  10849. dLog('deepseek')->error('图片OCR识别失败: ' . $e->getMessage());
  10850. logDB('deepseek', 'error', '图片OCR识别失败', ['error' => $e->getMessage()]);
  10851. Utils::throwError('20003:图片识别失败');
  10852. }
  10853. }
  10854. /**
  10855. * 调用火山引擎 OCR 服务识别图片文字
  10856. *
  10857. * @param string $base64Image base64 编码的图片数据
  10858. * @return string 识别的文字内容
  10859. */
  10860. private function callVolcEngineOCR($base64Image) {
  10861. $method = 'POST';
  10862. $service = 'cv';
  10863. $host = 'visual.volcengineapi.com';
  10864. $region = env('VOLC_REGION', 'cn-north-1');
  10865. $access_key = env('VOLC_AK');
  10866. $secret_key = env('VOLC_SK');
  10867. $action = 'OCRNormal';
  10868. $version = '2020-08-26';
  10869. if (!$access_key || !$secret_key) {
  10870. Utils::throwError('20003:请配置火山引擎 AK/SK');
  10871. }
  10872. // 请求体
  10873. $body = json_encode([
  10874. 'image_base64' => $base64Image
  10875. ]);
  10876. // 生成签名
  10877. $headers = $this->getVolcEngineSignHeaders(
  10878. $method, $service, $host, $region,
  10879. "Action={$action}&Version={$version}",
  10880. $access_key, $secret_key, $body
  10881. );
  10882. $client = new Client(['timeout' => 1800, 'verify' => false]);
  10883. $response = $client->post("https://{$host}/?Action={$action}&Version={$version}", [
  10884. 'headers' => $headers,
  10885. 'body' => $body
  10886. ]);
  10887. $response_arr = json_decode($response->getBody()->getContents(), true);
  10888. // 提取识别的文字
  10889. $textLines = [];
  10890. if (isset($response_arr['data']['line_texts'])) {
  10891. $textLines = $response_arr['data']['line_texts'];
  10892. } elseif (isset($response_arr['data']['ocr_infos'])) {
  10893. foreach ($response_arr['data']['ocr_infos'] as $info) {
  10894. if (isset($info['text'])) {
  10895. $textLines[] = $info['text'];
  10896. }
  10897. }
  10898. }
  10899. if (empty($textLines)) {
  10900. dLog('deepseek')->warning('OCR识别结果为空', ['response' => $response_arr]);
  10901. return '';
  10902. }
  10903. return implode("\n", $textLines);
  10904. }
  10905. /**
  10906. * 生成火山引擎 API 签名头(用于 OCR 等 POST 请求)
  10907. */
  10908. private function getVolcEngineSignHeaders($method, $service, $host, $region, $queryString, $access_key, $secret_key, $body = '') {
  10909. $contentType = 'application/json';
  10910. $accept = 'application/json';
  10911. // 获取当前UTC时间
  10912. $t = new DateTime('now', new DateTimeZone('UTC'));
  10913. $xDate = $t->format('Ymd\THis\Z');
  10914. $dateStamp = $t->format('Ymd');
  10915. // 计算 body 的 sha256 哈希
  10916. $payloadHash = hash('sha256', $body);
  10917. // 1. 拼接规范请求串
  10918. $canonicalUri = '/';
  10919. $canonicalQueryString = $queryString;
  10920. $canonicalHeaders = "content-type:{$contentType}\nhost:{$host}\nx-content-sha256:{$payloadHash}\nx-date:{$xDate}\n";
  10921. $signedHeaders = 'content-type;host;x-content-sha256;x-date';
  10922. $canonicalRequest = implode("\n", [
  10923. $method,
  10924. $canonicalUri,
  10925. $canonicalQueryString,
  10926. $canonicalHeaders,
  10927. $signedHeaders,
  10928. $payloadHash
  10929. ]);
  10930. // 2. 拼接待签名字符串
  10931. $algorithm = 'HMAC-SHA256';
  10932. $credentialScope = implode('/', [$dateStamp, $region, $service, 'request']);
  10933. $hashedCanonicalRequest = hash('sha256', $canonicalRequest);
  10934. $stringToSign = implode("\n", [
  10935. $algorithm,
  10936. $xDate,
  10937. $credentialScope,
  10938. $hashedCanonicalRequest
  10939. ]);
  10940. // 3. 计算签名
  10941. $signingKey = $this->getSignatureKey($secret_key, $dateStamp, $region, $service);
  10942. $signature = hash_hmac('sha256', $stringToSign, $signingKey);
  10943. // 4. 添加签名到请求头
  10944. $authorizationHeader = sprintf(
  10945. '%s Credential=%s/%s, SignedHeaders=%s, Signature=%s',
  10946. $algorithm,
  10947. $access_key,
  10948. $credentialScope,
  10949. $signedHeaders,
  10950. $signature
  10951. );
  10952. return [
  10953. 'Accept' => $accept,
  10954. 'Content-Type' => $contentType,
  10955. 'Host' => $host,
  10956. 'X-Date' => $xDate,
  10957. 'X-Content-Sha256'=> $payloadHash,
  10958. 'Authorization' => $authorizationHeader
  10959. ];
  10960. }
  10961. public function generateScriptWords($cid, $model = 'r1') {
  10962. ini_set('max_execution_time', 0);
  10963. if (!$cid) Utils::throwError('20003: 请选择章节!');
  10964. $content = DB::table('chapters as c')->leftJoin('chapter_contents as cc', 'c.chapter_content_id', '=', 'cc.id')->where('c.id', $cid)->value('cc.content');
  10965. // 模型兼容性处理和思考模式设置
  10966. $thinkingMode = 'disabled';
  10967. $reasoningEffort = 'high';
  10968. if ($model == 'r1') {
  10969. $model = 'deepseek-v4-flash'; // r1 映射到 deepseek-v4-flash 思考模式
  10970. $thinkingMode = 'enabled';
  10971. } else {
  10972. $model = 'deepseek-v4-flash'; // 默认映射到 deepseek-v4-flash 非思考模式
  10973. $thinkingMode = 'disabled';
  10974. }
  10975. $messages = [
  10976. [
  10977. 'role' => 'system',
  10978. 'content' => '下面有一段小说文本,请帮我将文本中的每句话按从上到下的顺序拆分成角色不同的剧本文稿(不得更改上下文顺序和内容),文稿形式严格按照“角色名(男或女):台词{情感}”输出,需要注意以下几点要求:
  10979. 1.角色名后不要加入任何其他词语,只能加不包括旁白的性别,在男或女中选
  10980. 2.非对话部分请全部用旁白角色代替
  10981. 3.情感必须在【开心、悲伤、生气、惊讶、恐惧、厌恶、激动、冷漠、中性、沮丧、撒娇、害羞、安慰鼓励、咆哮、温柔、自然讲述、情感电台、磁性、广告营销、气泡音、新闻播报、娱乐八卦】中选一个,不得使用其他词语'
  10982. ],
  10983. [
  10984. 'role' => 'user',
  10985. 'content' => $content
  10986. ]
  10987. ];
  10988. $post_data = [
  10989. 'model' => $model,
  10990. 'messages' => $messages,
  10991. // 'max_tokens' => 8192,
  10992. 'temperature' => (float)env('TEXT_TEMPERATURE'),
  10993. 'frequency_penalty' => 0,
  10994. 'presence_penalty' => 0,
  10995. 'thinking' => ['type' => $thinkingMode],
  10996. 'response_format' => [
  10997. 'type' => 'text'
  10998. ],
  10999. 'stream' => false
  11000. ];
  11001. if ($thinkingMode == 'enabled') $post_data['reasoning_effort'] = $reasoningEffort;
  11002. // 根据模型类型选择调用方法
  11003. $fullContent = '';
  11004. if (in_array($model, ['deepseek-reasoner', 'deepseek-chat', 'deepseek-v4-flash', 'deepseek-v4-pro'])) {
  11005. // DeepSeek 官方模型使用 DeepSeek API
  11006. $chatResult = $this->chatOnly($post_data);
  11007. } else if (in_array($model, $this->gpt_text_models)) {
  11008. // GPT-5.4 模型使用 TokenRouter API
  11009. $chatResult = $this->gpt54ChatOnly($post_data);
  11010. } else {
  11011. // 其他模型使用火山引擎API
  11012. $chatResult = $this->volcEngineChatCompletion($post_data);
  11013. }
  11014. if (is_array($chatResult)) {
  11015. $fullContent = $chatResult['fullContent'];
  11016. }
  11017. return $fullContent;
  11018. }
  11019. /**
  11020. * 智能化解析集数信息
  11021. * 支持多种表达方式,如:改成3集、调整成5集、修改为10集等
  11022. *
  11023. * @param string $prompt 用户输入的提示词
  11024. * @return int|null 解析出的集数,如果没有找到则返回null
  11025. */
  11026. private function extractEpisodeNumber($prompt)
  11027. {
  11028. if (empty($prompt)) {
  11029. return null;
  11030. }
  11031. // 定义各种可能的表达模式
  11032. $patterns = [
  11033. // 基本模式:改成N集、调整成N集、修改成N集
  11034. '/(?:改成|调整成|修改成|变成|设置成|设为|改为|调为|修改为|变为)\s*(\d+)\s*集/u',
  11035. // 扩展模式:分成N集、拆分成N集、分割成N集
  11036. '/(?:分成|拆分成|分割成|划分成|分为)\s*(\d+)\s*集/u',
  11037. // 数量模式:N集、共N集、总共N集
  11038. '/(?:共|总共|一共|总计)?\s*(\d+)\s*集/u',
  11039. // 制作模式:制作N集、生成N集、创建N集
  11040. '/(?:制作|生成|创建|产出|输出)\s*(\d+)\s*集/u',
  11041. // 计划模式:计划N集、预计N集、打算N集
  11042. '/(?:计划|预计|打算|准备|想要)\s*(\d+)\s*集/u',
  11043. // 需要模式:需要N集、要N集
  11044. '/(?:需要|要|需)\s*(\d+)\s*集/u',
  11045. // 中文数字模式:改成三集、调整成五集等
  11046. '/(?:改成|调整成|修改成|变成|设置成|设为|改为|调为|修改为|变为|分成|拆分成|分割成|划分成|分为|制作|生成|创建|产出|输出|计划|预计|打算|准备|想要|需要|要|需)\s*([一二三四五六七八九十]+)\s*集/u',
  11047. // 英文数字模式
  11048. '/(?:change\s+to|adjust\s+to|modify\s+to|set\s+to|make\s+it|split\s+into|divide\s+into)\s*(\d+)\s*(?:episodes?|eps?)/i',
  11049. ];
  11050. // 中文数字转阿拉伯数字的映射
  11051. $chineseNumbers = [
  11052. '一' => 1, '二' => 2, '三' => 3, '四' => 4, '五' => 5,
  11053. '六' => 6, '七' => 7, '八' => 8, '九' => 9, '十' => 10,
  11054. '十一' => 11, '十二' => 12, '十三' => 13, '十四' => 14, '十五' => 15,
  11055. '十六' => 16, '十七' => 17, '十八' => 18, '十九' => 19, '二十' => 20
  11056. ];
  11057. // 逐个尝试匹配模式
  11058. foreach ($patterns as $pattern) {
  11059. if (preg_match($pattern, $prompt, $matches)) {
  11060. $number = trim($matches[1]);
  11061. // 如果是中文数字,转换为阿拉伯数字
  11062. if (isset($chineseNumbers[$number])) {
  11063. return $chineseNumbers[$number];
  11064. }
  11065. // 如果是阿拉伯数字,直接返回
  11066. if (is_numeric($number)) {
  11067. $episodeNum = intval($number);
  11068. // 合理性检查:集数应该在1-100之间
  11069. if ($episodeNum >= 1 && $episodeNum <= 100) {
  11070. return $episodeNum;
  11071. }
  11072. }
  11073. }
  11074. }
  11075. return null;
  11076. }
  11077. /**
  11078. * 调用火山引擎对话(Chat) API
  11079. *
  11080. * @param array $params 包含以下参数:
  11081. * - model: 模型ID(必填)
  11082. * - messages: 消息列表(必填)
  11083. * - stream: 是否流式输出(可选,默认false)
  11084. * - max_tokens: 最大输出token数(可选)
  11085. * - temperature: 采样温度(可选,默认1)
  11086. * - top_p: 核采样概率(可选,默认0.7)
  11087. * - frequency_penalty: 频率惩罚系数(可选,默认0)
  11088. * - presence_penalty: 存在惩罚系数(可选,默认0)
  11089. * - stop: 停止词(可选)
  11090. * - tools: 工具列表(可选)
  11091. * @return array|Generator 非流式返回数组,流式返回生成器
  11092. */
  11093. public function volcEngineChatCompletion(array $params)
  11094. {
  11095. $apiKey = env('VOLC_AI_API_KEY');
  11096. if (empty($apiKey)) {
  11097. Utils::throwError('20003:火山引擎API Key未配置,请检查环境变量VOLC_AI_API_KEY');
  11098. }
  11099. // 构建请求参数
  11100. $originalModel = $params['model'] ?? 'deepseek-v3-2-251201';
  11101. $requestData = [
  11102. 'model' => isset(\App\Consts\BaseConst::MODELS_MAP[$originalModel]) ? \App\Consts\BaseConst::MODELS_MAP[$originalModel] : $originalModel,
  11103. 'messages' => $params['messages'] ?? [],
  11104. ];
  11105. if (!in_array($originalModel, $this->valid_text_models)) {
  11106. Utils::throwError('20003:该模型不支持!');
  11107. }
  11108. // 添加可选参数
  11109. if (isset($params['stream'])) {
  11110. $requestData['stream'] = $params['stream'];
  11111. }
  11112. if (isset($params['stream_options'])) {
  11113. $requestData['stream_options'] = $params['stream_options'];
  11114. }
  11115. if (isset($params['max_tokens'])) {
  11116. $requestData['max_tokens'] = $params['max_tokens'];
  11117. }else if (isset($params['max_completion_tokens'])) {
  11118. $requestData['max_completion_tokens'] = $params['max_completion_tokens'];
  11119. }else {
  11120. $requestData['max_completion_tokens'] = 100000;
  11121. }
  11122. if (isset($params['temperature'])) {
  11123. $requestData['temperature'] = $params['temperature'];
  11124. }
  11125. if (isset($params['top_p'])) {
  11126. $requestData['top_p'] = $params['top_p'];
  11127. }
  11128. if (isset($params['frequency_penalty'])) {
  11129. $requestData['frequency_penalty'] = $params['frequency_penalty'];
  11130. }
  11131. if (isset($params['presence_penalty'])) {
  11132. $requestData['presence_penalty'] = $params['presence_penalty'];
  11133. }
  11134. if (isset($params['stop'])) {
  11135. $requestData['stop'] = $params['stop'];
  11136. }
  11137. if (isset($params['tools'])) {
  11138. $requestData['tools'] = $params['tools'];
  11139. }
  11140. if (isset($params['tool_choice'])) {
  11141. $requestData['tool_choice'] = $params['tool_choice'];
  11142. }
  11143. if (isset($params['response_format'])) {
  11144. $requestData['response_format'] = $params['response_format'];
  11145. }
  11146. if (isset($params['thinking'])) {
  11147. // 如果 thinking 已经是数组格式,直接使用;否则转换为正确格式
  11148. if (is_array($params['thinking'])) {
  11149. $requestData['thinking'] = $params['thinking'];
  11150. if (isset($params['reasoning_effort']) && $params['thinking']['type'] == 'enabled') {
  11151. $requestData['reasoning_effort'] = $params['reasoning_effort'];
  11152. }
  11153. } else {
  11154. $requestData['thinking'] = ['type' => $params['thinking']];
  11155. if (isset($params['reasoning_effort']) && $params['thinking'] == 'enabled') {
  11156. $requestData['reasoning_effort'] = $params['reasoning_effort'];
  11157. }
  11158. }
  11159. } else {
  11160. $requestData['thinking'] = ['type' => 'disabled'];
  11161. }
  11162. dLog('deepseek')->info('火山引擎对话API请求参数: ', $requestData);
  11163. $client = new Client(['verify' => false, 'timeout' => 1800]);
  11164. try {
  11165. // 判断是否为流式输出
  11166. $isStream = isset($params['stream']) && $params['stream'] === true;
  11167. if ($isStream) {
  11168. // 流式输出
  11169. return $this->volcEngineChatCompletionStream($client, $apiKey, $requestData);
  11170. } else {
  11171. // 非流式输出
  11172. $response = $client->post('https://ark.cn-beijing.volces.com/api/v3/chat/completions', [
  11173. 'headers' => [
  11174. 'Authorization' => 'Bearer ' . $apiKey,
  11175. 'Content-Type' => 'application/json',
  11176. ],
  11177. 'json' => $requestData
  11178. ]);
  11179. $responseData = json_decode($response->getBody(), true);
  11180. dLog('deepseek')->info('火山引擎对话API响应: ', $responseData);
  11181. $usage = isset($responseData['usage']) ? $responseData['usage'] : [];
  11182. if (isset($responseData['choices']) && count($responseData['choices']) > 0) {
  11183. $fullContent = isset($responseData['choices'][0]['message']['content']) ? $responseData['choices'][0]['message']['content'] : '';
  11184. $fullReasoningContent = isset($responseData['choices'][0]['message']['reasoning_content']) ? $responseData['choices'][0]['message']['reasoning_content'] : '';
  11185. }
  11186. return [
  11187. 'fullContent' => $fullContent,
  11188. 'fullReasoningContent' => $fullReasoningContent,
  11189. 'usage' => $usage
  11190. ];
  11191. }
  11192. } catch (\Exception $e) {
  11193. dLog('deepseek')->error('火山引擎对话API请求异常: ' . $e->getMessage());
  11194. logDB('deepseek', 'error', '火山引擎对话API请求失败', ['error' => $e->getMessage(), 'model' => $requestData['model']]);
  11195. Utils::throwError('20003:火山引擎对话API请求失败: ' . $e->getMessage());
  11196. }
  11197. }
  11198. /**
  11199. * 火山引擎对话API流式输出
  11200. *
  11201. * @param Client $client HTTP客户端
  11202. * @param string $apiKey API密钥
  11203. * @param array $requestData 请求数据
  11204. * @return Generator
  11205. */
  11206. private function volcEngineChatCompletionStream($client, $apiKey, $requestData)
  11207. {
  11208. try {
  11209. $response = $client->post('https://ark.cn-beijing.volces.com/api/v3/chat/completions', [
  11210. 'headers' => [
  11211. 'Authorization' => 'Bearer ' . $apiKey,
  11212. 'Content-Type' => 'application/json',
  11213. ],
  11214. 'json' => $requestData,
  11215. 'stream' => true
  11216. ]);
  11217. $body = $response->getBody();
  11218. $buffer = '';
  11219. $fullContent = '';
  11220. $fullReasoningContent = '';
  11221. $usage = [];
  11222. dLog('deepseek')->info('开始读取火山引擎对话API流式响应');
  11223. // 逐行读取流式响应
  11224. while (!$body->eof()) {
  11225. $chunk = $body->read(1024);
  11226. $buffer .= $chunk;
  11227. // 按行分割
  11228. $lines = explode("\n", $buffer);
  11229. $buffer = array_pop($lines);
  11230. foreach ($lines as $line) {
  11231. $line = trim($line);
  11232. if (empty($line)) {
  11233. continue;
  11234. }
  11235. // 检查是否是SSE数据行
  11236. if (strpos($line, 'data: ') !== 0) {
  11237. continue;
  11238. }
  11239. $data = substr($line, 6);
  11240. if ($data === '[DONE]') {
  11241. dLog('deepseek')->info('收到结束标记');
  11242. break 2;
  11243. }
  11244. try {
  11245. $json = json_decode($data, true);
  11246. if (json_last_error() !== JSON_ERROR_NONE) {
  11247. dLog('deepseek')->warning('JSON解析错误: ' . json_last_error_msg());
  11248. continue;
  11249. }
  11250. if (isset($json['choices'][0]['delta'])) {
  11251. $delta = $json['choices'][0]['delta'];
  11252. // 处理思维链内容
  11253. if (isset($delta['reasoning_content'])) {
  11254. $fullReasoningContent .= $delta['reasoning_content'];
  11255. yield [
  11256. 'type' => 'reasoning',
  11257. 'content' => $delta['reasoning_content'],
  11258. 'full_reasoning' => $fullReasoningContent
  11259. ];
  11260. }
  11261. // 处理回答内容
  11262. if (isset($delta['content'])) {
  11263. $fullContent .= $delta['content'];
  11264. yield [
  11265. 'type' => 'content',
  11266. 'content' => $delta['content'],
  11267. ];
  11268. }
  11269. }
  11270. // 获取使用统计信息
  11271. if (isset($json['usage'])) {
  11272. $usage = $json['usage'];
  11273. dLog('deepseek')->info('收到使用统计', ['usage' => $usage]);
  11274. }
  11275. } catch (\Exception $e) {
  11276. dLog('deepseek')->error('解析流式响应失败: ' . $e->getMessage());
  11277. continue;
  11278. }
  11279. }
  11280. }
  11281. dLog('deepseek')->info('流式读取完成', [
  11282. 'content_length' => strlen($fullContent),
  11283. 'reasoning_length' => strlen($fullReasoningContent)
  11284. ]);
  11285. yield [
  11286. 'type' => 'done',
  11287. 'full_content' => $fullContent,
  11288. 'full_reasoning' => $fullReasoningContent,
  11289. 'usage' => $usage
  11290. ];
  11291. } catch (\Exception $e) {
  11292. dLog('deepseek')->error('火山引擎对话API流式请求异常: ' . $e->getMessage());
  11293. logDB('deepseek', 'error', '火山引擎对话API流式请求失败', ['error' => $e->getMessage()]);
  11294. throw $e;
  11295. }
  11296. }
  11297. /**
  11298. * 检查并创建图片生成任务
  11299. *
  11300. * @param array $merged_items 合并后的资源列表(roles 或 scenes)
  11301. * @param array $global_items 全局资源列表(来自 mp_animes 表)
  11302. * @param string $nameKey 资源名称字段('role' 或 'scene')
  11303. * @param string $art_style 美术风格
  11304. * @return array 更新后的资源列表
  11305. */
  11306. private function checkAndCreateImageTasks(array $merged_items, array $global_items, string $nameKey, string $art_style = ''): array
  11307. {
  11308. // 确保参数为数组
  11309. $merged_items = is_array($merged_items) ? $merged_items : [];
  11310. $global_items = is_array($global_items) ? $global_items : [];
  11311. // 构建全局资源映射表,用于快速查找
  11312. $global_map = [];
  11313. foreach ($global_items as $item) {
  11314. $itemKey = $this->normalizeEpisodeResourceKey(getProp($item, $nameKey));
  11315. if ($itemKey === '') {
  11316. continue;
  11317. }
  11318. $global_map[$itemKey] = $item;
  11319. }
  11320. // 遍历合并后的资源列表,检查是否需要创建图片生成任务
  11321. foreach ($merged_items as &$item) {
  11322. $item_name = getProp($item, $nameKey);
  11323. $item_description = getProp($item, 'description');
  11324. // $item_url = getProp($item, 'url');
  11325. // // 如果已有图片URL,跳过
  11326. // if (!empty($item_url)) {
  11327. // continue;
  11328. // }
  11329. // 如果是旁白角色,跳过
  11330. if ($nameKey === 'role' && $item_name === '旁白') {
  11331. continue;
  11332. }
  11333. $itemKey = $this->normalizeEpisodeResourceKey($item_name);
  11334. if ($itemKey === '') {
  11335. continue;
  11336. }
  11337. $need_create_task = false;
  11338. // 条件1:在全局资源中找不到匹配的名称
  11339. if (!isset($global_map[$itemKey])) {
  11340. $need_create_task = true;
  11341. } else {
  11342. // 条件2:名称匹配但描述或 pic_prompt 不一致
  11343. $global_description = trim((string)getProp($global_map[$itemKey], 'description'));
  11344. $current_description = trim((string)$item_description);
  11345. $global_pic_prompt = trim((string)getProp($global_map[$itemKey], 'pic_prompt'));
  11346. $current_pic_prompt = trim((string)getProp($item, 'pic_prompt'));
  11347. // 如果 description 或 pic_prompt 有变化,需要重新生成
  11348. if ($global_description !== $current_description || $global_pic_prompt !== $current_pic_prompt) {
  11349. $need_create_task = true;
  11350. }
  11351. }
  11352. // 如果需要创建任务,调用图片生成服务
  11353. if ($need_create_task) {
  11354. try {
  11355. // 优先使用 pic_prompt,如果没有则使用 description
  11356. $pic_prompt = getProp($item, 'pic_prompt');
  11357. $description = !empty($pic_prompt) ? trim((string)$pic_prompt) : $item_description;
  11358. // 添加美术风格前缀
  11359. if ($art_style) {
  11360. $prefix = $nameKey === 'role' ? '主体描述' : '场景描述';
  11361. // $description = "美术风格:\n{$art_style}\n\n{$prefix}:{$description}";
  11362. $description = "{$prefix}:{$description}";
  11363. }
  11364. $params = [
  11365. 'prompt' => $description,
  11366. 'ref_img_urls' => []
  11367. ];
  11368. $task = $this->aiImageGenerationService->createImageGenerationTask($params);
  11369. $task_id = $task->id;
  11370. if ($task_id) {
  11371. $item['task_id'] = $task_id;
  11372. $item['task_status'] = 'processing';
  11373. $resource_type = $nameKey === 'role' ? '角色' : '场景';
  11374. dLog('deepseek')->info("{$resource_type}({$item_name})创建图片生成任务成功", ['task_id' => $task_id]);
  11375. }
  11376. } catch (\Exception $e) {
  11377. $resource_type = $nameKey === 'role' ? '角色' : '场景';
  11378. dLog('deepseek')->error("{$resource_type}({$item_name})创建图片生成任务失败: " . $e->getMessage());
  11379. logDB('deepseek', 'error', "{$resource_type}创建图片生成任务失败", ['name' => $item_name, 'error' => $e->getMessage()]);
  11380. // 不抛出异常,继续处理其他资源
  11381. }
  11382. }
  11383. }
  11384. return $merged_items;
  11385. }
  11386. /**
  11387. * 同步新出现的主体和场景到全局
  11388. *
  11389. * @param int $anime_id 动漫ID
  11390. * @param array $merged_roles 合并后的角色列表
  11391. * @param array $merged_scenes 合并后的场景列表
  11392. * @param array $global_roles 全局角色列表
  11393. * @param array $global_scenes 全局场景列表
  11394. * @return void
  11395. */
  11396. private function syncNewResourcesToGlobal(
  11397. int $anime_id,
  11398. array $merged_roles,
  11399. array $merged_scenes,
  11400. array $global_roles,
  11401. array $global_scenes
  11402. ): void {
  11403. // 构建全局角色映射表
  11404. $global_role_map = [];
  11405. foreach ($global_roles as $role) {
  11406. $roleKey = $this->normalizeEpisodeResourceKey(getProp($role, 'role'));
  11407. if ($roleKey !== '') {
  11408. $global_role_map[$roleKey] = $role;
  11409. }
  11410. }
  11411. // 构建全局场景映射表
  11412. $global_scene_map = [];
  11413. foreach ($global_scenes as $scene) {
  11414. $sceneKey = $this->normalizeEpisodeResourceKey(getProp($scene, 'scene'));
  11415. if ($sceneKey !== '') {
  11416. $global_scene_map[$sceneKey] = $scene;
  11417. }
  11418. }
  11419. $need_update = false;
  11420. $new_global_roles = $global_roles;
  11421. $new_global_scenes = $global_scenes;
  11422. // 检查并添加新角色到全局
  11423. foreach ($merged_roles as $role) {
  11424. $role_name = getProp($role, 'role');
  11425. // 跳过旁白
  11426. if ($role_name === '旁白') {
  11427. continue;
  11428. }
  11429. $roleKey = $this->normalizeEpisodeResourceKey($role_name);
  11430. if ($roleKey === '') {
  11431. continue;
  11432. }
  11433. // 如果全局中不存在该角色,添加到全局
  11434. if (!isset($global_role_map[$roleKey])) {
  11435. $new_global_roles[] = [
  11436. 'role' => $role_name,
  11437. 'description' => getProp($role, 'description', ''),
  11438. 'pic_prompt' => getProp($role, 'pic_prompt', ''),
  11439. 'voice_name' => getProp($role, 'voice_name', ''),
  11440. 'voice_type' => getProp($role, 'voice_type', ''),
  11441. 'voice_audio_url' => getProp($role, 'voice_audio_url', ''),
  11442. 'url' => getProp($role, 'url', ''),
  11443. 'task_id' => getProp($role, 'task_id', ''),
  11444. 'task_status' => getProp($role, 'task_status', ''),
  11445. ];
  11446. $global_role_map[$roleKey] = true; // 标记已添加
  11447. $need_update = true;
  11448. dLog('deepseek')->info("新角色同步到全局", [
  11449. 'anime_id' => $anime_id,
  11450. 'role' => $role_name,
  11451. 'task_id' => getProp($role, 'task_id', ''),
  11452. ]);
  11453. }
  11454. // else {
  11455. // // 如果角色已存在,但描述、pic_prompt或图片信息有更新,则更新全局数据
  11456. // $global_role = $global_role_map[$roleKey];
  11457. // if (is_array($global_role)) {
  11458. // $updated = false;
  11459. // $update_fields = [];
  11460. // // 检查描述是否更新
  11461. // $current_description = trim((string)getProp($role, 'description'));
  11462. // $global_description = trim((string)getProp($global_role, 'description'));
  11463. // if ($current_description !== '' && $current_description !== $global_description) {
  11464. // $updated = true;
  11465. // $update_fields[] = 'description';
  11466. // }
  11467. // // 检查pic_prompt是否更新
  11468. // $current_pic_prompt = trim((string)getProp($role, 'pic_prompt'));
  11469. // $global_pic_prompt = trim((string)getProp($global_role, 'pic_prompt'));
  11470. // if ($current_pic_prompt !== '' && $current_pic_prompt !== $global_pic_prompt) {
  11471. // $updated = true;
  11472. // $update_fields[] = 'pic_prompt';
  11473. // }
  11474. // // 检查图片任务信息是否更新
  11475. // $current_task_id = getProp($role, 'task_id');
  11476. // $global_task_id = getProp($global_role, 'task_id');
  11477. // if ($current_task_id && $current_task_id !== $global_task_id) {
  11478. // $updated = true;
  11479. // $update_fields[] = 'task_id';
  11480. // }
  11481. // // 如果有更新,同步到全局
  11482. // if ($updated) {
  11483. // foreach ($new_global_roles as &$global_role_item) {
  11484. // $global_role_key = $this->normalizeEpisodeResourceKey(getProp($global_role_item, 'role'));
  11485. // if ($global_role_key === $roleKey) {
  11486. // if (in_array('description', $update_fields)) {
  11487. // $global_role_item['description'] = $current_description;
  11488. // }
  11489. // if (in_array('pic_prompt', $update_fields)) {
  11490. // $global_role_item['pic_prompt'] = $current_pic_prompt;
  11491. // }
  11492. // if (in_array('task_id', $update_fields)) {
  11493. // $global_role_item['task_id'] = $current_task_id;
  11494. // $global_role_item['task_status'] = getProp($role, 'task_status', '');
  11495. // $global_role_item['url'] = getProp($role, 'url', '');
  11496. // }
  11497. // break;
  11498. // }
  11499. // }
  11500. // $need_update = true;
  11501. // dLog('deepseek')->info("角色信息更新到全局", [
  11502. // 'anime_id' => $anime_id,
  11503. // 'role' => $role_name,
  11504. // 'update_fields' => implode(',', $update_fields),
  11505. // ]);
  11506. // }
  11507. // }
  11508. // }
  11509. }
  11510. // 检查并添加新场景到全局
  11511. foreach ($merged_scenes as $scene) {
  11512. $scene_name = getProp($scene, 'scene');
  11513. $sceneKey = $this->normalizeEpisodeResourceKey($scene_name);
  11514. if ($sceneKey === '') {
  11515. continue;
  11516. }
  11517. // 如果全局中不存在该场景,添加到全局
  11518. if (!isset($global_scene_map[$sceneKey])) {
  11519. $new_global_scenes[] = [
  11520. 'scene' => $scene_name,
  11521. 'description' => getProp($scene, 'description', ''),
  11522. 'pic_prompt' => getProp($scene, 'pic_prompt', ''),
  11523. 'url' => getProp($scene, 'url', ''),
  11524. 'task_id' => getProp($scene, 'task_id', ''),
  11525. 'task_status' => getProp($scene, 'task_status', ''),
  11526. ];
  11527. $global_scene_map[$sceneKey] = true; // 标记已添加
  11528. $need_update = true;
  11529. dLog('deepseek')->info("新场景同步到全局", [
  11530. 'anime_id' => $anime_id,
  11531. 'scene' => $scene_name,
  11532. 'task_id' => getProp($scene, 'task_id', ''),
  11533. ]);
  11534. }
  11535. // else {
  11536. // // 如果场景已存在,但描述、pic_prompt或图片信息有更新,则更新全局数据
  11537. // $global_scene = $global_scene_map[$sceneKey];
  11538. // if (is_array($global_scene)) {
  11539. // $updated = false;
  11540. // $update_fields = [];
  11541. // // 检查描述是否更新
  11542. // $current_description = trim((string)getProp($scene, 'description'));
  11543. // $global_description = trim((string)getProp($global_scene, 'description'));
  11544. // if ($current_description !== '' && $current_description !== $global_description) {
  11545. // $updated = true;
  11546. // $update_fields[] = 'description';
  11547. // }
  11548. // // 检查pic_prompt是否更新
  11549. // $current_pic_prompt = trim((string)getProp($scene, 'pic_prompt'));
  11550. // $global_pic_prompt = trim((string)getProp($global_scene, 'pic_prompt'));
  11551. // if ($current_pic_prompt !== '' && $current_pic_prompt !== $global_pic_prompt) {
  11552. // $updated = true;
  11553. // $update_fields[] = 'pic_prompt';
  11554. // }
  11555. // // 检查图片任务信息是否更新
  11556. // $current_task_id = getProp($scene, 'task_id');
  11557. // $global_task_id = getProp($global_scene, 'task_id');
  11558. // if ($current_task_id && $current_task_id !== $global_task_id) {
  11559. // $updated = true;
  11560. // $update_fields[] = 'task_id';
  11561. // }
  11562. // // 如果有更新,同步到全局
  11563. // if ($updated) {
  11564. // foreach ($new_global_scenes as &$global_scene_item) {
  11565. // $global_scene_key = $this->normalizeEpisodeResourceKey(getProp($global_scene_item, 'scene'));
  11566. // if ($global_scene_key === $sceneKey) {
  11567. // if (in_array('description', $update_fields)) {
  11568. // $global_scene_item['description'] = $current_description;
  11569. // }
  11570. // if (in_array('pic_prompt', $update_fields)) {
  11571. // $global_scene_item['pic_prompt'] = $current_pic_prompt;
  11572. // }
  11573. // if (in_array('task_id', $update_fields)) {
  11574. // $global_scene_item['task_id'] = $current_task_id;
  11575. // $global_scene_item['task_status'] = getProp($scene, 'task_status', '');
  11576. // $global_scene_item['url'] = getProp($scene, 'url', '');
  11577. // }
  11578. // break;
  11579. // }
  11580. // }
  11581. // $need_update = true;
  11582. // dLog('deepseek')->info("场景信息更新到全局", [
  11583. // 'anime_id' => $anime_id,
  11584. // 'scene' => $scene_name,
  11585. // 'update_fields' => implode(',', $update_fields),
  11586. // ]);
  11587. // }
  11588. // }
  11589. // }
  11590. }
  11591. // 如果有新增或更新,更新数据库
  11592. if ($need_update) {
  11593. $update_data = [
  11594. 'roles' => json_encode($new_global_roles, 256),
  11595. 'scenes' => json_encode($new_global_scenes, 256),
  11596. 'updated_at' => date('Y-m-d H:i:s'),
  11597. ];
  11598. $result = DB::table('mp_animes')->where('id', $anime_id)->update($update_data);
  11599. if ($result !== false) {
  11600. dLog('deepseek')->info("全局角色和场景更新成功", [
  11601. 'anime_id' => $anime_id,
  11602. 'roles_count' => count($new_global_roles),
  11603. 'scenes_count' => count($new_global_scenes),
  11604. ]);
  11605. } else {
  11606. dLog('deepseek')->error("全局角色和场景更新失败", ['anime_id' => $anime_id]);
  11607. logDB('deepseek', 'error', '全局角色和场景更新失败', ['anime_id' => $anime_id]);
  11608. }
  11609. }
  11610. }
  11611. }